From 5ea05a3066d1508c128e36f80de9505a2fd841c7 Mon Sep 17 00:00:00 2001 From: andreaturli Date: Fri, 12 Nov 2010 22:08:53 +0100 Subject: [PATCH 01/31] templateBuilder improvement --- .../compute/LibvirtComputeService.java | 2 +- .../LibvirtComputeServiceContextModule.java | 49 ++++++++++++++----- .../LibvirtComputeServiceAdapter.java | 19 +++++-- .../compute/LibvirtExperimentLiveTest.java | 17 ++++--- 4 files changed, 63 insertions(+), 24 deletions(-) diff --git a/sandbox/libvirt/src/main/java/org/jclouds/libvirt/compute/LibvirtComputeService.java b/sandbox/libvirt/src/main/java/org/jclouds/libvirt/compute/LibvirtComputeService.java index 676f4bfacd..f1cdc3b68f 100644 --- a/sandbox/libvirt/src/main/java/org/jclouds/libvirt/compute/LibvirtComputeService.java +++ b/sandbox/libvirt/src/main/java/org/jclouds/libvirt/compute/LibvirtComputeService.java @@ -103,7 +103,7 @@ public class LibvirtComputeService extends BaseComputeService { @Override public void destroyNode(String id) { super.destroyNode(id); - eliminateDomain(id); + //eliminateDomain(id); } private void eliminateDomain(String id) { diff --git a/sandbox/libvirt/src/main/java/org/jclouds/libvirt/compute/domain/LibvirtComputeServiceContextModule.java b/sandbox/libvirt/src/main/java/org/jclouds/libvirt/compute/domain/LibvirtComputeServiceContextModule.java index fc3876eea4..223b8ed737 100644 --- a/sandbox/libvirt/src/main/java/org/jclouds/libvirt/compute/domain/LibvirtComputeServiceContextModule.java +++ b/sandbox/libvirt/src/main/java/org/jclouds/libvirt/compute/domain/LibvirtComputeServiceContextModule.java @@ -19,28 +19,31 @@ package org.jclouds.libvirt.compute.domain; -import static com.google.common.collect.Maps.newLinkedHashMap; import static org.jclouds.libvirt.LibvirtConstants.PROPERTY_LIBVIRT_DOMAIN_DIR; +import java.io.File; +import java.io.IOException; +import java.io.StringReader; import java.net.URI; -import java.util.Map; +import java.util.Collection; import javax.inject.Named; import javax.inject.Singleton; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.xpath.XPathExpressionException; +import org.apache.commons.io.FileUtils; +import org.apache.commons.io.filefilter.WildcardFileFilter; import org.jclouds.Constants; -import org.jclouds.compute.ComputeService; import org.jclouds.compute.ComputeServiceAdapter; import org.jclouds.compute.config.StandaloneComputeServiceContextModule; import org.jclouds.compute.domain.Hardware; import org.jclouds.compute.domain.NodeMetadata; import org.jclouds.compute.domain.TemplateBuilder; -import org.jclouds.compute.internal.BaseComputeService; import org.jclouds.compute.suppliers.DefaultLocationSupplier; import org.jclouds.domain.Location; import org.jclouds.libvirt.Datacenter; import org.jclouds.libvirt.Image; -import org.jclouds.libvirt.compute.LibvirtComputeService; import org.jclouds.libvirt.compute.functions.DatacenterToLocation; import org.jclouds.libvirt.compute.functions.DomainToHardware; import org.jclouds.libvirt.compute.functions.DomainToNodeMetadata; @@ -50,15 +53,20 @@ import org.jclouds.rest.annotations.Provider; import org.libvirt.Connect; import org.libvirt.Domain; import org.libvirt.LibvirtException; +import org.xml.sax.InputSource; +import org.xml.sax.SAXException; +import com.google.common.base.Charsets; import com.google.common.base.Function; -import com.google.common.base.Splitter; import com.google.common.base.Supplier; +import com.google.common.collect.Iterables; +import com.google.common.io.Files; import com.google.inject.Injector; import com.google.inject.Key; import com.google.inject.Provides; import com.google.inject.TypeLiteral; import com.google.inject.name.Names; +import com.jamesmurty.utils.XMLBuilder; /** * @@ -82,7 +90,7 @@ StandaloneComputeServiceContextModule { bind(new TypeLiteral>() { }).to(DatacenterToLocation.class); - bind(ComputeService.class).to(LibvirtComputeService.class); + //bind(ComputeService.class).to(LibvirtComputeService.class); } @Provides @@ -95,22 +103,37 @@ StandaloneComputeServiceContextModule { @Override protected TemplateBuilder provideTemplate(Injector injector, TemplateBuilder template) { - //String domainDir = injector.getInstance(Key.get(String.class, Names.named(PROPERTY_LIBVIRT_DOMAIN_DIR))); - String domainDir = ""; - System.out.println("++++ domain dir: " + domainDir); + String domainDir = injector.getInstance(Key.get(String.class, Names.named(PROPERTY_LIBVIRT_DOMAIN_DIR))); String hardwareId = searchForHardwareIdInDomainDir(domainDir); String image = searchForImageIdInDomainDir(domainDir); return template.hardwareId(hardwareId).imageId(image) ; } + private String searchForImageIdInDomainDir(String domainDir) { // TODO return "1"; } - + + @SuppressWarnings("unchecked") private String searchForHardwareIdInDomainDir(String domainDir) { - // TODO - return "c7ff2039-a9f1-a659-7f91-e0f82f59d52e"; + + Collection xmlDomains = FileUtils.listFiles( new File(domainDir), new WildcardFileFilter("*.xml"), null); + String uuid = ""; + try { + String fromXML = Files.toString(Iterables.get(xmlDomains, 0), Charsets.UTF_8); + XMLBuilder builder = XMLBuilder.parse(new InputSource(new StringReader(fromXML))); + uuid = builder.xpathFind("/domain/uuid").getElement().getTextContent(); + } catch (IOException e) { + e.printStackTrace(); + } catch (ParserConfigurationException e) { + e.printStackTrace(); + } catch (SAXException e) { + e.printStackTrace(); + } catch (XPathExpressionException e) { + e.printStackTrace(); + } + return uuid; } /* diff --git a/sandbox/libvirt/src/main/java/org/jclouds/libvirt/compute/strategy/LibvirtComputeServiceAdapter.java b/sandbox/libvirt/src/main/java/org/jclouds/libvirt/compute/strategy/LibvirtComputeServiceAdapter.java index 9d8782ef4b..3cab923e3d 100644 --- a/sandbox/libvirt/src/main/java/org/jclouds/libvirt/compute/strategy/LibvirtComputeServiceAdapter.java +++ b/sandbox/libvirt/src/main/java/org/jclouds/libvirt/compute/strategy/LibvirtComputeServiceAdapter.java @@ -100,7 +100,7 @@ public class LibvirtComputeServiceAdapter implements ComputeServiceAdapter Date: Tue, 23 Nov 2010 23:11:28 -0800 Subject: [PATCH 02/31] GoGrid's images might have their description null. Return empty string in this case. --- gogrid/src/main/java/org/jclouds/gogrid/domain/ServerImage.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/gogrid/src/main/java/org/jclouds/gogrid/domain/ServerImage.java b/gogrid/src/main/java/org/jclouds/gogrid/domain/ServerImage.java index 17466febc4..b739f86ee9 100644 --- a/gogrid/src/main/java/org/jclouds/gogrid/domain/ServerImage.java +++ b/gogrid/src/main/java/org/jclouds/gogrid/domain/ServerImage.java @@ -89,6 +89,8 @@ public class ServerImage implements Comparable { } public String getDescription() { + if (description == null) + return ""; return description; } From b4417fcdd135f330bce1030a479367a28c50dc55 Mon Sep 17 00:00:00 2001 From: tbatchelli MBP Date: Tue, 23 Nov 2010 23:12:13 -0800 Subject: [PATCH 03/31] GoGrid credential list might contain credentials that are not for computes. --- ...rNameToCredentialsMapFromJsonResponse.java | 4 +- .../ParseCredentialsFromJsonResponseTest.java | 2 +- .../src/test/resources/test_credential.json | 197 ++++++++++-------- 3 files changed, 113 insertions(+), 90 deletions(-) diff --git a/gogrid/src/main/java/org/jclouds/gogrid/functions/ParseServerNameToCredentialsMapFromJsonResponse.java b/gogrid/src/main/java/org/jclouds/gogrid/functions/ParseServerNameToCredentialsMapFromJsonResponse.java index 23199f6838..1525454d35 100644 --- a/gogrid/src/main/java/org/jclouds/gogrid/functions/ParseServerNameToCredentialsMapFromJsonResponse.java +++ b/gogrid/src/main/java/org/jclouds/gogrid/functions/ParseServerNameToCredentialsMapFromJsonResponse.java @@ -99,7 +99,8 @@ public class ParseServerNameToCredentialsMapFromJsonResponse implements @Override public int compareTo(Password o) { - return server.getName().compareTo(o.getServer().getName()); + if (null == o.getServer() || null == server) return -1; + return server.getName().compareTo(o.getServer().getName()); } } @@ -107,6 +108,7 @@ public class ParseServerNameToCredentialsMapFromJsonResponse implements public Map apply(HttpResponse arg0) { Map serverNameToCredentials = Maps.newHashMap(); for (Password password : json.apply(arg0).getList()) { + if( null != password.getServer()) serverNameToCredentials.put(password.getServer().getName(), new Credentials(password.getUserName(), password.getPassword())); } diff --git a/gogrid/src/test/java/org/jclouds/gogrid/functions/ParseCredentialsFromJsonResponseTest.java b/gogrid/src/test/java/org/jclouds/gogrid/functions/ParseCredentialsFromJsonResponseTest.java index 50503d1383..0ce6b8bd4a 100644 --- a/gogrid/src/test/java/org/jclouds/gogrid/functions/ParseCredentialsFromJsonResponseTest.java +++ b/gogrid/src/test/java/org/jclouds/gogrid/functions/ParseCredentialsFromJsonResponseTest.java @@ -71,7 +71,7 @@ public class ParseCredentialsFromJsonResponseTest { ParseCredentialsFromJsonResponse parser = i.getInstance(ParseCredentialsFromJsonResponse.class); Credentials creds = parser.apply(response); assertEquals(creds.identity, "root"); - assertEquals(creds.credential, "dig44sos"); + assertEquals(creds.credential, "zot40ced"); } diff --git a/gogrid/src/test/resources/test_credential.json b/gogrid/src/test/resources/test_credential.json index 924fbf5aa0..18bdec7887 100644 --- a/gogrid/src/test/resources/test_credential.json +++ b/gogrid/src/test/resources/test_credential.json @@ -1,103 +1,124 @@ { "list": [ - { - "password": "dig44sos", - "object": "password", - "username": "root", - "server": { - "object": "server", - "isSandbox": false, + { + "password": "zot40ced", + "object": "password", + "username": "root", + "server": { + "isSandbox": false, + "object": "server", + "type": { + "id": 1, + "description": "Web or Application Server", + "name": "Web Server", + "object": "option" + }, + "os": { + "id": 17, + "description": "CentOS 5.3 (64-bit)", + "name": "CentOS 5.3 (64-bit)", + "object": "option" + }, + "image": { "type": { - "object": "option", + "id": 1, "description": "Web or Application Server", "name": "Web Server", - "id": 1 + "object": "option" }, + "owner": { + "id": -1, + "name": "GoGrid", + "object": "customer" + }, + "updatedTime": 1257789076417, + "isActive": true, + "id": 1532, + "isPublic": true, + "name": "centos5.3_64_base", + "billingtokens": [ + { + "id": 47, + "price": 0, + "name": "CentOS 5.3 64bit", + "object": "billingtoken" + } + ], + "object": "serverimage", + "friendlyName": "CentOS 5.3 (64-bit) w/ None", "os": { - "object": "option", + "id": 17, "description": "CentOS 5.3 (64-bit)", "name": "CentOS 5.3 (64-bit)", - "id": 17 - }, - "image": { - "type": { - "object": "option", - "description": "Web or Application Server", - "name": "Web Server", - "id": 1 - }, - "owner": { - "object": "customer", - "name": "Gear6", - "id": 26443 - }, - "updatedTime": 1265675466171, - "isActive": true, - "id": 2500, - "createdTime": 1265412834154, - "isPublic": true, - "billingtokens": [ - { - "price": 0, - "name": "CentOS 5.3 64bit", - "id": 47 - }, - { - "price": 60, - "name": "Gear 6 Paid Version", - "id": 76 - } - ], - "object": "serverimage", - "friendlyName": "gear6-memcache-server-2.3.6.2-x86_64", - "os": { - "object": "option", - "description": "CentOS 5.3 (64-bit)", - "name": "CentOS 5.3 (64-bit)", - "id": 17 - }, - "price": 60, - "description": "Gear6 Memcache Server 2.3.6.2 (64 bit)", - "state": { - "object": "option", - "description": "Image is available for adds", - "name": "Available", - "id": 2 - }, - "location": "26443/GSI-7f498260-2b8a-43ef-aa77-5b403f8f739a.img", - "name": "GSI-7f498260-2b8a-43ef-aa77-5b403f8f739a" + "object": "option" }, + "price": 0, + "description": "CentOS 5.3 (64-bit) w/ None", "state": { - "object": "option", - "description": "Server is in active state.", - "name": "On", - "id": 1 + "id": 2, + "description": "Image is available for adds", + "name": "Available", + "object": "option" }, - "ram": { - "object": "option", - "description": "Server with 512MB RAM", - "name": "512MB", - "id": 1 - }, - "name": "gogrid-19", - "ip": { - "object": "ip", - "public": true, - "subnet": "204.51.240.176/255.255.255.240", - "state": { - "object": "option", - "description": "IP is reserved or in use", - "name": "Assigned", - "id": 2 - }, - "ip": "204.51.240.189", - "id": 1313090 - }, - "id": 77332 + "location": "gogrid/GSI-939ef909-84b8-4a2f-ad56-02ccd7da05ff.img", + "name": "bogus", + "architecture": { + "id": 2, + "description": "64 bit OS", + "name": "64-bit", + "object": "option" + } }, - "id": 82647, - "applicationtype": "os" - } + "state": { + "id": 1, + "description": "Server is in active state.", + "name": "On", + "object": "option" + }, + "ram": { + "id": 1, + "description": "Server with 512MB RAM", + "name": "512MB", + "object": "option" + }, + "name": "proxied-944", + "ip": { + "id": 1104200, + "subnet": "173.1.155.16/255.255.255.240", + "state": { + "id": 2, + "description": "IP is reserved or in use", + "name": "Assigned", + "object": "option" + }, + "datacenter": { + "id": 1, + "description": "US West 1 Datacenter", + "name": "US-West-1", + "object": "option" + }, + "object": "ip", + "public": true, + "ip": "173.1.155.19" + }, + "datacenter": { + "id": 1, + "description": "US West 1 Datacenter", + "name": "US-West-1", + "object": "option" + }, + "id": 134551 + }, + "id": 142243, + "applicationtype": "os" + }, + { + "id": 28000, + "username": "22290", + "applicationtype": "cloudstorage", + "object": "password", + "password": "200FMd2nDeomtfW." + } ], "summary": { "total": 6, @@ -107,4 +128,4 @@ }, "status": "success", "method": "/support/password/list" -} \ No newline at end of file +} From 9f51726239039a6f63b3bb6597c9f30412dc6bcd Mon Sep 17 00:00:00 2001 From: Adrian Cole Date: Wed, 24 Nov 2010 10:43:54 +0100 Subject: [PATCH 04/31] Issue 413: removed use of guice internal @Nullable annotations --- .../java/org/jclouds/aws/ec2/domain/BlockDeviceMapping.java | 3 ++- .../src/main/java/org/jclouds/aws/ec2/domain/Image.java | 3 ++- .../src/main/java/org/jclouds/aws/ec2/domain/KeyPair.java | 2 +- .../org/jclouds/aws/ec2/domain/PublicIpInstanceIdPair.java | 2 +- .../main/java/org/jclouds/aws/ec2/domain/Reservation.java | 3 ++- .../java/org/jclouds/aws/ec2/domain/RunningInstance.java | 3 ++- .../src/main/java/org/jclouds/aws/s3/domain/S3Object.java | 3 ++- aws/demos/googleappengine/pom.xml | 2 +- .../storage/blob/domain/internal/BlobPropertiesImpl.java | 3 ++- .../java/org/jclouds/blobstore/TransientAsyncBlobStore.java | 6 +++--- .../src/main/java/org/jclouds/blobstore/domain/Blob.java | 4 +++- .../jclouds/blobstore/domain/internal/BlobMetadataImpl.java | 4 ++-- .../blobstore/domain/internal/StorageMetadataImpl.java | 4 ++-- core/pom.xml | 2 +- .../org/jclouds/domain/internal/ResourceMetadataImpl.java | 3 ++- demos/gae-tweetstore/pom.xml | 2 +- .../org/jclouds/filesystem/FilesystemAsyncBlobStore.java | 6 +++--- .../org/jclouds/rackspace/cloudfiles/domain/CFObject.java | 3 ++- .../cloudservers/options/CreateSharedIpGroupOptions.java | 3 ++- 19 files changed, 36 insertions(+), 25 deletions(-) diff --git a/aws/core/src/main/java/org/jclouds/aws/ec2/domain/BlockDeviceMapping.java b/aws/core/src/main/java/org/jclouds/aws/ec2/domain/BlockDeviceMapping.java index a254e3085d..7cb5a0b81a 100644 --- a/aws/core/src/main/java/org/jclouds/aws/ec2/domain/BlockDeviceMapping.java +++ b/aws/core/src/main/java/org/jclouds/aws/ec2/domain/BlockDeviceMapping.java @@ -21,10 +21,11 @@ package org.jclouds.aws.ec2.domain; import static com.google.common.base.Preconditions.checkNotNull; +import javax.annotation.Nullable; + import com.google.common.collect.ImmutableMultimap; import com.google.common.collect.LinkedHashMultimap; import com.google.common.collect.Multimap; -import com.google.inject.internal.Nullable; /** * Defines the mapping of volumes for diff --git a/aws/core/src/main/java/org/jclouds/aws/ec2/domain/Image.java b/aws/core/src/main/java/org/jclouds/aws/ec2/domain/Image.java index 33cd5021cf..11f3ab00ec 100644 --- a/aws/core/src/main/java/org/jclouds/aws/ec2/domain/Image.java +++ b/aws/core/src/main/java/org/jclouds/aws/ec2/domain/Image.java @@ -24,10 +24,11 @@ import static com.google.common.base.Preconditions.checkNotNull; import java.util.Map; import java.util.Set; +import javax.annotation.Nullable; + import com.google.common.collect.Iterables; import com.google.common.collect.Maps; import com.google.common.collect.Sets; -import com.google.inject.internal.Nullable; /** * diff --git a/aws/core/src/main/java/org/jclouds/aws/ec2/domain/KeyPair.java b/aws/core/src/main/java/org/jclouds/aws/ec2/domain/KeyPair.java index eedcd60428..1c572c144c 100644 --- a/aws/core/src/main/java/org/jclouds/aws/ec2/domain/KeyPair.java +++ b/aws/core/src/main/java/org/jclouds/aws/ec2/domain/KeyPair.java @@ -21,7 +21,7 @@ package org.jclouds.aws.ec2.domain; import static com.google.common.base.Preconditions.checkNotNull; -import com.google.inject.internal.Nullable; +import javax.annotation.Nullable; /** * diff --git a/aws/core/src/main/java/org/jclouds/aws/ec2/domain/PublicIpInstanceIdPair.java b/aws/core/src/main/java/org/jclouds/aws/ec2/domain/PublicIpInstanceIdPair.java index 891a075a31..1a947a7dcf 100644 --- a/aws/core/src/main/java/org/jclouds/aws/ec2/domain/PublicIpInstanceIdPair.java +++ b/aws/core/src/main/java/org/jclouds/aws/ec2/domain/PublicIpInstanceIdPair.java @@ -21,7 +21,7 @@ package org.jclouds.aws.ec2.domain; import static com.google.common.base.Preconditions.checkNotNull; -import com.google.inject.internal.Nullable; +import javax.annotation.Nullable; /** * diff --git a/aws/core/src/main/java/org/jclouds/aws/ec2/domain/Reservation.java b/aws/core/src/main/java/org/jclouds/aws/ec2/domain/Reservation.java index 0657f19a12..6d6619d7c2 100644 --- a/aws/core/src/main/java/org/jclouds/aws/ec2/domain/Reservation.java +++ b/aws/core/src/main/java/org/jclouds/aws/ec2/domain/Reservation.java @@ -24,9 +24,10 @@ import static com.google.common.base.Preconditions.checkNotNull; import java.util.LinkedHashSet; import java.util.Set; +import javax.annotation.Nullable; + import com.google.common.collect.Iterables; import com.google.common.collect.Sets; -import com.google.inject.internal.Nullable; /** * diff --git a/aws/core/src/main/java/org/jclouds/aws/ec2/domain/RunningInstance.java b/aws/core/src/main/java/org/jclouds/aws/ec2/domain/RunningInstance.java index a2a7a575df..ed4ed62499 100644 --- a/aws/core/src/main/java/org/jclouds/aws/ec2/domain/RunningInstance.java +++ b/aws/core/src/main/java/org/jclouds/aws/ec2/domain/RunningInstance.java @@ -25,12 +25,13 @@ import java.util.Date; import java.util.Map; import java.util.Set; +import javax.annotation.Nullable; + import org.jclouds.aws.ec2.domain.Attachment.Status; import com.google.common.collect.Iterables; import com.google.common.collect.Maps; import com.google.common.collect.Sets; -import com.google.inject.internal.Nullable; /** * diff --git a/aws/core/src/main/java/org/jclouds/aws/s3/domain/S3Object.java b/aws/core/src/main/java/org/jclouds/aws/s3/domain/S3Object.java index da4478e78b..bf2c43695a 100644 --- a/aws/core/src/main/java/org/jclouds/aws/s3/domain/S3Object.java +++ b/aws/core/src/main/java/org/jclouds/aws/s3/domain/S3Object.java @@ -19,10 +19,11 @@ package org.jclouds.aws.s3.domain; +import javax.annotation.Nullable; + import org.jclouds.io.PayloadEnclosing; import com.google.common.collect.Multimap; -import com.google.inject.internal.Nullable; /** * Amazon S3 is designed to store objects. Objects are stored in buckets and consist of a diff --git a/aws/demos/googleappengine/pom.xml b/aws/demos/googleappengine/pom.xml index 65f5964ce1..c3a39338fa 100644 --- a/aws/demos/googleappengine/pom.xml +++ b/aws/demos/googleappengine/pom.xml @@ -52,7 +52,7 @@ com.google.code.guice guice-servlet - 2.1-r1201 + 3.0-snapshot-20101120 displaytag diff --git a/azure/src/main/java/org/jclouds/azure/storage/blob/domain/internal/BlobPropertiesImpl.java b/azure/src/main/java/org/jclouds/azure/storage/blob/domain/internal/BlobPropertiesImpl.java index 3233257cd6..e84ed48e84 100644 --- a/azure/src/main/java/org/jclouds/azure/storage/blob/domain/internal/BlobPropertiesImpl.java +++ b/azure/src/main/java/org/jclouds/azure/storage/blob/domain/internal/BlobPropertiesImpl.java @@ -26,6 +26,8 @@ import java.net.URI; import java.util.Date; import java.util.Map; +import javax.annotation.Nullable; + import org.jclouds.azure.storage.blob.domain.BlobProperties; import org.jclouds.azure.storage.blob.domain.BlobType; import org.jclouds.azure.storage.blob.domain.LeaseStatus; @@ -33,7 +35,6 @@ import org.jclouds.io.ContentMetadata; import org.jclouds.io.payloads.BaseImmutableContentMetadata; import com.google.common.collect.Maps; -import com.google.inject.internal.Nullable; /** * Allows you to manipulate metadata. diff --git a/blobstore/src/main/java/org/jclouds/blobstore/TransientAsyncBlobStore.java b/blobstore/src/main/java/org/jclouds/blobstore/TransientAsyncBlobStore.java index 5b2bae075b..f308d57d18 100755 --- a/blobstore/src/main/java/org/jclouds/blobstore/TransientAsyncBlobStore.java +++ b/blobstore/src/main/java/org/jclouds/blobstore/TransientAsyncBlobStore.java @@ -49,27 +49,28 @@ import java.util.Collections; import java.util.Date; import java.util.List; import java.util.Map; +import java.util.Map.Entry; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; -import java.util.Map.Entry; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ExecutorService; +import javax.annotation.Nullable; import javax.inject.Inject; import javax.inject.Named; import javax.ws.rs.core.HttpHeaders; import org.jclouds.Constants; import org.jclouds.blobstore.domain.Blob; +import org.jclouds.blobstore.domain.Blob.Factory; import org.jclouds.blobstore.domain.BlobMetadata; import org.jclouds.blobstore.domain.MutableBlobMetadata; import org.jclouds.blobstore.domain.MutableStorageMetadata; import org.jclouds.blobstore.domain.PageSet; import org.jclouds.blobstore.domain.StorageMetadata; import org.jclouds.blobstore.domain.StorageType; -import org.jclouds.blobstore.domain.Blob.Factory; import org.jclouds.blobstore.domain.internal.MutableStorageMetadataImpl; import org.jclouds.blobstore.domain.internal.PageSetImpl; import org.jclouds.blobstore.functions.HttpGetOptionsListToGetOptions; @@ -103,7 +104,6 @@ import com.google.common.collect.Iterables; import com.google.common.collect.Multimaps; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; -import com.google.inject.internal.Nullable; /** * Implementation of {@link BaseAsyncBlobStore} which keeps all data in a local Map object. diff --git a/blobstore/src/main/java/org/jclouds/blobstore/domain/Blob.java b/blobstore/src/main/java/org/jclouds/blobstore/domain/Blob.java index 51bc1d4351..e618c08ca4 100644 --- a/blobstore/src/main/java/org/jclouds/blobstore/domain/Blob.java +++ b/blobstore/src/main/java/org/jclouds/blobstore/domain/Blob.java @@ -19,10 +19,12 @@ package org.jclouds.blobstore.domain; +import javax.annotation.Nullable; + +import org.jclouds.io.Payload; import org.jclouds.io.PayloadEnclosing; import com.google.common.collect.Multimap; -import com.google.inject.internal.Nullable; /** * Value type for an HTTP Blob service. Blobs are stored in containers and consist of a diff --git a/blobstore/src/main/java/org/jclouds/blobstore/domain/internal/BlobMetadataImpl.java b/blobstore/src/main/java/org/jclouds/blobstore/domain/internal/BlobMetadataImpl.java index bcc8f4be3e..17659b73a6 100644 --- a/blobstore/src/main/java/org/jclouds/blobstore/domain/internal/BlobMetadataImpl.java +++ b/blobstore/src/main/java/org/jclouds/blobstore/domain/internal/BlobMetadataImpl.java @@ -26,14 +26,14 @@ import java.net.URI; import java.util.Date; import java.util.Map; +import javax.annotation.Nullable; + import org.jclouds.blobstore.domain.Blob; import org.jclouds.blobstore.domain.BlobMetadata; import org.jclouds.blobstore.domain.StorageType; import org.jclouds.domain.Location; import org.jclouds.io.ContentMetadata; -import com.google.inject.internal.Nullable; - /** * System and user Metadata for the {@link Blob}. * diff --git a/blobstore/src/main/java/org/jclouds/blobstore/domain/internal/StorageMetadataImpl.java b/blobstore/src/main/java/org/jclouds/blobstore/domain/internal/StorageMetadataImpl.java index 4e416806d9..7a347eaf46 100644 --- a/blobstore/src/main/java/org/jclouds/blobstore/domain/internal/StorageMetadataImpl.java +++ b/blobstore/src/main/java/org/jclouds/blobstore/domain/internal/StorageMetadataImpl.java @@ -26,13 +26,13 @@ import java.net.URI; import java.util.Date; import java.util.Map; +import javax.annotation.Nullable; + import org.jclouds.blobstore.domain.StorageMetadata; import org.jclouds.blobstore.domain.StorageType; import org.jclouds.domain.Location; import org.jclouds.domain.internal.ResourceMetadataImpl; -import com.google.inject.internal.Nullable; - /** * Idpayload of the object * diff --git a/core/pom.xml b/core/pom.xml index dae3ed8250..4abd10c9bb 100644 --- a/core/pom.xml +++ b/core/pom.xml @@ -81,7 +81,7 @@ com.google.code.guice guice - 2.1-r1201 + 3.0-snapshot-20101120 javax.inject diff --git a/core/src/main/java/org/jclouds/domain/internal/ResourceMetadataImpl.java b/core/src/main/java/org/jclouds/domain/internal/ResourceMetadataImpl.java index fbc55edde7..38d6b6352f 100644 --- a/core/src/main/java/org/jclouds/domain/internal/ResourceMetadataImpl.java +++ b/core/src/main/java/org/jclouds/domain/internal/ResourceMetadataImpl.java @@ -25,11 +25,12 @@ import java.io.Serializable; import java.net.URI; import java.util.Map; +import javax.annotation.Nullable; + import org.jclouds.domain.Location; import org.jclouds.domain.ResourceMetadata; import com.google.common.collect.Maps; -import com.google.inject.internal.Nullable; /** * Idpayload of the object diff --git a/demos/gae-tweetstore/pom.xml b/demos/gae-tweetstore/pom.xml index 6b3063661a..7c716e5702 100644 --- a/demos/gae-tweetstore/pom.xml +++ b/demos/gae-tweetstore/pom.xml @@ -103,7 +103,7 @@ com.google.code.guice guice-servlet - 2.1-r1201 + 3.0-snapshot-20101120 displaytag diff --git a/filesystem/src/main/java/org/jclouds/filesystem/FilesystemAsyncBlobStore.java b/filesystem/src/main/java/org/jclouds/filesystem/FilesystemAsyncBlobStore.java index 3ffde30ddf..d8622888ac 100644 --- a/filesystem/src/main/java/org/jclouds/filesystem/FilesystemAsyncBlobStore.java +++ b/filesystem/src/main/java/org/jclouds/filesystem/FilesystemAsyncBlobStore.java @@ -49,12 +49,13 @@ import java.util.Collection; import java.util.Date; import java.util.List; import java.util.Map; +import java.util.Map.Entry; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; -import java.util.Map.Entry; import java.util.concurrent.ExecutorService; +import javax.annotation.Nullable; import javax.annotation.Resource; import javax.inject.Inject; import javax.inject.Named; @@ -66,13 +67,13 @@ import org.jclouds.blobstore.BlobStoreContext; import org.jclouds.blobstore.ContainerNotFoundException; import org.jclouds.blobstore.KeyNotFoundException; import org.jclouds.blobstore.domain.Blob; +import org.jclouds.blobstore.domain.Blob.Factory; import org.jclouds.blobstore.domain.BlobMetadata; import org.jclouds.blobstore.domain.MutableBlobMetadata; import org.jclouds.blobstore.domain.MutableStorageMetadata; import org.jclouds.blobstore.domain.PageSet; import org.jclouds.blobstore.domain.StorageMetadata; import org.jclouds.blobstore.domain.StorageType; -import org.jclouds.blobstore.domain.Blob.Factory; import org.jclouds.blobstore.domain.internal.MutableBlobMetadataImpl; import org.jclouds.blobstore.domain.internal.MutableStorageMetadataImpl; import org.jclouds.blobstore.domain.internal.PageSetImpl; @@ -107,7 +108,6 @@ import com.google.common.base.Throwables; import com.google.common.collect.Iterables; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; -import com.google.inject.internal.Nullable; /** * diff --git a/rackspace/src/main/java/org/jclouds/rackspace/cloudfiles/domain/CFObject.java b/rackspace/src/main/java/org/jclouds/rackspace/cloudfiles/domain/CFObject.java index abefae7c34..182916521a 100644 --- a/rackspace/src/main/java/org/jclouds/rackspace/cloudfiles/domain/CFObject.java +++ b/rackspace/src/main/java/org/jclouds/rackspace/cloudfiles/domain/CFObject.java @@ -19,10 +19,11 @@ package org.jclouds.rackspace.cloudfiles.domain; +import javax.annotation.Nullable; + import org.jclouds.io.PayloadEnclosing; import com.google.common.collect.Multimap; -import com.google.inject.internal.Nullable; /** * diff --git a/rackspace/src/main/java/org/jclouds/rackspace/cloudservers/options/CreateSharedIpGroupOptions.java b/rackspace/src/main/java/org/jclouds/rackspace/cloudservers/options/CreateSharedIpGroupOptions.java index a69269654f..3b5af4042a 100644 --- a/rackspace/src/main/java/org/jclouds/rackspace/cloudservers/options/CreateSharedIpGroupOptions.java +++ b/rackspace/src/main/java/org/jclouds/rackspace/cloudservers/options/CreateSharedIpGroupOptions.java @@ -24,11 +24,12 @@ import static com.google.common.base.Preconditions.checkNotNull; import java.util.Map; +import javax.annotation.Nullable; + import org.jclouds.http.HttpRequest; import org.jclouds.rest.binders.BindToJsonPayload; import com.google.common.collect.ImmutableMap; -import com.google.inject.internal.Nullable; /** * From e6110c96fdd7c3273170e9e8814921ce4ca9283c Mon Sep 17 00:00:00 2001 From: Adrian Cole Date: Wed, 24 Nov 2010 10:58:51 +0100 Subject: [PATCH 05/31] Issue 413: removed use of guice internal @Nullable annotations --- .../org/jclouds/atmosonline/saas/domain/AtmosObject.java | 3 ++- .../compute/strategy/VCloudExpressListNodesStrategy.java | 2 +- .../vcloud/compute/strategy/VCloudListNodesStrategy.java | 2 +- .../org/jclouds/vcloud/compute/util/VCloudComputeUtils.java | 2 +- .../org/jclouds/vcloud/domain/internal/CatalogImpl.java | 3 ++- .../java/org/jclouds/vcloud/domain/internal/ErrorImpl.java | 4 ++-- .../java/org/jclouds/vcloud/domain/internal/TaskImpl.java | 6 +++--- .../domain/network/internal/VCloudExpressNetworkImpl.java | 3 ++- ...remarkBindInstantiateVAppTemplateParamsToXmlPayload.java | 4 ++-- .../options/TerremarkInstantiateVAppTemplateOptions.java | 2 +- 10 files changed, 17 insertions(+), 14 deletions(-) diff --git a/atmos/src/main/java/org/jclouds/atmosonline/saas/domain/AtmosObject.java b/atmos/src/main/java/org/jclouds/atmosonline/saas/domain/AtmosObject.java index 2580857ae4..00e942bd77 100644 --- a/atmos/src/main/java/org/jclouds/atmosonline/saas/domain/AtmosObject.java +++ b/atmos/src/main/java/org/jclouds/atmosonline/saas/domain/AtmosObject.java @@ -19,10 +19,11 @@ package org.jclouds.atmosonline.saas.domain; +import javax.annotation.Nullable; + import org.jclouds.io.PayloadEnclosing; import com.google.common.collect.Multimap; -import com.google.inject.internal.Nullable; /** * Amazon Atmos is designed to store objects. Objects are stored in buckets and consist of a diff --git a/vcloud/core/src/main/java/org/jclouds/vcloud/compute/strategy/VCloudExpressListNodesStrategy.java b/vcloud/core/src/main/java/org/jclouds/vcloud/compute/strategy/VCloudExpressListNodesStrategy.java index 206ed9ff2d..7452357933 100644 --- a/vcloud/core/src/main/java/org/jclouds/vcloud/compute/strategy/VCloudExpressListNodesStrategy.java +++ b/vcloud/core/src/main/java/org/jclouds/vcloud/compute/strategy/VCloudExpressListNodesStrategy.java @@ -45,9 +45,9 @@ import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Predicate; import com.google.common.base.Splitter; import com.google.common.base.Supplier; +import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; import com.google.inject.Inject; -import com.google.inject.internal.util.ImmutableSet; /** * @author Adrian Cole diff --git a/vcloud/core/src/main/java/org/jclouds/vcloud/compute/strategy/VCloudListNodesStrategy.java b/vcloud/core/src/main/java/org/jclouds/vcloud/compute/strategy/VCloudListNodesStrategy.java index 6d5751ca4e..1963dbdbba 100644 --- a/vcloud/core/src/main/java/org/jclouds/vcloud/compute/strategy/VCloudListNodesStrategy.java +++ b/vcloud/core/src/main/java/org/jclouds/vcloud/compute/strategy/VCloudListNodesStrategy.java @@ -45,9 +45,9 @@ import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Predicate; import com.google.common.base.Splitter; import com.google.common.base.Supplier; +import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; import com.google.inject.Inject; -import com.google.inject.internal.util.ImmutableSet; /** * @author Adrian Cole diff --git a/vcloud/core/src/main/java/org/jclouds/vcloud/compute/util/VCloudComputeUtils.java b/vcloud/core/src/main/java/org/jclouds/vcloud/compute/util/VCloudComputeUtils.java index f737bb4f92..d2c195257e 100644 --- a/vcloud/core/src/main/java/org/jclouds/vcloud/compute/util/VCloudComputeUtils.java +++ b/vcloud/core/src/main/java/org/jclouds/vcloud/compute/util/VCloudComputeUtils.java @@ -37,7 +37,7 @@ import org.jclouds.vcloud.domain.ovf.ResourceType; import org.jclouds.vcloud.domain.ovf.VCloudNetworkAdapter; import com.google.common.collect.Iterables; -import com.google.inject.internal.util.Sets; +import com.google.common.collect.Sets; /** * diff --git a/vcloud/core/src/main/java/org/jclouds/vcloud/domain/internal/CatalogImpl.java b/vcloud/core/src/main/java/org/jclouds/vcloud/domain/internal/CatalogImpl.java index df2c8c4512..3314216f09 100644 --- a/vcloud/core/src/main/java/org/jclouds/vcloud/domain/internal/CatalogImpl.java +++ b/vcloud/core/src/main/java/org/jclouds/vcloud/domain/internal/CatalogImpl.java @@ -26,13 +26,14 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import javax.annotation.Nullable; + import org.jclouds.vcloud.domain.Catalog; import org.jclouds.vcloud.domain.ReferenceType; import org.jclouds.vcloud.domain.Task; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; -import com.google.inject.internal.Nullable; /** * Locations of resources in vCloud diff --git a/vcloud/core/src/main/java/org/jclouds/vcloud/domain/internal/ErrorImpl.java b/vcloud/core/src/main/java/org/jclouds/vcloud/domain/internal/ErrorImpl.java index 1b25c3e9e7..f1d198a229 100644 --- a/vcloud/core/src/main/java/org/jclouds/vcloud/domain/internal/ErrorImpl.java +++ b/vcloud/core/src/main/java/org/jclouds/vcloud/domain/internal/ErrorImpl.java @@ -21,9 +21,9 @@ package org.jclouds.vcloud.domain.internal; import static com.google.common.base.Preconditions.checkNotNull; -import org.jclouds.vcloud.domain.VCloudError; +import javax.annotation.Nullable; -import com.google.inject.internal.Nullable; +import org.jclouds.vcloud.domain.VCloudError; /** * diff --git a/vcloud/core/src/main/java/org/jclouds/vcloud/domain/internal/TaskImpl.java b/vcloud/core/src/main/java/org/jclouds/vcloud/domain/internal/TaskImpl.java index 61a6fe4843..de1287459c 100644 --- a/vcloud/core/src/main/java/org/jclouds/vcloud/domain/internal/TaskImpl.java +++ b/vcloud/core/src/main/java/org/jclouds/vcloud/domain/internal/TaskImpl.java @@ -24,13 +24,13 @@ import static com.google.common.base.Preconditions.checkNotNull; import java.net.URI; import java.util.Date; +import javax.annotation.Nullable; + import org.jclouds.vcloud.VCloudMediaType; -import org.jclouds.vcloud.domain.VCloudError; import org.jclouds.vcloud.domain.ReferenceType; import org.jclouds.vcloud.domain.Task; import org.jclouds.vcloud.domain.TaskStatus; - -import com.google.inject.internal.Nullable; +import org.jclouds.vcloud.domain.VCloudError; /** * diff --git a/vcloud/core/src/main/java/org/jclouds/vcloud/domain/network/internal/VCloudExpressNetworkImpl.java b/vcloud/core/src/main/java/org/jclouds/vcloud/domain/network/internal/VCloudExpressNetworkImpl.java index 17f2023439..f0845b53f4 100644 --- a/vcloud/core/src/main/java/org/jclouds/vcloud/domain/network/internal/VCloudExpressNetworkImpl.java +++ b/vcloud/core/src/main/java/org/jclouds/vcloud/domain/network/internal/VCloudExpressNetworkImpl.java @@ -22,6 +22,8 @@ package org.jclouds.vcloud.domain.network.internal; import java.net.URI; import java.util.Set; +import javax.annotation.Nullable; + import org.jclouds.vcloud.domain.ReferenceType; import org.jclouds.vcloud.domain.internal.ReferenceTypeImpl; import org.jclouds.vcloud.domain.network.FenceMode; @@ -30,7 +32,6 @@ import org.jclouds.vcloud.domain.network.firewall.FirewallRule; import org.jclouds.vcloud.domain.network.nat.rules.PortForwardingRule; import com.google.common.collect.Sets; -import com.google.inject.internal.Nullable; /** * Locations of resources in vCloud diff --git a/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/binders/TerremarkBindInstantiateVAppTemplateParamsToXmlPayload.java b/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/binders/TerremarkBindInstantiateVAppTemplateParamsToXmlPayload.java index f5f316ae06..8e6dd54ca3 100644 --- a/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/binders/TerremarkBindInstantiateVAppTemplateParamsToXmlPayload.java +++ b/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/binders/TerremarkBindInstantiateVAppTemplateParamsToXmlPayload.java @@ -26,9 +26,10 @@ import static org.jclouds.vcloud.reference.VCloudConstants.PROPERTY_VCLOUD_XML_S import java.net.URI; import java.util.Map; -import java.util.SortedMap; import java.util.Map.Entry; +import java.util.SortedMap; +import javax.annotation.Nullable; import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; @@ -41,7 +42,6 @@ import org.jclouds.vcloud.endpoints.Network; import org.jclouds.vcloud.options.InstantiateVAppTemplateOptions; import org.jclouds.vcloud.terremark.options.TerremarkInstantiateVAppTemplateOptions; -import com.google.inject.internal.Nullable; import com.jamesmurty.utils.XMLBuilder; /** diff --git a/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/options/TerremarkInstantiateVAppTemplateOptions.java b/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/options/TerremarkInstantiateVAppTemplateOptions.java index a518b8c4b0..e58096bf5e 100644 --- a/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/options/TerremarkInstantiateVAppTemplateOptions.java +++ b/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/options/TerremarkInstantiateVAppTemplateOptions.java @@ -24,7 +24,7 @@ import java.util.Map; import org.jclouds.vcloud.domain.network.NetworkConfig; import org.jclouds.vcloud.options.InstantiateVAppTemplateOptions; -import com.google.inject.internal.util.Maps; +import com.google.common.collect.Maps; /** * From f4870b547c20c3636b0a5fa6ef1d07544f988603 Mon Sep 17 00:00:00 2001 From: Adrian Cole Date: Thu, 25 Nov 2010 15:18:16 +0100 Subject: [PATCH 06/31] bad method mapping for count-blobs --- blobstore/src/main/clojure/org/jclouds/blobstore.clj | 2 +- blobstore/src/test/clojure/org/jclouds/blobstore_test.clj | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/blobstore/src/main/clojure/org/jclouds/blobstore.clj b/blobstore/src/main/clojure/org/jclouds/blobstore.clj index 3807697c1a..3081e91ace 100644 --- a/blobstore/src/main/clojure/org/jclouds/blobstore.clj +++ b/blobstore/src/main/clojure/org/jclouds/blobstore.clj @@ -299,7 +299,7 @@ Options can also be specified for extension modules ([container-name] (count-blobs container-name *blobstore*)) ([container-name blobstore] - (.countBlob blobstore container-name))) + (.countBlobs blobstore container-name))) (defn blobs "List the blobs in a container: diff --git a/blobstore/src/test/clojure/org/jclouds/blobstore_test.clj b/blobstore/src/test/clojure/org/jclouds/blobstore_test.clj index d75fa91c7e..2b1ec948f9 100644 --- a/blobstore/src/test/clojure/org/jclouds/blobstore_test.clj +++ b/blobstore/src/test/clojure/org/jclouds/blobstore_test.clj @@ -70,6 +70,7 @@ (is (= 1 (count (list-container "container" :max-results 1)))) (create-directory "container" "dir") (is (upload-blob "container" "dir/blob2" "blob2")) + (is (= 3 (count-blobs "container"))) (is (= 3 (count (list-container "container")))) (is (= 4 (count (list-container "container" :recursive true)))) (is (= 3 (count (list-container "container" :with-details true)))) From b41eedf882d23afdfa0aa1e0fe649c5fdebab156 Mon Sep 17 00:00:00 2001 From: Adrian Cole Date: Thu, 25 Nov 2010 20:09:27 +0100 Subject: [PATCH 07/31] issue 378:cannot recreate a destroyed node set in ec2 --- .../aws/ec2/compute/EC2ComputeService.java | 4 +- .../compute/TestCanRecreateTagLiveTest.java | 106 ++++++++++++++++++ 2 files changed, 108 insertions(+), 2 deletions(-) create mode 100644 aws/core/src/test/java/org/jclouds/aws/ec2/compute/TestCanRecreateTagLiveTest.java diff --git a/aws/core/src/main/java/org/jclouds/aws/ec2/compute/EC2ComputeService.java b/aws/core/src/main/java/org/jclouds/aws/ec2/compute/EC2ComputeService.java index 681b81acc3..c1ab245837 100644 --- a/aws/core/src/main/java/org/jclouds/aws/ec2/compute/EC2ComputeService.java +++ b/aws/core/src/main/java/org/jclouds/aws/ec2/compute/EC2ComputeService.java @@ -116,7 +116,7 @@ public class EC2ComputeService extends BaseComputeService { ec2Client.getPlacementGroupServices().deletePlacementGroupInRegion(region, group); checkState(placementGroupDeleted.apply(new PlacementGroup(region, group, "cluster", State.PENDING)), String.format("placementGroup region(%s) name(%s) failed to delete", region, group)); - placementGroupMap.remove(new RegionAndName(region, tag)); + placementGroupMap.remove(new RegionAndName(region, group)); logger.debug("<< deleted placementGroup(%s)", group); } catch (AWSResponseException e) { if (e.getError().getCode().equals("InvalidPlacementGroup.InUse")) { @@ -142,7 +142,7 @@ public class EC2ComputeService extends BaseComputeService { logger.debug(">> deleting securityGroup(%s)", group); ec2Client.getSecurityGroupServices().deleteSecurityGroupInRegion(region, group); // TODO: test this clear happens - securityGroupMap.remove(new RegionNameAndIngressRules(region, tag, null, false)); + securityGroupMap.remove(new RegionNameAndIngressRules(region, group, null, false)); logger.debug("<< deleted securityGroup(%s)", group); } } diff --git a/aws/core/src/test/java/org/jclouds/aws/ec2/compute/TestCanRecreateTagLiveTest.java b/aws/core/src/test/java/org/jclouds/aws/ec2/compute/TestCanRecreateTagLiveTest.java new file mode 100644 index 0000000000..b706ccb0f3 --- /dev/null +++ b/aws/core/src/test/java/org/jclouds/aws/ec2/compute/TestCanRecreateTagLiveTest.java @@ -0,0 +1,106 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.aws.ec2.compute; + +import static com.google.common.base.Preconditions.checkNotNull; + +import java.io.FileNotFoundException; +import java.io.IOException; +import java.util.Properties; + +import org.jclouds.Constants; +import org.jclouds.compute.ComputeServiceContext; +import org.jclouds.compute.ComputeServiceContextFactory; +import org.jclouds.compute.RunNodesException; +import org.jclouds.compute.predicates.NodePredicates; +import org.jclouds.logging.log4j.config.Log4JLoggingModule; +import org.jclouds.ssh.jsch.config.JschSshClientModule; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.BeforeGroups; +import org.testng.annotations.Test; + +import com.google.common.base.Throwables; +import com.google.common.collect.ImmutableSet; +import com.google.inject.Module; + +/** + * + * @author Adrian Cole + */ +@Test(groups = "live") +public class TestCanRecreateTagLiveTest { + + private ComputeServiceContext context; + protected String provider = "ec2"; + protected String identity; + protected String credential; + protected String endpoint; + protected String apiversion; + + @BeforeClass + protected void setupCredentials() { + identity = checkNotNull(System.getProperty("test." + provider + ".identity"), "test." + provider + ".identity"); + credential = System.getProperty("test." + provider + ".credential"); + endpoint = System.getProperty("test." + provider + ".endpoint"); + apiversion = System.getProperty("test." + provider + ".apiversion"); + } + + protected Properties setupProperties() { + Properties overrides = new Properties(); + overrides.setProperty(Constants.PROPERTY_TRUST_ALL_CERTS, "true"); + overrides.setProperty(Constants.PROPERTY_RELAX_HOSTNAME, "true"); + overrides.setProperty(provider + ".identity", identity); + if (credential != null) + overrides.setProperty(provider + ".credential", credential); + if (endpoint != null) + overrides.setProperty(provider + ".endpoint", endpoint); + if (apiversion != null) + overrides.setProperty(provider + ".apiversion", apiversion); + return overrides; + } + + @BeforeGroups(groups = { "live" }) + public void setupClient() throws FileNotFoundException, IOException { + setupCredentials(); + Properties overrides = setupProperties(); + context = new ComputeServiceContextFactory().createContext(provider, + ImmutableSet. of(new Log4JLoggingModule(), new JschSshClientModule()), overrides); + } + + public void testCanRecreateTag() throws Exception { + + String tag = PREFIX + "recreate"; + context.getComputeService().destroyNodesMatching(NodePredicates.withTag(tag)); + + try { + context.getComputeService().runNodesWithTag(tag, 1); + context.getComputeService().destroyNodesMatching(NodePredicates.withTag(tag)); + context.getComputeService().runNodesWithTag(tag, 1); + } catch (RunNodesException e) { + System.err.println(e.getNodeErrors().keySet()); + Throwables.propagate(e); + } finally { + context.getComputeService().destroyNodesMatching(NodePredicates.withTag(tag)); + } + } + + public static final String PREFIX = System.getProperty("user.name") + "ec2"; + +} From 512eb0139c532a68e125b0533ce737110cb4fe3a Mon Sep 17 00:00:00 2001 From: Mattias Holmqvist Date: Thu, 25 Nov 2010 23:29:26 +0100 Subject: [PATCH 08/31] Fixing issue 406. Handling the NullPointerException (NullOutputException) from MapMaker$ComputingMapAdapter.get() call. --- .../RunningInstanceToNodeMetadata.java | 19 ++++++-- .../RunningInstanceToNodeMetadataTest.java | 45 +++++++++++++++++-- 2 files changed, 57 insertions(+), 7 deletions(-) diff --git a/aws/core/src/main/java/org/jclouds/aws/ec2/compute/functions/RunningInstanceToNodeMetadata.java b/aws/core/src/main/java/org/jclouds/aws/ec2/compute/functions/RunningInstanceToNodeMetadata.java index e73e225ddf..c3a9daaf15 100644 --- a/aws/core/src/main/java/org/jclouds/aws/ec2/compute/functions/RunningInstanceToNodeMetadata.java +++ b/aws/core/src/main/java/org/jclouds/aws/ec2/compute/functions/RunningInstanceToNodeMetadata.java @@ -101,9 +101,20 @@ public class RunningInstanceToNodeMetadata implements Function nullReturningFunction = new Function() { + + @Override + public Image apply(@Nullable RegionAndName from) { + return null; + } + }; + Map instanceToImage = new MapMaker().makeComputingMap(nullReturningFunction); + + RunningInstanceToNodeMetadata parser = createNodeParser(ImmutableSet.of(m1_small().build()), ImmutableSet + .of(provider), ImmutableMap + .of(), EC2ComputeServiceDependenciesModule.instanceToNodeState, instanceToImage); + + RunningInstance server = firstInstanceFromResource("/ec2/describe_instances_nova.xml"); + + assertEquals(parser.apply(server), new NodeMetadataBuilder().state(NodeState.TERMINATED).privateAddresses( + ImmutableSet.of("10.128.207.5")).tag("NOTAG-i-9slweygo").imageId("us-east-1/ami-25CB1213").id( + "us-east-1/i-9slweygo").providerId("i-9slweygo").hardware(m1_small().build()).location( + provider).build()); + } + + protected RunningInstance firstInstanceFromResource(String resource) { RunningInstance server = Iterables.get(Iterables.get(DescribeInstancesResponseHandlerTest - .parseRunningInstances(resource), 0), 0); + .parseRunningInstances(resource), 0), 0); return server; } protected RunningInstanceToNodeMetadata createNodeParser(final ImmutableSet hardware, - final ImmutableSet locations, Set images, - Map credentialStore) { + final ImmutableSet locations, + Set images, + Map credentialStore) { Map instanceToNodeState = EC2ComputeServiceDependenciesModule.instanceToNodeState; Map instanceToImage = Maps.uniqueIndex(images, new Function() { @@ -159,6 +191,13 @@ public class RunningInstanceToNodeMetadataTest { } }); + + return createNodeParser(hardware, locations, credentialStore, instanceToNodeState, instanceToImage); + } + + private RunningInstanceToNodeMetadata createNodeParser(final ImmutableSet hardware, final + ImmutableSet locations, Map credentialStore, Map + instanceToNodeState, Map instanceToImage) { Supplier> locationSupplier = new Supplier>() { @Override From ea3b75874e72b5d7f38b7e4af62df154c8e26a0c Mon Sep 17 00:00:00 2001 From: Adrian Cole Date: Sat, 27 Nov 2010 01:31:09 +0100 Subject: [PATCH 09/31] added server model to elastichosts --- .../elastichosts/domain/BlockDevice.java | 73 ++++ .../domain/CreateDriveRequest.java | 2 +- .../jclouds/elastichosts/domain/Device.java | 91 +++++ .../elastichosts/domain/DriveData.java | 6 +- .../elastichosts/domain/DriveInfo.java | 47 +-- .../elastichosts/domain/IDEDevice.java | 83 +++++ .../org/jclouds/elastichosts/domain/Item.java | 199 +++++++++++ .../elastichosts/domain/MediaType.java | 50 +++ .../jclouds/elastichosts/domain/Model.java | 47 +++ .../org/jclouds/elastichosts/domain/NIC.java | 122 +++++++ .../elastichosts/domain/SCSIDevice.java | 81 +++++ .../jclouds/elastichosts/domain/Server.java | 337 ++++++++++++++++++ .../org/jclouds/elastichosts/domain/VNC.java | 105 ++++++ .../domain/internal/BaseDrive.java | 118 +++--- ...aluesDelimitedByBlankLinesToDriveInfo.java | 8 +- .../ElasticHostsClientLiveTest.java | 6 +- 16 files changed, 1288 insertions(+), 87 deletions(-) create mode 100644 sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/domain/BlockDevice.java create mode 100644 sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/domain/Device.java create mode 100644 sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/domain/IDEDevice.java create mode 100644 sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/domain/Item.java create mode 100644 sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/domain/MediaType.java create mode 100644 sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/domain/Model.java create mode 100644 sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/domain/NIC.java create mode 100644 sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/domain/SCSIDevice.java create mode 100644 sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/domain/Server.java create mode 100644 sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/domain/VNC.java diff --git a/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/domain/BlockDevice.java b/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/domain/BlockDevice.java new file mode 100644 index 0000000000..b3b37f3a16 --- /dev/null +++ b/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/domain/BlockDevice.java @@ -0,0 +1,73 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.elastichosts.domain; + +import static com.google.common.base.Preconditions.checkArgument; + +/** + * + * @author Adrian Cole + */ +public class BlockDevice extends Device { + + private final char index; + + public BlockDevice(String driveUuid, MediaType mediaType, char index) { + super(driveUuid, mediaType); + checkArgument(index >= 0 && index < 8, "index must be between 0 and 7"); + this.index = index; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + index; + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + BlockDevice other = (BlockDevice) obj; + if (index != other.index) + return false; + return true; + } + + @Override + public String getId() { + return String.format("block:%d", index); + } + + public char getIndex() { + return index; + } + + @Override + public String toString() { + return "[id=" + getId() + ", driveUuid=" + driveUuid + ", mediaType=" + mediaType + "]"; + } +} \ No newline at end of file diff --git a/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/domain/CreateDriveRequest.java b/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/domain/CreateDriveRequest.java index 49123531b9..8c19b768d2 100644 --- a/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/domain/CreateDriveRequest.java +++ b/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/domain/CreateDriveRequest.java @@ -112,7 +112,7 @@ public class CreateDriveRequest extends BaseDrive { public CreateDriveRequest(String name, long size, @Nullable ClaimType claimType, Iterable readers, Iterable tags, Map userMetadata, @Nullable String encryptionCipher, Iterable avoid) { - super(name, size, claimType, readers, tags, userMetadata); + super(null, name, size, claimType, readers, tags, userMetadata); this.encryptionCipher = encryptionCipher; this.avoid = ImmutableSet.copyOf(checkNotNull(avoid, "avoid")); } diff --git a/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/domain/Device.java b/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/domain/Device.java new file mode 100644 index 0000000000..0291c8f863 --- /dev/null +++ b/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/domain/Device.java @@ -0,0 +1,91 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.elastichosts.domain; + +import static com.google.common.base.Preconditions.checkNotNull; + +/** + * + * @author Adrian Cole + */ +public abstract class Device { + protected final String driveUuid; + protected final MediaType mediaType; + + public Device(String driveUuid, MediaType mediaType) { + this.driveUuid = checkNotNull(driveUuid, "driveUuid"); + this.mediaType = checkNotNull(mediaType, "mediaType"); + } + + /** + * id generated based on the device bus, unit, and/or index numbers; + */ + public abstract String getId(); + + /** + * + * @return Drive UUID to connect as specified device. + */ + public String getDriveUuid() { + return driveUuid; + } + + /** + * + * @return set to 'cdrom' to simulate a cdrom, set to 'disk' or leave unset to simulate a hard + * disk. + */ + public MediaType getMediaType() { + return mediaType; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((driveUuid == null) ? 0 : driveUuid.hashCode()); + result = prime * result + ((mediaType == null) ? 0 : mediaType.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; + Device other = (Device) obj; + if (driveUuid == null) { + if (other.driveUuid != null) + return false; + } else if (!driveUuid.equals(other.driveUuid)) + return false; + if (mediaType != other.mediaType) + return false; + return true; + } + + @Override + public String toString() { + return "[driveUuid=" + driveUuid + ", mediaType=" + mediaType + "]"; + } +} \ No newline at end of file diff --git a/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/domain/DriveData.java b/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/domain/DriveData.java index 74bd811299..c4be82a0b3 100644 --- a/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/domain/DriveData.java +++ b/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/domain/DriveData.java @@ -82,12 +82,12 @@ public class DriveData extends BaseDrive { } public DriveData build() { - return new DriveData(name, size, claimType, readers, tags, userMetadata); + return new DriveData(uuid, name, size, claimType, readers, tags, userMetadata); } } - public DriveData(String name, long size, @Nullable ClaimType claimType, Iterable readers, + public DriveData(@Nullable String uuid, String name, long size, @Nullable ClaimType claimType, Iterable readers, Iterable tags, Map userMetadata) { - super(name, size, claimType, readers, tags, userMetadata); + super(uuid, name, size, claimType, readers, tags, userMetadata); } } \ No newline at end of file diff --git a/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/domain/DriveInfo.java b/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/domain/DriveInfo.java index 112b68ee30..2706b3e725 100644 --- a/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/domain/DriveInfo.java +++ b/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/domain/DriveInfo.java @@ -44,7 +44,6 @@ public class DriveInfo extends BaseDrive { private Set claimed = ImmutableSet.of(); private String encryptionCipher; private String description; - private String uuid; private Set driveType = ImmutableSet.of(); private String encryptionKey; private Boolean free; @@ -89,11 +88,6 @@ public class DriveInfo extends BaseDrive { return this; } - public Builder uuid(String uuid) { - this.uuid = uuid; - return this; - } - public Builder driveType(Iterable driveType) { this.driveType = ImmutableSet.copyOf(checkNotNull(driveType, "driveType")); return this; @@ -172,14 +166,6 @@ public class DriveInfo extends BaseDrive { return this; } - /** - * {@inheritDoc} - */ - @Override - public Builder name(String name) { - return Builder.class.cast(super.name(name)); - } - /** * {@inheritDoc} */ @@ -196,6 +182,22 @@ public class DriveInfo extends BaseDrive { return Builder.class.cast(super.size(size)); } + /** + * {@inheritDoc} + */ + @Override + public Builder uuid(String uuid) { + return Builder.class.cast(super.uuid(uuid)); + } + + /** + * {@inheritDoc} + */ + @Override + public Builder name(String name) { + return Builder.class.cast(super.name(name)); + } + /** * {@inheritDoc} */ @@ -233,8 +235,6 @@ public class DriveInfo extends BaseDrive { @Nullable private final String description; @Nullable - private final String uuid; - @Nullable private final Set driveType; @Nullable private final String encryptionCipher; @@ -264,18 +264,17 @@ public class DriveInfo extends BaseDrive { private final Long writeRequests; public DriveInfo(DriveStatus status, String user, Boolean autoexpanding, Integer bits, Iterable claimed, - ClaimType claimType, String description, String drive, Iterable driveType, String encryptionCipher, + ClaimType claimType, String description, String uuid, Iterable driveType, String encryptionCipher, String encryptionKey, Boolean free, String imaging, String installNotes, String name, String os, Iterable readers, Long readBytes, Long readRequests, Long size, Iterable tags, DriveType type, URI url, Iterable use, Map userMetadata, Long writeBytes, Long writeRequests) { - super(name, size, claimType, readers, tags, userMetadata); + super(uuid, name, size, claimType, readers, tags, userMetadata); this.status = status; this.user = user; this.autoexpanding = autoexpanding; this.bits = bits; this.claimed = ImmutableSet.copyOf(claimed); this.description = description; - this.uuid = drive; this.driveType = ImmutableSet.copyOf(driveType); this.encryptionCipher = encryptionCipher; this.encryptionKey = encryptionKey; @@ -326,19 +325,11 @@ public class DriveInfo extends BaseDrive { return claimed; } - // TODO + // TODO undocumented public String getDescription() { return description; } - /** - * - * @return uuid of the drive. - */ - public String getUuid() { - return uuid; - } - // TODO public Set getDriveType() { return driveType; diff --git a/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/domain/IDEDevice.java b/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/domain/IDEDevice.java new file mode 100644 index 0000000000..5a868be303 --- /dev/null +++ b/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/domain/IDEDevice.java @@ -0,0 +1,83 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.elastichosts.domain; + +import static com.google.common.base.Preconditions.checkArgument; + +/** + * + * @author Adrian Cole + */ +public class IDEDevice extends Device { + + private final char bus; + private final char unit; + + public IDEDevice(String driveUuid, MediaType mediaType, char bus, char unit) { + super(driveUuid, mediaType); + checkArgument(bus == 0 || bus == 1, "bus must be 0 or 1"); + checkArgument(unit == 0 || unit == 1, "unit must be 0 or 1"); + this.bus = bus; + this.unit = unit; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + bus; + result = prime * result + unit; + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + IDEDevice other = (IDEDevice) obj; + if (bus != other.bus) + return false; + if (unit != other.unit) + return false; + return true; + } + + @Override + public String getId() { + return String.format("ide:%d:%d", bus, unit); + } + + public char getBus() { + return bus; + } + + public char getUnit() { + return unit; + } + + @Override + public String toString() { + return "[id=" + getId() + ", driveUuid=" + driveUuid + ", mediaType=" + mediaType + "]"; + } +} \ No newline at end of file diff --git a/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/domain/Item.java b/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/domain/Item.java new file mode 100644 index 0000000000..62d6aa0fc3 --- /dev/null +++ b/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/domain/Item.java @@ -0,0 +1,199 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.elastichosts.domain; + +import static com.google.common.base.Preconditions.checkNotNull; + +import java.util.Map; +import java.util.Set; + +import javax.annotation.Nullable; + +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.ImmutableSet; + +/** + * + * @author Adrian Cole + */ +public class Item { + public static class Builder { + protected String uuid; + protected String name; + protected Set tags = ImmutableSet.of(); + protected Map userMetadata = ImmutableMap.of(); + + public Builder uuid(String uuid) { + this.uuid = uuid; + return this; + } + + public Builder name(String name) { + this.name = name; + return this; + } + + public Builder tags(Iterable tags) { + this.tags = ImmutableSet.copyOf(checkNotNull(tags, "tags")); + return this; + } + + public Builder userMetadata(Map userMetadata) { + this.userMetadata = ImmutableMap.copyOf(checkNotNull(userMetadata, "userMetadata")); + return this; + } + + public Item build() { + return new Item(uuid, name, tags, userMetadata); + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((name == null) ? 0 : name.hashCode()); + result = prime * result + ((tags == null) ? 0 : tags.hashCode()); + result = prime * result + ((userMetadata == null) ? 0 : userMetadata.hashCode()); + result = prime * result + ((uuid == null) ? 0 : uuid.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; + Builder other = (Builder) obj; + if (name == null) { + if (other.name != null) + return false; + } else if (!name.equals(other.name)) + return false; + if (tags == null) { + if (other.tags != null) + return false; + } else if (!tags.equals(other.tags)) + return false; + if (userMetadata == null) { + if (other.userMetadata != null) + return false; + } else if (!userMetadata.equals(other.userMetadata)) + return false; + if (uuid == null) { + if (other.uuid != null) + return false; + } else if (!uuid.equals(other.uuid)) + return false; + return true; + } + } + + @Nullable + protected final String uuid; + protected final String name; + protected final Set tags; + protected final Map userMetadata; + + public Item(@Nullable String uuid, String name, Iterable tags, Map userMetadata) { + this.uuid = uuid; + this.name = checkNotNull(name, "name"); + this.tags = ImmutableSet.copyOf(checkNotNull(tags, "tags")); + this.userMetadata = ImmutableMap.copyOf(checkNotNull(userMetadata, "userMetadata")); + } + + /** + * + * @return uuid of the item. + */ + @Nullable + public String getUuid() { + return uuid; + } + + /** + * + * @return name of the item + */ + public String getName() { + return name; + } + + /** + * + * @return list of tags + */ + public Set getTags() { + return tags; + } + + /** + * + * @return user-defined KEY VALUE pairs + */ + public Map getUserMetadata() { + return userMetadata; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((name == null) ? 0 : name.hashCode()); + result = prime * result + ((tags == null) ? 0 : tags.hashCode()); + result = prime * result + ((userMetadata == null) ? 0 : userMetadata.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; + Item other = (Item) obj; + if (name == null) { + if (other.name != null) + return false; + } else if (!name.equals(other.name)) + return false; + if (tags == null) { + if (other.tags != null) + return false; + } else if (!tags.equals(other.tags)) + return false; + if (userMetadata == null) { + if (other.userMetadata != null) + return false; + } else if (!userMetadata.equals(other.userMetadata)) + return false; + return true; + } + + @Override + public String toString() { + return "[uuid=" + uuid + ", name=" + name + ", tags=" + tags + ", userMetadata=" + userMetadata + "]"; + } + +} \ No newline at end of file diff --git a/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/domain/MediaType.java b/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/domain/MediaType.java new file mode 100644 index 0000000000..dcdd7362b8 --- /dev/null +++ b/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/domain/MediaType.java @@ -0,0 +1,50 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.elastichosts.domain; + +import static com.google.common.base.Preconditions.checkNotNull; + +/** + * Media type - set to 'cdrom' to simulate a cdrom, set to 'disk' or leave unset to simulate a hard + * disk. + * + * @author Adrian Cole + */ +public enum MediaType { + DISK, CDROM, UNRECOGNIZED; + + public String value() { + return name().toLowerCase(); + } + + @Override + public String toString() { + return value(); + } + + public static MediaType fromValue(String type) { + try { + return valueOf(checkNotNull(type, "type").toUpperCase()); + } catch (IllegalArgumentException e) { + return UNRECOGNIZED; + } + } + +} \ No newline at end of file diff --git a/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/domain/Model.java b/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/domain/Model.java new file mode 100644 index 0000000000..e58a9300da --- /dev/null +++ b/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/domain/Model.java @@ -0,0 +1,47 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.elastichosts.domain; + +import static com.google.common.base.Preconditions.checkNotNull; + +/** + * + * @author Adrian Cole + */ +public enum Model { + E1000, RTl8139, VIRTIO, UNRECOGNIZED; + + public String value() { + return name().toLowerCase(); + } + + @Override + public String toString() { + return value(); + } + + public static Model fromValue(String model) { + try { + return valueOf(checkNotNull(model, "model").toUpperCase()); + } catch (IllegalArgumentException e) { + return UNRECOGNIZED; + } + } +} \ No newline at end of file diff --git a/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/domain/NIC.java b/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/domain/NIC.java new file mode 100644 index 0000000000..fcc8678a6b --- /dev/null +++ b/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/domain/NIC.java @@ -0,0 +1,122 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.elastichosts.domain; + +import static com.google.common.base.Preconditions.checkNotNull; + +import javax.annotation.Nullable; + +/** + * + * @author Adrian Cole + */ +public class NIC { + private final String dhcp; + private final Model model; + private final String vlan; + private final String mac; + + public NIC(@Nullable String dhcp, Model model, @Nullable String vlan, @Nullable String mac) { + this.dhcp = dhcp; + this.model = checkNotNull(model, "model"); + this.vlan = vlan; + this.mac = mac; + } + + /** + * + * @return The IP address offered by DHCP to network interface 0. If unset, no address is + * offered. Set to 'auto' to allocate a temporary IP at boot. + */ + public String getDhcp() { + return dhcp; + } + + /** + * + * @return Create network interface with given type (use 'e1000' as default value; 'rtl8139' or + * 'virtio' are also available). + */ + public Model getModel() { + return model; + } + + /** + * + * @return The VLAN to which the network interface is attached. + */ + public String getVlan() { + return vlan; + } + + /** + * + * @return The MAC address of the network interface. If unset, a randomly generated address is + * used. If set, should be unique on the VLAN. + */ + public String getMac() { + return mac; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((dhcp == null) ? 0 : dhcp.hashCode()); + result = prime * result + ((mac == null) ? 0 : mac.hashCode()); + result = prime * result + ((model == null) ? 0 : model.hashCode()); + result = prime * result + ((vlan == null) ? 0 : vlan.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; + NIC other = (NIC) obj; + if (dhcp == null) { + if (other.dhcp != null) + return false; + } else if (!dhcp.equals(other.dhcp)) + return false; + if (mac == null) { + if (other.mac != null) + return false; + } else if (!mac.equals(other.mac)) + return false; + if (model != other.model) + return false; + if (vlan == null) { + if (other.vlan != null) + return false; + } else if (!vlan.equals(other.vlan)) + return false; + return true; + } + + @Override + public String toString() { + return "[dhcp=" + dhcp + ", model=" + model + ", vlan=" + vlan + ", mac=" + mac + "]"; + } +} \ No newline at end of file diff --git a/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/domain/SCSIDevice.java b/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/domain/SCSIDevice.java new file mode 100644 index 0000000000..caee290987 --- /dev/null +++ b/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/domain/SCSIDevice.java @@ -0,0 +1,81 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.elastichosts.domain; + +import static com.google.common.base.Preconditions.checkArgument; + +/** + * + * @author Adrian Cole + */ +public class SCSIDevice extends Device { + + private final char bus = 0; + private final char unit; + + public SCSIDevice(String driveUuid, MediaType mediaType, char unit) { + super(driveUuid, mediaType); + checkArgument(unit >= 0 && unit < 8, "unit must be between 0 and 7"); + this.unit = unit; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + bus; + result = prime * result + unit; + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + SCSIDevice other = (SCSIDevice) obj; + if (bus != other.bus) + return false; + if (unit != other.unit) + return false; + return true; + } + + public char getBus() { + return bus; + } + + public char getUnit() { + return unit; + } + + @Override + public String getId() { + return String.format("scsi:%d:%d", bus, unit); + } + + @Override + public String toString() { + return "[id=" + getId() + ", driveUuid=" + driveUuid + ", mediaType=" + mediaType + "]"; + } +} \ No newline at end of file diff --git a/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/domain/Server.java b/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/domain/Server.java new file mode 100644 index 0000000000..1083b09f24 --- /dev/null +++ b/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/domain/Server.java @@ -0,0 +1,337 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.elastichosts.domain; + +import static com.google.common.base.Preconditions.checkNotNull; + +import java.util.List; +import java.util.Map; +import java.util.Set; + +import javax.annotation.Nullable; + +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableSet; + +/** + * + * @author Adrian Cole + */ +public class Server extends Item { + // + // user UUID + // status active|stopped + // cpu CPU + // smp SMP + // mem MEM + // bootDeviceIds UUID + // description DESCRIPTION + // ide:0:0 UUID + // ide:0:1 UUID + // ide:1:0 UUID + // ide:1:1 UUID + // nic:0:model NIC_0_MODEL + // nic:0:dhcp NIC_0_DHCP + // nic:1:model NIC_1_MODEL + // nic:1:vlan NIC_1_VLAN + // vnc:ip VNC_IP + // vnc:password VNC_PASS + + public static class Builder extends Item.Builder { + protected int cpu; + protected Integer smp; + protected int mem; + protected boolean persistent; + protected Set devices = ImmutableSet.of(); + protected Set bootDeviceIds = ImmutableSet.of(); + protected List nics = ImmutableList.of(); + protected String user; + protected VNC vnc; + // TODO undocumented + protected String description; + + public Builder cpu(int cpu) { + this.cpu = cpu; + return this; + } + + public Builder smp(Integer smp) { + this.smp = smp; + return this; + } + + public Builder mem(int mem) { + this.mem = mem; + return this; + } + + public Builder persistent(boolean persistent) { + this.persistent = persistent; + return this; + } + + public Builder devices(Iterable devices) { + this.devices = ImmutableSet.copyOf(checkNotNull(devices, "devices")); + return this; + } + + public Builder bootDeviceIds(Iterable bootDeviceIds) { + this.bootDeviceIds = ImmutableSet.copyOf(checkNotNull(bootDeviceIds, "bootDeviceIds")); + return this; + } + + public Builder nics(Iterable nics) { + this.nics = ImmutableList.copyOf(checkNotNull(nics, "nics")); + return this; + } + + public Builder user(String user) { + this.user = user; + return this; + } + + public Builder vnc(VNC vnc) { + this.vnc = vnc; + return this; + } + + public Builder description(String description) { + this.description = description; + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public Builder uuid(String uuid) { + return Builder.class.cast(super.uuid(uuid)); + } + + /** + * {@inheritDoc} + */ + @Override + public Builder name(String name) { + return Builder.class.cast(super.name(name)); + } + + /** + * {@inheritDoc} + */ + @Override + public Builder tags(Iterable tags) { + return Builder.class.cast(super.tags(tags)); + } + + /** + * {@inheritDoc} + */ + @Override + public Builder userMetadata(Map userMetadata) { + return Builder.class.cast(super.userMetadata(userMetadata)); + } + + public Server build() { + return new Server(uuid, name, cpu, smp, mem, persistent, devices, tags, bootDeviceIds, userMetadata, nics, + user, vnc, description); + } + } + + protected final int cpu; + protected final Integer smp; + protected final int mem; + protected final boolean persistent; + protected final Set devices; + protected final Set bootDeviceIds; + @Nullable + protected final String user; + protected final List nics; + protected final VNC vnc; + @Nullable + private final String description; + + public Server(@Nullable String uuid, String name, int cpu, @Nullable Integer smp, int mem, boolean persistent, + Iterable devices, Iterable bootDeviceIds, Iterable tags, + Map userMetadata, Iterable nics, @Nullable String user, VNC vnc, String description) { + super(uuid, name, tags, userMetadata); + this.cpu = cpu; + this.smp = smp; + this.mem = mem; + this.persistent = persistent; + this.devices = ImmutableSet.copyOf(checkNotNull(devices, "devices")); + this.bootDeviceIds = ImmutableSet.copyOf(checkNotNull(bootDeviceIds, "bootDeviceIds")); + this.nics = ImmutableList.copyOf(checkNotNull(nics, "nics")); + this.user = user; + this.vnc = checkNotNull(vnc, "vnc"); + this.description = description; + } + + /** + * + * @return CPU quota in core MHz. + */ + public int getCpu() { + return cpu; + } + + /** + * + * @return number of virtual processors or null if calculated based on cpu. + */ + public Integer getSmp() { + return smp; + } + + /** + * + * @return virtual memory size in MB. + */ + public int getMem() { + return mem; + } + + /** + * + * @return 'true' means that server will revert to a 'stopped' status on server stop or shutdown, + * rather than being destroyed automatically. + */ + public boolean isPersistent() { + return persistent; + } + + /** + * + * @return set of devices present + */ + public Set getDevices() { + return devices; + } + + /** + * + * @return ids of the devices to boot, e.g. ide:0:0 or ide:1:0 + * @see Device#getId() + */ + public Set getBootDeviceIds() { + return bootDeviceIds; + } + + public List getNics() { + return nics; + } + + // TODO undocumented + /** + * + * @return owner of the server. + */ + public String getUser() { + return user; + } + + public VNC getVnc() { + return vnc; + } + + // TODO undocumented + public String getDescription() { + return description; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = super.hashCode(); + result = prime * result + ((bootDeviceIds == null) ? 0 : bootDeviceIds.hashCode()); + result = prime * result + cpu; + result = prime * result + ((description == null) ? 0 : description.hashCode()); + result = prime * result + ((devices == null) ? 0 : devices.hashCode()); + result = prime * result + mem; + result = prime * result + ((nics == null) ? 0 : nics.hashCode()); + result = prime * result + (persistent ? 1231 : 1237); + result = prime * result + ((smp == null) ? 0 : smp.hashCode()); + result = prime * result + ((user == null) ? 0 : user.hashCode()); + result = prime * result + ((vnc == null) ? 0 : vnc.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (!super.equals(obj)) + return false; + if (getClass() != obj.getClass()) + return false; + Server other = (Server) obj; + if (bootDeviceIds == null) { + if (other.bootDeviceIds != null) + return false; + } else if (!bootDeviceIds.equals(other.bootDeviceIds)) + return false; + if (cpu != other.cpu) + return false; + if (description == null) { + if (other.description != null) + return false; + } else if (!description.equals(other.description)) + return false; + if (devices == null) { + if (other.devices != null) + return false; + } else if (!devices.equals(other.devices)) + return false; + if (mem != other.mem) + return false; + if (nics == null) { + if (other.nics != null) + return false; + } else if (!nics.equals(other.nics)) + return false; + if (persistent != other.persistent) + return false; + if (smp == null) { + if (other.smp != null) + return false; + } else if (!smp.equals(other.smp)) + return false; + if (user == null) { + if (other.user != null) + return false; + } else if (!user.equals(other.user)) + return false; + if (vnc == null) { + if (other.vnc != null) + return false; + } else if (!vnc.equals(other.vnc)) + return false; + return true; + } + + @Override + public String toString() { + return "[uuid=" + uuid + ", name=" + name + ", tags=" + tags + ", userMetadata=" + userMetadata + ", cpu=" + cpu + + ", smp=" + smp + ", mem=" + mem + ", persistent=" + persistent + ", devices=" + devices + + ", bootDeviceIds=" + bootDeviceIds + ", user=" + user + ", nics=" + nics + ", vnc=" + vnc + + ", description=" + description + "]"; + } + +} \ No newline at end of file diff --git a/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/domain/VNC.java b/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/domain/VNC.java new file mode 100644 index 0000000000..41364a1d66 --- /dev/null +++ b/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/domain/VNC.java @@ -0,0 +1,105 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.elastichosts.domain; + +import javax.annotation.Nullable; + +/** + * + * @author Adrian Cole + */ +public class VNC { + @Nullable + private final String ip; + @Nullable + private final String password; + private final boolean tls; + + public VNC(String ip, String password, boolean tls) { + this.ip = ip; + this.password = password; + this.tls = tls; + } + + /** + * + * @return IP address for overlay VNC access on port 5900. Set to 'auto', to reuse nic:0:dhcp if + * available, or otherwise allocate a temporary IP at boot. + */ + public String getIp() { + return ip; + } + + /** + * + * @return Password for VNC access. If unset, VNC is disabled. + */ + public String getPassword() { + return password; + } + + /** + * + * @return Set to 'on' to require VeNCrypt-style TLS auth in addition to the password. If this is + * unset, only unencrypted VNC is available. + */ + public boolean isTls() { + return tls; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((ip == null) ? 0 : ip.hashCode()); + result = prime * result + ((password == null) ? 0 : password.hashCode()); + result = prime * result + (tls ? 1231 : 1237); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + VNC other = (VNC) obj; + if (ip == null) { + if (other.ip != null) + return false; + } else if (!ip.equals(other.ip)) + return false; + if (password == null) { + if (other.password != null) + return false; + } else if (!password.equals(other.password)) + return false; + if (tls != other.tls) + return false; + return true; + } + + @Override + public String toString() { + return "[ip=" + ip + ", password=" + password + ", tls=" + tls + "]"; + } +} \ No newline at end of file diff --git a/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/domain/internal/BaseDrive.java b/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/domain/internal/BaseDrive.java index 00039824dd..abc2a8ea0c 100644 --- a/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/domain/internal/BaseDrive.java +++ b/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/domain/internal/BaseDrive.java @@ -27,33 +27,25 @@ import java.util.Set; import javax.annotation.Nullable; import org.jclouds.elastichosts.domain.ClaimType; +import org.jclouds.elastichosts.domain.Item; import com.google.common.collect.ImmutableSet; -import com.google.inject.internal.util.ImmutableMap; /** * * @author Adrian Cole */ -public class BaseDrive { - public static class Builder { - protected String name; +public class BaseDrive extends Item { + public static class Builder extends Item.Builder { protected long size; protected ClaimType claimType = ClaimType.EXCLUSIVE; protected Set readers = ImmutableSet.of(); - protected Set tags = ImmutableSet.of(); - protected Map userMetadata = ImmutableMap.of(); public Builder claimType(ClaimType claimType) { this.claimType = claimType; return this; } - public Builder name(String name) { - this.name = name; - return this; - } - public Builder readers(Iterable readers) { this.readers = ImmutableSet.copyOf(checkNotNull(readers, "readers")); return this; @@ -64,36 +56,84 @@ public class BaseDrive { return this; } - public Builder tags(Iterable tags) { - this.tags = ImmutableSet.copyOf(checkNotNull(tags, "tags")); - return this; + /** + * {@inheritDoc} + */ + @Override + public Builder uuid(String uuid) { + return Builder.class.cast(super.uuid(uuid)); } + /** + * {@inheritDoc} + */ + @Override + public Builder name(String name) { + return Builder.class.cast(super.name(name)); + } + + /** + * {@inheritDoc} + */ + @Override + public Builder tags(Iterable tags) { + return Builder.class.cast(super.tags(tags)); + } + + /** + * {@inheritDoc} + */ + @Override public Builder userMetadata(Map userMetadata) { - this.userMetadata = ImmutableMap.copyOf(checkNotNull(userMetadata, "userMetadata")); - return this; + return Builder.class.cast(super.userMetadata(userMetadata)); } public BaseDrive build() { - return new BaseDrive(name, size, claimType, readers, tags, userMetadata); + return new BaseDrive(uuid, name, size, claimType, readers, tags, userMetadata); + } + + @Override + public int hashCode() { + final int prime = 31; + int result = super.hashCode(); + result = prime * result + ((claimType == null) ? 0 : claimType.hashCode()); + result = prime * result + ((readers == null) ? 0 : readers.hashCode()); + result = prime * result + (int) (size ^ (size >>> 32)); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (!super.equals(obj)) + return false; + if (getClass() != obj.getClass()) + return false; + Builder other = (Builder) obj; + if (claimType != other.claimType) + return false; + if (readers == null) { + if (other.readers != null) + return false; + } else if (!readers.equals(other.readers)) + return false; + if (size != other.size) + return false; + return true; } } - protected final String name; protected final long size; protected final ClaimType claimType; protected final Set readers; - protected final Set tags; - protected final Map userMetadata; - public BaseDrive(String name, long size, @Nullable ClaimType claimType, Iterable readers, - Iterable tags, Map userMetadata) { - this.name = checkNotNull(name, "name"); + public BaseDrive(@Nullable String uuid, String name, long size, @Nullable ClaimType claimType, + Iterable readers, Iterable tags, Map userMetadata) { + super(uuid, name, tags, userMetadata); this.size = size; this.claimType = checkNotNull(claimType, "set claimType to exclusive, not null"); this.readers = ImmutableSet.copyOf(checkNotNull(readers, "readers")); - this.tags = ImmutableSet.copyOf(checkNotNull(tags, "tags")); - this.userMetadata = ImmutableMap.copyOf(checkNotNull(userMetadata, "userMetadata")); } /** @@ -106,14 +146,6 @@ public class BaseDrive { return claimType; } - /** - * - * @return Drive name - */ - public String getName() { - return name; - } - /** * * @return list of users allowed to read from a drive or 'ffffffff-ffff-ffff-ffff-ffffffffffff' @@ -131,22 +163,6 @@ public class BaseDrive { return size; } - /** - * - * @return list of tags - */ - public Set getTags() { - return tags; - } - - /** - * - * @return user-defined KEY VALUE pairs - */ - public Map getUserMetadata() { - return userMetadata; - } - @Override public int hashCode() { final int prime = 31; @@ -198,8 +214,8 @@ public class BaseDrive { @Override public String toString() { - return "[name=" + name + ", size=" + size + ", claimType=" + claimType + ", readers=" + readers + ", tags=" - + tags + ", userMetadata=" + userMetadata + "]"; + return "[uuid=" + uuid + ", name=" + name + ", tags=" + tags + ", userMetadata=" + userMetadata + ", size=" + + size + ", claimType=" + claimType + ", readers=" + readers + "]"; } } \ No newline at end of file diff --git a/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/functions/KeyValuesDelimitedByBlankLinesToDriveInfo.java b/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/functions/KeyValuesDelimitedByBlankLinesToDriveInfo.java index c23af58932..d57a52f976 100644 --- a/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/functions/KeyValuesDelimitedByBlankLinesToDriveInfo.java +++ b/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/functions/KeyValuesDelimitedByBlankLinesToDriveInfo.java @@ -21,6 +21,7 @@ package org.jclouds.elastichosts.functions; import java.util.Set; +import javax.inject.Inject; import javax.inject.Singleton; import org.jclouds.elastichosts.domain.DriveInfo; @@ -35,7 +36,12 @@ import com.google.common.collect.Iterables; */ @Singleton public class KeyValuesDelimitedByBlankLinesToDriveInfo implements Function { - ListOfKeyValuesDelimitedByBlankLinesToDriveInfoSet setParser; + private final ListOfKeyValuesDelimitedByBlankLinesToDriveInfoSet setParser; + + @Inject + public KeyValuesDelimitedByBlankLinesToDriveInfo(ListOfKeyValuesDelimitedByBlankLinesToDriveInfoSet setParser) { + this.setParser = setParser; + } @Override public DriveInfo apply(HttpResponse response) { diff --git a/sandbox/elastichosts/src/test/java/org/jclouds/elastichosts/ElasticHostsClientLiveTest.java b/sandbox/elastichosts/src/test/java/org/jclouds/elastichosts/ElasticHostsClientLiveTest.java index 139985f530..bdab04b67d 100644 --- a/sandbox/elastichosts/src/test/java/org/jclouds/elastichosts/ElasticHostsClientLiveTest.java +++ b/sandbox/elastichosts/src/test/java/org/jclouds/elastichosts/ElasticHostsClientLiveTest.java @@ -157,10 +157,10 @@ public class ElasticHostsClientLiveTest { } - info = client.createDrive(new CreateDriveRequest.Builder().name(prefix).size(1024 * 1024l).build()); + info = client.createDrive(new CreateDriveRequest.Builder().name(prefix).size(4 * 1024 * 1024l).build()); assertNotNull(info.getUuid()); assertEquals(info.getName(), prefix); - assertEquals(info.getSize(), 1024 * 1024l); + assertEquals(info.getSize(), 4 * 1024 * 1024l); assertEquals(info, client.getDriveInfo(info.getUuid())); } @@ -179,7 +179,7 @@ public class ElasticHostsClientLiveTest { } try { - info2 = client.createDrive(new CreateDriveRequest.Builder().name(prefix + "2").size(1024 * 1024l).build()); + info2 = client.createDrive(new CreateDriveRequest.Builder().name(prefix + "2").size(4 * 1024 * 1024l).build()); client.imageDrive(info.getUuid(), info2.getUuid()); // TODO block until complete From 3d633b1768517c26631b174d7b98f0b55c3960db Mon Sep 17 00:00:00 2001 From: Hubert Iwaniuk Date: Mon, 29 Nov 2010 17:41:24 +0100 Subject: [PATCH 10/31] Big file upload and download fixes --- sandbox/ning/pom.xml | 8 +- .../ning/NingHttpCommandExecutorService.java | 79 ++++++++----------- .../NingHttpCommandExecutorServiceTest.java | 8 +- 3 files changed, 35 insertions(+), 60 deletions(-) diff --git a/sandbox/ning/pom.xml b/sandbox/ning/pom.xml index 0cd3b31c10..d24559668c 100644 --- a/sandbox/ning/pom.xml +++ b/sandbox/ning/pom.xml @@ -42,13 +42,7 @@ com.ning async-http-client - 1.3.1 - - - com.google.collections - google-collections - - + 1.4.0 org.mortbay.jetty diff --git a/sandbox/ning/src/main/java/org/jclouds/http/ning/NingHttpCommandExecutorService.java b/sandbox/ning/src/main/java/org/jclouds/http/ning/NingHttpCommandExecutorService.java index fef934692f..a99212590b 100644 --- a/sandbox/ning/src/main/java/org/jclouds/http/ning/NingHttpCommandExecutorService.java +++ b/sandbox/ning/src/main/java/org/jclouds/http/ning/NingHttpCommandExecutorService.java @@ -19,33 +19,6 @@ package org.jclouds.http.ning; -import static com.google.common.base.Preconditions.checkNotNull; -import static com.google.common.base.Throwables.propagate; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.List; -import java.util.Map.Entry; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.Future; - -import javax.inject.Singleton; -import javax.ws.rs.core.HttpHeaders; - -import org.jclouds.crypto.CryptoStreams; -import org.jclouds.http.HttpCommand; -import org.jclouds.http.HttpCommandExecutorService; -import org.jclouds.http.HttpRequest; -import org.jclouds.http.HttpRequestFilter; -import org.jclouds.http.HttpResponse; -import org.jclouds.http.HttpUtils; -import org.jclouds.http.handlers.DelegatingErrorHandler; -import org.jclouds.http.handlers.DelegatingRetryHandler; -import org.jclouds.http.internal.BaseHttpCommandExecutorService; -import org.jclouds.io.Payload; -import org.jclouds.io.Payloads; - import com.google.common.base.Function; import com.google.common.base.Throwables; import com.google.common.collect.LinkedHashMultimap; @@ -59,7 +32,31 @@ import com.ning.http.client.AsyncHttpClient; import com.ning.http.client.Request; import com.ning.http.client.RequestBuilder; import com.ning.http.client.Response; -import com.ning.http.client.Request.EntityWriter; +import org.jclouds.crypto.CryptoStreams; +import org.jclouds.http.HttpCommand; +import org.jclouds.http.HttpCommandExecutorService; +import org.jclouds.http.HttpRequest; +import org.jclouds.http.HttpRequestFilter; +import org.jclouds.http.HttpResponse; +import org.jclouds.http.HttpUtils; +import org.jclouds.http.handlers.DelegatingErrorHandler; +import org.jclouds.http.handlers.DelegatingRetryHandler; +import org.jclouds.http.internal.BaseHttpCommandExecutorService; +import org.jclouds.io.Payload; +import org.jclouds.io.Payloads; +import org.jclouds.io.payloads.FilePayload; + +import javax.inject.Singleton; +import javax.ws.rs.core.HttpHeaders; +import java.io.IOException; +import java.io.InputStream; +import java.util.List; +import java.util.Map.Entry; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Future; + +import static com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.base.Throwables.propagate; /** * Todo Write me @@ -128,21 +125,7 @@ public class NingHttpCommandExecutorService implements HttpCommandExecutorServic @Singleton public static class ConvertToNingRequest implements Function { - private static class PayloadEntityWriter implements EntityWriter { - private final Payload payload; - - public PayloadEntityWriter(Payload payload) { - this.payload = payload; - } - - @Override - public void writeEntity(OutputStream out) throws IOException { - payload.writeTo(out); - - } - } - - public Request apply(HttpRequest request) { + public Request apply(HttpRequest request) { for (HttpRequestFilter filter : request.getFilters()) { filter.filter(request); @@ -188,9 +171,13 @@ public class NingHttpCommandExecutorService implements HttpCommandExecutorServic return builder.build(); } - void setPayload(RequestBuilder requestBuilder, Payload payload) { - requestBuilder.setBody(new PayloadEntityWriter(payload)); - } + void setPayload(RequestBuilder requestBuilder, Payload payload) { + if (payload instanceof FilePayload) { + requestBuilder.setBody(((FilePayload) payload).getRawContent()); + } else { + requestBuilder.setBody(payload.getInput()); + } + } } @Singleton diff --git a/sandbox/ning/src/test/java/org/jclouds/http/ning/NingHttpCommandExecutorServiceTest.java b/sandbox/ning/src/test/java/org/jclouds/http/ning/NingHttpCommandExecutorServiceTest.java index 527c301cc7..7fe8eb1774 100644 --- a/sandbox/ning/src/test/java/org/jclouds/http/ning/NingHttpCommandExecutorServiceTest.java +++ b/sandbox/ning/src/test/java/org/jclouds/http/ning/NingHttpCommandExecutorServiceTest.java @@ -62,10 +62,4 @@ public class NingHttpCommandExecutorServiceTest extends BaseHttpCommandExecutorS props.setProperty(PROPERTY_IO_WORKER_THREADS, 3 + ""); props.setProperty(PROPERTY_USER_THREADS, 0 + ""); } - - // OOM - @Test(enabled = false, invocationCount = 1, timeOut = 5000) - public void testGetBigFile() throws ExecutionException, InterruptedException, TimeoutException, IOException { - } - -} \ No newline at end of file +} From 8ce596be507fbedcdefac96ad5a38b8e8dd6cbcd Mon Sep 17 00:00:00 2001 From: Adrian Cole Date: Tue, 30 Nov 2010 11:45:26 +0000 Subject: [PATCH 11/31] updated cargo version --- tools/antcontrib/samples/cargooverssh/build.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tools/antcontrib/samples/cargooverssh/build.xml b/tools/antcontrib/samples/cargooverssh/build.xml index c61ea8afe7..75fd1444f2 100644 --- a/tools/antcontrib/samples/cargooverssh/build.xml +++ b/tools/antcontrib/samples/cargooverssh/build.xml @@ -58,8 +58,8 @@ - - + + From 53ac4751f54330277fd4994d355898fe18b765e5 Mon Sep 17 00:00:00 2001 From: Adrian Cole Date: Tue, 30 Nov 2010 11:46:25 +0000 Subject: [PATCH 12/31] Issue 414: fixed length problem on string payload by eagerly encoding to UTF-8 --- .../internal/BaseBlobIntegrationTest.java | 79 ++++++++++--------- .../BaseBlobStoreIntegrationTest.java | 58 ++++++++------ .../jclouds/io/payloads/StringPayload.java | 15 +++- .../src/main/java/org/jclouds/util/Utils.java | 2 +- 4 files changed, 85 insertions(+), 69 deletions(-) diff --git a/blobstore/src/test/java/org/jclouds/blobstore/integration/internal/BaseBlobIntegrationTest.java b/blobstore/src/test/java/org/jclouds/blobstore/integration/internal/BaseBlobIntegrationTest.java index d7bd8911d8..31aeb4628f 100755 --- a/blobstore/src/test/java/org/jclouds/blobstore/integration/internal/BaseBlobIntegrationTest.java +++ b/blobstore/src/test/java/org/jclouds/blobstore/integration/internal/BaseBlobIntegrationTest.java @@ -97,7 +97,7 @@ public class BaseBlobIntegrationTest extends BaseBlobStoreIntegrationTest { @SuppressWarnings("unchecked") public static InputSupplier getTestDataSupplier() throws IOException { byte[] oneConstitution = ByteStreams.toByteArray(new GZIPInputStream(BaseJettyTest.class - .getResourceAsStream("/const.txt.gz"))); + .getResourceAsStream("/const.txt.gz"))); InputSupplier constitutionSupplier = ByteStreams.newInputStreamSupplier(oneConstitution); InputSupplier temp = ByteStreams.join(constitutionSupplier); @@ -120,24 +120,24 @@ public class BaseBlobIntegrationTest extends BaseBlobStoreIntegrationTest { Map> responses = Maps.newHashMap(); for (int i = 0; i < 10; i++) { - responses.put(i, Futures.compose(context.getAsyncBlobStore().getBlob(containerName, key), - new Function() { + responses.put(i, + Futures.compose(context.getAsyncBlobStore().getBlob(containerName, key), new Function() { - @Override - public Void apply(Blob from) { - try { - assertEquals(CryptoStreams.md5(from.getPayload()), oneHundredOneConstitutionsMD5); - checkContentDisposition(from, expectedContentDisposition); - } catch (IOException e) { - Throwables.propagate(e); - } - return null; + @Override + public Void apply(Blob from) { + try { + assertEquals(CryptoStreams.md5(from.getPayload()), oneHundredOneConstitutionsMD5); + checkContentDisposition(from, expectedContentDisposition); + } catch (IOException e) { + Throwables.propagate(e); } + return null; + } - }, this.exec)); + }, this.exec)); } Map exceptions = awaitCompletion(responses, exec, 30000l, Logger.CONSOLE, - "get constitution"); + "get constitution"); assert exceptions.size() == 0 : exceptions; } finally { @@ -156,7 +156,6 @@ public class BaseBlobIntegrationTest extends BaseBlobStoreIntegrationTest { context.getBlobStore().putBlob(containerName, sourceObject); } - @Test(groups = { "integration", "live" }) public void testGetIfModifiedSince() throws InterruptedException { String containerName = getContainerName(); @@ -365,15 +364,15 @@ public class BaseBlobIntegrationTest extends BaseBlobStoreIntegrationTest { @DataProvider(name = "delete") public Object[][] createData() { - return new Object[][] { { "normal" }, { "sp ace" }, { "qu?stion" }, { "unic₪de" }, { "path/foo" }, { "colon:" }, - { "asteri*k" }, { "quote\"" }, { "{greaten" }, { "p|pe" } }; + return new Object[][] { { "normal" }, { "sp ace" }, { "qu?stion" }, { "unic₪de" }, { "path/foo" }, + { "colon:" }, { "asteri*k" }, { "quote\"" }, { "{greaten" }, { "p|pe" } }; } @Test(groups = { "integration", "live" }, dataProvider = "delete") public void deleteObject(String key) throws InterruptedException { String containerName = getContainerName(); try { - addBlobToContainer(containerName, key); + addBlobToContainer(containerName, key, key, MediaType.TEXT_PLAIN); context.getBlobStore().removeBlob(containerName, key); assertContainerEmptyDeleting(containerName, key); } finally { @@ -383,17 +382,19 @@ public class BaseBlobIntegrationTest extends BaseBlobStoreIntegrationTest { private void assertContainerEmptyDeleting(String containerName, String key) { Iterable listing = Iterables.filter(context.getBlobStore().list(containerName), - new Predicate() { + new Predicate() { - @Override - public boolean apply(StorageMetadata input) { - return input.getType() == StorageType.BLOB; - } + @Override + public boolean apply(StorageMetadata input) { + return input.getType() == StorageType.BLOB; + } - }); - assertEquals(Iterables.size(listing), 0, String.format( - "deleting %s, we still have %s blobs left in container %s, using encoding %s", key, Iterables - .size(listing), containerName, LOCAL_ENCODING)); + }); + assertEquals( + Iterables.size(listing), + 0, + String.format("deleting %s, we still have %s blobs left in container %s, using encoding %s", key, + Iterables.size(listing), containerName, LOCAL_ENCODING)); } @Test(groups = { "integration", "live" }) @@ -413,13 +414,13 @@ public class BaseBlobIntegrationTest extends BaseBlobStoreIntegrationTest { String realObject = Utils.toStringAndClose(new FileInputStream("pom.xml")); return new Object[][] { { "file", "text/xml", new File("pom.xml"), realObject }, - { "string", "text/xml", realObject, realObject }, - { "bytes", "application/octet-stream", realObject.getBytes(), realObject } }; + { "string", "text/xml", realObject, realObject }, + { "bytes", "application/octet-stream", realObject.getBytes(), realObject } }; } @Test(groups = { "integration", "live" }, dataProvider = "putTests") public void testPutObject(String key, String type, Object content, Object realObject) throws InterruptedException, - IOException { + IOException { Blob blob = context.getBlobStore().newBlob(key); blob.setPayload(Payloads.newPayload(content)); blob.getMetadata().getContentMetadata().setContentType(type); @@ -486,32 +487,32 @@ public class BaseBlobIntegrationTest extends BaseBlobStoreIntegrationTest { protected void checkContentType(Blob blob, String contentType) { assert blob.getPayload().getContentMetadata().getContentType().startsWith(contentType) : blob.getPayload() - .getContentMetadata().getContentType(); + .getContentMetadata().getContentType(); assert blob.getMetadata().getContentMetadata().getContentType().startsWith(contentType) : blob.getMetadata() - .getContentMetadata().getContentType(); + .getContentMetadata().getContentType(); } protected void checkContentDisposition(Blob blob, String contentDisposition) { assert blob.getPayload().getContentMetadata().getContentDisposition().startsWith(contentDisposition) : blob - .getPayload().getContentMetadata().getContentDisposition(); + .getPayload().getContentMetadata().getContentDisposition(); assert blob.getMetadata().getContentMetadata().getContentDisposition().startsWith(contentDisposition) : blob - .getMetadata().getContentMetadata().getContentDisposition(); + .getMetadata().getContentMetadata().getContentDisposition(); } protected void checkContentEncoding(Blob blob, String contentEncoding) { assert blob.getPayload().getContentMetadata().getContentEncoding().startsWith(contentEncoding) : blob - .getPayload().getContentMetadata().getContentEncoding(); + .getPayload().getContentMetadata().getContentEncoding(); assert blob.getMetadata().getContentMetadata().getContentEncoding().startsWith(contentEncoding) : blob - .getMetadata().getContentMetadata().getContentEncoding(); + .getMetadata().getContentMetadata().getContentEncoding(); } protected void checkContentLanguage(Blob blob, String contentLanguage) { assert blob.getPayload().getContentMetadata().getContentLanguage().startsWith(contentLanguage) : blob - .getPayload().getContentMetadata().getContentLanguage(); + .getPayload().getContentMetadata().getContentLanguage(); assert blob.getMetadata().getContentMetadata().getContentLanguage().startsWith(contentLanguage) : blob - .getMetadata().getContentMetadata().getContentLanguage(); + .getMetadata().getContentMetadata().getContentLanguage(); } @@ -565,7 +566,7 @@ public class BaseBlobIntegrationTest extends BaseBlobStoreIntegrationTest { protected void validateMetadata(BlobMetadata metadata) throws IOException { assert metadata.getContentMetadata().getContentType().startsWith("text/plain") : metadata.getContentMetadata() - .getContentType(); + .getContentType(); assertEquals(metadata.getContentMetadata().getContentLength(), new Long(TEST_STRING.length())); assertEquals(metadata.getUserMetadata().get("adrian"), "powderpuff"); checkMD5(metadata); diff --git a/blobstore/src/test/java/org/jclouds/blobstore/integration/internal/BaseBlobStoreIntegrationTest.java b/blobstore/src/test/java/org/jclouds/blobstore/integration/internal/BaseBlobStoreIntegrationTest.java index 05fe4074e1..e928ea6840 100644 --- a/blobstore/src/test/java/org/jclouds/blobstore/integration/internal/BaseBlobStoreIntegrationTest.java +++ b/blobstore/src/test/java/org/jclouds/blobstore/integration/internal/BaseBlobStoreIntegrationTest.java @@ -25,8 +25,8 @@ import static org.testng.Assert.assertEquals; import java.io.IOException; import java.util.Map; -import java.util.Set; import java.util.Map.Entry; +import java.util.Set; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.CancellationException; @@ -35,6 +35,8 @@ import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; +import javax.ws.rs.core.MediaType; + import org.jclouds.blobstore.BlobStoreContext; import org.jclouds.blobstore.attr.ConsistencyModel; import org.jclouds.blobstore.domain.Blob; @@ -60,13 +62,13 @@ public class BaseBlobStoreIntegrationTest { protected static final String TEST_STRING = String.format(XML_STRING_FORMAT, "apple"); protected Map fiveStrings = ImmutableMap.of("one", String.format(XML_STRING_FORMAT, "apple"), "two", - String.format(XML_STRING_FORMAT, "bear"), "three", String.format(XML_STRING_FORMAT, "candy"), "four", - String.format(XML_STRING_FORMAT, "dogma"), "five", String.format(XML_STRING_FORMAT, "emma")); + String.format(XML_STRING_FORMAT, "bear"), "three", String.format(XML_STRING_FORMAT, "candy"), "four", + String.format(XML_STRING_FORMAT, "dogma"), "five", String.format(XML_STRING_FORMAT, "emma")); - protected Map fiveStringsUnderPath = ImmutableMap.of("path/1", String.format(XML_STRING_FORMAT, - "apple"), "path/2", String.format(XML_STRING_FORMAT, "bear"), "path/3", String.format(XML_STRING_FORMAT, - "candy"), "path/4", String.format(XML_STRING_FORMAT, "dogma"), "path/5", String.format(XML_STRING_FORMAT, - "emma")); + protected Map fiveStringsUnderPath = ImmutableMap.of("path/1", + String.format(XML_STRING_FORMAT, "apple"), "path/2", String.format(XML_STRING_FORMAT, "bear"), "path/3", + String.format(XML_STRING_FORMAT, "candy"), "path/4", String.format(XML_STRING_FORMAT, "dogma"), "path/5", + String.format(XML_STRING_FORMAT, "emma")); public static long INCONSISTENCY_WINDOW = 10000; protected static volatile AtomicInteger containerIndex = new AtomicInteger(0); @@ -90,7 +92,7 @@ public class BaseBlobStoreIntegrationTest { @SuppressWarnings("unchecked") private BlobStoreContext getCloudResources(ITestContext testContext) throws ClassNotFoundException, - InstantiationException, IllegalAccessException, Exception { + InstantiationException, IllegalAccessException, Exception { String initializerClass = checkNotNull(System.getProperty("test.initializer"), "test.initializer"); Class clazz = (Class) Class.forName(initializerClass); BaseTestInitializer initializer = clazz.newInstance(); @@ -123,7 +125,7 @@ public class BaseBlobStoreIntegrationTest { private static volatile boolean initialized = false; protected void createContainersSharedByAllThreads(BlobStoreContext context, ITestContext testContext) - throws Exception { + throws Exception { while (!initialized) { synchronized (BaseBlobStoreIntegrationTest.class) { if (!initialized) { @@ -174,12 +176,12 @@ public class BaseBlobStoreIntegrationTest { try { for (int i = 0; i < 2; i++) { Iterable testContainers = Iterables.filter(context.getBlobStore().list(), - new Predicate() { - public boolean apply(StorageMetadata input) { - return (input.getType() == StorageType.CONTAINER || input.getType() == StorageType.FOLDER) - && input.getName().startsWith(CONTAINER_PREFIX.toLowerCase()); - } - }); + new Predicate() { + public boolean apply(StorageMetadata input) { + return (input.getType() == StorageType.CONTAINER || input.getType() == StorageType.FOLDER) + && input.getName().startsWith(CONTAINER_PREFIX.toLowerCase()); + } + }); for (StorageMetadata container : testContainers) { deleteContainerOrWarnIfUnable(context, container.getName()); } @@ -200,7 +202,7 @@ public class BaseBlobStoreIntegrationTest { * we will try up to the inconsistency window to see if the assertion completes. */ protected static void assertConsistencyAware(BlobStoreContext context, Runnable assertion) - throws InterruptedException { + throws InterruptedException { if (context.getConsistencyModel() == ConsistencyModel.STRICT) { assertion.run(); return; @@ -226,7 +228,7 @@ public class BaseBlobStoreIntegrationTest { } protected static void createContainerAndEnsureEmpty(BlobStoreContext context, final String containerName) - throws InterruptedException { + throws InterruptedException { context.getBlobStore().createContainerInLocation(null, containerName); if (context.getConsistencyModel() == ConsistencyModel.EVENTUAL) Thread.sleep(1000); @@ -238,9 +240,13 @@ public class BaseBlobStoreIntegrationTest { } protected String addBlobToContainer(String sourceContainer, String key) { + return addBlobToContainer(sourceContainer, key, TEST_STRING, MediaType.TEXT_XML); + } + + protected String addBlobToContainer(String sourceContainer, String key, String payload, String contentType) { Blob sourceObject = context.getBlobStore().newBlob(key); - sourceObject.setPayload(TEST_STRING); - sourceObject.getMetadata().getContentMetadata().setContentType("text/xml"); + sourceObject.setPayload(payload); + sourceObject.getMetadata().getContentMetadata().setContentType(contentType); return addBlobToContainer(sourceContainer, sourceObject); } @@ -270,19 +276,19 @@ public class BaseBlobStoreIntegrationTest { } protected void assertConsistencyAwareContainerSize(final String containerName, final int count) - throws InterruptedException { + throws InterruptedException { assertConsistencyAware(new Runnable() { public void run() { try { assert context.getBlobStore().countBlobs(containerName) == count : String.format( - "expected only %d values in %s: %s", count, containerName, Sets.newHashSet(Iterables.transform( - context.getBlobStore().list(containerName), new Function() { + "expected only %d values in %s: %s", count, containerName, Sets.newHashSet(Iterables.transform( + context.getBlobStore().list(containerName), new Function() { - public String apply(StorageMetadata from) { - return from.getName(); - } + public String apply(StorageMetadata from) { + return from.getName(); + } - }))); + }))); } catch (Exception e) { Throwables.propagateIfPossible(e); } diff --git a/core/src/main/java/org/jclouds/io/payloads/StringPayload.java b/core/src/main/java/org/jclouds/io/payloads/StringPayload.java index 34a06f9b40..ddd6795381 100644 --- a/core/src/main/java/org/jclouds/io/payloads/StringPayload.java +++ b/core/src/main/java/org/jclouds/io/payloads/StringPayload.java @@ -19,18 +19,27 @@ package org.jclouds.io.payloads; +import java.io.ByteArrayInputStream; import java.io.InputStream; -import org.jclouds.util.Utils; +import com.google.common.base.Charsets; /** + * This implementation converts the String to a byte array using UTF-8 encoding. If you wish to use + * a different encoding, please use {@link ByteArrayPayload}. + * * @author Adrian Cole */ public class StringPayload extends BasePayload { + private final byte[] bytes; + + // it is possible to discover length by walking the string and updating current length based on + // character code. However, this is process intense, and assumes an encoding type of UTF-8 public StringPayload(String content) { super(content); - getContentMetadata().setContentLength((long) content.length()); + this.bytes = content.getBytes(Charsets.UTF_8); + getContentMetadata().setContentLength(new Long(bytes.length)); } /** @@ -38,7 +47,7 @@ public class StringPayload extends BasePayload { */ @Override public InputStream getInput() { - return Utils.toInputStream(content); + return new ByteArrayInputStream(bytes); } } \ No newline at end of file diff --git a/core/src/main/java/org/jclouds/util/Utils.java b/core/src/main/java/org/jclouds/util/Utils.java index e439a5f561..3032fce497 100644 --- a/core/src/main/java/org/jclouds/util/Utils.java +++ b/core/src/main/java/org/jclouds/util/Utils.java @@ -47,10 +47,10 @@ import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.Map; +import java.util.Map.Entry; import java.util.NoSuchElementException; import java.util.Properties; import java.util.Set; -import java.util.Map.Entry; import java.util.regex.Matcher; import java.util.regex.Pattern; From 1212f50d516a31adb74dd24a07b86ed07ca304c6 Mon Sep 17 00:00:00 2001 From: Adrian Cole Date: Tue, 30 Nov 2010 14:07:59 +0000 Subject: [PATCH 13/31] missing test --- .../io/payloads/StringPayloadTest.java | 40 +++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 core/src/test/java/org/jclouds/io/payloads/StringPayloadTest.java diff --git a/core/src/test/java/org/jclouds/io/payloads/StringPayloadTest.java b/core/src/test/java/org/jclouds/io/payloads/StringPayloadTest.java new file mode 100644 index 0000000000..6a0fbfa7c8 --- /dev/null +++ b/core/src/test/java/org/jclouds/io/payloads/StringPayloadTest.java @@ -0,0 +1,40 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.io.payloads; + +import static org.testng.Assert.assertEquals; + +import org.jclouds.io.Payload; +import org.testng.annotations.Test; + +import com.google.common.base.Charsets; + +/** + * + * @author Adrian Cole + */ +@Test +public class StringPayloadTest { + public void testLengthIsCorrectPerUTF8() { + Payload stringPayload = new StringPayload("unic₪de"); + assertEquals(stringPayload.getContentMetadata().getContentLength(), new Long( + "unic₪de".getBytes(Charsets.UTF_8).length)); + } +} From 552e2f1193562547e7505c7909913487f3c0386b Mon Sep 17 00:00:00 2001 From: Adrian Cole Date: Tue, 30 Nov 2010 15:48:58 +0000 Subject: [PATCH 14/31] added scaleup-storage, and workaround as it doesn't yet support bucket location --- .../handlers/ParseAWSErrorFromXmlContent.java | 2 +- ...UpCloudBlobStoreContextContextBuilder.java | 45 ++++++++++ .../config/S3BlobStoreContextModule.java | 9 ++ .../ScaleUpCloudBlobStoreContextModule.java | 41 +++++++++ .../functions/BucketToResourceMetadata.java | 52 +---------- .../functions/LocationFromBucketLocation.java | 88 +++++++++++++++++++ .../ReturnFalseIfBucketAlreadyOwnedByYou.java | 15 +++- core/src/main/resources/rest.properties | 4 + 8 files changed, 203 insertions(+), 53 deletions(-) create mode 100644 aws/core/src/main/java/org/jclouds/aws/s3/blobstore/ScaleUpCloudBlobStoreContextContextBuilder.java create mode 100644 aws/core/src/main/java/org/jclouds/aws/s3/blobstore/config/ScaleUpCloudBlobStoreContextModule.java create mode 100644 aws/core/src/main/java/org/jclouds/aws/s3/blobstore/functions/LocationFromBucketLocation.java diff --git a/aws/core/src/main/java/org/jclouds/aws/handlers/ParseAWSErrorFromXmlContent.java b/aws/core/src/main/java/org/jclouds/aws/handlers/ParseAWSErrorFromXmlContent.java index cf0e97b924..09293550bc 100755 --- a/aws/core/src/main/java/org/jclouds/aws/handlers/ParseAWSErrorFromXmlContent.java +++ b/aws/core/src/main/java/org/jclouds/aws/handlers/ParseAWSErrorFromXmlContent.java @@ -94,7 +94,7 @@ public class ParseAWSErrorFromXmlContent implements HttpErrorHandler { && (error.getCode().endsWith(".NotFound") || error.getCode().endsWith(".Unknown"))) exception = new ResourceNotFoundException(message, exception); else if ((error != null && error.getCode() != null && (error.getCode().equals("IncorrectState") || error - .getCode().endsWith(".Duplicate"))) || (message != null && message.indexOf("already exists") != -1)) + .getCode().endsWith(".Duplicate"))) || (message != null && (message.indexOf("already exists") != -1))) exception = new IllegalStateException(message, exception); else if (error != null && error.getCode() != null && error.getCode().equals("AuthFailure")) exception = new AuthorizationException(exception.getMessage(), exception); diff --git a/aws/core/src/main/java/org/jclouds/aws/s3/blobstore/ScaleUpCloudBlobStoreContextContextBuilder.java b/aws/core/src/main/java/org/jclouds/aws/s3/blobstore/ScaleUpCloudBlobStoreContextContextBuilder.java new file mode 100644 index 0000000000..9a433a8945 --- /dev/null +++ b/aws/core/src/main/java/org/jclouds/aws/s3/blobstore/ScaleUpCloudBlobStoreContextContextBuilder.java @@ -0,0 +1,45 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.aws.s3.blobstore; + +import java.util.List; +import java.util.Properties; + +import org.jclouds.aws.s3.S3ContextBuilder; +import org.jclouds.aws.s3.blobstore.config.ScaleUpCloudBlobStoreContextModule; + +import com.google.inject.Module; + +/** + * + * @author Adrian Cole + */ +public class ScaleUpCloudBlobStoreContextContextBuilder extends S3ContextBuilder { + + public ScaleUpCloudBlobStoreContextContextBuilder(Properties props) { + super(props); + } + + @Override + protected void addContextModule(List modules) { + modules.add(new ScaleUpCloudBlobStoreContextModule()); + } + +} \ No newline at end of file diff --git a/aws/core/src/main/java/org/jclouds/aws/s3/blobstore/config/S3BlobStoreContextModule.java b/aws/core/src/main/java/org/jclouds/aws/s3/blobstore/config/S3BlobStoreContextModule.java index 9ca1d87698..2a93fee09a 100755 --- a/aws/core/src/main/java/org/jclouds/aws/s3/blobstore/config/S3BlobStoreContextModule.java +++ b/aws/core/src/main/java/org/jclouds/aws/s3/blobstore/config/S3BlobStoreContextModule.java @@ -29,6 +29,8 @@ import org.jclouds.aws.s3.S3Client; import org.jclouds.aws.s3.blobstore.S3AsyncBlobStore; import org.jclouds.aws.s3.blobstore.S3BlobRequestSigner; import org.jclouds.aws.s3.blobstore.S3BlobStore; +import org.jclouds.aws.s3.blobstore.functions.LocationFromBucketLocation; +import org.jclouds.aws.s3.domain.BucketMetadata; import org.jclouds.aws.suppliers.DefaultLocationSupplier; import org.jclouds.blobstore.AsyncBlobStore; import org.jclouds.blobstore.BlobRequestSigner; @@ -43,6 +45,7 @@ import org.jclouds.domain.LocationScope; import org.jclouds.domain.internal.LocationImpl; import org.jclouds.rest.annotations.Provider; +import com.google.common.base.Function; import com.google.common.base.Supplier; import com.google.common.base.Suppliers; import com.google.common.collect.Sets; @@ -70,6 +73,12 @@ public class S3BlobStoreContextModule extends AbstractModule { bind(BlobStoreContext.class).to(new TypeLiteral>() { }).in(Scopes.SINGLETON); bind(BlobRequestSigner.class).to(S3BlobRequestSigner.class); + bindBucketLocationStrategy(); + } + + protected void bindBucketLocationStrategy() { + bind(new TypeLiteral>() { + }).to(LocationFromBucketLocation.class); } @Provides diff --git a/aws/core/src/main/java/org/jclouds/aws/s3/blobstore/config/ScaleUpCloudBlobStoreContextModule.java b/aws/core/src/main/java/org/jclouds/aws/s3/blobstore/config/ScaleUpCloudBlobStoreContextModule.java new file mode 100644 index 0000000000..771d3fbc2f --- /dev/null +++ b/aws/core/src/main/java/org/jclouds/aws/s3/blobstore/config/ScaleUpCloudBlobStoreContextModule.java @@ -0,0 +1,41 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.aws.s3.blobstore.config; + +import org.jclouds.aws.s3.domain.BucketMetadata; +import org.jclouds.domain.Location; + +import com.google.common.base.Function; +import com.google.common.base.Functions; +import com.google.inject.TypeLiteral; + +/** + * + * @author Adrian Cole + */ +public class ScaleUpCloudBlobStoreContextModule extends S3BlobStoreContextModule { + + @SuppressWarnings("rawtypes") + @Override + protected void bindBucketLocationStrategy() { + bind(new TypeLiteral>() { + }).toInstance((Function)Functions.constant(null)); + } +} diff --git a/aws/core/src/main/java/org/jclouds/aws/s3/blobstore/functions/BucketToResourceMetadata.java b/aws/core/src/main/java/org/jclouds/aws/s3/blobstore/functions/BucketToResourceMetadata.java index a1a891be0b..85b33c9219 100644 --- a/aws/core/src/main/java/org/jclouds/aws/s3/blobstore/functions/BucketToResourceMetadata.java +++ b/aws/core/src/main/java/org/jclouds/aws/s3/blobstore/functions/BucketToResourceMetadata.java @@ -19,80 +19,36 @@ package org.jclouds.aws.s3.blobstore.functions; -import java.util.NoSuchElementException; -import java.util.Set; -import javax.annotation.Resource; import javax.inject.Inject; import javax.inject.Singleton; -import org.jclouds.aws.s3.S3Client; import org.jclouds.aws.s3.domain.BucketMetadata; -import org.jclouds.blobstore.ContainerNotFoundException; import org.jclouds.blobstore.domain.MutableStorageMetadata; import org.jclouds.blobstore.domain.StorageMetadata; import org.jclouds.blobstore.domain.StorageType; import org.jclouds.blobstore.domain.internal.MutableStorageMetadataImpl; -import org.jclouds.collect.Memoized; import org.jclouds.domain.Location; -import org.jclouds.logging.Logger; import com.google.common.base.Function; -import com.google.common.base.Predicate; -import com.google.common.base.Supplier; -import com.google.common.collect.Iterables; /** * @author Adrian Cole */ @Singleton public class BucketToResourceMetadata implements Function { - private final S3Client client; - private final Location onlyLocation; - private final Supplier> locations; - - @Resource - protected Logger logger = Logger.NULL; + private final Function locationOfBucket; @Inject - BucketToResourceMetadata(S3Client client, @Memoized Supplier> locations) { - this.client = client; - this.onlyLocation = locations.get().size() == 1 ? Iterables.get(locations.get(), 0) : null; - this.locations = locations; + BucketToResourceMetadata(Function locationOfBucket) { + this.locationOfBucket = locationOfBucket; } public StorageMetadata apply(BucketMetadata from) { MutableStorageMetadata to = new MutableStorageMetadataImpl(); to.setName(from.getName()); to.setType(StorageType.CONTAINER); - to.setLocation(onlyLocation != null ? onlyLocation : getLocation(from)); + to.setLocation(locationOfBucket.apply(from)); return to; } - - private Location getLocation(BucketMetadata from) { - try { - Set locations = this.locations.get(); - final String region = client.getBucketLocation(from.getName()); - assert region != null : String.format("could not get region for %s", from.getName()); - if (region != null) { - try { - return Iterables.find(locations, new Predicate() { - - @Override - public boolean apply(Location input) { - return input.getId().equalsIgnoreCase(region.toString()); - } - - }); - } catch (NoSuchElementException e) { - logger.error("could not get location for region %s in %s", region, locations); - } - } else { - logger.error("could not get region for %s", from.getName()); - } - } catch (ContainerNotFoundException e) { - logger.error(e, "could not get region for %s, as service suggests the bucket doesn't exist", from.getName()); - } - return null; - } } \ No newline at end of file diff --git a/aws/core/src/main/java/org/jclouds/aws/s3/blobstore/functions/LocationFromBucketLocation.java b/aws/core/src/main/java/org/jclouds/aws/s3/blobstore/functions/LocationFromBucketLocation.java new file mode 100644 index 0000000000..3a3c62814f --- /dev/null +++ b/aws/core/src/main/java/org/jclouds/aws/s3/blobstore/functions/LocationFromBucketLocation.java @@ -0,0 +1,88 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.aws.s3.blobstore.functions; + +import java.util.NoSuchElementException; +import java.util.Set; + +import javax.annotation.Resource; +import javax.inject.Inject; +import javax.inject.Singleton; + +import org.jclouds.aws.s3.S3Client; +import org.jclouds.aws.s3.domain.BucketMetadata; +import org.jclouds.blobstore.ContainerNotFoundException; +import org.jclouds.collect.Memoized; +import org.jclouds.domain.Location; +import org.jclouds.logging.Logger; + +import com.google.common.base.Function; +import com.google.common.base.Predicate; +import com.google.common.base.Supplier; +import com.google.common.collect.Iterables; + +/** + * @author Adrian Cole + */ +@Singleton +public class LocationFromBucketLocation implements Function { + private final Location onlyLocation; + private final Supplier> locations; + private final S3Client client; + + @Resource + protected Logger logger = Logger.NULL; + + @Inject + LocationFromBucketLocation(S3Client client, @Memoized Supplier> locations) { + this.client = client; + this.onlyLocation = locations.get().size() == 1 ? Iterables.get(locations.get(), 0) : null; + this.locations = locations; + } + + public Location apply(BucketMetadata from) { + if (onlyLocation != null) + return onlyLocation; + try { + Set locations = this.locations.get(); + final String region = client.getBucketLocation(from.getName()); + assert region != null : String.format("could not get region for %s", from.getName()); + if (region != null) { + try { + return Iterables.find(locations, new Predicate() { + + @Override + public boolean apply(Location input) { + return input.getId().equalsIgnoreCase(region.toString()); + } + + }); + } catch (NoSuchElementException e) { + logger.error("could not get location for region %s in %s", region, locations); + } + } else { + logger.error("could not get region for %s", from.getName()); + } + } catch (ContainerNotFoundException e) { + logger.error(e, "could not get region for %s, as service suggests the bucket doesn't exist", from.getName()); + } + return null; + } +} \ No newline at end of file diff --git a/aws/core/src/main/java/org/jclouds/aws/s3/functions/ReturnFalseIfBucketAlreadyOwnedByYou.java b/aws/core/src/main/java/org/jclouds/aws/s3/functions/ReturnFalseIfBucketAlreadyOwnedByYou.java index 2aa6a30213..a9512fd53e 100755 --- a/aws/core/src/main/java/org/jclouds/aws/s3/functions/ReturnFalseIfBucketAlreadyOwnedByYou.java +++ b/aws/core/src/main/java/org/jclouds/aws/s3/functions/ReturnFalseIfBucketAlreadyOwnedByYou.java @@ -19,8 +19,14 @@ package org.jclouds.aws.s3.functions; +import static com.google.common.base.Throwables.getCausalChain; +import static com.google.common.collect.Iterables.filter; +import static com.google.common.collect.Iterables.get; +import static com.google.common.collect.Iterables.size; import static org.jclouds.util.Utils.propagateOrNull; +import java.util.List; + import javax.inject.Singleton; import org.jclouds.aws.AWSResponseException; @@ -35,11 +41,12 @@ import com.google.common.base.Function; public class ReturnFalseIfBucketAlreadyOwnedByYou implements Function { public Boolean apply(Exception from) { - if (from instanceof AWSResponseException) { - AWSResponseException responseException = (AWSResponseException) from; - if ("BucketAlreadyOwnedByYou".equals(responseException.getError().getCode())) { + List throwables = getCausalChain(from); + + Iterable matchingAWSResponseException = filter(throwables, AWSResponseException.class); + if (size(matchingAWSResponseException) >= 1 && get(matchingAWSResponseException, 0).getError() != null) { + if (get(matchingAWSResponseException, 0).getError().getCode().equals("BucketAlreadyOwnedByYou")) return false; - } } return Boolean.class.cast(propagateOrNull(from)); } diff --git a/core/src/main/resources/rest.properties b/core/src/main/resources/rest.properties index 9108d8ad63..242414993d 100644 --- a/core/src/main/resources/rest.properties +++ b/core/src/main/resources/rest.properties @@ -119,6 +119,10 @@ walrus.propertiesbuilder=org.jclouds.aws.s3.WalrusPropertiesBuilder googlestorage.contextbuilder=org.jclouds.aws.s3.S3ContextBuilder googlestorage.propertiesbuilder=org.jclouds.aws.s3.GoogleStoragePropertiesBuilder +scaleup-storage.contextbuilder=org.jclouds.aws.s3.blobstore.ScaleUpCloudBlobStoreContextContextBuilder +scaleup-storage.propertiesbuilder=org.jclouds.aws.s3.S3PropertiesBuilder +scaleup-storage.endpoint=https://scs.scaleupstorage.com + transient.contextbuilder=org.jclouds.blobstore.TransientBlobStoreContextBuilder transient.propertiesbuilder=org.jclouds.blobstore.TransientBlobStorePropertiesBuilder From 9ff54e5956b73bfd9e903f9a0f6569d678c67bb4 Mon Sep 17 00:00:00 2001 From: Adrian Cole Date: Tue, 30 Nov 2010 16:06:06 +0000 Subject: [PATCH 15/31] worked around case problem in scaleup-storage --- .../functions/ParseSystemAndUserMetadataFromHeaders.java | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/blobstore/src/main/java/org/jclouds/blobstore/functions/ParseSystemAndUserMetadataFromHeaders.java b/blobstore/src/main/java/org/jclouds/blobstore/functions/ParseSystemAndUserMetadataFromHeaders.java index c8762ad605..9af2635e36 100755 --- a/blobstore/src/main/java/org/jclouds/blobstore/functions/ParseSystemAndUserMetadataFromHeaders.java +++ b/blobstore/src/main/java/org/jclouds/blobstore/functions/ParseSystemAndUserMetadataFromHeaders.java @@ -87,8 +87,11 @@ public class ParseSystemAndUserMetadataFromHeaders implements Function Date: Wed, 1 Dec 2010 00:17:37 +0000 Subject: [PATCH 16/31] shortened tag names in ec2 tests --- .../jclouds/aws/ec2/compute/EC2ComputeServiceLiveTest.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/aws/core/src/test/java/org/jclouds/aws/ec2/compute/EC2ComputeServiceLiveTest.java b/aws/core/src/test/java/org/jclouds/aws/ec2/compute/EC2ComputeServiceLiveTest.java index 5465771925..1e57c9672d 100644 --- a/aws/core/src/test/java/org/jclouds/aws/ec2/compute/EC2ComputeServiceLiveTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/ec2/compute/EC2ComputeServiceLiveTest.java @@ -106,7 +106,7 @@ public class EC2ComputeServiceLiveTest extends BaseComputeServiceLiveTest { InstanceClient instanceClient = EC2Client.class.cast(context.getProviderSpecificContext().getApi()) .getInstanceServices(); - String tag = this.tag + "optionsandlogin"; + String tag = this.tag + "onl"; TemplateOptions options = client.templateOptions(); @@ -190,7 +190,7 @@ public class EC2ComputeServiceLiveTest extends BaseComputeServiceLiveTest { InstanceClient instanceClient = EC2Client.class.cast(context.getProviderSpecificContext().getApi()) .getInstanceServices(); - String tag = this.tag + "optionsnokey"; + String tag = this.tag + "onk"; TemplateOptions options = client.templateOptions(); @@ -250,7 +250,7 @@ public class EC2ComputeServiceLiveTest extends BaseComputeServiceLiveTest { InstanceClient instanceClient = EC2Client.class.cast(context.getProviderSpecificContext().getApi()) .getInstanceServices(); - String tag = this.tag + "optionswithsubnetid"; + String tag = this.tag + "ons"; TemplateOptions options = client.templateOptions(); From 989500ded674d8ae092444d4d88510fc97c66beb Mon Sep 17 00:00:00 2001 From: Adrian Cole Date: Wed, 1 Dec 2010 15:59:37 +0000 Subject: [PATCH 17/31] shortened test tag names to try and workaround a character limitation --- .../jclouds/aws/ec2/compute/EC2ComputeServiceLiveTest.java | 6 +++--- .../compute/EucalyptusComputeServiceLiveTestDisabled.java | 2 +- .../org/jclouds/compute/BaseComputeServiceLiveTest.java | 4 ++-- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/aws/core/src/test/java/org/jclouds/aws/ec2/compute/EC2ComputeServiceLiveTest.java b/aws/core/src/test/java/org/jclouds/aws/ec2/compute/EC2ComputeServiceLiveTest.java index 1e57c9672d..496d7c0b7c 100644 --- a/aws/core/src/test/java/org/jclouds/aws/ec2/compute/EC2ComputeServiceLiveTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/ec2/compute/EC2ComputeServiceLiveTest.java @@ -106,7 +106,7 @@ public class EC2ComputeServiceLiveTest extends BaseComputeServiceLiveTest { InstanceClient instanceClient = EC2Client.class.cast(context.getProviderSpecificContext().getApi()) .getInstanceServices(); - String tag = this.tag + "onl"; + String tag = this.tag + "o"; TemplateOptions options = client.templateOptions(); @@ -190,7 +190,7 @@ public class EC2ComputeServiceLiveTest extends BaseComputeServiceLiveTest { InstanceClient instanceClient = EC2Client.class.cast(context.getProviderSpecificContext().getApi()) .getInstanceServices(); - String tag = this.tag + "onk"; + String tag = this.tag + "k"; TemplateOptions options = client.templateOptions(); @@ -250,7 +250,7 @@ public class EC2ComputeServiceLiveTest extends BaseComputeServiceLiveTest { InstanceClient instanceClient = EC2Client.class.cast(context.getProviderSpecificContext().getApi()) .getInstanceServices(); - String tag = this.tag + "ons"; + String tag = this.tag + "g"; TemplateOptions options = client.templateOptions(); diff --git a/aws/core/src/test/java/org/jclouds/aws/ec2/compute/EucalyptusComputeServiceLiveTestDisabled.java b/aws/core/src/test/java/org/jclouds/aws/ec2/compute/EucalyptusComputeServiceLiveTestDisabled.java index a61b0659a3..c85cfe7bb0 100644 --- a/aws/core/src/test/java/org/jclouds/aws/ec2/compute/EucalyptusComputeServiceLiveTestDisabled.java +++ b/aws/core/src/test/java/org/jclouds/aws/ec2/compute/EucalyptusComputeServiceLiveTestDisabled.java @@ -43,7 +43,7 @@ public class EucalyptusComputeServiceLiveTestDisabled extends EC2ComputeServiceL @Override public void setServiceDefaults() { // security groups must be <30 characters - tag = "euc"; + tag = "eu"; } @Override diff --git a/compute/src/test/java/org/jclouds/compute/BaseComputeServiceLiveTest.java b/compute/src/test/java/org/jclouds/compute/BaseComputeServiceLiveTest.java index f967f6a063..d01e7d5244 100755 --- a/compute/src/test/java/org/jclouds/compute/BaseComputeServiceLiveTest.java +++ b/compute/src/test/java/org/jclouds/compute/BaseComputeServiceLiveTest.java @@ -200,7 +200,7 @@ public abstract class BaseComputeServiceLiveTest { // starting this one alphabetically before create2nodes.. @Test(enabled = true, dependsOnMethods = { "testCompareSizes" }) public void testAScriptExecutionAfterBootWithBasicTemplate() throws Exception { - String tag = this.tag + "run"; + String tag = this.tag + "r"; try { client.destroyNodesMatching(withTag(tag)); } catch (Exception e) { @@ -460,7 +460,7 @@ public abstract class BaseComputeServiceLiveTest { @Test(enabled = true) public void testCreateAndRunAService() throws Exception { - String tag = this.tag + "service"; + String tag = this.tag + "s"; try { client.destroyNodesMatching(withTag(tag)); } catch (Exception e) { From 243fcfab81a79ca310569bfcfee5a6371c70834b Mon Sep 17 00:00:00 2001 From: Adrian Cole Date: Wed, 1 Dec 2010 22:41:25 +0000 Subject: [PATCH 18/31] Issue 412: split cloudsigma and elastichosts apis --- core/pom.xml | 2 +- .../src/main/java/org/jclouds/util/Utils.java | 31 ++ core/src/main/resources/rest.properties | 6 + .../test/java/org/jclouds/util/UtilsTest.java | 12 +- sandbox/elastichosts/pom.xml | 2 +- .../cloudsigma/CloudSigmaAsyncClient.java | 125 ++++++ .../jclouds/cloudsigma/CloudSigmaClient.java | 87 ++++ .../cloudsigma/CloudSigmaContextBuilder.java | 45 ++ .../CloudSigmaPropertiesBuilder.java | 47 ++ .../config/CloudSigmaRestClientModule.java | 76 ++++ .../jclouds/cloudsigma/domain/DriveInfo.java | 415 ++++++++++++++++++ .../domain/DriveType.java | 2 +- .../functions/CreateDriveRequestToMap.java | 58 +++ .../cloudsigma/functions/DriveDataToMap.java | 59 +++ ...aluesDelimitedByBlankLinesToDriveInfo.java | 53 +++ ...esDelimitedByBlankLinesToDriveInfoSet.java | 61 +++ .../cloudsigma/functions/MapToDriveInfo.java | 72 +++ .../CommonElasticHostsAsyncClient.java | 114 +++++ .../CommonElasticHostsClient.java | 90 ++++ .../elastichosts/ElasticHostsAsyncClient.java | 89 +--- .../elastichosts/ElasticHostsClient.java | 77 +--- .../ElasticHostsPropertiesBuilder.java | 2 - ...ndCreateDriveRequestToPlainTextString.java | 6 +- .../BindDriveDataToPlainTextString.java | 6 +- .../config/ElasticHostsRestClientModule.java | 21 +- .../elastichosts/domain/DriveInfo.java | 360 +++------------ .../functions/MapToDriveInfo.java | 24 +- .../elastichosts/functions/SplitNewlines.java | 8 +- .../handlers/ElasticHostsErrorHandler.java | 5 +- .../cloudsigma/CloudSigmaAsyncClientTest.java | 180 ++++++++ .../cloudsigma/CloudSigmaClientLiveTest.java | 72 +++ .../cloudsigma/ProvidersInPropertiesTest.java | 47 ++ ...sDelimitedByBlankLinesToDriveInfoTest.java | 50 +++ ...limitedByBlankLinesToDriveInfoSetTest.java | 52 +++ .../functions/MapToDriveInfoTest.java | 97 ++++ .../CommonElasticHostsClientLiveTest.java | 176 ++++++++ .../ElasticHostsAsyncClientTest.java | 60 +-- .../ElasticHostsClientLiveTest.java | 187 +------- .../ProvidersInPropertiesTest.java | 47 ++ ...eateDriveRequestToPlainTextStringTest.java | 20 +- .../BindDriveDataToPlainTextStringTest.java | 23 +- ...sDelimitedByBlankLinesToDriveInfoTest.java | 50 +++ .../functions/MapToDriveInfoTest.java | 14 +- .../ElasticHostsErrorHandlerTest.java | 6 + .../src/test/resources/cloudsigma/drive.txt | 26 ++ .../elastichosts/src/test/resources/drive.txt | 11 - .../elastichosts/src/test/resources/uuids.txt | 2 +- 47 files changed, 2333 insertions(+), 742 deletions(-) create mode 100644 sandbox/elastichosts/src/main/java/org/jclouds/cloudsigma/CloudSigmaAsyncClient.java create mode 100644 sandbox/elastichosts/src/main/java/org/jclouds/cloudsigma/CloudSigmaClient.java create mode 100644 sandbox/elastichosts/src/main/java/org/jclouds/cloudsigma/CloudSigmaContextBuilder.java create mode 100644 sandbox/elastichosts/src/main/java/org/jclouds/cloudsigma/CloudSigmaPropertiesBuilder.java create mode 100644 sandbox/elastichosts/src/main/java/org/jclouds/cloudsigma/config/CloudSigmaRestClientModule.java create mode 100644 sandbox/elastichosts/src/main/java/org/jclouds/cloudsigma/domain/DriveInfo.java rename sandbox/elastichosts/src/main/java/org/jclouds/{elastichosts => cloudsigma}/domain/DriveType.java (96%) create mode 100644 sandbox/elastichosts/src/main/java/org/jclouds/cloudsigma/functions/CreateDriveRequestToMap.java create mode 100644 sandbox/elastichosts/src/main/java/org/jclouds/cloudsigma/functions/DriveDataToMap.java create mode 100644 sandbox/elastichosts/src/main/java/org/jclouds/cloudsigma/functions/KeyValuesDelimitedByBlankLinesToDriveInfo.java create mode 100644 sandbox/elastichosts/src/main/java/org/jclouds/cloudsigma/functions/ListOfKeyValuesDelimitedByBlankLinesToDriveInfoSet.java create mode 100644 sandbox/elastichosts/src/main/java/org/jclouds/cloudsigma/functions/MapToDriveInfo.java create mode 100644 sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/CommonElasticHostsAsyncClient.java create mode 100644 sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/CommonElasticHostsClient.java create mode 100644 sandbox/elastichosts/src/test/java/org/jclouds/cloudsigma/CloudSigmaAsyncClientTest.java create mode 100644 sandbox/elastichosts/src/test/java/org/jclouds/cloudsigma/CloudSigmaClientLiveTest.java create mode 100644 sandbox/elastichosts/src/test/java/org/jclouds/cloudsigma/ProvidersInPropertiesTest.java create mode 100644 sandbox/elastichosts/src/test/java/org/jclouds/cloudsigma/functions/KeyValuesDelimitedByBlankLinesToDriveInfoTest.java create mode 100644 sandbox/elastichosts/src/test/java/org/jclouds/cloudsigma/functions/ListOfKeyValuesDelimitedByBlankLinesToDriveInfoSetTest.java create mode 100644 sandbox/elastichosts/src/test/java/org/jclouds/cloudsigma/functions/MapToDriveInfoTest.java create mode 100644 sandbox/elastichosts/src/test/java/org/jclouds/elastichosts/CommonElasticHostsClientLiveTest.java create mode 100644 sandbox/elastichosts/src/test/java/org/jclouds/elastichosts/ProvidersInPropertiesTest.java create mode 100644 sandbox/elastichosts/src/test/java/org/jclouds/elastichosts/functions/KeyValuesDelimitedByBlankLinesToDriveInfoTest.java create mode 100644 sandbox/elastichosts/src/test/resources/cloudsigma/drive.txt diff --git a/core/pom.xml b/core/pom.xml index 4abd10c9bb..372ab3e87b 100644 --- a/core/pom.xml +++ b/core/pom.xml @@ -106,7 +106,7 @@ com.google.guava guava - r06 + r07 com.google.code.findbugs diff --git a/core/src/main/java/org/jclouds/util/Utils.java b/core/src/main/java/org/jclouds/util/Utils.java index 3032fce497..fabf3de3e3 100644 --- a/core/src/main/java/org/jclouds/util/Utils.java +++ b/core/src/main/java/org/jclouds/util/Utils.java @@ -21,7 +21,9 @@ package org.jclouds.util; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.base.Predicates.equalTo; import static com.google.common.base.Predicates.instanceOf; +import static com.google.common.base.Predicates.not; import static com.google.common.base.Predicates.notNull; import static com.google.common.base.Splitter.on; import static com.google.common.base.Throwables.getCausalChain; @@ -32,6 +34,7 @@ import static com.google.common.collect.Iterables.find; import static com.google.common.collect.Iterables.get; import static com.google.common.collect.Iterables.transform; import static com.google.common.collect.Lists.newArrayList; +import static com.google.common.collect.Maps.filterKeys; import static com.google.common.io.ByteStreams.toByteArray; import static com.google.common.io.Closeables.closeQuietly; import static org.jclouds.util.Patterns.CHAR_TO_PATTERN; @@ -70,6 +73,8 @@ import com.google.common.base.Predicate; import com.google.common.base.Splitter; import com.google.common.base.Supplier; import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.ImmutableMap.Builder; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Maps; import com.google.common.io.OutputSupplier; @@ -84,6 +89,32 @@ import com.google.inject.spi.Message; */ public class Utils { + /** + * If the supplied map contains the key {@code k1}, its value will be assigned to the key + * {@code k2}. Note that this doesn't modify the input map. + * + * @param + * type of value the map holds + * @param in + * the map you wish to make a copy of + * @param k1 + * old key + * @param k2 + * new key + * @return copy of the map with the value of the key re-routed, or the original, if it {@code k1} + * wasn't present. + */ + public static Map renameKey(Map in, String k1, String k2) { + if (in.containsKey(k1)) { + Builder builder = ImmutableMap.builder(); + builder.putAll(filterKeys(in, not(equalTo(k1)))); + V tags = in.get(k1); + builder.put(k2, tags); + in = builder.build(); + } + return in; + } + public static Supplier> composeMapSupplier(Iterable>> suppliers) { return new ListMapSupplier(suppliers); } diff --git a/core/src/main/resources/rest.properties b/core/src/main/resources/rest.properties index 242414993d..b971ca617f 100644 --- a/core/src/main/resources/rest.properties +++ b/core/src/main/resources/rest.properties @@ -89,6 +89,12 @@ bluelock-vcdirector.propertiesbuilder=org.jclouds.vcloud.bluelock.BlueLockVCloud gogrid.propertiesbuilder=org.jclouds.gogrid.GoGridPropertiesBuilder gogrid.contextbuilder=org.jclouds.gogrid.GoGridContextBuilder +elastichosts.propertiesbuilder=org.jclouds.elastichosts.ElasticHostsPropertiesBuilder +elastichosts.contextbuilder=org.jclouds.elastichosts.ElasticHostsContextBuilder + +cloudsigma.propertiesbuilder=org.jclouds.cloudsigma.CloudSigmaPropertiesBuilder +cloudsigma.contextbuilder=org.jclouds.cloudsigma.CloudSigmaContextBuilder + ibmdev.propertiesbuilder=org.jclouds.ibmdev.IBMDeveloperCloudPropertiesBuilder ibmdev.contextbuilder=org.jclouds.ibmdev.IBMDeveloperCloudContextBuilder diff --git a/core/src/test/java/org/jclouds/util/UtilsTest.java b/core/src/test/java/org/jclouds/util/UtilsTest.java index d17880b0db..8a5de24518 100644 --- a/core/src/test/java/org/jclouds/util/UtilsTest.java +++ b/core/src/test/java/org/jclouds/util/UtilsTest.java @@ -23,6 +23,7 @@ import static org.easymock.classextension.EasyMock.createMock; import static org.testng.Assert.assertEquals; import java.io.UnsupportedEncodingException; +import java.util.Map; import java.util.concurrent.TimeoutException; import org.jclouds.domain.Credentials; @@ -42,6 +43,15 @@ import com.google.inject.spi.Message; */ @Test(groups = "unit", testName = "jclouds.UtilsTest") public class UtilsTest { + public void testRenameKeyWhenNotFound() { + Map nothing = ImmutableMap.of(); + assertEquals(Utils.renameKey(nothing, "foo", "bar"), nothing); + } + + public void testRenameKeyWhenFound() { + Map nothing = ImmutableMap.of("foo", "bar"); + assertEquals(Utils.renameKey(nothing, "foo", "bar"), ImmutableMap.of("bar", "bar")); + } public void testOverridingCredentialsWhenOverridingIsNull() { Credentials defaultCredentials = new Credentials("foo", "bar"); @@ -69,7 +79,7 @@ public class UtilsTest { assertEquals(Utils.overrideCredentialsIfSupplied(defaultCredentials, overridingCredentials), new Credentials( "foo", "bar")); } - + public void testGetCause() { AuthorizationException aex = createMock(AuthorizationException.class); Message message = new Message(ImmutableList.of(), "test", aex); diff --git a/sandbox/elastichosts/pom.xml b/sandbox/elastichosts/pom.xml index cda61b4f8a..8a58d9789a 100644 --- a/sandbox/elastichosts/pom.xml +++ b/sandbox/elastichosts/pom.xml @@ -28,7 +28,7 @@ org.jclouds jclouds-project 1.0-SNAPSHOT - ../project/pom.xml + ../../project/pom.xml org.jclouds jclouds-elastichosts diff --git a/sandbox/elastichosts/src/main/java/org/jclouds/cloudsigma/CloudSigmaAsyncClient.java b/sandbox/elastichosts/src/main/java/org/jclouds/cloudsigma/CloudSigmaAsyncClient.java new file mode 100644 index 0000000000..7530f2e3ae --- /dev/null +++ b/sandbox/elastichosts/src/main/java/org/jclouds/cloudsigma/CloudSigmaAsyncClient.java @@ -0,0 +1,125 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.cloudsigma; + +import java.util.Set; + +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.core.MediaType; + +import org.jclouds.cloudsigma.domain.DriveInfo; +import org.jclouds.cloudsigma.functions.KeyValuesDelimitedByBlankLinesToDriveInfo; +import org.jclouds.cloudsigma.functions.ListOfKeyValuesDelimitedByBlankLinesToDriveInfoSet; +import org.jclouds.elastichosts.CommonElasticHostsAsyncClient; +import org.jclouds.elastichosts.ElasticHostsClient; +import org.jclouds.elastichosts.binders.BindCreateDriveRequestToPlainTextString; +import org.jclouds.elastichosts.binders.BindDriveDataToPlainTextString; +import org.jclouds.elastichosts.domain.CreateDriveRequest; +import org.jclouds.elastichosts.domain.DriveData; +import org.jclouds.elastichosts.functions.SplitNewlines; +import org.jclouds.http.filters.BasicAuthentication; +import org.jclouds.rest.annotations.BinderParam; +import org.jclouds.rest.annotations.ExceptionParser; +import org.jclouds.rest.annotations.RequestFilters; +import org.jclouds.rest.annotations.ResponseParser; +import org.jclouds.rest.functions.ReturnNullOnNotFoundOr404; + +import com.google.common.util.concurrent.ListenableFuture; + +/** + * Provides asynchronous access to CloudSigma via their REST API. + *

+ * + * @see ElasticHostsClient + * @see + * @author Adrian Cole + */ +@RequestFilters(BasicAuthentication.class) +@Consumes(MediaType.TEXT_PLAIN) +public interface CloudSigmaAsyncClient extends CommonElasticHostsAsyncClient { + + /** + * @see ElasticHostsClient#listStandardDrives() + */ + @GET + @Path("/drives/standard/list") + @ResponseParser(SplitNewlines.class) + ListenableFuture> listStandardDrives(); + + /** + * @see ElasticHostsClient#listStandardCds() + */ + @GET + @Path("/drives/standard/cd/list") + @ResponseParser(SplitNewlines.class) + ListenableFuture> listStandardCds(); + + /** + * @see ElasticHostsClient#listStandardImages() + */ + @GET + @Path("/drives/standard/img/list") + @ResponseParser(SplitNewlines.class) + ListenableFuture> listStandardImages(); + + /** + * @see ElasticHostsClient#listDriveInfo() + */ + @Override + @GET + @Path("/drives/info") + @ResponseParser(ListOfKeyValuesDelimitedByBlankLinesToDriveInfoSet.class) + ListenableFuture> listDriveInfo(); + + /** + * @see ElasticHostsClient#getDriveInfo + */ + @Override + @GET + @ExceptionParser(ReturnNullOnNotFoundOr404.class) + @ResponseParser(KeyValuesDelimitedByBlankLinesToDriveInfo.class) + @Path("/drives/{uuid}/info") + ListenableFuture getDriveInfo(@PathParam("uuid") String uuid); + + /** + * @see ElasticHostsClient#createDrive + */ + @Override + @POST + @ExceptionParser(ReturnNullOnNotFoundOr404.class) + @ResponseParser(KeyValuesDelimitedByBlankLinesToDriveInfo.class) + @Path("/drives/create") + ListenableFuture createDrive( + @BinderParam(BindCreateDriveRequestToPlainTextString.class) CreateDriveRequest createDrive); + + /** + * @see ElasticHostsClient#setDriveData + */ + @POST + @ExceptionParser(ReturnNullOnNotFoundOr404.class) + @ResponseParser(KeyValuesDelimitedByBlankLinesToDriveInfo.class) + @Path("/drives/{uuid}/set") + ListenableFuture setDriveData(@PathParam("uuid") String uuid, + @BinderParam(BindDriveDataToPlainTextString.class) DriveData createDrive); +} diff --git a/sandbox/elastichosts/src/main/java/org/jclouds/cloudsigma/CloudSigmaClient.java b/sandbox/elastichosts/src/main/java/org/jclouds/cloudsigma/CloudSigmaClient.java new file mode 100644 index 0000000000..512cea40ec --- /dev/null +++ b/sandbox/elastichosts/src/main/java/org/jclouds/cloudsigma/CloudSigmaClient.java @@ -0,0 +1,87 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.cloudsigma; + +import java.util.Set; +import java.util.concurrent.TimeUnit; + +import org.jclouds.cloudsigma.domain.DriveInfo; +import org.jclouds.concurrent.Timeout; +import org.jclouds.elastichosts.CommonElasticHostsClient; +import org.jclouds.elastichosts.domain.CreateDriveRequest; +import org.jclouds.elastichosts.domain.DriveData; + +/** + * Provides synchronous access to CloudSigma. + *

+ * + * @see CloudSigmaAsyncClient + * @see + * @author Adrian Cole + */ +@Timeout(duration = 60, timeUnit = TimeUnit.SECONDS) +public interface CloudSigmaClient extends CommonElasticHostsClient { + + /** + * list of drive uuids that are in the library + * + * @return or empty set if no drives are found + */ + Set listStandardDrives(); + + /** + * list of cd uuids that are in the library + * + * @return or empty set if no cds are found + */ + Set listStandardCds(); + + /** + * list of image uuids that are in the library + * + * @return or empty set if no images are found + */ + Set listStandardImages(); + + /** + * {@inheritDoc} + */ + @Override + Set listDriveInfo(); + + /** + * {@inheritDoc} + */ + @Override + DriveInfo getDriveInfo(String uuid); + + /** + * {@inheritDoc} + */ + @Override + DriveInfo createDrive(CreateDriveRequest createDrive); + + /** + * {@inheritDoc} + */ + @Override + DriveInfo setDriveData(String uuid, DriveData driveData); + +} diff --git a/sandbox/elastichosts/src/main/java/org/jclouds/cloudsigma/CloudSigmaContextBuilder.java b/sandbox/elastichosts/src/main/java/org/jclouds/cloudsigma/CloudSigmaContextBuilder.java new file mode 100644 index 0000000000..d69dfc3874 --- /dev/null +++ b/sandbox/elastichosts/src/main/java/org/jclouds/cloudsigma/CloudSigmaContextBuilder.java @@ -0,0 +1,45 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.cloudsigma; + +import java.util.List; +import java.util.Properties; + +import org.jclouds.cloudsigma.config.CloudSigmaRestClientModule; +import org.jclouds.rest.RestContextBuilder; + +import com.google.inject.Module; + +/** + * + * @author Adrian Cole + */ +public class CloudSigmaContextBuilder extends + RestContextBuilder { + + public CloudSigmaContextBuilder(Properties props) { + super(CloudSigmaClient.class, CloudSigmaAsyncClient.class, props); + } + + protected void addClientModule(List modules) { + modules.add(new CloudSigmaRestClientModule()); + } + +} diff --git a/sandbox/elastichosts/src/main/java/org/jclouds/cloudsigma/CloudSigmaPropertiesBuilder.java b/sandbox/elastichosts/src/main/java/org/jclouds/cloudsigma/CloudSigmaPropertiesBuilder.java new file mode 100644 index 0000000000..d1daf9bde5 --- /dev/null +++ b/sandbox/elastichosts/src/main/java/org/jclouds/cloudsigma/CloudSigmaPropertiesBuilder.java @@ -0,0 +1,47 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.cloudsigma; + +import static org.jclouds.Constants.PROPERTY_API_VERSION; +import static org.jclouds.Constants.PROPERTY_ENDPOINT; + +import java.util.Properties; + +import org.jclouds.PropertiesBuilder; + +/** + * Builds properties used in CloudSigma Clients + * + * @author Adrian Cole + */ +public class CloudSigmaPropertiesBuilder extends PropertiesBuilder { + @Override + protected Properties defaultProperties() { + Properties properties = super.defaultProperties(); + properties.setProperty(PROPERTY_ENDPOINT, "https://api.cloudsigma.com"); + properties.setProperty(PROPERTY_API_VERSION, "1.0"); + return properties; + } + + public CloudSigmaPropertiesBuilder(Properties properties) { + super(properties); + } + +} diff --git a/sandbox/elastichosts/src/main/java/org/jclouds/cloudsigma/config/CloudSigmaRestClientModule.java b/sandbox/elastichosts/src/main/java/org/jclouds/cloudsigma/config/CloudSigmaRestClientModule.java new file mode 100644 index 0000000000..cc1e5815f2 --- /dev/null +++ b/sandbox/elastichosts/src/main/java/org/jclouds/cloudsigma/config/CloudSigmaRestClientModule.java @@ -0,0 +1,76 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.cloudsigma.config; + +import java.util.Map; + +import org.jclouds.cloudsigma.CloudSigmaAsyncClient; +import org.jclouds.cloudsigma.CloudSigmaClient; +import org.jclouds.cloudsigma.functions.CreateDriveRequestToMap; +import org.jclouds.cloudsigma.functions.DriveDataToMap; +import org.jclouds.elastichosts.domain.CreateDriveRequest; +import org.jclouds.elastichosts.domain.DriveData; +import org.jclouds.elastichosts.handlers.ElasticHostsErrorHandler; +import org.jclouds.http.HttpErrorHandler; +import org.jclouds.http.RequiresHttp; +import org.jclouds.http.annotation.ClientError; +import org.jclouds.http.annotation.Redirection; +import org.jclouds.http.annotation.ServerError; +import org.jclouds.rest.ConfiguresRestClient; +import org.jclouds.rest.config.RestClientModule; + +import com.google.common.base.Function; +import com.google.inject.TypeLiteral; + +/** + * Configures the CloudSigma connection. + * + * @author Adrian Cole + */ +@RequiresHttp +@ConfiguresRestClient +public class CloudSigmaRestClientModule extends RestClientModule { + + public CloudSigmaRestClientModule() { + super(CloudSigmaClient.class, CloudSigmaAsyncClient.class); + } + + @Override + protected void bindErrorHandlers() { + bind(HttpErrorHandler.class).annotatedWith(Redirection.class).to(ElasticHostsErrorHandler.class); + bind(HttpErrorHandler.class).annotatedWith(ClientError.class).to(ElasticHostsErrorHandler.class); + bind(HttpErrorHandler.class).annotatedWith(ServerError.class).to(ElasticHostsErrorHandler.class); + } + + @Override + protected void configure() { + super.configure(); + bind(new TypeLiteral>>() { + }).to(CreateDriveRequestToMap.class); + bind(new TypeLiteral>>() { + }).to(DriveDataToMap.class); + } + + @Override + protected void bindRetryHandlers() { + // TODO + } + +} diff --git a/sandbox/elastichosts/src/main/java/org/jclouds/cloudsigma/domain/DriveInfo.java b/sandbox/elastichosts/src/main/java/org/jclouds/cloudsigma/domain/DriveInfo.java new file mode 100644 index 0000000000..797989c999 --- /dev/null +++ b/sandbox/elastichosts/src/main/java/org/jclouds/cloudsigma/domain/DriveInfo.java @@ -0,0 +1,415 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.cloudsigma.domain; + +import static com.google.common.base.Preconditions.checkNotNull; + +import java.net.URI; +import java.util.Map; +import java.util.Set; + +import org.jclouds.elastichosts.domain.ClaimType; +import org.jclouds.elastichosts.domain.DriveStatus; + +import com.google.common.collect.ImmutableSet; + +/** + * + * @author Adrian Cole + */ +public class DriveInfo extends org.jclouds.elastichosts.domain.DriveInfo { + public static class Builder extends org.jclouds.elastichosts.domain.DriveInfo.Builder { + private Boolean autoexpanding; + private Integer bits; + private String description; + private Set driveType = ImmutableSet.of(); + private String encryptionKey; + private Boolean free; + private String installNotes; + private String os; + private DriveType type; + private URI url; + + public Builder autoexpanding(Boolean autoexpanding) { + this.autoexpanding = autoexpanding; + return this; + } + + public Builder bits(Integer bits) { + this.bits = bits; + return this; + } + + public Builder description(String description) { + this.description = description; + return this; + } + + public Builder driveType(Iterable driveType) { + this.driveType = ImmutableSet.copyOf(checkNotNull(driveType, "driveType")); + return this; + } + + public Builder encryptionKey(String encryptionKey) { + this.encryptionKey = encryptionKey; + return this; + } + + public Builder free(Boolean free) { + this.free = free; + return this; + } + + public Builder installNotes(String installNotes) { + this.installNotes = installNotes; + return this; + } + + public Builder os(String os) { + this.os = os; + return this; + } + + public Builder type(DriveType type) { + this.type = type; + return this; + } + + public Builder url(URI url) { + this.url = url; + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public Builder status(DriveStatus status) { + return Builder.class.cast(super.status(status)); + } + + /** + * {@inheritDoc} + */ + @Override + public Builder user(String user) { + return Builder.class.cast(super.user(user)); + } + + /** + * {@inheritDoc} + */ + @Override + public Builder claimed(Iterable claimed) { + return Builder.class.cast(super.claimed(claimed)); + } + + /** + * {@inheritDoc} + */ + @Override + public Builder imaging(String imaging) { + return Builder.class.cast(super.imaging(imaging)); + } + + /** + * {@inheritDoc} + */ + @Override + public Builder readBytes(long readBytes) { + return Builder.class.cast(super.readBytes(readBytes)); + } + + /** + * {@inheritDoc} + */ + @Override + public Builder readRequests(long readRequests) { + return Builder.class.cast(super.readRequests(readRequests)); + } + + /** + * {@inheritDoc} + */ + @Override + public Builder writeBytes(long writeBytes) { + return Builder.class.cast(super.writeBytes(writeBytes)); + } + + /** + * {@inheritDoc} + */ + @Override + public Builder writeRequests(long writeRequests) { + return Builder.class.cast(super.writeRequests(writeRequests)); + } + + /** + * {@inheritDoc} + */ + @Override + public Builder encryptionCipher(String encryptionCipher) { + return Builder.class.cast(super.encryptionCipher(encryptionCipher)); + } + + /** + * {@inheritDoc} + */ + @Override + public Builder claimType(ClaimType claimType) { + return Builder.class.cast(super.claimType(claimType)); + } + + /** + * {@inheritDoc} + */ + @Override + public Builder readers(Iterable readers) { + return Builder.class.cast(super.readers(readers)); + } + + /** + * {@inheritDoc} + */ + @Override + public Builder size(long size) { + return Builder.class.cast(super.size(size)); + } + + /** + * {@inheritDoc} + */ + @Override + public Builder uuid(String uuid) { + return Builder.class.cast(super.uuid(uuid)); + } + + /** + * {@inheritDoc} + */ + @Override + public Builder name(String name) { + return Builder.class.cast(super.name(name)); + } + + /** + * {@inheritDoc} + */ + @Override + public Builder tags(Iterable tags) { + return Builder.class.cast(super.tags(tags)); + } + + /** + * {@inheritDoc} + */ + @Override + public Builder userMetadata(Map userMetadata) { + return Builder.class.cast(super.userMetadata(userMetadata)); + } + + public static Builder fromDriveInfo(org.jclouds.elastichosts.domain.DriveInfo driveInfo) { + return new Builder().uuid(driveInfo.getUuid()).name(driveInfo.getName()).size(driveInfo.getSize()) + .claimType(driveInfo.getClaimType()).readers(driveInfo.getReaders()).tags(driveInfo.getTags()) + .userMetadata(driveInfo.getUserMetadata()).status(driveInfo.getStatus()).user(driveInfo.getUser()) + .claimed(driveInfo.getClaimed()).encryptionCipher(driveInfo.getEncryptionCipher()) + .imaging(driveInfo.getImaging()).readBytes(driveInfo.getReadBytes()) + .readRequests(driveInfo.getReadRequests()).writeBytes(driveInfo.getWriteBytes()) + .writeRequests(driveInfo.getWriteRequests()); + } + + /** + * {@inheritDoc} + */ + @Override + public DriveInfo build() { + return new DriveInfo(uuid, name, size, claimType, readers, tags, userMetadata, status, user, claimed, + encryptionCipher, imaging, readBytes, readRequests, writeBytes, writeRequests, autoexpanding, bits, + description, driveType, encryptionKey, free, installNotes, os, type, url); + } + } + + private final Boolean autoexpanding; + private final Integer bits; + private final String description; + private final ImmutableSet driveType; + private final String encryptionKey; + private final Boolean free; + private final String installNotes; + private final String os; + private final DriveType type; + private final URI url; + + public DriveInfo(String uuid, String name, long size, ClaimType claimType, Iterable readers, + Iterable tags, Map userMetadata, DriveStatus status, String user, Set claimed, + String encryptionCipher, String imaging, long readBytes, long readRequests, long writeBytes, + long writeRequests, Boolean autoexpanding, Integer bits, String description, Iterable driveType, + String encryptionKey, Boolean free, String installNotes, String os, DriveType type, URI url) { + super(uuid, name, size, claimType, readers, tags, userMetadata, status, user, claimed, encryptionCipher, imaging, + readBytes, readRequests, writeBytes, writeRequests); + this.autoexpanding = autoexpanding; + this.bits = bits; + this.description = description; + this.driveType = ImmutableSet.copyOf(driveType); + this.encryptionKey = encryptionKey; + this.free = free; + this.installNotes = installNotes; + this.os = os; + this.type = type; + this.url = url; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = super.hashCode(); + result = prime * result + ((autoexpanding == null) ? 0 : autoexpanding.hashCode()); + result = prime * result + ((bits == null) ? 0 : bits.hashCode()); + result = prime * result + ((description == null) ? 0 : description.hashCode()); + result = prime * result + ((driveType == null) ? 0 : driveType.hashCode()); + result = prime * result + ((encryptionKey == null) ? 0 : encryptionKey.hashCode()); + result = prime * result + ((free == null) ? 0 : free.hashCode()); + result = prime * result + ((installNotes == null) ? 0 : installNotes.hashCode()); + result = prime * result + ((os == null) ? 0 : os.hashCode()); + result = prime * result + ((type == null) ? 0 : type.hashCode()); + result = prime * result + ((url == null) ? 0 : url.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (!super.equals(obj)) + return false; + if (getClass() != obj.getClass()) + return false; + DriveInfo other = (DriveInfo) obj; + if (autoexpanding == null) { + if (other.autoexpanding != null) + return false; + } else if (!autoexpanding.equals(other.autoexpanding)) + return false; + if (bits == null) { + if (other.bits != null) + return false; + } else if (!bits.equals(other.bits)) + return false; + if (description == null) { + if (other.description != null) + return false; + } else if (!description.equals(other.description)) + return false; + if (driveType == null) { + if (other.driveType != null) + return false; + } else if (!driveType.equals(other.driveType)) + return false; + if (encryptionKey == null) { + if (other.encryptionKey != null) + return false; + } else if (!encryptionKey.equals(other.encryptionKey)) + return false; + if (free == null) { + if (other.free != null) + return false; + } else if (!free.equals(other.free)) + return false; + if (installNotes == null) { + if (other.installNotes != null) + return false; + } else if (!installNotes.equals(other.installNotes)) + return false; + if (os == null) { + if (other.os != null) + return false; + } else if (!os.equals(other.os)) + return false; + if (type != other.type) + return false; + if (url == null) { + if (other.url != null) + return false; + } else if (!url.equals(other.url)) + return false; + return true; + } + + // TODO + public Boolean getAutoexpanding() { + return autoexpanding; + } + + // TODO + public Integer getBits() { + return bits; + } + + // TODO undocumented + public String getDescription() { + return description; + } + + // TODO + public Set getDriveType() { + return driveType; + } + + // TODO + public String getEncryptionKey() { + return encryptionKey; + } + + // TODO + public Boolean getFree() { + return free; + } + + // TODO + public String getInstallNotes() { + return installNotes; + } + + // TODO + public String getOs() { + return os; + } + + // TODO + public DriveType getType() { + return type; + } + + // TODO + + @Override + public String toString() { + return "[size=" + size + ", claimType=" + claimType + ", readers=" + readers + ", uuid=" + uuid + ", name=" + + name + ", tags=" + tags + ", userMetadata=" + userMetadata + ", autoexpanding=" + autoexpanding + + ", bits=" + bits + ", description=" + description + ", driveType=" + driveType + ", encryptionKey=" + + encryptionKey + ", free=" + free + ", installNotes=" + installNotes + ", os=" + os + ", type=" + type + + ", url=" + url + "]"; + } + + public URI getUrl() { + return url; + } + +} \ No newline at end of file diff --git a/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/domain/DriveType.java b/sandbox/elastichosts/src/main/java/org/jclouds/cloudsigma/domain/DriveType.java similarity index 96% rename from sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/domain/DriveType.java rename to sandbox/elastichosts/src/main/java/org/jclouds/cloudsigma/domain/DriveType.java index cb0cdced08..528320ddd7 100644 --- a/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/domain/DriveType.java +++ b/sandbox/elastichosts/src/main/java/org/jclouds/cloudsigma/domain/DriveType.java @@ -17,7 +17,7 @@ * ==================================================================== */ -package org.jclouds.elastichosts.domain; +package org.jclouds.cloudsigma.domain; import static com.google.common.base.Preconditions.checkNotNull; diff --git a/sandbox/elastichosts/src/main/java/org/jclouds/cloudsigma/functions/CreateDriveRequestToMap.java b/sandbox/elastichosts/src/main/java/org/jclouds/cloudsigma/functions/CreateDriveRequestToMap.java new file mode 100644 index 0000000000..da1dd353ae --- /dev/null +++ b/sandbox/elastichosts/src/main/java/org/jclouds/cloudsigma/functions/CreateDriveRequestToMap.java @@ -0,0 +1,58 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.cloudsigma.functions; + +import static org.jclouds.util.Utils.renameKey; + +import java.util.Map; + +import javax.inject.Inject; +import javax.inject.Singleton; + +import org.jclouds.elastichosts.domain.CreateDriveRequest; + +import com.google.common.base.Function; +import com.google.common.collect.Maps; + +/** + * + * @author Adrian Cole + */ +@Singleton +public class CreateDriveRequestToMap implements Function> { + private final org.jclouds.elastichosts.functions.CreateDriveRequestToMap baseDriveToMap; + + @Inject + public CreateDriveRequestToMap(org.jclouds.elastichosts.functions.CreateDriveRequestToMap baseDriveToMap) { + this.baseDriveToMap = baseDriveToMap; + } + + @Override + public Map apply(CreateDriveRequest from) { + return Maps.transformEntries(renameKey(baseDriveToMap.apply(from), "tags", "use"), + new Maps.EntryTransformer() { + + @Override + public String transformEntry(String arg0, String arg1) { + return "use".equals(arg0) ? arg1.replace(' ', ',') : arg1; + } + + }); } +} \ No newline at end of file diff --git a/sandbox/elastichosts/src/main/java/org/jclouds/cloudsigma/functions/DriveDataToMap.java b/sandbox/elastichosts/src/main/java/org/jclouds/cloudsigma/functions/DriveDataToMap.java new file mode 100644 index 0000000000..a85395d637 --- /dev/null +++ b/sandbox/elastichosts/src/main/java/org/jclouds/cloudsigma/functions/DriveDataToMap.java @@ -0,0 +1,59 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.cloudsigma.functions; + +import static org.jclouds.util.Utils.renameKey; + +import java.util.Map; + +import javax.inject.Inject; +import javax.inject.Singleton; + +import org.jclouds.elastichosts.domain.DriveData; + +import com.google.common.base.Function; +import com.google.common.collect.Maps; + +/** + * + * @author Adrian Cole + */ +@Singleton +public class DriveDataToMap implements Function> { + private final org.jclouds.elastichosts.functions.DriveDataToMap baseDriveToMap; + + @Inject + public DriveDataToMap(org.jclouds.elastichosts.functions.DriveDataToMap baseDriveToMap) { + this.baseDriveToMap = baseDriveToMap; + } + + @Override + public Map apply(DriveData from) { + return Maps.transformEntries(renameKey(baseDriveToMap.apply(from), "tags", "use"), + new Maps.EntryTransformer() { + + @Override + public String transformEntry(String arg0, String arg1) { + return "use".equals(arg0) ? arg1.replace(' ', ',') : arg1; + } + + }); + } +} \ No newline at end of file diff --git a/sandbox/elastichosts/src/main/java/org/jclouds/cloudsigma/functions/KeyValuesDelimitedByBlankLinesToDriveInfo.java b/sandbox/elastichosts/src/main/java/org/jclouds/cloudsigma/functions/KeyValuesDelimitedByBlankLinesToDriveInfo.java new file mode 100644 index 0000000000..3f9cf3912c --- /dev/null +++ b/sandbox/elastichosts/src/main/java/org/jclouds/cloudsigma/functions/KeyValuesDelimitedByBlankLinesToDriveInfo.java @@ -0,0 +1,53 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.cloudsigma.functions; + +import java.util.Set; + +import javax.inject.Inject; +import javax.inject.Singleton; + +import org.jclouds.cloudsigma.domain.DriveInfo; +import org.jclouds.http.HttpResponse; + +import com.google.common.base.Function; +import com.google.common.collect.Iterables; + +/** + * + * @author Adrian Cole + */ +@Singleton +public class KeyValuesDelimitedByBlankLinesToDriveInfo implements Function { + private final ListOfKeyValuesDelimitedByBlankLinesToDriveInfoSet setParser; + + @Inject + public KeyValuesDelimitedByBlankLinesToDriveInfo(ListOfKeyValuesDelimitedByBlankLinesToDriveInfoSet setParser) { + this.setParser = setParser; + } + + @Override + public DriveInfo apply(HttpResponse response) { + Set drives = setParser.apply(response); + if (drives.size() == 0) + return null; + return Iterables.get(drives, 0); + } +} \ No newline at end of file diff --git a/sandbox/elastichosts/src/main/java/org/jclouds/cloudsigma/functions/ListOfKeyValuesDelimitedByBlankLinesToDriveInfoSet.java b/sandbox/elastichosts/src/main/java/org/jclouds/cloudsigma/functions/ListOfKeyValuesDelimitedByBlankLinesToDriveInfoSet.java new file mode 100644 index 0000000000..6c56045561 --- /dev/null +++ b/sandbox/elastichosts/src/main/java/org/jclouds/cloudsigma/functions/ListOfKeyValuesDelimitedByBlankLinesToDriveInfoSet.java @@ -0,0 +1,61 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.cloudsigma.functions; + +import java.util.Set; + +import javax.inject.Inject; +import javax.inject.Singleton; + +import org.jclouds.cloudsigma.domain.DriveInfo; +import org.jclouds.elastichosts.functions.ListOfKeyValuesDelimitedByBlankLinesToListOfMaps; +import org.jclouds.http.HttpResponse; +import org.jclouds.http.functions.ReturnStringIf2xx; + +import com.google.common.base.Function; +import com.google.common.collect.ImmutableSet; +import com.google.common.collect.Iterables; + +/** + * + * @author Adrian Cole + */ +@Singleton +public class ListOfKeyValuesDelimitedByBlankLinesToDriveInfoSet implements Function> { + private final ReturnStringIf2xx returnStringIf200; + private final ListOfKeyValuesDelimitedByBlankLinesToListOfMaps mapConverter; + private final MapToDriveInfo mapToDrive; + + @Inject + ListOfKeyValuesDelimitedByBlankLinesToDriveInfoSet(ReturnStringIf2xx returnStringIf200, + ListOfKeyValuesDelimitedByBlankLinesToListOfMaps mapConverter, MapToDriveInfo mapToDrive) { + this.returnStringIf200 = returnStringIf200; + this.mapConverter = mapConverter; + this.mapToDrive = mapToDrive; + } + + @Override + public Set apply(HttpResponse response) { + String text = returnStringIf200.apply(response); + if (text == null || text.trim().equals("")) + return ImmutableSet. of(); + return ImmutableSet.copyOf(Iterables.transform(mapConverter.apply(text), mapToDrive)); + } +} \ No newline at end of file diff --git a/sandbox/elastichosts/src/main/java/org/jclouds/cloudsigma/functions/MapToDriveInfo.java b/sandbox/elastichosts/src/main/java/org/jclouds/cloudsigma/functions/MapToDriveInfo.java new file mode 100644 index 0000000000..b9074d3d26 --- /dev/null +++ b/sandbox/elastichosts/src/main/java/org/jclouds/cloudsigma/functions/MapToDriveInfo.java @@ -0,0 +1,72 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.cloudsigma.functions; + +import java.net.URI; +import java.util.Map; + +import javax.inject.Inject; +import javax.inject.Singleton; + +import org.jclouds.cloudsigma.domain.DriveInfo; +import org.jclouds.cloudsigma.domain.DriveType; + +import com.google.common.base.Function; +import com.google.common.base.Splitter; + +/** + * + * @author Adrian Cole + */ +@Singleton +public class MapToDriveInfo implements Function, DriveInfo> { + private final org.jclouds.elastichosts.functions.MapToDriveInfo mapToDriveInfo; + + @Inject + public MapToDriveInfo(org.jclouds.elastichosts.functions.MapToDriveInfo mapToDriveInfo) { + this.mapToDriveInfo = mapToDriveInfo; + } + + @Override + public DriveInfo apply(Map from) { + if (from.size() == 0) + return null; + DriveInfo.Builder builder = DriveInfo.Builder.fromDriveInfo(mapToDriveInfo.apply(from)); + if (from.containsKey("use")) + builder.tags(Splitter.on(',').split(from.get("use"))); + if (from.containsKey("bits")) + builder.bits(new Integer(from.get("bits"))); + if (from.containsKey("url")) + builder.url(URI.create(from.get("url"))); + builder.encryptionKey(from.get("encryption:key")); + builder.description(from.get("description")); + builder.installNotes(from.get("install_notes")); + builder.os(from.get("os")); + if (from.containsKey("drive_type")) + builder.driveType(Splitter.on(',').split(from.get("drive_type"))); + if (from.containsKey("autoexpanding")) + builder.autoexpanding(new Boolean(from.get("autoexpanding"))); + if (from.containsKey("free")) + builder.free(new Boolean(from.get("free"))); + if (from.containsKey("type")) + builder.type(DriveType.fromValue(from.get("type"))); + return builder.build(); + } +} \ No newline at end of file diff --git a/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/CommonElasticHostsAsyncClient.java b/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/CommonElasticHostsAsyncClient.java new file mode 100644 index 0000000000..1a597533a9 --- /dev/null +++ b/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/CommonElasticHostsAsyncClient.java @@ -0,0 +1,114 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.elastichosts; + +import java.util.Set; + +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.core.MediaType; + +import org.jclouds.elastichosts.binders.BindCreateDriveRequestToPlainTextString; +import org.jclouds.elastichosts.binders.BindDriveDataToPlainTextString; +import org.jclouds.elastichosts.domain.CreateDriveRequest; +import org.jclouds.elastichosts.domain.DriveData; +import org.jclouds.elastichosts.domain.DriveInfo; +import org.jclouds.elastichosts.functions.KeyValuesDelimitedByBlankLinesToDriveInfo; +import org.jclouds.elastichosts.functions.ListOfKeyValuesDelimitedByBlankLinesToDriveInfoSet; +import org.jclouds.elastichosts.functions.SplitNewlines; +import org.jclouds.http.filters.BasicAuthentication; +import org.jclouds.rest.annotations.BinderParam; +import org.jclouds.rest.annotations.ExceptionParser; +import org.jclouds.rest.annotations.RequestFilters; +import org.jclouds.rest.annotations.ResponseParser; +import org.jclouds.rest.functions.ReturnNullOnNotFoundOr404; +import org.jclouds.rest.functions.ReturnVoidOnNotFoundOr404; + +import com.google.common.util.concurrent.ListenableFuture; + +/** + * Provides asynchronous access to ElasticHosts via their REST API. + *

+ * + * @see ElasticHostsClient + * @see + * @author Adrian Cole + */ +@RequestFilters(BasicAuthentication.class) +@Consumes(MediaType.TEXT_PLAIN) +public interface CommonElasticHostsAsyncClient { + + /** + * @see ElasticHostsClient#listDrives() + */ + @GET + @Path("/drives/list") + @ResponseParser(SplitNewlines.class) + ListenableFuture> listDrives(); + + /** + * @see ElasticHostsClient#listDriveInfo() + */ + @GET + @Path("/drives/info") + @ResponseParser(ListOfKeyValuesDelimitedByBlankLinesToDriveInfoSet.class) + ListenableFuture> listDriveInfo(); + + /** + * @see ElasticHostsClient#getDriveInfo + */ + @GET + @ExceptionParser(ReturnNullOnNotFoundOr404.class) + @ResponseParser(KeyValuesDelimitedByBlankLinesToDriveInfo.class) + @Path("/drives/{uuid}/info") + ListenableFuture getDriveInfo(@PathParam("uuid") String uuid); + + /** + * @see ElasticHostsClient#createDrive + */ + @POST + @ExceptionParser(ReturnNullOnNotFoundOr404.class) + @ResponseParser(KeyValuesDelimitedByBlankLinesToDriveInfo.class) + @Path("/drives/create") + ListenableFuture createDrive( + @BinderParam(BindCreateDriveRequestToPlainTextString.class) CreateDriveRequest createDrive); + + /** + * @see ElasticHostsClient#setDriveData + */ + @POST + @ExceptionParser(ReturnNullOnNotFoundOr404.class) + @ResponseParser(KeyValuesDelimitedByBlankLinesToDriveInfo.class) + @Path("/drives/{uuid}/set") + ListenableFuture setDriveData(@PathParam("uuid") String uuid, + @BinderParam(BindDriveDataToPlainTextString.class) DriveData createDrive); + + /** + * @see ElasticHostsClient#destroyDrive + */ + @POST + @Path("/drives/{uuid}/destroy") + @ExceptionParser(ReturnVoidOnNotFoundOr404.class) + ListenableFuture destroyDrive(@PathParam("uuid") String uuid); + +} diff --git a/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/CommonElasticHostsClient.java b/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/CommonElasticHostsClient.java new file mode 100644 index 0000000000..940818591d --- /dev/null +++ b/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/CommonElasticHostsClient.java @@ -0,0 +1,90 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.elastichosts; + +import java.util.Set; +import java.util.concurrent.TimeUnit; + +import org.jclouds.concurrent.Timeout; +import org.jclouds.elastichosts.domain.CreateDriveRequest; +import org.jclouds.elastichosts.domain.DriveData; +import org.jclouds.elastichosts.domain.DriveInfo; + +/** + * Provides synchronous access to ElasticHosts. + *

+ * + * @see ElasticHostsAsyncClient + * @see + * @author Adrian Cole + */ +@Timeout(duration = 60, timeUnit = TimeUnit.SECONDS) +public interface CommonElasticHostsClient { + /** + * list of drive uuids in your account + * + * @return or empty set if no drives are found + */ + Set listDrives(); + + /** + * Get all drives info + * + * @return or empty set if no drives are found + */ + Set listDriveInfo(); + + /** + * @param uuid + * what to get + * @return null, if not found + */ + DriveInfo getDriveInfo(String uuid); + + /** + * create a new drive + * + * @param createDrive + * required parameters: name, size + * @return newly created drive + */ + DriveInfo createDrive(CreateDriveRequest createDrive); + + /** + * set extra drive data + * + * @param uuid + * what drive to change + * @param driveData + * what values to change + * @return new data + */ + DriveInfo setDriveData(String uuid, DriveData driveData); + + /** + * Destroy a drive + * + * @param uuid + * what to delete + */ + void destroyDrive(String uuid); + + +} diff --git a/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/ElasticHostsAsyncClient.java b/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/ElasticHostsAsyncClient.java index b41c5dbd89..211b25b448 100644 --- a/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/ElasticHostsAsyncClient.java +++ b/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/ElasticHostsAsyncClient.java @@ -19,8 +19,6 @@ package org.jclouds.elastichosts; -import java.util.Set; - import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.POST; @@ -29,17 +27,9 @@ import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; -import org.jclouds.elastichosts.binders.BindCreateDriveRequestToPlainTextString; -import org.jclouds.elastichosts.binders.BindDriveDataToPlainTextString; import org.jclouds.elastichosts.binders.BindReadDriveOptionsToPath; -import org.jclouds.elastichosts.domain.CreateDriveRequest; -import org.jclouds.elastichosts.domain.DriveData; -import org.jclouds.elastichosts.domain.DriveInfo; import org.jclouds.elastichosts.domain.ImageConversionType; -import org.jclouds.elastichosts.functions.KeyValuesDelimitedByBlankLinesToDriveInfo; -import org.jclouds.elastichosts.functions.ListOfKeyValuesDelimitedByBlankLinesToDriveInfoSet; import org.jclouds.elastichosts.functions.ReturnPayload; -import org.jclouds.elastichosts.functions.SplitNewlines; import org.jclouds.elastichosts.options.ReadDriveOptions; import org.jclouds.http.filters.BasicAuthentication; import org.jclouds.io.Payload; @@ -62,84 +52,7 @@ import com.google.common.util.concurrent.ListenableFuture; */ @RequestFilters(BasicAuthentication.class) @Consumes(MediaType.TEXT_PLAIN) -public interface ElasticHostsAsyncClient { - - /** - * @see ElasticHostsClient#listDrives() - */ - @GET - @Path("/drives/list") - @ResponseParser(SplitNewlines.class) - ListenableFuture> listDrives(); - - /** - * @see ElasticHostsClient#listStandardDrives() - */ - @GET - @Path("/drives/standard/list") - @ResponseParser(SplitNewlines.class) - ListenableFuture> listStandardDrives(); - - /** - * @see ElasticHostsClient#listStandardCds() - */ - @GET - @Path("/drives/standard/cd/list") - @ResponseParser(SplitNewlines.class) - ListenableFuture> listStandardCds(); - - /** - * @see ElasticHostsClient#listStandardImages() - */ - @GET - @Path("/drives/standard/img/list") - @ResponseParser(SplitNewlines.class) - ListenableFuture> listStandardImages(); - - /** - * @see ElasticHostsClient#listDriveInfo() - */ - @GET - @Path("/drives/info") - @ResponseParser(ListOfKeyValuesDelimitedByBlankLinesToDriveInfoSet.class) - ListenableFuture> listDriveInfo(); - - /** - * @see ElasticHostsClient#getDriveInfo - */ - @GET - @ExceptionParser(ReturnNullOnNotFoundOr404.class) - @ResponseParser(KeyValuesDelimitedByBlankLinesToDriveInfo.class) - @Path("/drives/{uuid}/info") - ListenableFuture getDriveInfo(@PathParam("uuid") String uuid); - - /** - * @see ElasticHostsClient#createDrive - */ - @POST - @ExceptionParser(ReturnNullOnNotFoundOr404.class) - @ResponseParser(KeyValuesDelimitedByBlankLinesToDriveInfo.class) - @Path("/drives/create") - ListenableFuture createDrive( - @BinderParam(BindCreateDriveRequestToPlainTextString.class) CreateDriveRequest createDrive); - - /** - * @see ElasticHostsClient#setDriveData - */ - @POST - @ExceptionParser(ReturnNullOnNotFoundOr404.class) - @ResponseParser(KeyValuesDelimitedByBlankLinesToDriveInfo.class) - @Path("/drives/{uuid}/set") - ListenableFuture setDriveData(@PathParam("uuid") String uuid, - @BinderParam(BindDriveDataToPlainTextString.class) DriveData createDrive); - - /** - * @see ElasticHostsClient#destroyDrive - */ - @POST - @Path("/drives/{uuid}/destroy") - @ExceptionParser(ReturnVoidOnNotFoundOr404.class) - ListenableFuture destroyDrive(@PathParam("uuid") String uuid); +public interface ElasticHostsAsyncClient extends CommonElasticHostsAsyncClient { /** * @see ElasticHostsClient#imageDrive(String,String) diff --git a/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/ElasticHostsClient.java b/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/ElasticHostsClient.java index 9c1d964254..9f5fa3df91 100644 --- a/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/ElasticHostsClient.java +++ b/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/ElasticHostsClient.java @@ -19,13 +19,9 @@ package org.jclouds.elastichosts; -import java.util.Set; import java.util.concurrent.TimeUnit; import org.jclouds.concurrent.Timeout; -import org.jclouds.elastichosts.domain.CreateDriveRequest; -import org.jclouds.elastichosts.domain.DriveData; -import org.jclouds.elastichosts.domain.DriveInfo; import org.jclouds.elastichosts.domain.ImageConversionType; import org.jclouds.elastichosts.options.ReadDriveOptions; import org.jclouds.io.Payload; @@ -38,77 +34,8 @@ import org.jclouds.io.Payload; * @see * @author Adrian Cole */ -@Timeout(duration = 30, timeUnit = TimeUnit.SECONDS) -public interface ElasticHostsClient { - /** - * list of drive uuids in your account - * - * @return or empty set if no drives are found - */ - Set listDrives(); - - /** - * list of drive uuids that are in the library - * - * @return or empty set if no drives are found - */ - Set listStandardDrives(); - - /** - * list of cd uuids that are in the library - * - * @return or empty set if no cds are found - */ - Set listStandardCds(); - - /** - * list of image uuids that are in the library - * - * @return or empty set if no images are found - */ - Set listStandardImages(); - - /** - * Get all drives info - * - * @return or empty set if no drives are found - */ - Set listDriveInfo(); - - /** - * @param uuid - * what to get - * @return null, if not found - */ - DriveInfo getDriveInfo(String uuid); - - /** - * create a new drive - * - * @param createDrive - * required parameters: name, size - * @return newly created drive - */ - DriveInfo createDrive(CreateDriveRequest createDrive); - - /** - * set extra drive data - * - * @param uuid - * what drive to change - * @param driveData - * what values to change - * @return new data - */ - DriveInfo setDriveData(String uuid, DriveData driveData); - - /** - * Destroy a drive - * - * @param uuid - * what to delete - */ - void destroyDrive(String uuid); +@Timeout(duration = 60, timeUnit = TimeUnit.SECONDS) +public interface ElasticHostsClient extends CommonElasticHostsClient { /** * Image a drive from another drive. The actual imaging process is asynchronous, with progress diff --git a/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/ElasticHostsPropertiesBuilder.java b/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/ElasticHostsPropertiesBuilder.java index ead9d89ef3..19e536294d 100644 --- a/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/ElasticHostsPropertiesBuilder.java +++ b/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/ElasticHostsPropertiesBuilder.java @@ -20,7 +20,6 @@ package org.jclouds.elastichosts; import static org.jclouds.Constants.PROPERTY_API_VERSION; -import static org.jclouds.Constants.PROPERTY_ENDPOINT; import java.util.Properties; @@ -35,7 +34,6 @@ public class ElasticHostsPropertiesBuilder extends PropertiesBuilder { @Override protected Properties defaultProperties() { Properties properties = super.defaultProperties(); - properties.setProperty(PROPERTY_ENDPOINT, "https://api.elastichosts.com"); properties.setProperty(PROPERTY_API_VERSION, "1.0"); return properties; } diff --git a/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/binders/BindCreateDriveRequestToPlainTextString.java b/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/binders/BindCreateDriveRequestToPlainTextString.java index 83cb9bc2a1..f634ffa27f 100644 --- a/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/binders/BindCreateDriveRequestToPlainTextString.java +++ b/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/binders/BindCreateDriveRequestToPlainTextString.java @@ -28,11 +28,11 @@ import javax.inject.Singleton; import javax.ws.rs.core.MediaType; import org.jclouds.elastichosts.domain.CreateDriveRequest; -import org.jclouds.elastichosts.functions.CreateDriveRequestToMap; import org.jclouds.elastichosts.functions.ListOfMapsToListOfKeyValuesDelimitedByBlankLines; import org.jclouds.http.HttpRequest; import org.jclouds.rest.Binder; +import com.google.common.base.Function; import com.google.common.collect.ImmutableSet; /** @@ -41,11 +41,11 @@ import com.google.common.collect.ImmutableSet; */ @Singleton public class BindCreateDriveRequestToPlainTextString implements Binder { - private final CreateDriveRequestToMap createDriveRequestToMap; + private final Function> createDriveRequestToMap; private final ListOfMapsToListOfKeyValuesDelimitedByBlankLines listOfMapsToListOfKeyValuesDelimitedByBlankLines; @Inject - public BindCreateDriveRequestToPlainTextString(CreateDriveRequestToMap createDriveRequestToMap, + public BindCreateDriveRequestToPlainTextString(Function> createDriveRequestToMap, ListOfMapsToListOfKeyValuesDelimitedByBlankLines listOfMapsToListOfKeyValuesDelimitedByBlankLines) { this.createDriveRequestToMap = createDriveRequestToMap; this.listOfMapsToListOfKeyValuesDelimitedByBlankLines = listOfMapsToListOfKeyValuesDelimitedByBlankLines; diff --git a/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/binders/BindDriveDataToPlainTextString.java b/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/binders/BindDriveDataToPlainTextString.java index cb62e165a7..631bb8b181 100644 --- a/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/binders/BindDriveDataToPlainTextString.java +++ b/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/binders/BindDriveDataToPlainTextString.java @@ -28,11 +28,11 @@ import javax.inject.Singleton; import javax.ws.rs.core.MediaType; import org.jclouds.elastichosts.domain.DriveData; -import org.jclouds.elastichosts.functions.DriveDataToMap; import org.jclouds.elastichosts.functions.ListOfMapsToListOfKeyValuesDelimitedByBlankLines; import org.jclouds.http.HttpRequest; import org.jclouds.rest.Binder; +import com.google.common.base.Function; import com.google.common.collect.ImmutableSet; /** @@ -41,11 +41,11 @@ import com.google.common.collect.ImmutableSet; */ @Singleton public class BindDriveDataToPlainTextString implements Binder { - private final DriveDataToMap createDriveRequestToMap; + private final Function> createDriveRequestToMap; private final ListOfMapsToListOfKeyValuesDelimitedByBlankLines listOfMapsToListOfKeyValuesDelimitedByBlankLines; @Inject - public BindDriveDataToPlainTextString(DriveDataToMap createDriveRequestToMap, + public BindDriveDataToPlainTextString(Function> createDriveRequestToMap, ListOfMapsToListOfKeyValuesDelimitedByBlankLines listOfMapsToListOfKeyValuesDelimitedByBlankLines) { this.createDriveRequestToMap = createDriveRequestToMap; this.listOfMapsToListOfKeyValuesDelimitedByBlankLines = listOfMapsToListOfKeyValuesDelimitedByBlankLines; diff --git a/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/config/ElasticHostsRestClientModule.java b/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/config/ElasticHostsRestClientModule.java index e5f91ad7d1..129ae9d2c0 100644 --- a/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/config/ElasticHostsRestClientModule.java +++ b/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/config/ElasticHostsRestClientModule.java @@ -19,8 +19,14 @@ package org.jclouds.elastichosts.config; +import java.util.Map; + import org.jclouds.elastichosts.ElasticHostsAsyncClient; import org.jclouds.elastichosts.ElasticHostsClient; +import org.jclouds.elastichosts.domain.CreateDriveRequest; +import org.jclouds.elastichosts.domain.DriveData; +import org.jclouds.elastichosts.functions.CreateDriveRequestToMap; +import org.jclouds.elastichosts.functions.DriveDataToMap; import org.jclouds.elastichosts.handlers.ElasticHostsErrorHandler; import org.jclouds.http.HttpErrorHandler; import org.jclouds.http.RequiresHttp; @@ -30,6 +36,9 @@ import org.jclouds.http.annotation.ServerError; import org.jclouds.rest.ConfiguresRestClient; import org.jclouds.rest.config.RestClientModule; +import com.google.common.base.Function; +import com.google.inject.TypeLiteral; + /** * Configures the ElasticHosts connection. * @@ -37,13 +46,21 @@ import org.jclouds.rest.config.RestClientModule; */ @RequiresHttp @ConfiguresRestClient -public class ElasticHostsRestClientModule extends - RestClientModule { +public class ElasticHostsRestClientModule extends RestClientModule { public ElasticHostsRestClientModule() { super(ElasticHostsClient.class, ElasticHostsAsyncClient.class); } + @Override + protected void configure() { + super.configure(); + bind(new TypeLiteral>>() { + }).to(CreateDriveRequestToMap.class); + bind(new TypeLiteral>>() { + }).to(DriveDataToMap.class); + } + @Override protected void bindErrorHandlers() { bind(HttpErrorHandler.class).annotatedWith(Redirection.class).to(ElasticHostsErrorHandler.class); diff --git a/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/domain/DriveInfo.java b/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/domain/DriveInfo.java index 2706b3e725..d755dbe1fe 100644 --- a/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/domain/DriveInfo.java +++ b/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/domain/DriveInfo.java @@ -21,7 +21,6 @@ package org.jclouds.elastichosts.domain; import static com.google.common.base.Preconditions.checkNotNull; -import java.net.URI; import java.util.Map; import java.util.Set; @@ -37,26 +36,18 @@ import com.google.common.collect.ImmutableSet; */ public class DriveInfo extends BaseDrive { public static class Builder extends BaseDrive.Builder { - private DriveStatus status; - private String user; - private Boolean autoexpanding; - private Integer bits; - private Set claimed = ImmutableSet.of(); - private String encryptionCipher; - private String description; - private Set driveType = ImmutableSet.of(); - private String encryptionKey; - private Boolean free; - private String imaging; - private String installNotes; - private String os; - private Long readBytes; - private Long readRequests; - private DriveType type; - private URI url; - private Set use = ImmutableSet.of(); - private Long writeBytes; - private Long writeRequests; + + protected DriveStatus status; + protected String user; + protected Set claimed = ImmutableSet.of(); + @Nullable + protected String encryptionCipher; + @Nullable + protected String imaging; + protected long readBytes; + protected long readRequests; + protected long writeBytes; + protected long writeRequests; public Builder status(DriveStatus status) { this.status = status; @@ -68,91 +59,41 @@ public class DriveInfo extends BaseDrive { return this; } - public Builder autoexpanding(Boolean autoexpanding) { - this.autoexpanding = autoexpanding; - return this; - } - - public Builder bits(Integer bits) { - this.bits = bits; - return this; - } - public Builder claimed(Iterable claimed) { this.claimed = ImmutableSet.copyOf(checkNotNull(claimed, "claimed")); return this; } - public Builder description(String description) { - this.description = description; - return this; - } - - public Builder driveType(Iterable driveType) { - this.driveType = ImmutableSet.copyOf(checkNotNull(driveType, "driveType")); - return this; - } - - public Builder encryptionKey(String encryptionKey) { - this.encryptionKey = encryptionKey; - return this; - } - - public Builder free(Boolean free) { - this.free = free; - return this; - } - public Builder imaging(String imaging) { this.imaging = imaging; return this; } - public Builder installNotes(String installNotes) { - this.installNotes = installNotes; - return this; - } - - public Builder os(String os) { - this.os = os; - return this; - } - - public Builder readBytes(Long readBytes) { + public Builder readBytes(long readBytes) { this.readBytes = readBytes; return this; } - public Builder readRequests(Long readRequests) { + public Builder readRequests(long readRequests) { this.readRequests = readRequests; return this; } - public Builder type(DriveType type) { - this.type = type; - return this; - } - - public Builder url(URI url) { - this.url = url; - return this; - } - - public Builder use(Iterable use) { - this.use = ImmutableSet.copyOf(checkNotNull(use, "use")); - return this; - } - - public Builder writeBytes(Long writeBytes) { + public Builder writeBytes(long writeBytes) { this.writeBytes = writeBytes; return this; } - public Builder writeRequests(Long writeRequests) { + public Builder writeRequests(long writeRequests) { this.writeRequests = writeRequests; return this; } + public Builder encryptionCipher(String encryptionCipher) { + this.encryptionCipher = encryptionCipher; + return this; + } + /** * {@inheritDoc} */ @@ -161,11 +102,6 @@ public class DriveInfo extends BaseDrive { return Builder.class.cast(super.claimType(claimType)); } - public Builder encryptionCipher(String encryptionCipher) { - this.encryptionCipher = encryptionCipher; - return this; - } - /** * {@inheritDoc} */ @@ -214,79 +150,50 @@ public class DriveInfo extends BaseDrive { return Builder.class.cast(super.userMetadata(userMetadata)); } + public static Builder fromDriveInfo(DriveInfo driveInfo) { + return new Builder().uuid(driveInfo.getUuid()).name(driveInfo.getName()).size(driveInfo.getSize()) + .claimType(driveInfo.getClaimType()).readers(driveInfo.getReaders()).tags(driveInfo.getTags()) + .userMetadata(driveInfo.getUserMetadata()).status(driveInfo.getStatus()).user(driveInfo.getUser()) + .claimed(driveInfo.getClaimed()).encryptionCipher(driveInfo.getEncryptionCipher()) + .imaging(driveInfo.getImaging()).readBytes(driveInfo.getReadBytes()) + .readRequests(driveInfo.getReadRequests()).writeBytes(driveInfo.getWriteBytes()) + .writeRequests(driveInfo.getWriteRequests()); + } + /** * {@inheritDoc} */ @Override public DriveInfo build() { - return new DriveInfo(status, user, autoexpanding, bits, claimed, claimType, description, uuid, driveType, - encryptionCipher, encryptionKey, free, imaging, installNotes, name, os, readers, readBytes, - readRequests, size, tags, type, url, use, userMetadata, writeBytes, writeRequests); + return new DriveInfo(uuid, name, size, claimType, readers, tags, userMetadata, status, user, claimed, + encryptionCipher, imaging, readBytes, readRequests, writeBytes, writeRequests); } + } - private final DriveStatus status; - private final String user; + protected final DriveStatus status; + protected final String user; + protected final Set claimed; @Nullable - private final Boolean autoexpanding; + protected final String encryptionCipher; @Nullable - private final Integer bits; - private final Set claimed; - @Nullable - private final String description; - @Nullable - private final Set driveType; - @Nullable - private final String encryptionCipher; - @Nullable - private final String encryptionKey; - @Nullable - private final Boolean free; - @Nullable - private final String imaging; - @Nullable - private final String installNotes; - @Nullable - private final String os; - @Nullable - private final Long readBytes; - @Nullable - private final Long readRequests; - @Nullable - private final DriveType type; - @Nullable - private final URI url; - @Nullable - private final Set use; - @Nullable - private final Long writeBytes; - @Nullable - private final Long writeRequests; + protected final String imaging; + protected final long readBytes; + protected final long readRequests; + protected final long writeBytes; + protected final long writeRequests; - public DriveInfo(DriveStatus status, String user, Boolean autoexpanding, Integer bits, Iterable claimed, - ClaimType claimType, String description, String uuid, Iterable driveType, String encryptionCipher, - String encryptionKey, Boolean free, String imaging, String installNotes, String name, String os, - Iterable readers, Long readBytes, Long readRequests, Long size, Iterable tags, DriveType type, - URI url, Iterable use, Map userMetadata, Long writeBytes, Long writeRequests) { + public DriveInfo(String uuid, String name, long size, ClaimType claimType, Iterable readers, + Iterable tags, Map userMetadata, DriveStatus status, String user, Set claimed, + String encryptionCipher, String imaging, long readBytes, long readRequests, long writeBytes, long writeRequests) { super(uuid, name, size, claimType, readers, tags, userMetadata); this.status = status; this.user = user; - this.autoexpanding = autoexpanding; - this.bits = bits; this.claimed = ImmutableSet.copyOf(claimed); - this.description = description; - this.driveType = ImmutableSet.copyOf(driveType); this.encryptionCipher = encryptionCipher; - this.encryptionKey = encryptionKey; - this.free = free; this.imaging = imaging; - this.installNotes = installNotes; - this.os = os; this.readBytes = readBytes; this.readRequests = readRequests; - this.type = type; - this.url = url; - this.use = ImmutableSet.copyOf(use); this.writeBytes = writeBytes; this.writeRequests = writeRequests; } @@ -307,16 +214,6 @@ public class DriveInfo extends BaseDrive { return user; } - // TODO - public Boolean getAutoexpanding() { - return autoexpanding; - } - - // TODO - public Integer getBits() { - return bits; - } - /** * * @return if drive is in use by a server, values are the server uuids @@ -325,16 +222,6 @@ public class DriveInfo extends BaseDrive { return claimed; } - // TODO undocumented - public String getDescription() { - return description; - } - - // TODO - public Set getDriveType() { - return driveType; - } - /** * * @return either 'none' or 'aes-xts-plain' (the default) @@ -344,16 +231,6 @@ public class DriveInfo extends BaseDrive { return encryptionCipher; } - // TODO - public String getEncryptionKey() { - return encryptionKey; - } - - // TODO - public Boolean getFree() { - return free; - } - /** * * @return percentage completed of drive imaging if this is underway, or 'queued' if waiting for @@ -363,21 +240,11 @@ public class DriveInfo extends BaseDrive { return imaging; } - // TODO - public String getInstallNotes() { - return installNotes; - } - - // TODO - public String getOs() { - return os; - } - /** * * @return Cumulative i/o byte/request count for each drive */ - public Long getReadBytes() { + public long getReadBytes() { return readBytes; } @@ -385,31 +252,15 @@ public class DriveInfo extends BaseDrive { * * @return Cumulative i/o byte/request count for each drive */ - public Long getReadRequests() { + public long getReadRequests() { return readRequests; } - // TODO - public DriveType getType() { - return type; - } - - // TODO - - public URI getUrl() { - return url; - } - - // TODO is this the same as tags? - public Set getUse() { - return use; - } - /** * * @return Cumulative i/o byte/request count for each drive */ - public Long getWriteBytes() { + public long getWriteBytes() { return writeBytes; } @@ -417,7 +268,7 @@ public class DriveInfo extends BaseDrive { * * @return Cumulative i/o byte/request count for each drive */ - public Long getWriteRequests() { + public long getWriteRequests() { return writeRequests; } @@ -425,26 +276,15 @@ public class DriveInfo extends BaseDrive { public int hashCode() { final int prime = 31; int result = super.hashCode(); - result = prime * result + ((autoexpanding == null) ? 0 : autoexpanding.hashCode()); - result = prime * result + ((bits == null) ? 0 : bits.hashCode()); result = prime * result + ((claimed == null) ? 0 : claimed.hashCode()); - result = prime * result + ((description == null) ? 0 : description.hashCode()); - result = prime * result + ((uuid == null) ? 0 : uuid.hashCode()); - result = prime * result + ((driveType == null) ? 0 : driveType.hashCode()); - result = prime * result + ((encryptionKey == null) ? 0 : encryptionKey.hashCode()); - result = prime * result + ((free == null) ? 0 : free.hashCode()); + result = prime * result + ((encryptionCipher == null) ? 0 : encryptionCipher.hashCode()); result = prime * result + ((imaging == null) ? 0 : imaging.hashCode()); - result = prime * result + ((installNotes == null) ? 0 : installNotes.hashCode()); - result = prime * result + ((os == null) ? 0 : os.hashCode()); - result = prime * result + ((readBytes == null) ? 0 : readBytes.hashCode()); - result = prime * result + ((readRequests == null) ? 0 : readRequests.hashCode()); + result = prime * result + (int) (readBytes ^ (readBytes >>> 32)); + result = prime * result + (int) (readRequests ^ (readRequests >>> 32)); result = prime * result + ((status == null) ? 0 : status.hashCode()); - result = prime * result + ((type == null) ? 0 : type.hashCode()); - result = prime * result + ((url == null) ? 0 : url.hashCode()); - result = prime * result + ((use == null) ? 0 : use.hashCode()); result = prime * result + ((user == null) ? 0 : user.hashCode()); - result = prime * result + ((writeBytes == null) ? 0 : writeBytes.hashCode()); - result = prime * result + ((writeRequests == null) ? 0 : writeRequests.hashCode()); + result = prime * result + (int) (writeBytes ^ (writeBytes >>> 32)); + result = prime * result + (int) (writeRequests ^ (writeRequests >>> 32)); return result; } @@ -457,112 +297,46 @@ public class DriveInfo extends BaseDrive { if (getClass() != obj.getClass()) return false; DriveInfo other = (DriveInfo) obj; - if (autoexpanding == null) { - if (other.autoexpanding != null) - return false; - } else if (!autoexpanding.equals(other.autoexpanding)) - return false; - if (bits == null) { - if (other.bits != null) - return false; - } else if (!bits.equals(other.bits)) - return false; if (claimed == null) { if (other.claimed != null) return false; } else if (!claimed.equals(other.claimed)) return false; - if (description == null) { - if (other.description != null) + if (encryptionCipher == null) { + if (other.encryptionCipher != null) return false; - } else if (!description.equals(other.description)) - return false; - if (uuid == null) { - if (other.uuid != null) - return false; - } else if (!uuid.equals(other.uuid)) - return false; - if (driveType == null) { - if (other.driveType != null) - return false; - } else if (!driveType.equals(other.driveType)) - return false; - if (encryptionKey == null) { - if (other.encryptionKey != null) - return false; - } else if (!encryptionKey.equals(other.encryptionKey)) - return false; - if (free == null) { - if (other.free != null) - return false; - } else if (!free.equals(other.free)) + } else if (!encryptionCipher.equals(other.encryptionCipher)) return false; if (imaging == null) { if (other.imaging != null) return false; } else if (!imaging.equals(other.imaging)) return false; - if (installNotes == null) { - if (other.installNotes != null) - return false; - } else if (!installNotes.equals(other.installNotes)) + if (readBytes != other.readBytes) return false; - if (os == null) { - if (other.os != null) - return false; - } else if (!os.equals(other.os)) - return false; - if (readBytes == null) { - if (other.readBytes != null) - return false; - } else if (!readBytes.equals(other.readBytes)) - return false; - if (readRequests == null) { - if (other.readRequests != null) - return false; - } else if (!readRequests.equals(other.readRequests)) + if (readRequests != other.readRequests) return false; if (status != other.status) return false; - if (type != other.type) - return false; - if (url == null) { - if (other.url != null) - return false; - } else if (!url.equals(other.url)) - return false; - if (use == null) { - if (other.use != null) - return false; - } else if (!use.equals(other.use)) - return false; if (user == null) { if (other.user != null) return false; } else if (!user.equals(other.user)) return false; - if (writeBytes == null) { - if (other.writeBytes != null) - return false; - } else if (!writeBytes.equals(other.writeBytes)) + if (writeBytes != other.writeBytes) return false; - if (writeRequests == null) { - if (other.writeRequests != null) - return false; - } else if (!writeRequests.equals(other.writeRequests)) + if (writeRequests != other.writeRequests) return false; return true; } @Override public String toString() { - return "[name=" + name + ", size=" + size + ", claimType=" + claimType + ", readers=" + readers + ", tags=" - + tags + ", userMetadata=" + userMetadata + ", encryptionCipher=" + encryptionCipher + ", status=" + status - + ", user=" + user + ", autoexpanding=" + autoexpanding + ", bits=" + bits + ", claimed=" + claimed - + ", description=" + description + ", drive=" + uuid + ", driveType=" + driveType + ", encryptionKey=" - + encryptionKey + ", free=" + free + ", imaging=" + imaging + ", installNotes=" + installNotes + ", os=" - + os + ", readBytes=" + readBytes + ", readRequests=" + readRequests + ", type=" + type + ", url=" + url - + ", use=" + use + ", writeBytes=" + writeBytes + ", writeRequests=" + writeRequests + "]"; + return "[size=" + size + ", claimType=" + claimType + ", readers=" + readers + ", uuid=" + uuid + ", name=" + + name + ", tags=" + tags + ", userMetadata=" + userMetadata + ", status=" + status + ", user=" + user + + ", claimed=" + claimed + ", encryptionCipher=" + encryptionCipher + ", imaging=" + imaging + + ", readBytes=" + readBytes + ", readRequests=" + readRequests + ", writeBytes=" + writeBytes + + ", writeRequests=" + writeRequests + "]"; } } \ No newline at end of file diff --git a/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/functions/MapToDriveInfo.java b/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/functions/MapToDriveInfo.java index 73660f478c..9dff9d6e0e 100644 --- a/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/functions/MapToDriveInfo.java +++ b/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/functions/MapToDriveInfo.java @@ -19,7 +19,6 @@ package org.jclouds.elastichosts.functions; -import java.net.URI; import java.util.Map; import java.util.Map.Entry; @@ -28,7 +27,6 @@ import javax.inject.Singleton; import org.jclouds.elastichosts.domain.ClaimType; import org.jclouds.elastichosts.domain.DriveInfo; import org.jclouds.elastichosts.domain.DriveStatus; -import org.jclouds.elastichosts.domain.DriveType; import com.google.common.base.Function; import com.google.common.base.Splitter; @@ -45,26 +43,18 @@ public class MapToDriveInfo implements Function, DriveInfo> if (from.size() == 0) return null; DriveInfo.Builder builder = new DriveInfo.Builder(); + builder.name(from.get("name")); + if (from.containsKey("tags")) + builder.tags(Splitter.on(' ').split(from.get("tags"))); if (from.containsKey("status")) builder.status(DriveStatus.fromValue(from.get("status"))); - if (from.containsKey("use")) - builder.use(Splitter.on(',').split(from.get("use"))); - builder.name(from.get("name")); - if (from.containsKey("bits")) - builder.bits(new Integer(from.get("bits"))); - if (from.containsKey("url")) - builder.url(URI.create(from.get("url"))); if (from.containsKey("read:bytes")) builder.readBytes(new Long(from.get("read:bytes"))); if (from.containsKey("read:requests")) builder.readRequests(new Long(from.get("read:requests"))); builder.user(from.get("user")); builder.encryptionCipher(from.get("encryption:cipher")); - builder.encryptionKey(from.get("encryption:key")); - builder.description(from.get("description")); builder.uuid(from.get("drive")); - builder.installNotes(from.get("install_notes")); - builder.os(from.get("os")); if (from.containsKey("write:bytes")) builder.writeBytes(new Long(from.get("write:bytes"))); if (from.containsKey("write:requests")) @@ -73,16 +63,8 @@ public class MapToDriveInfo implements Function, DriveInfo> builder.claimType(ClaimType.fromValue(from.get("claim:type"))); if (from.containsKey("claimed")) builder.claimed(Splitter.on(' ').split(from.get("claimed"))); - if (from.containsKey("drive_type")) - builder.driveType(Splitter.on(',').split(from.get("drive_type"))); - if (from.containsKey("autoexpanding")) - builder.autoexpanding(new Boolean(from.get("autoexpanding"))); if (from.containsKey("readers")) builder.readers(Splitter.on(' ').split(from.get("readers"))); - if (from.containsKey("free")) - builder.free(new Boolean(from.get("free"))); - if (from.containsKey("type")) - builder.type(DriveType.fromValue(from.get("type"))); if (from.containsKey("size")) builder.size(new Long(from.get("size"))); Map metadata = Maps.newLinkedHashMap(); diff --git a/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/functions/SplitNewlines.java b/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/functions/SplitNewlines.java index a9d45ec24e..b1eb47e972 100644 --- a/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/functions/SplitNewlines.java +++ b/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/functions/SplitNewlines.java @@ -19,6 +19,11 @@ package org.jclouds.elastichosts.functions; +import static com.google.common.base.Predicates.equalTo; +import static com.google.common.base.Predicates.not; +import static com.google.common.collect.Iterables.filter; +import static com.google.common.collect.Sets.newTreeSet; + import java.util.Set; import javax.inject.Inject; @@ -29,7 +34,6 @@ import org.jclouds.http.functions.ReturnStringIf2xx; import com.google.common.base.Function; import com.google.common.base.Splitter; -import com.google.common.collect.Sets; /** * @@ -46,6 +50,6 @@ public class SplitNewlines implements Function> { @Override public Set apply(HttpResponse response) { - return Sets.newTreeSet(Splitter.on('\n').split(returnStringIf200.apply(response))); + return newTreeSet(filter(Splitter.on('\n').split(returnStringIf200.apply(response)), not(equalTo("")))); } } \ No newline at end of file diff --git a/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/handlers/ElasticHostsErrorHandler.java b/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/handlers/ElasticHostsErrorHandler.java index a8c59baae4..5361abc0e6 100644 --- a/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/handlers/ElasticHostsErrorHandler.java +++ b/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/handlers/ElasticHostsErrorHandler.java @@ -61,7 +61,10 @@ public class ElasticHostsErrorHandler implements HttpErrorHandler { response.getStatusLine()); switch (response.getStatusCode()) { case 400: - exception = new IllegalArgumentException(message, exception); + if (message != null && message.indexOf("could not be found") != -1) + exception = new ResourceNotFoundException(message, exception); + else + exception = new IllegalArgumentException(message, exception); break; case 401: exception = new AuthorizationException(message, exception); diff --git a/sandbox/elastichosts/src/test/java/org/jclouds/cloudsigma/CloudSigmaAsyncClientTest.java b/sandbox/elastichosts/src/test/java/org/jclouds/cloudsigma/CloudSigmaAsyncClientTest.java new file mode 100644 index 0000000000..77d23d1103 --- /dev/null +++ b/sandbox/elastichosts/src/test/java/org/jclouds/cloudsigma/CloudSigmaAsyncClientTest.java @@ -0,0 +1,180 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.cloudsigma; + +import static org.testng.Assert.assertEquals; + +import java.io.IOException; +import java.lang.reflect.Method; +import java.util.Properties; + +import org.jclouds.cloudsigma.functions.KeyValuesDelimitedByBlankLinesToDriveInfo; +import org.jclouds.cloudsigma.functions.ListOfKeyValuesDelimitedByBlankLinesToDriveInfoSet; +import org.jclouds.elastichosts.domain.CreateDriveRequest; +import org.jclouds.elastichosts.domain.DriveData; +import org.jclouds.elastichosts.functions.SplitNewlines; +import org.jclouds.http.HttpRequest; +import org.jclouds.http.filters.BasicAuthentication; +import org.jclouds.rest.RestClientTest; +import org.jclouds.rest.RestContextFactory; +import org.jclouds.rest.RestContextSpec; +import org.jclouds.rest.functions.ReturnNullOnNotFoundOr404; +import org.jclouds.rest.internal.GeneratedHttpRequest; +import org.jclouds.rest.internal.RestAnnotationProcessor; +import org.testng.annotations.Test; + +import com.google.common.collect.ImmutableList; +import com.google.inject.TypeLiteral; + +/** + * Tests annotation parsing of {@code CloudSigmaAsyncClient} + * + * @author Adrian Cole + */ +@Test(groups = "unit", testName = "cloudsigma.CloudSigmaAsyncClientTest") +public class CloudSigmaAsyncClientTest extends RestClientTest { + + public void testListStandardDrives() throws SecurityException, NoSuchMethodException, IOException { + Method method = CloudSigmaAsyncClient.class.getMethod("listStandardDrives"); + GeneratedHttpRequest httpRequest = processor.createRequest(method); + + assertRequestLineEquals(httpRequest, "GET https://api.cloudsigma.com/drives/standard/list HTTP/1.1"); + assertNonPayloadHeadersEqual(httpRequest, "Accept: text/plain\n"); + assertPayloadEquals(httpRequest, null, null, false); + + assertResponseParserClassEquals(method, httpRequest, SplitNewlines.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(httpRequest); + } + + public void testListStandardCds() throws SecurityException, NoSuchMethodException, IOException { + Method method = CloudSigmaAsyncClient.class.getMethod("listStandardCds"); + GeneratedHttpRequest httpRequest = processor.createRequest(method); + + assertRequestLineEquals(httpRequest, "GET https://api.cloudsigma.com/drives/standard/cd/list HTTP/1.1"); + assertNonPayloadHeadersEqual(httpRequest, "Accept: text/plain\n"); + assertPayloadEquals(httpRequest, null, null, false); + + assertResponseParserClassEquals(method, httpRequest, SplitNewlines.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(httpRequest); + } + + public void testListStandardImages() throws SecurityException, NoSuchMethodException, IOException { + Method method = CloudSigmaAsyncClient.class.getMethod("listStandardImages"); + GeneratedHttpRequest httpRequest = processor.createRequest(method); + + assertRequestLineEquals(httpRequest, "GET https://api.cloudsigma.com/drives/standard/img/list HTTP/1.1"); + assertNonPayloadHeadersEqual(httpRequest, "Accept: text/plain\n"); + assertPayloadEquals(httpRequest, null, null, false); + + assertResponseParserClassEquals(method, httpRequest, SplitNewlines.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(httpRequest); + } + + public void testListDriveInfo() throws SecurityException, NoSuchMethodException, IOException { + Method method = CloudSigmaAsyncClient.class.getMethod("listDriveInfo"); + GeneratedHttpRequest httpRequest = processor.createRequest(method); + + assertRequestLineEquals(httpRequest, "GET https://api.cloudsigma.com/drives/info HTTP/1.1"); + assertNonPayloadHeadersEqual(httpRequest, "Accept: text/plain\n"); + assertPayloadEquals(httpRequest, null, null, false); + + assertResponseParserClassEquals(method, httpRequest, ListOfKeyValuesDelimitedByBlankLinesToDriveInfoSet.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(httpRequest); + } + + public void testGetDriveInfo() throws SecurityException, NoSuchMethodException, IOException { + Method method = CloudSigmaAsyncClient.class.getMethod("getDriveInfo", String.class); + GeneratedHttpRequest httpRequest = processor.createRequest(method, "uuid"); + + assertRequestLineEquals(httpRequest, "GET https://api.cloudsigma.com/drives/uuid/info HTTP/1.1"); + assertNonPayloadHeadersEqual(httpRequest, "Accept: text/plain\n"); + assertPayloadEquals(httpRequest, null, null, false); + + assertResponseParserClassEquals(method, httpRequest, KeyValuesDelimitedByBlankLinesToDriveInfo.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, ReturnNullOnNotFoundOr404.class); + + checkFilters(httpRequest); + + } + + public void testCreateDrive() throws SecurityException, NoSuchMethodException, IOException { + Method method = CloudSigmaAsyncClient.class.getMethod("createDrive", CreateDriveRequest.class); + GeneratedHttpRequest httpRequest = processor.createRequest(method, + new CreateDriveRequest.Builder().name("foo").tags(ImmutableList.of("production", "candy")).size(10000l).build()); + + assertRequestLineEquals(httpRequest, "POST https://api.cloudsigma.com/drives/create HTTP/1.1"); + assertNonPayloadHeadersEqual(httpRequest, "Accept: text/plain\n"); + assertPayloadEquals(httpRequest, "name foo\nsize 10000\nuse production,candy", "text/plain", false); + + assertResponseParserClassEquals(method, httpRequest, KeyValuesDelimitedByBlankLinesToDriveInfo.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, ReturnNullOnNotFoundOr404.class); + + checkFilters(httpRequest); + + } + + public void testSetDriveData() throws SecurityException, NoSuchMethodException, IOException { + Method method = CloudSigmaAsyncClient.class.getMethod("setDriveData", String.class, DriveData.class); + GeneratedHttpRequest httpRequest = processor.createRequest(method, "100", + new DriveData.Builder().name("foo").size(10000l).tags(ImmutableList.of("production", "candy")).build()); + + assertRequestLineEquals(httpRequest, "POST https://api.cloudsigma.com/drives/100/set HTTP/1.1"); + assertNonPayloadHeadersEqual(httpRequest, "Accept: text/plain\n"); + assertPayloadEquals(httpRequest, "name foo\nsize 10000\nuse production,candy", "text/plain", false); + + assertResponseParserClassEquals(method, httpRequest, KeyValuesDelimitedByBlankLinesToDriveInfo.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, ReturnNullOnNotFoundOr404.class); + + checkFilters(httpRequest); + + } + + @Override + protected void checkFilters(HttpRequest request) { + assertEquals(request.getFilters().size(), 1); + assertEquals(request.getFilters().get(0).getClass(), BasicAuthentication.class); + } + + @Override + protected TypeLiteral> createTypeLiteral() { + return new TypeLiteral>() { + }; + } + + @Override + public RestContextSpec createContextSpec() { + return new RestContextFactory().createContextSpec("cloudsigma", "foo", "bar", new Properties()); + } +} diff --git a/sandbox/elastichosts/src/test/java/org/jclouds/cloudsigma/CloudSigmaClientLiveTest.java b/sandbox/elastichosts/src/test/java/org/jclouds/cloudsigma/CloudSigmaClientLiveTest.java new file mode 100644 index 0000000000..bc3fae31a3 --- /dev/null +++ b/sandbox/elastichosts/src/test/java/org/jclouds/cloudsigma/CloudSigmaClientLiveTest.java @@ -0,0 +1,72 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.cloudsigma; + +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotNull; + +import java.util.Set; + +import org.jclouds.cloudsigma.domain.DriveInfo; +import org.jclouds.cloudsigma.domain.DriveType; +import org.jclouds.elastichosts.CommonElasticHostsClientLiveTest; +import org.testng.annotations.Test; + +/** + * Tests behavior of {@code CloudSigmaClient} + * + * @author Adrian Cole + */ +@Test(groups = "live", testName = "cloudsigma.CloudSigmaClientLiveTest") +public class CloudSigmaClientLiveTest extends CommonElasticHostsClientLiveTest { + + public CloudSigmaClientLiveTest() { + provider = "cloudsigma"; + } + + @Test + public void testListStandardDrives() throws Exception { + Set drives = client.listStandardDrives(); + assertNotNull(drives); + } + + @Test + public void testListStandardCds() throws Exception { + Set drives = client.listStandardCds(); + assertNotNull(drives); + } + + @Test + public void testListStandardImages() throws Exception { + Set drives = client.listStandardImages(); + assertNotNull(drives); + } + @Override + protected void checkDriveMatchesGet(org.jclouds.elastichosts.domain.DriveInfo newInfo) { + super.checkDriveMatchesGet(newInfo); + assertEquals(DriveInfo.class.cast(newInfo).getType(), DriveType.DISK); + } + + @Override + protected void checkCreatedDrive() { + super.checkCreatedDrive(); + assertEquals(DriveInfo.class.cast(info).getType(), null); + } +} diff --git a/sandbox/elastichosts/src/test/java/org/jclouds/cloudsigma/ProvidersInPropertiesTest.java b/sandbox/elastichosts/src/test/java/org/jclouds/cloudsigma/ProvidersInPropertiesTest.java new file mode 100644 index 0000000000..6e9d0a1af3 --- /dev/null +++ b/sandbox/elastichosts/src/test/java/org/jclouds/cloudsigma/ProvidersInPropertiesTest.java @@ -0,0 +1,47 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.cloudsigma; + +import org.jclouds.util.Utils; +import org.testng.annotations.Test; + +import com.google.common.collect.Iterables; + +/** + * + * @author Adrian Cole + * + */ +@Test(groups = "unit") +public class ProvidersInPropertiesTest { + + @Test + public void testSupportedProviders() { + Iterable providers = Utils.getSupportedProviders(); + assert Iterables.contains(providers, "cloudsigma") : providers; + } +// +// @Test +// public void testSupportedComputeServiceProviders() { +// Iterable providers = ComputeServiceUtils.getSupportedProviders(); +// assert Iterables.contains(providers, "cloudsigma") : providers; +// } + +} diff --git a/sandbox/elastichosts/src/test/java/org/jclouds/cloudsigma/functions/KeyValuesDelimitedByBlankLinesToDriveInfoTest.java b/sandbox/elastichosts/src/test/java/org/jclouds/cloudsigma/functions/KeyValuesDelimitedByBlankLinesToDriveInfoTest.java new file mode 100644 index 0000000000..8af9256de7 --- /dev/null +++ b/sandbox/elastichosts/src/test/java/org/jclouds/cloudsigma/functions/KeyValuesDelimitedByBlankLinesToDriveInfoTest.java @@ -0,0 +1,50 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.cloudsigma.functions; + +import static org.testng.Assert.assertEquals; + +import org.jclouds.http.HttpResponse; +import org.jclouds.io.Payloads; +import org.testng.annotations.Test; + +import com.google.inject.Guice; + +/** + * + * @author Adrian Cole + */ +@Test(groups = { "unit" }) +public class KeyValuesDelimitedByBlankLinesToDriveInfoTest { + + private static final KeyValuesDelimitedByBlankLinesToDriveInfo FN = Guice.createInjector().getInstance( + KeyValuesDelimitedByBlankLinesToDriveInfo.class); + + public void testNone() { + assertEquals(FN.apply(new HttpResponse(200, "", Payloads.newStringPayload(""))), null); + assertEquals(FN.apply(new HttpResponse(200, "", Payloads.newStringPayload("\n\n"))), null); + assertEquals(FN.apply(new HttpResponse(200, "", null)), null); + } + + public void testOne() { + assertEquals(FN.apply(new HttpResponse(200, "", Payloads.newInputStreamPayload(MapToDriveInfoTest.class + .getResourceAsStream("/cloudsigma/drive.txt")))), MapToDriveInfoTest.ONE); + } +} \ No newline at end of file diff --git a/sandbox/elastichosts/src/test/java/org/jclouds/cloudsigma/functions/ListOfKeyValuesDelimitedByBlankLinesToDriveInfoSetTest.java b/sandbox/elastichosts/src/test/java/org/jclouds/cloudsigma/functions/ListOfKeyValuesDelimitedByBlankLinesToDriveInfoSetTest.java new file mode 100644 index 0000000000..82b5631e98 --- /dev/null +++ b/sandbox/elastichosts/src/test/java/org/jclouds/cloudsigma/functions/ListOfKeyValuesDelimitedByBlankLinesToDriveInfoSetTest.java @@ -0,0 +1,52 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.cloudsigma.functions; + +import static org.testng.Assert.assertEquals; + +import org.jclouds.cloudsigma.domain.DriveInfo; +import org.jclouds.http.HttpResponse; +import org.jclouds.io.Payloads; +import org.testng.annotations.Test; + +import com.google.common.collect.ImmutableSet; +import com.google.inject.Guice; + +/** + * + * @author Adrian Cole + */ +@Test(groups = { "unit" }) +public class ListOfKeyValuesDelimitedByBlankLinesToDriveInfoSetTest { + + private static final ListOfKeyValuesDelimitedByBlankLinesToDriveInfoSet FN = Guice.createInjector().getInstance( + ListOfKeyValuesDelimitedByBlankLinesToDriveInfoSet.class); + + public void testNone() { + assertEquals(FN.apply(new HttpResponse(200, "", Payloads.newStringPayload(""))), ImmutableSet. of()); + assertEquals(FN.apply(new HttpResponse(200, "", Payloads.newStringPayload("\n\n"))), ImmutableSet. of()); + assertEquals(FN.apply(new HttpResponse(200, "", null)), ImmutableSet. of()); + } + + public void testOne() { + assertEquals(FN.apply(new HttpResponse(200, "", Payloads.newInputStreamPayload(MapToDriveInfoTest.class + .getResourceAsStream("/cloudsigma/drive.txt")))), ImmutableSet. of(MapToDriveInfoTest.ONE)); + } +} \ No newline at end of file diff --git a/sandbox/elastichosts/src/test/java/org/jclouds/cloudsigma/functions/MapToDriveInfoTest.java b/sandbox/elastichosts/src/test/java/org/jclouds/cloudsigma/functions/MapToDriveInfoTest.java new file mode 100644 index 0000000000..b021756c40 --- /dev/null +++ b/sandbox/elastichosts/src/test/java/org/jclouds/cloudsigma/functions/MapToDriveInfoTest.java @@ -0,0 +1,97 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.cloudsigma.functions; + +import static org.testng.Assert.assertEquals; + +import java.io.IOException; +import java.net.URI; +import java.util.Map; + +import org.jclouds.cloudsigma.domain.DriveInfo; +import org.jclouds.cloudsigma.domain.DriveType; +import org.jclouds.elastichosts.domain.ClaimType; +import org.jclouds.elastichosts.domain.DriveStatus; +import org.jclouds.elastichosts.functions.ListOfKeyValuesDelimitedByBlankLinesToListOfMaps; +import org.jclouds.util.Utils; +import org.testng.annotations.Test; + +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.ImmutableSet; + +/** + * + * @author Adrian Cole + */ +@Test(groups = { "unit" }) +public class MapToDriveInfoTest { + public static DriveInfo ONE = new DriveInfo.Builder() + .status(DriveStatus.ACTIVE) + .tags(ImmutableSet.of("networking", "security", "gateway")) + .name("Ubuntu 10.10 Server Edition Linux 64bit Preinstalled System") + .bits(64) + .url(URI.create("http://www.ubuntu.com")) + .readBytes(4096l) + .user("58ca3c1f-7629-4771-9b71-863f40153ba4") + .encryptionCipher("aes-xts-plain") + .encryptionKey("ba6c2a4897072e9f25920ed73bd522e9c10d89f30a215158cccf8d0f654ac643") + .description("The Ubuntu Linux distribution brings the spirit of Ubuntu to the software world.") + .uuid("b8171d28-755a-4271-b891-7998871a160e") + .installNotes("first line\n\n") + .os("linux") + .writeBytes(8589938688l) + .claimType(ClaimType.SHARED) + .claimed( + ImmutableSet.of( + "00109617-2c6b-424b-9cfa-5b572c17bafe:guest:692cd1c7-a863-4a22-8170-fc6e6feb68af:ide:0:0", + "00031836-a624-4b22-bc7d-41ff8977087b:guest:a1414360-7c24-4730-8c97-180bf7775a71:ide:0:0", + "0002c6df-a1d2-4d1d-96f0-f95405a28183:guest:386f1cc7-affc-49c1-82a5-2f8e412170e4:ide:0:0", + "00031836-a624-4b22-bc7d-41ff8977087b:guest:17b076be-430d-4a76-9df3-b9896fec82a5:ide:0:0", + "000663ee-9fb6-4461-90f6-01327a4aff07:guest:f83b519f-feab-42cf-859c-f61495681ada:ide:0:1"))// + .driveType(ImmutableSet.of("installcd", "livecd"))// + .autoexpanding(false).readers(ImmutableSet.of("ffffffff-ffff-ffff-ffff-ffffffffffff"))// + .readRequests(1l)// + .free(true)// + .type(DriveType.DISK)// + .writeRequests(2097153l)// + .size(8589934592l)// + .userMetadata(ImmutableMap.of("foo", "bar", "baz", "raz")).build(); + + private static final MapToDriveInfo MAP_TO_DRIVE = new MapToDriveInfo( + new org.jclouds.elastichosts.functions.MapToDriveInfo()); + + public void testEmptyMapReturnsNull() { + assertEquals(MAP_TO_DRIVE.apply(ImmutableMap. of()), null); + } + + public void testBasics() { + DriveInfo expects = new DriveInfo.Builder().name("foo").size(100l).build(); + assertEquals(MAP_TO_DRIVE.apply(ImmutableMap.of("name", "foo", "size", "100")), expects); + } + + public void testComplete() throws IOException { + + Map input = new ListOfKeyValuesDelimitedByBlankLinesToListOfMaps().apply( + Utils.toStringAndClose(MapToDriveInfoTest.class.getResourceAsStream("/cloudsigma/drive.txt"))).get(0); + + assertEquals(MAP_TO_DRIVE.apply(input), ONE); + + } +} \ No newline at end of file diff --git a/sandbox/elastichosts/src/test/java/org/jclouds/elastichosts/CommonElasticHostsClientLiveTest.java b/sandbox/elastichosts/src/test/java/org/jclouds/elastichosts/CommonElasticHostsClientLiveTest.java new file mode 100644 index 0000000000..835ee12a9d --- /dev/null +++ b/sandbox/elastichosts/src/test/java/org/jclouds/elastichosts/CommonElasticHostsClientLiveTest.java @@ -0,0 +1,176 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.elastichosts; + +import static com.google.common.base.Preconditions.checkNotNull; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotNull; + +import java.util.Properties; +import java.util.Set; + +import org.jclouds.Constants; +import org.jclouds.elastichosts.domain.ClaimType; +import org.jclouds.elastichosts.domain.CreateDriveRequest; +import org.jclouds.elastichosts.domain.DriveData; +import org.jclouds.elastichosts.domain.DriveInfo; +import org.jclouds.elastichosts.domain.DriveStatus; +import org.jclouds.logging.log4j.config.Log4JLoggingModule; +import org.jclouds.rest.RestContext; +import org.jclouds.rest.RestContextFactory; +import org.testng.annotations.AfterGroups; +import org.testng.annotations.BeforeGroups; +import org.testng.annotations.Test; + +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.ImmutableSet; +import com.google.inject.Module; + +/** + * Tests behavior of {@code CommonElasticHostsClient} + * + * @author Adrian Cole + */ +@Test(groups = "live", sequential = true) +public abstract class CommonElasticHostsClientLiveTest { + + protected S client; + protected RestContext context; + + protected String provider = "elastichosts"; + protected String identity; + protected String credential; + protected String endpoint; + protected String apiversion; + + protected void setupCredentials() { + identity = checkNotNull(System.getProperty("test." + provider + ".identity"), "test." + provider + ".identity"); + credential = System.getProperty("test." + provider + ".credential"); + endpoint = System.getProperty("test." + provider + ".endpoint"); + apiversion = System.getProperty("test." + provider + ".apiversion"); + } + + protected Properties setupProperties() { + Properties overrides = new Properties(); + overrides.setProperty(Constants.PROPERTY_TRUST_ALL_CERTS, "true"); + overrides.setProperty(Constants.PROPERTY_RELAX_HOSTNAME, "true"); + overrides.setProperty(provider + ".identity", identity); + if (credential != null) + overrides.setProperty(provider + ".credential", credential); + if (endpoint != null) + overrides.setProperty(provider + ".endpoint", endpoint); + if (apiversion != null) + overrides.setProperty(provider + ".apiversion", apiversion); + return overrides; + } + + @BeforeGroups(groups = "live") + public void setupClient() { + setupCredentials(); + Properties overrides = setupProperties(); + context = new RestContextFactory().createContext(provider, ImmutableSet. of(new Log4JLoggingModule()), + overrides); + + client = context.getApi(); + } + + @AfterGroups(groups = "live") + void tearDown() { + if (context != null) + context.close(); + } + + @Test + public void testListDrives() throws Exception { + Set drives = client.listDrives(); + assertNotNull(drives); + } + + @Test + public void testListDriveInfo() throws Exception { + Set drives = client.listDriveInfo(); + assertNotNull(drives); + } + + @Test + public void testGetDrive() throws Exception { + for (String driveUUID : client.listDrives()) { + assert !"".equals(driveUUID); + assertNotNull(client.getDriveInfo(driveUUID)); + } + } + + protected String prefix = System.getProperty("user.name") + ".test"; + protected DriveInfo info; + + @Test + public void testCreate() throws Exception { + info = client.createDrive(new CreateDriveRequest.Builder().name(prefix).size(4 * 1024 * 1024l).build()); + checkCreatedDrive(); + + DriveInfo newInfo = client.getDriveInfo(info.getUuid()); + checkDriveMatchesGet(newInfo); + + } + + protected void checkDriveMatchesGet(DriveInfo newInfo) { + assertEquals(newInfo.getUuid(), info.getUuid()); + } + + protected void checkCreatedDrive() { + assertNotNull(info.getUuid()); + assertNotNull(info.getUser()); + assertEquals(info.getName(), prefix); + assertEquals(info.getSize(), 4 * 1024 * 1024l); + assertEquals(info.getStatus(), DriveStatus.ACTIVE); + // for some reason, these occasionally return as 4096,1 + // assertEquals(info.getReadBytes(), 0l); + // assertEquals(info.getWriteBytes(), 0l); + // assertEquals(info.getReadRequests(), 0l); + // assertEquals(info.getWriteRequests(), 0l); + assertEquals(info.getEncryptionCipher(), "aes-xts-plain"); + } + + @Test(dependsOnMethods = "testCreate") + public void testSetDriveData() throws Exception { + + DriveInfo info2 = client.setDriveData( + info.getUuid(), + new DriveData.Builder().claimType(ClaimType.SHARED).name("rediculous") + .readers(ImmutableSet.of("ffffffff-ffff-ffff-ffff-ffffffffffff")) + .tags(ImmutableSet.of("networking", "security", "gateway")) + .userMetadata(ImmutableMap.of("foo", "bar")).build()); + + assertNotNull(info2.getUuid(), info.getUuid()); + assertEquals(info2.getName(), "rediculous"); + assertEquals(info2.getClaimType(), ClaimType.SHARED); + assertEquals(info2.getReaders(), ImmutableSet.of("ffffffff-ffff-ffff-ffff-ffffffffffff")); + assertEquals(info2.getTags(), ImmutableSet.of("networking", "security", "gateway")); + assertEquals(info2.getUserMetadata(), ImmutableMap.of("foo", "bar")); + info = info2; + } + + @Test(dependsOnMethods = "testSetDriveData") + public void testDestroyDrive() throws Exception { + client.destroyDrive(info.getUuid()); + assertEquals(client.getDriveInfo(info.getUuid()), null); + } + +} diff --git a/sandbox/elastichosts/src/test/java/org/jclouds/elastichosts/ElasticHostsAsyncClientTest.java b/sandbox/elastichosts/src/test/java/org/jclouds/elastichosts/ElasticHostsAsyncClientTest.java index a183686169..093f5da40d 100644 --- a/sandbox/elastichosts/src/test/java/org/jclouds/elastichosts/ElasticHostsAsyncClientTest.java +++ b/sandbox/elastichosts/src/test/java/org/jclouds/elastichosts/ElasticHostsAsyncClientTest.java @@ -19,11 +19,11 @@ package org.jclouds.elastichosts; -import static org.jclouds.rest.RestContextFactory.contextSpec; import static org.testng.Assert.assertEquals; import java.io.IOException; import java.lang.reflect.Method; +import java.util.Properties; import javax.ws.rs.core.MediaType; @@ -41,6 +41,7 @@ import org.jclouds.http.functions.ReleasePayloadAndReturn; import org.jclouds.io.Payload; import org.jclouds.io.Payloads; import org.jclouds.rest.RestClientTest; +import org.jclouds.rest.RestContextFactory; import org.jclouds.rest.RestContextSpec; import org.jclouds.rest.functions.ReturnNullOnNotFoundOr404; import org.jclouds.rest.functions.ReturnVoidOnNotFoundOr404; @@ -48,6 +49,7 @@ import org.jclouds.rest.internal.GeneratedHttpRequest; import org.jclouds.rest.internal.RestAnnotationProcessor; import org.testng.annotations.Test; +import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import com.google.inject.TypeLiteral; @@ -75,7 +77,7 @@ public class ElasticHostsAsyncClientTest extends RestClientTest httpRequest = processor.createRequest(method); - - assertRequestLineEquals(httpRequest, "GET https://api.elastichosts.com/drives/standard/list HTTP/1.1"); - assertNonPayloadHeadersEqual(httpRequest, "Accept: text/plain\n"); - assertPayloadEquals(httpRequest, null, null, false); - - assertResponseParserClassEquals(method, httpRequest, SplitNewlines.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, null); - - checkFilters(httpRequest); - } - - public void testListStandardCds() throws SecurityException, NoSuchMethodException, IOException { - Method method = ElasticHostsAsyncClient.class.getMethod("listStandardCds"); - GeneratedHttpRequest httpRequest = processor.createRequest(method); - - assertRequestLineEquals(httpRequest, "GET https://api.elastichosts.com/drives/standard/cd/list HTTP/1.1"); - assertNonPayloadHeadersEqual(httpRequest, "Accept: text/plain\n"); - assertPayloadEquals(httpRequest, null, null, false); - - assertResponseParserClassEquals(method, httpRequest, SplitNewlines.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, null); - - checkFilters(httpRequest); - } - - public void testListStandardImages() throws SecurityException, NoSuchMethodException, IOException { - Method method = ElasticHostsAsyncClient.class.getMethod("listStandardImages"); - GeneratedHttpRequest httpRequest = processor.createRequest(method); - - assertRequestLineEquals(httpRequest, "GET https://api.elastichosts.com/drives/standard/img/list HTTP/1.1"); - assertNonPayloadHeadersEqual(httpRequest, "Accept: text/plain\n"); - assertPayloadEquals(httpRequest, null, null, false); - - assertResponseParserClassEquals(method, httpRequest, SplitNewlines.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, null); - - checkFilters(httpRequest); - } - public void testListDriveInfo() throws SecurityException, NoSuchMethodException, IOException { Method method = ElasticHostsAsyncClient.class.getMethod("listDriveInfo"); GeneratedHttpRequest httpRequest = processor.createRequest(method); @@ -183,11 +140,11 @@ public class ElasticHostsAsyncClientTest extends RestClientTest httpRequest = processor.createRequest(method, "100", - new DriveData.Builder().name("foo").size(10000l).build()); + new DriveData.Builder().name("foo").size(10000l).tags(ImmutableList.of("production", "candy")).build()); assertRequestLineEquals(httpRequest, "POST https://api.elastichosts.com/drives/100/set HTTP/1.1"); assertNonPayloadHeadersEqual(httpRequest, "Accept: text/plain\n"); - assertPayloadEquals(httpRequest, "name foo\nsize 10000", "text/plain", false); + assertPayloadEquals(httpRequest, "name foo\nsize 10000\ntags production candy", "text/plain", false); assertResponseParserClassEquals(method, httpRequest, KeyValuesDelimitedByBlankLinesToDriveInfo.class); assertSaxResponseParserClassEquals(method, null); @@ -324,7 +281,8 @@ public class ElasticHostsAsyncClientTest extends RestClientTest createContextSpec() { - return contextSpec("elastichosts", "https://api.elastichosts.com", "1.0", "identity", "credential", - ElasticHostsClient.class, ElasticHostsAsyncClient.class); + Properties props = new Properties(); + props.setProperty("elastichosts.endpoint", "https://api.elastichosts.com"); + return new RestContextFactory().createContextSpec("elastichosts", "foo", "bar", props); } } diff --git a/sandbox/elastichosts/src/test/java/org/jclouds/elastichosts/ElasticHostsClientLiveTest.java b/sandbox/elastichosts/src/test/java/org/jclouds/elastichosts/ElasticHostsClientLiveTest.java index bdab04b67d..b037658c95 100644 --- a/sandbox/elastichosts/src/test/java/org/jclouds/elastichosts/ElasticHostsClientLiveTest.java +++ b/sandbox/elastichosts/src/test/java/org/jclouds/elastichosts/ElasticHostsClientLiveTest.java @@ -19,165 +19,57 @@ package org.jclouds.elastichosts; -import static com.google.common.base.Preconditions.checkNotNull; -import static org.jclouds.rest.RestContextFactory.contextSpec; -import static org.jclouds.rest.RestContextFactory.createContext; import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertNotNull; import java.io.IOException; -import java.util.Properties; -import java.util.Set; -import org.jclouds.Constants; -import org.jclouds.elastichosts.domain.ClaimType; import org.jclouds.elastichosts.domain.CreateDriveRequest; -import org.jclouds.elastichosts.domain.DriveData; import org.jclouds.elastichosts.domain.DriveInfo; +import org.jclouds.elastichosts.options.ReadDriveOptions; import org.jclouds.io.Payloads; -import org.jclouds.logging.log4j.config.Log4JLoggingModule; -import org.jclouds.rest.RestContext; import org.jclouds.util.Utils; -import org.testng.annotations.AfterGroups; -import org.testng.annotations.BeforeGroups; import org.testng.annotations.Test; -import com.google.common.base.Predicate; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.ImmutableSet; -import com.google.common.collect.Iterables; -import com.google.inject.Module; - /** * Tests behavior of {@code ElasticHostsClient} * * @author Adrian Cole */ @Test(groups = "live", testName = "elastichosts.ElasticHostsClientLiveTest") -public class ElasticHostsClientLiveTest { - - private ElasticHostsClient client; - private RestContext context; - - protected String provider = "elastichosts"; - protected String identity; - protected String credential; - protected String endpoint; - protected String apiversion; - - protected void setupCredentials() { - identity = checkNotNull(System.getProperty("test." + provider + ".identity"), "test." + provider + ".identity"); - credential = System.getProperty("test." + provider + ".credential"); - endpoint = System.getProperty("test." + provider + ".endpoint"); - apiversion = System.getProperty("test." + provider + ".apiversion"); - } - - protected Properties setupProperties() { - Properties overrides = new Properties(); - overrides.setProperty(Constants.PROPERTY_TRUST_ALL_CERTS, "true"); - overrides.setProperty(Constants.PROPERTY_RELAX_HOSTNAME, "true"); - overrides.setProperty(provider + ".identity", identity); - if (credential != null) - overrides.setProperty(provider + ".credential", credential); - if (endpoint != null) - overrides.setProperty(provider + ".endpoint", endpoint); - if (apiversion != null) - overrides.setProperty(provider + ".apiversion", apiversion); - return overrides; - } - - @BeforeGroups(groups = { "live" }) - public void setupClient() { - setupCredentials(); - Properties overrides = setupProperties(); - context = createContext( - contextSpec(provider, endpoint, "1.0", identity, credential, ElasticHostsClient.class, - ElasticHostsAsyncClient.class, (Class) ElasticHostsPropertiesBuilder.class, - (Class) ElasticHostsContextBuilder.class, ImmutableSet. of(new Log4JLoggingModule())), - overrides); - - client = context.getApi(); - } - - @AfterGroups(groups = "live") - void tearDown() { - if (context != null) - context.close(); - } - - @Test - public void testListDrives() throws Exception { - Set drives = client.listDrives(); - assertNotNull(drives); - } - - @Test - public void testListDriveInfo() throws Exception { - Set drives = client.listDriveInfo(); - assertNotNull(drives); - } - - @Test - public void testListStandardDrives() throws Exception { - Set drives = client.listStandardDrives(); - assertNotNull(drives); - } - - @Test - public void testListStandardCds() throws Exception { - Set drives = client.listStandardCds(); - assertNotNull(drives); - } - - @Test - public void testListStandardImages() throws Exception { - Set drives = client.listStandardImages(); - assertNotNull(drives); - } - - @Test - public void testGetDrive() throws Exception { - for (String driveUUID : client.listDrives()) { - assertNotNull(client.getDriveInfo(driveUUID)); - } - for (String driveUUID : client.listStandardDrives()) { - assertNotNull(client.getDriveInfo(driveUUID)); - } - } - - private String prefix = System.getProperty("user.name") + ".test"; - private DriveInfo info; +public class ElasticHostsClientLiveTest extends + CommonElasticHostsClientLiveTest { private DriveInfo info2; - @Test + @Override + public void testGetDrive() throws Exception { + super.testGetDrive(); + } + + @Override public void testCreate() throws Exception { - try { - findAndDestroyDrive(prefix); - } catch (Exception e) { + super.testCreate(); + } - } - - info = client.createDrive(new CreateDriveRequest.Builder().name(prefix).size(4 * 1024 * 1024l).build()); - assertNotNull(info.getUuid()); - assertEquals(info.getName(), prefix); - assertEquals(info.getSize(), 4 * 1024 * 1024l); - assertEquals(info, client.getDriveInfo(info.getUuid())); + @Override + public void testSetDriveData() throws Exception { + super.testSetDriveData(); + } + @Override + public void testDestroyDrive() throws Exception { + super.testDestroyDrive(); } @Test(dependsOnMethods = "testCreate") public void testWeCanReadAndWriteToDrive() throws IOException { client.writeDrive(info.getUuid(), Payloads.newStringPayload("foo")); - assertEquals(Utils.toStringAndClose(client.readDrive(info.getUuid()).getInput()), "foo"); + assertEquals(Utils.toStringAndClose(client.readDrive(info.getUuid(), ReadDriveOptions.Builder.offset(0).size(3)) + .getInput()), "foo"); } @Test(dependsOnMethods = "testWeCanReadAndWriteToDrive") public void testWeCopyADriveContentsViaGzip() throws IOException { - try { - findAndDestroyDrive(prefix + "2"); - } catch (Exception e) { - } try { info2 = client.createDrive(new CreateDriveRequest.Builder().name(prefix + "2").size(4 * 1024 * 1024l).build()); client.imageDrive(info.getUuid(), info2.getUuid()); @@ -186,46 +78,9 @@ public class ElasticHostsClientLiveTest { System.err.println("state " + client.getDriveInfo(info2.getUuid())); assertEquals(Utils.toStringAndClose(client.readDrive(info2.getUuid()).getInput()), "foo"); } finally { - findAndDestroyDrive(prefix + "2"); + client.destroyDrive(info2.getUuid()); } } - @Test(dependsOnMethods = "testCreate") - public void testSetDriveData() throws Exception { - - DriveInfo info2 = client.setDriveData( - info.getUuid(), - new DriveData.Builder().claimType(ClaimType.SHARED).name("rediculous") - .readers(ImmutableSet.of("ffffffff-ffff-ffff-ffff-ffffffffffff")) - .tags(ImmutableSet.of("tag1", "tag2")).userMetadata(ImmutableMap.of("foo", "bar")).build()); - - assertNotNull(info2.getUuid(), info.getUuid()); - assertEquals(info.getName(), "rediculous"); - assertEquals(info.getClaimType(), ClaimType.SHARED); - assertEquals(info.getReaders(), ImmutableSet.of("ffffffff-ffff-ffff-ffff-ffffffffffff")); - assertEquals(info.getTags(), ImmutableSet.of("tag1", "tag2")); - assertEquals(info.getUserMetadata(), ImmutableMap.of("foo", "bar")); - } - - @Test(dependsOnMethods = "testSetDriveData") - public void testDestroyDrive() throws Exception { - - findAndDestroyDrive(prefix); - assertEquals(client.getDriveInfo(info.getUuid()), null); - - } - - protected void findAndDestroyDrive(final String prefix) { - DriveInfo drive = Iterables.find(client.listDriveInfo(), new Predicate() { - - @Override - public boolean apply(DriveInfo input) { - return input.getName().equals(prefix); - } - - }); - client.destroyDrive(drive.getUuid()); - } - } diff --git a/sandbox/elastichosts/src/test/java/org/jclouds/elastichosts/ProvidersInPropertiesTest.java b/sandbox/elastichosts/src/test/java/org/jclouds/elastichosts/ProvidersInPropertiesTest.java new file mode 100644 index 0000000000..28bc7adb37 --- /dev/null +++ b/sandbox/elastichosts/src/test/java/org/jclouds/elastichosts/ProvidersInPropertiesTest.java @@ -0,0 +1,47 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.elastichosts; + +import org.jclouds.util.Utils; +import org.testng.annotations.Test; + +import com.google.common.collect.Iterables; + +/** + * + * @author Adrian Cole + * + */ +@Test(groups = "unit") +public class ProvidersInPropertiesTest { + + @Test + public void testSupportedProviders() { + Iterable providers = Utils.getSupportedProviders(); + assert Iterables.contains(providers, "elastichosts") : providers; + } +// +// @Test +// public void testSupportedComputeServiceProviders() { +// Iterable providers = ComputeServiceUtils.getSupportedProviders(); +// assert Iterables.contains(providers, "cloudsigma") : providers; +// } + +} diff --git a/sandbox/elastichosts/src/test/java/org/jclouds/elastichosts/binders/BindCreateDriveRequestToPlainTextStringTest.java b/sandbox/elastichosts/src/test/java/org/jclouds/elastichosts/binders/BindCreateDriveRequestToPlainTextStringTest.java index 855d709410..e66810e671 100644 --- a/sandbox/elastichosts/src/test/java/org/jclouds/elastichosts/binders/BindCreateDriveRequestToPlainTextStringTest.java +++ b/sandbox/elastichosts/src/test/java/org/jclouds/elastichosts/binders/BindCreateDriveRequestToPlainTextStringTest.java @@ -23,18 +23,25 @@ import static org.testng.Assert.assertEquals; import java.io.IOException; import java.net.URI; +import java.util.Map; import javax.ws.rs.core.MediaType; import org.jclouds.elastichosts.domain.ClaimType; import org.jclouds.elastichosts.domain.CreateDriveRequest; +import org.jclouds.elastichosts.domain.DriveData; +import org.jclouds.elastichosts.functions.CreateDriveRequestToMap; +import org.jclouds.elastichosts.functions.DriveDataToMap; import org.jclouds.http.HttpRequest; import org.jclouds.util.Utils; import org.testng.annotations.Test; +import com.google.common.base.Function; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; +import com.google.inject.AbstractModule; import com.google.inject.Guice; +import com.google.inject.TypeLiteral; /** * @@ -43,8 +50,17 @@ import com.google.inject.Guice; @Test(groups = { "unit" }) public class BindCreateDriveRequestToPlainTextStringTest { - private static final BindCreateDriveRequestToPlainTextString FN = Guice.createInjector().getInstance( - BindCreateDriveRequestToPlainTextString.class); + private static final BindCreateDriveRequestToPlainTextString FN = Guice.createInjector(new AbstractModule() { + + @Override + protected void configure() { + bind(new TypeLiteral>>() { + }).to(CreateDriveRequestToMap.class); + bind(new TypeLiteral>>() { + }).to(DriveDataToMap.class); + } + + }).getInstance(BindCreateDriveRequestToPlainTextString.class); public void testSimple() { HttpRequest request = new HttpRequest("POST", URI.create("https://host/drives/create")); diff --git a/sandbox/elastichosts/src/test/java/org/jclouds/elastichosts/binders/BindDriveDataToPlainTextStringTest.java b/sandbox/elastichosts/src/test/java/org/jclouds/elastichosts/binders/BindDriveDataToPlainTextStringTest.java index 9209275ec7..319003d83e 100644 --- a/sandbox/elastichosts/src/test/java/org/jclouds/elastichosts/binders/BindDriveDataToPlainTextStringTest.java +++ b/sandbox/elastichosts/src/test/java/org/jclouds/elastichosts/binders/BindDriveDataToPlainTextStringTest.java @@ -23,18 +23,25 @@ import static org.testng.Assert.assertEquals; import java.io.IOException; import java.net.URI; +import java.util.Map; import javax.ws.rs.core.MediaType; import org.jclouds.elastichosts.domain.ClaimType; +import org.jclouds.elastichosts.domain.CreateDriveRequest; import org.jclouds.elastichosts.domain.DriveData; +import org.jclouds.elastichosts.functions.CreateDriveRequestToMap; +import org.jclouds.elastichosts.functions.DriveDataToMap; import org.jclouds.http.HttpRequest; import org.jclouds.util.Utils; import org.testng.annotations.Test; +import com.google.common.base.Function; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; +import com.google.inject.AbstractModule; import com.google.inject.Guice; +import com.google.inject.TypeLiteral; /** * @@ -43,8 +50,17 @@ import com.google.inject.Guice; @Test(groups = { "unit" }) public class BindDriveDataToPlainTextStringTest { - private static final BindDriveDataToPlainTextString FN = Guice.createInjector().getInstance( - BindDriveDataToPlainTextString.class); + private static final BindDriveDataToPlainTextString FN = Guice.createInjector(new AbstractModule() { + + @Override + protected void configure() { + bind(new TypeLiteral>>() { + }).to(CreateDriveRequestToMap.class); + bind(new TypeLiteral>>() { + }).to(DriveDataToMap.class); + } + + }).getInstance(BindDriveDataToPlainTextString.class); public void testSimple() { HttpRequest request = new HttpRequest("POST", URI.create("https://host/drives/create")); @@ -66,8 +82,7 @@ public class BindDriveDataToPlainTextStringTest { FN.bindToRequest(request, input); assertEquals(request.getPayload().getContentMetadata().getContentType(), MediaType.TEXT_PLAIN); assertEquals(request.getPayload().getRawContent(), - Utils.toStringAndClose(BindDriveDataToPlainTextStringTest.class - .getResourceAsStream("/drive_data.txt"))); + Utils.toStringAndClose(BindDriveDataToPlainTextStringTest.class.getResourceAsStream("/drive_data.txt"))); } } \ No newline at end of file diff --git a/sandbox/elastichosts/src/test/java/org/jclouds/elastichosts/functions/KeyValuesDelimitedByBlankLinesToDriveInfoTest.java b/sandbox/elastichosts/src/test/java/org/jclouds/elastichosts/functions/KeyValuesDelimitedByBlankLinesToDriveInfoTest.java new file mode 100644 index 0000000000..e528ab1878 --- /dev/null +++ b/sandbox/elastichosts/src/test/java/org/jclouds/elastichosts/functions/KeyValuesDelimitedByBlankLinesToDriveInfoTest.java @@ -0,0 +1,50 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.elastichosts.functions; + +import static org.testng.Assert.assertEquals; + +import org.jclouds.http.HttpResponse; +import org.jclouds.io.Payloads; +import org.testng.annotations.Test; + +import com.google.inject.Guice; + +/** + * + * @author Adrian Cole + */ +@Test(groups = { "unit" }) +public class KeyValuesDelimitedByBlankLinesToDriveInfoTest { + + private static final KeyValuesDelimitedByBlankLinesToDriveInfo FN = Guice.createInjector().getInstance( + KeyValuesDelimitedByBlankLinesToDriveInfo.class); + + public void testNone() { + assertEquals(FN.apply(new HttpResponse(200, "", Payloads.newStringPayload(""))), null); + assertEquals(FN.apply(new HttpResponse(200, "", Payloads.newStringPayload("\n\n"))), null); + assertEquals(FN.apply(new HttpResponse(200, "", null)), null); + } + + public void testOne() { + assertEquals(FN.apply(new HttpResponse(200, "", Payloads.newInputStreamPayload(MapToDriveInfoTest.class + .getResourceAsStream("/drive.txt")))), MapToDriveInfoTest.ONE); + } +} \ No newline at end of file diff --git a/sandbox/elastichosts/src/test/java/org/jclouds/elastichosts/functions/MapToDriveInfoTest.java b/sandbox/elastichosts/src/test/java/org/jclouds/elastichosts/functions/MapToDriveInfoTest.java index 252408a751..7b40037446 100644 --- a/sandbox/elastichosts/src/test/java/org/jclouds/elastichosts/functions/MapToDriveInfoTest.java +++ b/sandbox/elastichosts/src/test/java/org/jclouds/elastichosts/functions/MapToDriveInfoTest.java @@ -22,13 +22,11 @@ package org.jclouds.elastichosts.functions; import static org.testng.Assert.assertEquals; import java.io.IOException; -import java.net.URI; import java.util.Map; import org.jclouds.elastichosts.domain.ClaimType; import org.jclouds.elastichosts.domain.DriveInfo; import org.jclouds.elastichosts.domain.DriveStatus; -import org.jclouds.elastichosts.domain.DriveType; import org.jclouds.util.Utils; import org.testng.annotations.Test; @@ -43,18 +41,11 @@ import com.google.common.collect.ImmutableSet; public class MapToDriveInfoTest { public static DriveInfo ONE = new DriveInfo.Builder() .status(DriveStatus.ACTIVE) - .use(ImmutableSet.of("networking", "security", "gateway")) .name("Ubuntu 10.10 Server Edition Linux 64bit Preinstalled System") - .bits(64) - .url(URI.create("http://www.ubuntu.com")) .readBytes(4096l) .user("58ca3c1f-7629-4771-9b71-863f40153ba4") .encryptionCipher("aes-xts-plain") - .encryptionKey("ba6c2a4897072e9f25920ed73bd522e9c10d89f30a215158cccf8d0f654ac643") - .description("The Ubuntu Linux distribution brings the spirit of Ubuntu to the software world.") .uuid("b8171d28-755a-4271-b891-7998871a160e") - .installNotes("first line\n\n") - .os("linux") .writeBytes(8589938688l) .claimType(ClaimType.SHARED) .claimed( @@ -64,11 +55,8 @@ public class MapToDriveInfoTest { "0002c6df-a1d2-4d1d-96f0-f95405a28183:guest:386f1cc7-affc-49c1-82a5-2f8e412170e4:ide:0:0", "00031836-a624-4b22-bc7d-41ff8977087b:guest:17b076be-430d-4a76-9df3-b9896fec82a5:ide:0:0", "000663ee-9fb6-4461-90f6-01327a4aff07:guest:f83b519f-feab-42cf-859c-f61495681ada:ide:0:1"))// - .driveType(ImmutableSet.of("installcd", "livecd"))// - .autoexpanding(false).readers(ImmutableSet.of("ffffffff-ffff-ffff-ffff-ffffffffffff"))// + .readers(ImmutableSet.of("ffffffff-ffff-ffff-ffff-ffffffffffff"))// .readRequests(1l)// - .free(true)// - .type(DriveType.DISK)// .writeRequests(2097153l)// .size(8589934592l)// .userMetadata(ImmutableMap.of("foo", "bar", "baz", "raz")).build(); diff --git a/sandbox/elastichosts/src/test/java/org/jclouds/elastichosts/handlers/ElasticHostsErrorHandlerTest.java b/sandbox/elastichosts/src/test/java/org/jclouds/elastichosts/handlers/ElasticHostsErrorHandlerTest.java index d0fa1c2c03..99a84c8841 100644 --- a/sandbox/elastichosts/src/test/java/org/jclouds/elastichosts/handlers/ElasticHostsErrorHandlerTest.java +++ b/sandbox/elastichosts/src/test/java/org/jclouds/elastichosts/handlers/ElasticHostsErrorHandlerTest.java @@ -52,6 +52,12 @@ public class ElasticHostsErrorHandlerTest { IllegalArgumentException.class); } + @Test + public void test400MakesResourceNotFoundExceptionOnMessageNotFound() { + assertCodeMakes("GET", URI.create("https://elastichosts.com/foo"), 400, "", "errors:system Drive 8f9b42b1-26de-49ad-a3fd-d4fa06524339 could not be found. Please re-validate your entry.", + ResourceNotFoundException.class); + } + @Test public void test401MakesAuthorizationException() { assertCodeMakes("GET", URI.create("https://elastichosts.com/foo"), 401, "", "Unauthorized", diff --git a/sandbox/elastichosts/src/test/resources/cloudsigma/drive.txt b/sandbox/elastichosts/src/test/resources/cloudsigma/drive.txt new file mode 100644 index 0000000000..04372bb776 --- /dev/null +++ b/sandbox/elastichosts/src/test/resources/cloudsigma/drive.txt @@ -0,0 +1,26 @@ +status active +use networking,security,gateway +name Ubuntu 10.10 Server Edition Linux 64bit Preinstalled System +bits 64 +url http://www.ubuntu.com +read:bytes 4096 +user 58ca3c1f-7629-4771-9b71-863f40153ba4 +encryption:cipher aes-xts-plain +encryption:key ba6c2a4897072e9f25920ed73bd522e9c10d89f30a215158cccf8d0f654ac643 +description The Ubuntu Linux distribution brings the spirit of Ubuntu to the software world. +drive b8171d28-755a-4271-b891-7998871a160e +install_notes first line\n\n +os linux +write:bytes 8589938688 +claim:type shared +claimed 00109617-2c6b-424b-9cfa-5b572c17bafe:guest:692cd1c7-a863-4a22-8170-fc6e6feb68af:ide:0:0 00031836-a624-4b22-bc7d-41ff8977087b:guest:a1414360-7c24-4730-8c97-180bf7775a71:ide:0:0 0002c6df-a1d2-4d1d-96f0-f95405a28183:guest:386f1cc7-affc-49c1-82a5-2f8e412170e4:ide:0:0 00031836-a624-4b22-bc7d-41ff8977087b:guest:17b076be-430d-4a76-9df3-b9896fec82a5:ide:0:0 000663ee-9fb6-4461-90f6-01327a4aff07:guest:f83b519f-feab-42cf-859c-f61495681ada:ide:0:1 +drive_type installcd,livecd +autoexpanding false +readers ffffffff-ffff-ffff-ffff-ffffffffffff +read:requests 1 +free true +type disk +write:requests 2097153 +size 8589934592 +user:foo bar +user:baz raz \ No newline at end of file diff --git a/sandbox/elastichosts/src/test/resources/drive.txt b/sandbox/elastichosts/src/test/resources/drive.txt index 04372bb776..a88daebbc0 100644 --- a/sandbox/elastichosts/src/test/resources/drive.txt +++ b/sandbox/elastichosts/src/test/resources/drive.txt @@ -1,25 +1,14 @@ status active -use networking,security,gateway name Ubuntu 10.10 Server Edition Linux 64bit Preinstalled System -bits 64 -url http://www.ubuntu.com read:bytes 4096 user 58ca3c1f-7629-4771-9b71-863f40153ba4 encryption:cipher aes-xts-plain -encryption:key ba6c2a4897072e9f25920ed73bd522e9c10d89f30a215158cccf8d0f654ac643 -description The Ubuntu Linux distribution brings the spirit of Ubuntu to the software world. drive b8171d28-755a-4271-b891-7998871a160e -install_notes first line\n\n -os linux write:bytes 8589938688 claim:type shared claimed 00109617-2c6b-424b-9cfa-5b572c17bafe:guest:692cd1c7-a863-4a22-8170-fc6e6feb68af:ide:0:0 00031836-a624-4b22-bc7d-41ff8977087b:guest:a1414360-7c24-4730-8c97-180bf7775a71:ide:0:0 0002c6df-a1d2-4d1d-96f0-f95405a28183:guest:386f1cc7-affc-49c1-82a5-2f8e412170e4:ide:0:0 00031836-a624-4b22-bc7d-41ff8977087b:guest:17b076be-430d-4a76-9df3-b9896fec82a5:ide:0:0 000663ee-9fb6-4461-90f6-01327a4aff07:guest:f83b519f-feab-42cf-859c-f61495681ada:ide:0:1 -drive_type installcd,livecd -autoexpanding false readers ffffffff-ffff-ffff-ffff-ffffffffffff read:requests 1 -free true -type disk write:requests 2097153 size 8589934592 user:foo bar diff --git a/sandbox/elastichosts/src/test/resources/uuids.txt b/sandbox/elastichosts/src/test/resources/uuids.txt index b54f833b87..092a4f8d6d 100644 --- a/sandbox/elastichosts/src/test/resources/uuids.txt +++ b/sandbox/elastichosts/src/test/resources/uuids.txt @@ -1,3 +1,3 @@ 7e8ab721-81c9-4cb9-a651-4cafbfe1501c ea6a8fdb-dab3-4d06-86c2-41a5835e6ed9 -74744450-d338-4087-b3b8-59b505110a57 \ No newline at end of file +74744450-d338-4087-b3b8-59b505110a57 From 51f40c84bfb220d863fef8f772793c6b97074498 Mon Sep 17 00:00:00 2001 From: Adrian Cole Date: Fri, 3 Dec 2010 18:44:39 +0000 Subject: [PATCH 19/31] renamed elastichosts to elasticstack --- core/src/main/resources/rest.properties | 4 +- .../{elastichosts => elasticstack}/pom.xml | 36 +++--- .../cloudsigma/CloudSigmaAsyncClient.java | 34 +++--- .../jclouds/cloudsigma/CloudSigmaClient.java | 10 +- .../cloudsigma/CloudSigmaContextBuilder.java | 0 .../CloudSigmaPropertiesBuilder.java | 0 .../config/CloudSigmaRestClientModule.java | 12 +- .../jclouds/cloudsigma/domain/DriveInfo.java | 10 +- .../jclouds/cloudsigma/domain/DriveType.java | 0 .../functions/CreateDriveRequestToMap.java | 6 +- .../cloudsigma/functions/DriveDataToMap.java | 6 +- ...aluesDelimitedByBlankLinesToDriveInfo.java | 0 ...esDelimitedByBlankLinesToDriveInfoSet.java | 2 +- .../cloudsigma/functions/MapToDriveInfo.java | 4 +- .../CommonElasticStackAsyncClient.java} | 36 +++--- .../CommonElasticStackClient.java} | 16 +-- .../ElasticStackAsyncClient.java} | 28 ++--- .../elasticstack/ElasticStackClient.java} | 16 +-- .../ElasticStackContextBuilder.java} | 14 +-- .../ElasticStackPropertiesBuilder.java} | 8 +- ...ndCreateDriveRequestToPlainTextString.java | 6 +- .../BindDriveDataToPlainTextString.java | 6 +- .../binders/BindReadDriveOptionsToPath.java | 4 +- .../config/ElasticStackRestClientModule.java} | 30 ++--- .../elasticstack}/domain/BlockDevice.java | 2 +- .../elasticstack}/domain/ClaimType.java | 2 +- .../domain/CreateDriveRequest.java | 4 +- .../jclouds/elasticstack}/domain/Device.java | 2 +- .../elasticstack}/domain/DriveData.java | 4 +- .../elasticstack}/domain/DriveInfo.java | 4 +- .../elasticstack}/domain/DriveStatus.java | 2 +- .../elasticstack}/domain/IDEDevice.java | 2 +- .../domain/ImageConversionType.java | 2 +- .../jclouds/elasticstack}/domain/Item.java | 2 +- .../elasticstack}/domain/MediaType.java | 2 +- .../jclouds/elasticstack}/domain/Model.java | 2 +- .../org/jclouds/elasticstack}/domain/NIC.java | 2 +- .../elasticstack}/domain/SCSIDevice.java | 2 +- .../jclouds/elasticstack}/domain/Server.java | 2 +- .../org/jclouds/elasticstack}/domain/VNC.java | 2 +- .../domain/internal/BaseDrive.java | 6 +- .../functions/BaseDriveToMap.java | 6 +- .../functions/CreateDriveRequestToMap.java | 4 +- .../functions/DriveDataToMap.java | 4 +- ...aluesDelimitedByBlankLinesToDriveInfo.java | 4 +- ...esDelimitedByBlankLinesToDriveInfoSet.java | 4 +- ...luesDelimitedByBlankLinesToListOfMaps.java | 2 +- ...oListOfKeyValuesDelimitedByBlankLines.java | 2 +- .../functions/MapToDriveInfo.java | 8 +- .../functions/ReturnPayload.java | 2 +- .../functions/SplitNewlines.java | 2 +- .../handlers/ElasticStackErrorHandler.java} | 4 +- .../options/ReadDriveOptions.java | 4 +- .../cloudsigma/CloudSigmaAsyncClientTest.java | 6 +- .../cloudsigma/CloudSigmaClientLiveTest.java | 6 +- .../cloudsigma/ProvidersInPropertiesTest.java | 0 ...sDelimitedByBlankLinesToDriveInfoTest.java | 0 ...limitedByBlankLinesToDriveInfoSetTest.java | 0 .../functions/MapToDriveInfoTest.java | 8 +- .../CommonElasticStackClientLiveTest.java} | 18 +-- .../ElasticStackAsyncClientTest.java} | 108 +++++++++--------- .../ElasticStackClientLiveTest.java} | 16 +-- .../ProvidersInPropertiesTest.java | 4 +- ...eateDriveRequestToPlainTextStringTest.java | 12 +- .../BindDriveDataToPlainTextStringTest.java | 12 +- .../BindReadDriveOptionsToPathTest.java | 4 +- .../functions/BaseDriveToMapTest.java | 6 +- .../CreateDriveRequestToMapTest.java | 6 +- .../functions/DriveDataToMapTest.java | 6 +- ...sDelimitedByBlankLinesToDriveInfoTest.java | 2 +- ...limitedByBlankLinesToDriveInfoSetTest.java | 4 +- ...DelimitedByBlankLinesToListOfMapsTest.java | 2 +- ...tOfKeyValuesDelimitedByBlankLinesTest.java | 2 +- .../functions/MapToDriveInfoTest.java | 8 +- .../functions/SplitNewlinesTest.java | 4 +- .../ElasticStackErrorHandlerTest.java} | 18 +-- .../options/ReadDriveOptionsTest.java | 6 +- .../src/test/resources/cloudsigma/drive.txt | 0 .../src/test/resources/create_drive.txt | 0 .../src/test/resources/drive.txt | 0 .../src/test/resources/drive_data.txt | 0 .../src/test/resources/log4j.xml | 0 .../src/test/resources/uuids.txt | 0 83 files changed, 318 insertions(+), 318 deletions(-) rename sandbox/{elastichosts => elasticstack}/pom.xml (83%) rename sandbox/{elastichosts => elasticstack}/src/main/java/org/jclouds/cloudsigma/CloudSigmaAsyncClient.java (79%) rename sandbox/{elastichosts => elasticstack}/src/main/java/org/jclouds/cloudsigma/CloudSigmaClient.java (87%) rename sandbox/{elastichosts => elasticstack}/src/main/java/org/jclouds/cloudsigma/CloudSigmaContextBuilder.java (100%) rename sandbox/{elastichosts => elasticstack}/src/main/java/org/jclouds/cloudsigma/CloudSigmaPropertiesBuilder.java (100%) rename sandbox/{elastichosts => elasticstack}/src/main/java/org/jclouds/cloudsigma/config/CloudSigmaRestClientModule.java (89%) rename sandbox/{elastichosts => elasticstack}/src/main/java/org/jclouds/cloudsigma/domain/DriveInfo.java (97%) rename sandbox/{elastichosts => elasticstack}/src/main/java/org/jclouds/cloudsigma/domain/DriveType.java (100%) rename sandbox/{elastichosts => elasticstack}/src/main/java/org/jclouds/cloudsigma/functions/CreateDriveRequestToMap.java (90%) rename sandbox/{elastichosts => elasticstack}/src/main/java/org/jclouds/cloudsigma/functions/DriveDataToMap.java (90%) rename sandbox/{elastichosts => elasticstack}/src/main/java/org/jclouds/cloudsigma/functions/KeyValuesDelimitedByBlankLinesToDriveInfo.java (100%) rename sandbox/{elastichosts => elasticstack}/src/main/java/org/jclouds/cloudsigma/functions/ListOfKeyValuesDelimitedByBlankLinesToDriveInfoSet.java (97%) rename sandbox/{elastichosts => elasticstack}/src/main/java/org/jclouds/cloudsigma/functions/MapToDriveInfo.java (95%) rename sandbox/{elastichosts/src/main/java/org/jclouds/elastichosts/CommonElasticHostsAsyncClient.java => elasticstack/src/main/java/org/jclouds/elasticstack/CommonElasticStackAsyncClient.java} (77%) rename sandbox/{elastichosts/src/main/java/org/jclouds/elastichosts/CommonElasticHostsClient.java => elasticstack/src/main/java/org/jclouds/elasticstack/CommonElasticStackClient.java} (83%) rename sandbox/{elastichosts/src/main/java/org/jclouds/elastichosts/ElasticHostsAsyncClient.java => elasticstack/src/main/java/org/jclouds/elasticstack/ElasticStackAsyncClient.java} (80%) rename sandbox/{elastichosts/src/main/java/org/jclouds/elastichosts/ElasticHostsClient.java => elasticstack/src/main/java/org/jclouds/elasticstack/ElasticStackClient.java} (86%) rename sandbox/{elastichosts/src/main/java/org/jclouds/elastichosts/ElasticHostsContextBuilder.java => elasticstack/src/main/java/org/jclouds/elasticstack/ElasticStackContextBuilder.java} (73%) rename sandbox/{elastichosts/src/main/java/org/jclouds/elastichosts/ElasticHostsPropertiesBuilder.java => elasticstack/src/main/java/org/jclouds/elasticstack/ElasticStackPropertiesBuilder.java} (84%) rename sandbox/{elastichosts/src/main/java/org/jclouds/elastichosts => elasticstack/src/main/java/org/jclouds/elasticstack}/binders/BindCreateDriveRequestToPlainTextString.java (93%) rename sandbox/{elastichosts/src/main/java/org/jclouds/elastichosts => elasticstack/src/main/java/org/jclouds/elasticstack}/binders/BindDriveDataToPlainTextString.java (93%) rename sandbox/{elastichosts/src/main/java/org/jclouds/elastichosts => elasticstack/src/main/java/org/jclouds/elasticstack}/binders/BindReadDriveOptionsToPath.java (95%) rename sandbox/{elastichosts/src/main/java/org/jclouds/elastichosts/config/ElasticHostsRestClientModule.java => elasticstack/src/main/java/org/jclouds/elasticstack/config/ElasticStackRestClientModule.java} (69%) rename sandbox/{elastichosts/src/main/java/org/jclouds/elastichosts => elasticstack/src/main/java/org/jclouds/elasticstack}/domain/BlockDevice.java (97%) rename sandbox/{elastichosts/src/main/java/org/jclouds/elastichosts => elasticstack/src/main/java/org/jclouds/elasticstack}/domain/ClaimType.java (97%) rename sandbox/{elastichosts/src/main/java/org/jclouds/elastichosts => elasticstack/src/main/java/org/jclouds/elasticstack}/domain/CreateDriveRequest.java (98%) rename sandbox/{elastichosts/src/main/java/org/jclouds/elastichosts => elasticstack/src/main/java/org/jclouds/elasticstack}/domain/Device.java (98%) rename sandbox/{elastichosts/src/main/java/org/jclouds/elastichosts => elasticstack/src/main/java/org/jclouds/elasticstack}/domain/DriveData.java (96%) rename sandbox/{elastichosts/src/main/java/org/jclouds/elastichosts => elasticstack/src/main/java/org/jclouds/elasticstack}/domain/DriveInfo.java (99%) rename sandbox/{elastichosts/src/main/java/org/jclouds/elastichosts => elasticstack/src/main/java/org/jclouds/elasticstack}/domain/DriveStatus.java (97%) rename sandbox/{elastichosts/src/main/java/org/jclouds/elastichosts => elasticstack/src/main/java/org/jclouds/elasticstack}/domain/IDEDevice.java (98%) rename sandbox/{elastichosts/src/main/java/org/jclouds/elastichosts => elasticstack/src/main/java/org/jclouds/elasticstack}/domain/ImageConversionType.java (96%) rename sandbox/{elastichosts/src/main/java/org/jclouds/elastichosts => elasticstack/src/main/java/org/jclouds/elasticstack}/domain/Item.java (99%) rename sandbox/{elastichosts/src/main/java/org/jclouds/elastichosts => elasticstack/src/main/java/org/jclouds/elasticstack}/domain/MediaType.java (97%) rename sandbox/{elastichosts/src/main/java/org/jclouds/elastichosts => elasticstack/src/main/java/org/jclouds/elasticstack}/domain/Model.java (96%) rename sandbox/{elastichosts/src/main/java/org/jclouds/elastichosts => elasticstack/src/main/java/org/jclouds/elasticstack}/domain/NIC.java (98%) rename sandbox/{elastichosts/src/main/java/org/jclouds/elastichosts => elasticstack/src/main/java/org/jclouds/elasticstack}/domain/SCSIDevice.java (98%) rename sandbox/{elastichosts/src/main/java/org/jclouds/elastichosts => elasticstack/src/main/java/org/jclouds/elasticstack}/domain/Server.java (99%) rename sandbox/{elastichosts/src/main/java/org/jclouds/elastichosts => elasticstack/src/main/java/org/jclouds/elasticstack}/domain/VNC.java (98%) rename sandbox/{elastichosts/src/main/java/org/jclouds/elastichosts => elasticstack/src/main/java/org/jclouds/elasticstack}/domain/internal/BaseDrive.java (97%) rename sandbox/{elastichosts/src/main/java/org/jclouds/elastichosts => elasticstack/src/main/java/org/jclouds/elasticstack}/functions/BaseDriveToMap.java (92%) rename sandbox/{elastichosts/src/main/java/org/jclouds/elastichosts => elasticstack/src/main/java/org/jclouds/elasticstack}/functions/CreateDriveRequestToMap.java (94%) rename sandbox/{elastichosts/src/main/java/org/jclouds/elastichosts => elasticstack/src/main/java/org/jclouds/elasticstack}/functions/DriveDataToMap.java (94%) rename sandbox/{elastichosts/src/main/java/org/jclouds/elastichosts => elasticstack/src/main/java/org/jclouds/elasticstack}/functions/KeyValuesDelimitedByBlankLinesToDriveInfo.java (94%) rename sandbox/{elastichosts/src/main/java/org/jclouds/elastichosts => elasticstack/src/main/java/org/jclouds/elasticstack}/functions/ListOfKeyValuesDelimitedByBlankLinesToDriveInfoSet.java (95%) rename sandbox/{elastichosts/src/main/java/org/jclouds/elastichosts => elasticstack/src/main/java/org/jclouds/elasticstack}/functions/ListOfKeyValuesDelimitedByBlankLinesToListOfMaps.java (97%) rename sandbox/{elastichosts/src/main/java/org/jclouds/elastichosts => elasticstack/src/main/java/org/jclouds/elasticstack}/functions/ListOfMapsToListOfKeyValuesDelimitedByBlankLines.java (97%) rename sandbox/{elastichosts/src/main/java/org/jclouds/elastichosts => elasticstack/src/main/java/org/jclouds/elasticstack}/functions/MapToDriveInfo.java (93%) rename sandbox/{elastichosts/src/main/java/org/jclouds/elastichosts => elasticstack/src/main/java/org/jclouds/elasticstack}/functions/ReturnPayload.java (96%) rename sandbox/{elastichosts/src/main/java/org/jclouds/elastichosts => elasticstack/src/main/java/org/jclouds/elasticstack}/functions/SplitNewlines.java (97%) rename sandbox/{elastichosts/src/main/java/org/jclouds/elastichosts/handlers/ElasticHostsErrorHandler.java => elasticstack/src/main/java/org/jclouds/elasticstack/handlers/ElasticStackErrorHandler.java} (97%) rename sandbox/{elastichosts/src/main/java/org/jclouds/elastichosts => elasticstack/src/main/java/org/jclouds/elasticstack}/options/ReadDriveOptions.java (95%) rename sandbox/{elastichosts => elasticstack}/src/test/java/org/jclouds/cloudsigma/CloudSigmaAsyncClientTest.java (98%) rename sandbox/{elastichosts => elasticstack}/src/test/java/org/jclouds/cloudsigma/CloudSigmaClientLiveTest.java (91%) rename sandbox/{elastichosts => elasticstack}/src/test/java/org/jclouds/cloudsigma/ProvidersInPropertiesTest.java (100%) rename sandbox/{elastichosts => elasticstack}/src/test/java/org/jclouds/cloudsigma/functions/KeyValuesDelimitedByBlankLinesToDriveInfoTest.java (100%) rename sandbox/{elastichosts => elasticstack}/src/test/java/org/jclouds/cloudsigma/functions/ListOfKeyValuesDelimitedByBlankLinesToDriveInfoSetTest.java (100%) rename sandbox/{elastichosts => elasticstack}/src/test/java/org/jclouds/cloudsigma/functions/MapToDriveInfoTest.java (94%) rename sandbox/{elastichosts/src/test/java/org/jclouds/elastichosts/CommonElasticHostsClientLiveTest.java => elasticstack/src/test/java/org/jclouds/elasticstack/CommonElasticStackClientLiveTest.java} (91%) rename sandbox/{elastichosts/src/test/java/org/jclouds/elastichosts/ElasticHostsAsyncClientTest.java => elasticstack/src/test/java/org/jclouds/elasticstack/ElasticStackAsyncClientTest.java} (77%) rename sandbox/{elastichosts/src/test/java/org/jclouds/elastichosts/ElasticHostsClientLiveTest.java => elasticstack/src/test/java/org/jclouds/elasticstack/ElasticStackClientLiveTest.java} (84%) rename sandbox/{elastichosts/src/test/java/org/jclouds/elastichosts => elasticstack/src/test/java/org/jclouds/elasticstack}/ProvidersInPropertiesTest.java (93%) rename sandbox/{elastichosts/src/test/java/org/jclouds/elastichosts => elasticstack/src/test/java/org/jclouds/elasticstack}/binders/BindCreateDriveRequestToPlainTextStringTest.java (91%) rename sandbox/{elastichosts/src/test/java/org/jclouds/elastichosts => elasticstack/src/test/java/org/jclouds/elasticstack}/binders/BindDriveDataToPlainTextStringTest.java (90%) rename sandbox/{elastichosts/src/test/java/org/jclouds/elastichosts => elasticstack/src/test/java/org/jclouds/elasticstack}/binders/BindReadDriveOptionsToPathTest.java (94%) rename sandbox/{elastichosts/src/test/java/org/jclouds/elastichosts => elasticstack/src/test/java/org/jclouds/elasticstack}/functions/BaseDriveToMapTest.java (93%) rename sandbox/{elastichosts/src/test/java/org/jclouds/elastichosts => elasticstack/src/test/java/org/jclouds/elasticstack}/functions/CreateDriveRequestToMapTest.java (94%) rename sandbox/{elastichosts/src/test/java/org/jclouds/elastichosts => elasticstack/src/test/java/org/jclouds/elasticstack}/functions/DriveDataToMapTest.java (94%) rename sandbox/{elastichosts/src/test/java/org/jclouds/elastichosts => elasticstack/src/test/java/org/jclouds/elasticstack}/functions/KeyValuesDelimitedByBlankLinesToDriveInfoTest.java (97%) rename sandbox/{elastichosts/src/test/java/org/jclouds/elastichosts => elasticstack/src/test/java/org/jclouds/elasticstack}/functions/ListOfKeyValuesDelimitedByBlankLinesToDriveInfoSetTest.java (95%) rename sandbox/{elastichosts/src/test/java/org/jclouds/elastichosts => elasticstack/src/test/java/org/jclouds/elasticstack}/functions/ListOfKeyValuesDelimitedByBlankLinesToListOfMapsTest.java (98%) rename sandbox/{elastichosts/src/test/java/org/jclouds/elastichosts => elasticstack/src/test/java/org/jclouds/elasticstack}/functions/ListOfMapsToListOfKeyValuesDelimitedByBlankLinesTest.java (97%) rename sandbox/{elastichosts/src/test/java/org/jclouds/elastichosts => elasticstack/src/test/java/org/jclouds/elasticstack}/functions/MapToDriveInfoTest.java (94%) rename sandbox/{elastichosts/src/test/java/org/jclouds/elastichosts => elasticstack/src/test/java/org/jclouds/elasticstack}/functions/SplitNewlinesTest.java (94%) rename sandbox/{elastichosts/src/test/java/org/jclouds/elastichosts/handlers/ElasticHostsErrorHandlerTest.java => elasticstack/src/test/java/org/jclouds/elasticstack/handlers/ElasticStackErrorHandlerTest.java} (87%) rename sandbox/{elastichosts/src/test/java/org/jclouds/elastichosts => elasticstack/src/test/java/org/jclouds/elasticstack}/options/ReadDriveOptionsTest.java (93%) rename sandbox/{elastichosts => elasticstack}/src/test/resources/cloudsigma/drive.txt (100%) rename sandbox/{elastichosts => elasticstack}/src/test/resources/create_drive.txt (100%) rename sandbox/{elastichosts => elasticstack}/src/test/resources/drive.txt (100%) rename sandbox/{elastichosts => elasticstack}/src/test/resources/drive_data.txt (100%) rename sandbox/{elastichosts => elasticstack}/src/test/resources/log4j.xml (100%) rename sandbox/{elastichosts => elasticstack}/src/test/resources/uuids.txt (100%) diff --git a/core/src/main/resources/rest.properties b/core/src/main/resources/rest.properties index b971ca617f..65ce7ab602 100644 --- a/core/src/main/resources/rest.properties +++ b/core/src/main/resources/rest.properties @@ -89,8 +89,8 @@ bluelock-vcdirector.propertiesbuilder=org.jclouds.vcloud.bluelock.BlueLockVCloud gogrid.propertiesbuilder=org.jclouds.gogrid.GoGridPropertiesBuilder gogrid.contextbuilder=org.jclouds.gogrid.GoGridContextBuilder -elastichosts.propertiesbuilder=org.jclouds.elastichosts.ElasticHostsPropertiesBuilder -elastichosts.contextbuilder=org.jclouds.elastichosts.ElasticHostsContextBuilder +elasticstack.propertiesbuilder=org.jclouds.elasticstack.ElasticStackPropertiesBuilder +elasticstack.contextbuilder=org.jclouds.elasticstack.ElasticStackContextBuilder cloudsigma.propertiesbuilder=org.jclouds.cloudsigma.CloudSigmaPropertiesBuilder cloudsigma.contextbuilder=org.jclouds.cloudsigma.CloudSigmaContextBuilder diff --git a/sandbox/elastichosts/pom.xml b/sandbox/elasticstack/pom.xml similarity index 83% rename from sandbox/elastichosts/pom.xml rename to sandbox/elasticstack/pom.xml index 8a58d9789a..9e3d3d15dd 100644 --- a/sandbox/elastichosts/pom.xml +++ b/sandbox/elasticstack/pom.xml @@ -31,14 +31,14 @@ ../../project/pom.xml org.jclouds - jclouds-elastichosts - jclouds ElasticHosts core - jclouds components to access ElasticHosts + jclouds-elasticstack + jclouds elasticstack core + jclouds components to access elasticstack - scm:svn:http://jclouds.googlecode.com/svn/trunk/elastichosts - scm:svn:https://jclouds.googlecode.com/svn/trunk/elastichosts - http://jclouds.googlecode.com/svn/trunk/elastichosts + scm:svn:http://jclouds.googlecode.com/svn/trunk/elasticstack + scm:svn:https://jclouds.googlecode.com/svn/trunk/elasticstack + http://jclouds.googlecode.com/svn/trunk/elasticstack @@ -59,10 +59,10 @@ trmkrun-ccc,test.trmk-924 - https://api.cloudsigma.com - 1.0 - FIXME - FIXME + https://api.cloudsigma.com + 1.0 + FIXME + FIXME @@ -108,20 +108,20 @@ - test.elastichosts.endpoint - ${test.elastichosts.endpoint} + test.elasticstack.endpoint + ${test.elasticstack.endpoint} - test.elastichosts.apiversion - ${test.elastichosts.apiversion} + test.elasticstack.apiversion + ${test.elasticstack.apiversion} - test.elastichosts.identity - ${test.elastichosts.identity} + test.elasticstack.identity + ${test.elasticstack.identity} - test.elastichosts.credential - ${test.elastichosts.credential} + test.elasticstack.credential + ${test.elasticstack.credential} jclouds.compute.blacklist-nodes diff --git a/sandbox/elastichosts/src/main/java/org/jclouds/cloudsigma/CloudSigmaAsyncClient.java b/sandbox/elasticstack/src/main/java/org/jclouds/cloudsigma/CloudSigmaAsyncClient.java similarity index 79% rename from sandbox/elastichosts/src/main/java/org/jclouds/cloudsigma/CloudSigmaAsyncClient.java rename to sandbox/elasticstack/src/main/java/org/jclouds/cloudsigma/CloudSigmaAsyncClient.java index 7530f2e3ae..45d2c2dba4 100644 --- a/sandbox/elastichosts/src/main/java/org/jclouds/cloudsigma/CloudSigmaAsyncClient.java +++ b/sandbox/elasticstack/src/main/java/org/jclouds/cloudsigma/CloudSigmaAsyncClient.java @@ -31,13 +31,13 @@ import javax.ws.rs.core.MediaType; import org.jclouds.cloudsigma.domain.DriveInfo; import org.jclouds.cloudsigma.functions.KeyValuesDelimitedByBlankLinesToDriveInfo; import org.jclouds.cloudsigma.functions.ListOfKeyValuesDelimitedByBlankLinesToDriveInfoSet; -import org.jclouds.elastichosts.CommonElasticHostsAsyncClient; -import org.jclouds.elastichosts.ElasticHostsClient; -import org.jclouds.elastichosts.binders.BindCreateDriveRequestToPlainTextString; -import org.jclouds.elastichosts.binders.BindDriveDataToPlainTextString; -import org.jclouds.elastichosts.domain.CreateDriveRequest; -import org.jclouds.elastichosts.domain.DriveData; -import org.jclouds.elastichosts.functions.SplitNewlines; +import org.jclouds.elasticstack.CommonElasticStackAsyncClient; +import org.jclouds.elasticstack.ElasticStackClient; +import org.jclouds.elasticstack.binders.BindCreateDriveRequestToPlainTextString; +import org.jclouds.elasticstack.binders.BindDriveDataToPlainTextString; +import org.jclouds.elasticstack.domain.CreateDriveRequest; +import org.jclouds.elasticstack.domain.DriveData; +import org.jclouds.elasticstack.functions.SplitNewlines; import org.jclouds.http.filters.BasicAuthentication; import org.jclouds.rest.annotations.BinderParam; import org.jclouds.rest.annotations.ExceptionParser; @@ -51,16 +51,16 @@ import com.google.common.util.concurrent.ListenableFuture; * Provides asynchronous access to CloudSigma via their REST API. *

* - * @see ElasticHostsClient + * @see ElasticStackClient * @see * @author Adrian Cole */ @RequestFilters(BasicAuthentication.class) @Consumes(MediaType.TEXT_PLAIN) -public interface CloudSigmaAsyncClient extends CommonElasticHostsAsyncClient { +public interface CloudSigmaAsyncClient extends CommonElasticStackAsyncClient { /** - * @see ElasticHostsClient#listStandardDrives() + * @see ElasticStackClient#listStandardDrives() */ @GET @Path("/drives/standard/list") @@ -68,7 +68,7 @@ public interface CloudSigmaAsyncClient extends CommonElasticHostsAsyncClient { ListenableFuture> listStandardDrives(); /** - * @see ElasticHostsClient#listStandardCds() + * @see ElasticStackClient#listStandardCds() */ @GET @Path("/drives/standard/cd/list") @@ -76,7 +76,7 @@ public interface CloudSigmaAsyncClient extends CommonElasticHostsAsyncClient { ListenableFuture> listStandardCds(); /** - * @see ElasticHostsClient#listStandardImages() + * @see ElasticStackClient#listStandardImages() */ @GET @Path("/drives/standard/img/list") @@ -84,16 +84,16 @@ public interface CloudSigmaAsyncClient extends CommonElasticHostsAsyncClient { ListenableFuture> listStandardImages(); /** - * @see ElasticHostsClient#listDriveInfo() + * @see ElasticStackClient#listDriveInfo() */ @Override @GET @Path("/drives/info") @ResponseParser(ListOfKeyValuesDelimitedByBlankLinesToDriveInfoSet.class) - ListenableFuture> listDriveInfo(); + ListenableFuture> listDriveInfo(); /** - * @see ElasticHostsClient#getDriveInfo + * @see ElasticStackClient#getDriveInfo */ @Override @GET @@ -103,7 +103,7 @@ public interface CloudSigmaAsyncClient extends CommonElasticHostsAsyncClient { ListenableFuture getDriveInfo(@PathParam("uuid") String uuid); /** - * @see ElasticHostsClient#createDrive + * @see ElasticStackClient#createDrive */ @Override @POST @@ -114,7 +114,7 @@ public interface CloudSigmaAsyncClient extends CommonElasticHostsAsyncClient { @BinderParam(BindCreateDriveRequestToPlainTextString.class) CreateDriveRequest createDrive); /** - * @see ElasticHostsClient#setDriveData + * @see ElasticStackClient#setDriveData */ @POST @ExceptionParser(ReturnNullOnNotFoundOr404.class) diff --git a/sandbox/elastichosts/src/main/java/org/jclouds/cloudsigma/CloudSigmaClient.java b/sandbox/elasticstack/src/main/java/org/jclouds/cloudsigma/CloudSigmaClient.java similarity index 87% rename from sandbox/elastichosts/src/main/java/org/jclouds/cloudsigma/CloudSigmaClient.java rename to sandbox/elasticstack/src/main/java/org/jclouds/cloudsigma/CloudSigmaClient.java index 512cea40ec..354ee916af 100644 --- a/sandbox/elastichosts/src/main/java/org/jclouds/cloudsigma/CloudSigmaClient.java +++ b/sandbox/elasticstack/src/main/java/org/jclouds/cloudsigma/CloudSigmaClient.java @@ -24,20 +24,20 @@ import java.util.concurrent.TimeUnit; import org.jclouds.cloudsigma.domain.DriveInfo; import org.jclouds.concurrent.Timeout; -import org.jclouds.elastichosts.CommonElasticHostsClient; -import org.jclouds.elastichosts.domain.CreateDriveRequest; -import org.jclouds.elastichosts.domain.DriveData; +import org.jclouds.elasticstack.CommonElasticStackClient; +import org.jclouds.elasticstack.domain.CreateDriveRequest; +import org.jclouds.elasticstack.domain.DriveData; /** * Provides synchronous access to CloudSigma. *

* * @see CloudSigmaAsyncClient - * @see + * @see * @author Adrian Cole */ @Timeout(duration = 60, timeUnit = TimeUnit.SECONDS) -public interface CloudSigmaClient extends CommonElasticHostsClient { +public interface CloudSigmaClient extends CommonElasticStackClient { /** * list of drive uuids that are in the library diff --git a/sandbox/elastichosts/src/main/java/org/jclouds/cloudsigma/CloudSigmaContextBuilder.java b/sandbox/elasticstack/src/main/java/org/jclouds/cloudsigma/CloudSigmaContextBuilder.java similarity index 100% rename from sandbox/elastichosts/src/main/java/org/jclouds/cloudsigma/CloudSigmaContextBuilder.java rename to sandbox/elasticstack/src/main/java/org/jclouds/cloudsigma/CloudSigmaContextBuilder.java diff --git a/sandbox/elastichosts/src/main/java/org/jclouds/cloudsigma/CloudSigmaPropertiesBuilder.java b/sandbox/elasticstack/src/main/java/org/jclouds/cloudsigma/CloudSigmaPropertiesBuilder.java similarity index 100% rename from sandbox/elastichosts/src/main/java/org/jclouds/cloudsigma/CloudSigmaPropertiesBuilder.java rename to sandbox/elasticstack/src/main/java/org/jclouds/cloudsigma/CloudSigmaPropertiesBuilder.java diff --git a/sandbox/elastichosts/src/main/java/org/jclouds/cloudsigma/config/CloudSigmaRestClientModule.java b/sandbox/elasticstack/src/main/java/org/jclouds/cloudsigma/config/CloudSigmaRestClientModule.java similarity index 89% rename from sandbox/elastichosts/src/main/java/org/jclouds/cloudsigma/config/CloudSigmaRestClientModule.java rename to sandbox/elasticstack/src/main/java/org/jclouds/cloudsigma/config/CloudSigmaRestClientModule.java index cc1e5815f2..453362e8ae 100644 --- a/sandbox/elastichosts/src/main/java/org/jclouds/cloudsigma/config/CloudSigmaRestClientModule.java +++ b/sandbox/elasticstack/src/main/java/org/jclouds/cloudsigma/config/CloudSigmaRestClientModule.java @@ -25,9 +25,9 @@ import org.jclouds.cloudsigma.CloudSigmaAsyncClient; import org.jclouds.cloudsigma.CloudSigmaClient; import org.jclouds.cloudsigma.functions.CreateDriveRequestToMap; import org.jclouds.cloudsigma.functions.DriveDataToMap; -import org.jclouds.elastichosts.domain.CreateDriveRequest; -import org.jclouds.elastichosts.domain.DriveData; -import org.jclouds.elastichosts.handlers.ElasticHostsErrorHandler; +import org.jclouds.elasticstack.domain.CreateDriveRequest; +import org.jclouds.elasticstack.domain.DriveData; +import org.jclouds.elasticstack.handlers.ElasticStackErrorHandler; import org.jclouds.http.HttpErrorHandler; import org.jclouds.http.RequiresHttp; import org.jclouds.http.annotation.ClientError; @@ -54,9 +54,9 @@ public class CloudSigmaRestClientModule extends RestClientModule> { - private final org.jclouds.elastichosts.functions.CreateDriveRequestToMap baseDriveToMap; + private final org.jclouds.elasticstack.functions.CreateDriveRequestToMap baseDriveToMap; @Inject - public CreateDriveRequestToMap(org.jclouds.elastichosts.functions.CreateDriveRequestToMap baseDriveToMap) { + public CreateDriveRequestToMap(org.jclouds.elasticstack.functions.CreateDriveRequestToMap baseDriveToMap) { this.baseDriveToMap = baseDriveToMap; } diff --git a/sandbox/elastichosts/src/main/java/org/jclouds/cloudsigma/functions/DriveDataToMap.java b/sandbox/elasticstack/src/main/java/org/jclouds/cloudsigma/functions/DriveDataToMap.java similarity index 90% rename from sandbox/elastichosts/src/main/java/org/jclouds/cloudsigma/functions/DriveDataToMap.java rename to sandbox/elasticstack/src/main/java/org/jclouds/cloudsigma/functions/DriveDataToMap.java index a85395d637..715098e6b8 100644 --- a/sandbox/elastichosts/src/main/java/org/jclouds/cloudsigma/functions/DriveDataToMap.java +++ b/sandbox/elasticstack/src/main/java/org/jclouds/cloudsigma/functions/DriveDataToMap.java @@ -26,7 +26,7 @@ import java.util.Map; import javax.inject.Inject; import javax.inject.Singleton; -import org.jclouds.elastichosts.domain.DriveData; +import org.jclouds.elasticstack.domain.DriveData; import com.google.common.base.Function; import com.google.common.collect.Maps; @@ -37,10 +37,10 @@ import com.google.common.collect.Maps; */ @Singleton public class DriveDataToMap implements Function> { - private final org.jclouds.elastichosts.functions.DriveDataToMap baseDriveToMap; + private final org.jclouds.elasticstack.functions.DriveDataToMap baseDriveToMap; @Inject - public DriveDataToMap(org.jclouds.elastichosts.functions.DriveDataToMap baseDriveToMap) { + public DriveDataToMap(org.jclouds.elasticstack.functions.DriveDataToMap baseDriveToMap) { this.baseDriveToMap = baseDriveToMap; } diff --git a/sandbox/elastichosts/src/main/java/org/jclouds/cloudsigma/functions/KeyValuesDelimitedByBlankLinesToDriveInfo.java b/sandbox/elasticstack/src/main/java/org/jclouds/cloudsigma/functions/KeyValuesDelimitedByBlankLinesToDriveInfo.java similarity index 100% rename from sandbox/elastichosts/src/main/java/org/jclouds/cloudsigma/functions/KeyValuesDelimitedByBlankLinesToDriveInfo.java rename to sandbox/elasticstack/src/main/java/org/jclouds/cloudsigma/functions/KeyValuesDelimitedByBlankLinesToDriveInfo.java diff --git a/sandbox/elastichosts/src/main/java/org/jclouds/cloudsigma/functions/ListOfKeyValuesDelimitedByBlankLinesToDriveInfoSet.java b/sandbox/elasticstack/src/main/java/org/jclouds/cloudsigma/functions/ListOfKeyValuesDelimitedByBlankLinesToDriveInfoSet.java similarity index 97% rename from sandbox/elastichosts/src/main/java/org/jclouds/cloudsigma/functions/ListOfKeyValuesDelimitedByBlankLinesToDriveInfoSet.java rename to sandbox/elasticstack/src/main/java/org/jclouds/cloudsigma/functions/ListOfKeyValuesDelimitedByBlankLinesToDriveInfoSet.java index 6c56045561..3d7d1a3d53 100644 --- a/sandbox/elastichosts/src/main/java/org/jclouds/cloudsigma/functions/ListOfKeyValuesDelimitedByBlankLinesToDriveInfoSet.java +++ b/sandbox/elasticstack/src/main/java/org/jclouds/cloudsigma/functions/ListOfKeyValuesDelimitedByBlankLinesToDriveInfoSet.java @@ -25,7 +25,7 @@ import javax.inject.Inject; import javax.inject.Singleton; import org.jclouds.cloudsigma.domain.DriveInfo; -import org.jclouds.elastichosts.functions.ListOfKeyValuesDelimitedByBlankLinesToListOfMaps; +import org.jclouds.elasticstack.functions.ListOfKeyValuesDelimitedByBlankLinesToListOfMaps; import org.jclouds.http.HttpResponse; import org.jclouds.http.functions.ReturnStringIf2xx; diff --git a/sandbox/elastichosts/src/main/java/org/jclouds/cloudsigma/functions/MapToDriveInfo.java b/sandbox/elasticstack/src/main/java/org/jclouds/cloudsigma/functions/MapToDriveInfo.java similarity index 95% rename from sandbox/elastichosts/src/main/java/org/jclouds/cloudsigma/functions/MapToDriveInfo.java rename to sandbox/elasticstack/src/main/java/org/jclouds/cloudsigma/functions/MapToDriveInfo.java index b9074d3d26..2910718e2a 100644 --- a/sandbox/elastichosts/src/main/java/org/jclouds/cloudsigma/functions/MapToDriveInfo.java +++ b/sandbox/elasticstack/src/main/java/org/jclouds/cloudsigma/functions/MapToDriveInfo.java @@ -37,10 +37,10 @@ import com.google.common.base.Splitter; */ @Singleton public class MapToDriveInfo implements Function, DriveInfo> { - private final org.jclouds.elastichosts.functions.MapToDriveInfo mapToDriveInfo; + private final org.jclouds.elasticstack.functions.MapToDriveInfo mapToDriveInfo; @Inject - public MapToDriveInfo(org.jclouds.elastichosts.functions.MapToDriveInfo mapToDriveInfo) { + public MapToDriveInfo(org.jclouds.elasticstack.functions.MapToDriveInfo mapToDriveInfo) { this.mapToDriveInfo = mapToDriveInfo; } diff --git a/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/CommonElasticHostsAsyncClient.java b/sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/CommonElasticStackAsyncClient.java similarity index 77% rename from sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/CommonElasticHostsAsyncClient.java rename to sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/CommonElasticStackAsyncClient.java index 1a597533a9..193b155b72 100644 --- a/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/CommonElasticHostsAsyncClient.java +++ b/sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/CommonElasticStackAsyncClient.java @@ -17,7 +17,7 @@ * ==================================================================== */ -package org.jclouds.elastichosts; +package org.jclouds.elasticstack; import java.util.Set; @@ -28,14 +28,14 @@ import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.core.MediaType; -import org.jclouds.elastichosts.binders.BindCreateDriveRequestToPlainTextString; -import org.jclouds.elastichosts.binders.BindDriveDataToPlainTextString; -import org.jclouds.elastichosts.domain.CreateDriveRequest; -import org.jclouds.elastichosts.domain.DriveData; -import org.jclouds.elastichosts.domain.DriveInfo; -import org.jclouds.elastichosts.functions.KeyValuesDelimitedByBlankLinesToDriveInfo; -import org.jclouds.elastichosts.functions.ListOfKeyValuesDelimitedByBlankLinesToDriveInfoSet; -import org.jclouds.elastichosts.functions.SplitNewlines; +import org.jclouds.elasticstack.binders.BindCreateDriveRequestToPlainTextString; +import org.jclouds.elasticstack.binders.BindDriveDataToPlainTextString; +import org.jclouds.elasticstack.domain.CreateDriveRequest; +import org.jclouds.elasticstack.domain.DriveData; +import org.jclouds.elasticstack.domain.DriveInfo; +import org.jclouds.elasticstack.functions.KeyValuesDelimitedByBlankLinesToDriveInfo; +import org.jclouds.elasticstack.functions.ListOfKeyValuesDelimitedByBlankLinesToDriveInfoSet; +import org.jclouds.elasticstack.functions.SplitNewlines; import org.jclouds.http.filters.BasicAuthentication; import org.jclouds.rest.annotations.BinderParam; import org.jclouds.rest.annotations.ExceptionParser; @@ -47,19 +47,19 @@ import org.jclouds.rest.functions.ReturnVoidOnNotFoundOr404; import com.google.common.util.concurrent.ListenableFuture; /** - * Provides asynchronous access to ElasticHosts via their REST API. + * Provides asynchronous access to elasticstack via their REST API. *

* - * @see ElasticHostsClient + * @see ElasticStackClient * @see * @author Adrian Cole */ @RequestFilters(BasicAuthentication.class) @Consumes(MediaType.TEXT_PLAIN) -public interface CommonElasticHostsAsyncClient { +public interface CommonElasticStackAsyncClient { /** - * @see ElasticHostsClient#listDrives() + * @see ElasticStackClient#listDrives() */ @GET @Path("/drives/list") @@ -67,7 +67,7 @@ public interface CommonElasticHostsAsyncClient { ListenableFuture> listDrives(); /** - * @see ElasticHostsClient#listDriveInfo() + * @see ElasticStackClient#listDriveInfo() */ @GET @Path("/drives/info") @@ -75,7 +75,7 @@ public interface CommonElasticHostsAsyncClient { ListenableFuture> listDriveInfo(); /** - * @see ElasticHostsClient#getDriveInfo + * @see ElasticStackClient#getDriveInfo */ @GET @ExceptionParser(ReturnNullOnNotFoundOr404.class) @@ -84,7 +84,7 @@ public interface CommonElasticHostsAsyncClient { ListenableFuture getDriveInfo(@PathParam("uuid") String uuid); /** - * @see ElasticHostsClient#createDrive + * @see ElasticStackClient#createDrive */ @POST @ExceptionParser(ReturnNullOnNotFoundOr404.class) @@ -94,7 +94,7 @@ public interface CommonElasticHostsAsyncClient { @BinderParam(BindCreateDriveRequestToPlainTextString.class) CreateDriveRequest createDrive); /** - * @see ElasticHostsClient#setDriveData + * @see ElasticStackClient#setDriveData */ @POST @ExceptionParser(ReturnNullOnNotFoundOr404.class) @@ -104,7 +104,7 @@ public interface CommonElasticHostsAsyncClient { @BinderParam(BindDriveDataToPlainTextString.class) DriveData createDrive); /** - * @see ElasticHostsClient#destroyDrive + * @see ElasticStackClient#destroyDrive */ @POST @Path("/drives/{uuid}/destroy") diff --git a/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/CommonElasticHostsClient.java b/sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/CommonElasticStackClient.java similarity index 83% rename from sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/CommonElasticHostsClient.java rename to sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/CommonElasticStackClient.java index 940818591d..0f0acad24f 100644 --- a/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/CommonElasticHostsClient.java +++ b/sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/CommonElasticStackClient.java @@ -17,26 +17,26 @@ * ==================================================================== */ -package org.jclouds.elastichosts; +package org.jclouds.elasticstack; import java.util.Set; import java.util.concurrent.TimeUnit; import org.jclouds.concurrent.Timeout; -import org.jclouds.elastichosts.domain.CreateDriveRequest; -import org.jclouds.elastichosts.domain.DriveData; -import org.jclouds.elastichosts.domain.DriveInfo; +import org.jclouds.elasticstack.domain.CreateDriveRequest; +import org.jclouds.elasticstack.domain.DriveData; +import org.jclouds.elasticstack.domain.DriveInfo; /** - * Provides synchronous access to ElasticHosts. + * Provides synchronous access to elasticstack. *

* - * @see ElasticHostsAsyncClient - * @see + * @see ElasticStackAsyncClient + * @see * @author Adrian Cole */ @Timeout(duration = 60, timeUnit = TimeUnit.SECONDS) -public interface CommonElasticHostsClient { +public interface CommonElasticStackClient { /** * list of drive uuids in your account * diff --git a/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/ElasticHostsAsyncClient.java b/sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/ElasticStackAsyncClient.java similarity index 80% rename from sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/ElasticHostsAsyncClient.java rename to sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/ElasticStackAsyncClient.java index 211b25b448..4314cdfb24 100644 --- a/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/ElasticHostsAsyncClient.java +++ b/sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/ElasticStackAsyncClient.java @@ -17,7 +17,7 @@ * ==================================================================== */ -package org.jclouds.elastichosts; +package org.jclouds.elasticstack; import javax.ws.rs.Consumes; import javax.ws.rs.GET; @@ -27,10 +27,10 @@ import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; -import org.jclouds.elastichosts.binders.BindReadDriveOptionsToPath; -import org.jclouds.elastichosts.domain.ImageConversionType; -import org.jclouds.elastichosts.functions.ReturnPayload; -import org.jclouds.elastichosts.options.ReadDriveOptions; +import org.jclouds.elasticstack.binders.BindReadDriveOptionsToPath; +import org.jclouds.elasticstack.domain.ImageConversionType; +import org.jclouds.elasticstack.functions.ReturnPayload; +import org.jclouds.elasticstack.options.ReadDriveOptions; import org.jclouds.http.filters.BasicAuthentication; import org.jclouds.io.Payload; import org.jclouds.rest.annotations.BinderParam; @@ -43,19 +43,19 @@ import org.jclouds.rest.functions.ReturnVoidOnNotFoundOr404; import com.google.common.util.concurrent.ListenableFuture; /** - * Provides asynchronous access to ElasticHosts via their REST API. + * Provides asynchronous access to elasticstack via their REST API. *

* - * @see ElasticHostsClient + * @see ElasticStackClient * @see * @author Adrian Cole */ @RequestFilters(BasicAuthentication.class) @Consumes(MediaType.TEXT_PLAIN) -public interface ElasticHostsAsyncClient extends CommonElasticHostsAsyncClient { +public interface ElasticStackAsyncClient extends CommonElasticStackAsyncClient { /** - * @see ElasticHostsClient#imageDrive(String,String) + * @see ElasticStackClient#imageDrive(String,String) */ @POST @Path("/drives/{destination}/image/{source}") @@ -63,7 +63,7 @@ public interface ElasticHostsAsyncClient extends CommonElasticHostsAsyncClient { ListenableFuture imageDrive(@PathParam("source") String source, @PathParam("destination") String destination); /** - * @see ElasticHostsClient#imageDrive(String,String,ImageConversionType) + * @see ElasticStackClient#imageDrive(String,String,ImageConversionType) */ @POST @Path("/drives/{destination}/image/{source}/{conversion}") @@ -72,7 +72,7 @@ public interface ElasticHostsAsyncClient extends CommonElasticHostsAsyncClient { @PathParam("conversion") ImageConversionType conversionType); /** - * @see ElasticHostsClient#readDrive(String) + * @see ElasticStackClient#readDrive(String) */ @GET @Consumes(MediaType.APPLICATION_OCTET_STREAM) @@ -82,7 +82,7 @@ public interface ElasticHostsAsyncClient extends CommonElasticHostsAsyncClient { ListenableFuture readDrive(@PathParam("uuid") String uuid); /** - * @see ElasticHostsClient#readDrive(String,ReadDriveOptions) + * @see ElasticStackClient#readDrive(String,ReadDriveOptions) */ @POST @Consumes(MediaType.APPLICATION_OCTET_STREAM) @@ -93,7 +93,7 @@ public interface ElasticHostsAsyncClient extends CommonElasticHostsAsyncClient { @BinderParam(BindReadDriveOptionsToPath.class) ReadDriveOptions options); /** - * @see ElasticHostsClient#writeDrive(String, Payload) + * @see ElasticStackClient#writeDrive(String, Payload) */ @POST @Produces(MediaType.APPLICATION_OCTET_STREAM) @@ -102,7 +102,7 @@ public interface ElasticHostsAsyncClient extends CommonElasticHostsAsyncClient { ListenableFuture writeDrive(@PathParam("uuid") String uuid, Payload content); /** - * @see ElasticHostsClient#writeDrive(String, Payload, long) + * @see ElasticStackClient#writeDrive(String, Payload, long) */ @POST @Produces(MediaType.APPLICATION_OCTET_STREAM) diff --git a/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/ElasticHostsClient.java b/sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/ElasticStackClient.java similarity index 86% rename from sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/ElasticHostsClient.java rename to sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/ElasticStackClient.java index 9f5fa3df91..5d4998c366 100644 --- a/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/ElasticHostsClient.java +++ b/sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/ElasticStackClient.java @@ -17,25 +17,25 @@ * ==================================================================== */ -package org.jclouds.elastichosts; +package org.jclouds.elasticstack; import java.util.concurrent.TimeUnit; import org.jclouds.concurrent.Timeout; -import org.jclouds.elastichosts.domain.ImageConversionType; -import org.jclouds.elastichosts.options.ReadDriveOptions; +import org.jclouds.elasticstack.domain.ImageConversionType; +import org.jclouds.elasticstack.options.ReadDriveOptions; import org.jclouds.io.Payload; /** - * Provides synchronous access to ElasticHosts. + * Provides synchronous access to elasticstack. *

* - * @see ElasticHostsAsyncClient - * @see + * @see ElasticStackAsyncClient + * @see * @author Adrian Cole */ @Timeout(duration = 60, timeUnit = TimeUnit.SECONDS) -public interface ElasticHostsClient extends CommonElasticHostsClient { +public interface ElasticStackClient extends CommonElasticStackClient { /** * Image a drive from another drive. The actual imaging process is asynchronous, with progress @@ -87,7 +87,7 @@ public interface ElasticHostsClient extends CommonElasticHostsClient { void writeDrive(String uuid, Payload content); /** - * @see ElasticHostsClient#writeDrive(String, Payload) + * @see ElasticStackClient#writeDrive(String, Payload) * @param offset * the byte offset in the target drive at which to start writing, not an offset in the * input stream. diff --git a/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/ElasticHostsContextBuilder.java b/sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/ElasticStackContextBuilder.java similarity index 73% rename from sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/ElasticHostsContextBuilder.java rename to sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/ElasticStackContextBuilder.java index 8090e5ad5a..9a072d3dac 100644 --- a/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/ElasticHostsContextBuilder.java +++ b/sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/ElasticStackContextBuilder.java @@ -17,12 +17,12 @@ * ==================================================================== */ -package org.jclouds.elastichosts; +package org.jclouds.elasticstack; import java.util.List; import java.util.Properties; -import org.jclouds.elastichosts.config.ElasticHostsRestClientModule; +import org.jclouds.elasticstack.config.ElasticStackRestClientModule; import org.jclouds.rest.RestContextBuilder; import com.google.inject.Module; @@ -31,15 +31,15 @@ import com.google.inject.Module; * * @author Adrian Cole */ -public class ElasticHostsContextBuilder extends - RestContextBuilder { +public class ElasticStackContextBuilder extends + RestContextBuilder { - public ElasticHostsContextBuilder(Properties props) { - super(ElasticHostsClient.class, ElasticHostsAsyncClient.class, props); + public ElasticStackContextBuilder(Properties props) { + super(ElasticStackClient.class, ElasticStackAsyncClient.class, props); } protected void addClientModule(List modules) { - modules.add(new ElasticHostsRestClientModule()); + modules.add(new ElasticStackRestClientModule()); } } diff --git a/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/ElasticHostsPropertiesBuilder.java b/sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/ElasticStackPropertiesBuilder.java similarity index 84% rename from sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/ElasticHostsPropertiesBuilder.java rename to sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/ElasticStackPropertiesBuilder.java index 19e536294d..4f1b2bd9ee 100644 --- a/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/ElasticHostsPropertiesBuilder.java +++ b/sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/ElasticStackPropertiesBuilder.java @@ -17,7 +17,7 @@ * ==================================================================== */ -package org.jclouds.elastichosts; +package org.jclouds.elasticstack; import static org.jclouds.Constants.PROPERTY_API_VERSION; @@ -26,11 +26,11 @@ import java.util.Properties; import org.jclouds.PropertiesBuilder; /** - * Builds properties used in ElasticHosts Clients + * Builds properties used in elasticstack Clients * * @author Adrian Cole */ -public class ElasticHostsPropertiesBuilder extends PropertiesBuilder { +public class ElasticStackPropertiesBuilder extends PropertiesBuilder { @Override protected Properties defaultProperties() { Properties properties = super.defaultProperties(); @@ -38,7 +38,7 @@ public class ElasticHostsPropertiesBuilder extends PropertiesBuilder { return properties; } - public ElasticHostsPropertiesBuilder(Properties properties) { + public ElasticStackPropertiesBuilder(Properties properties) { super(properties); } diff --git a/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/binders/BindCreateDriveRequestToPlainTextString.java b/sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/binders/BindCreateDriveRequestToPlainTextString.java similarity index 93% rename from sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/binders/BindCreateDriveRequestToPlainTextString.java rename to sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/binders/BindCreateDriveRequestToPlainTextString.java index f634ffa27f..332cbd06ed 100644 --- a/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/binders/BindCreateDriveRequestToPlainTextString.java +++ b/sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/binders/BindCreateDriveRequestToPlainTextString.java @@ -17,7 +17,7 @@ * ==================================================================== */ -package org.jclouds.elastichosts.binders; +package org.jclouds.elasticstack.binders; import static com.google.common.base.Preconditions.checkArgument; @@ -27,8 +27,8 @@ import javax.inject.Inject; import javax.inject.Singleton; import javax.ws.rs.core.MediaType; -import org.jclouds.elastichosts.domain.CreateDriveRequest; -import org.jclouds.elastichosts.functions.ListOfMapsToListOfKeyValuesDelimitedByBlankLines; +import org.jclouds.elasticstack.domain.CreateDriveRequest; +import org.jclouds.elasticstack.functions.ListOfMapsToListOfKeyValuesDelimitedByBlankLines; import org.jclouds.http.HttpRequest; import org.jclouds.rest.Binder; diff --git a/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/binders/BindDriveDataToPlainTextString.java b/sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/binders/BindDriveDataToPlainTextString.java similarity index 93% rename from sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/binders/BindDriveDataToPlainTextString.java rename to sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/binders/BindDriveDataToPlainTextString.java index 631bb8b181..006565b8c6 100644 --- a/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/binders/BindDriveDataToPlainTextString.java +++ b/sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/binders/BindDriveDataToPlainTextString.java @@ -17,7 +17,7 @@ * ==================================================================== */ -package org.jclouds.elastichosts.binders; +package org.jclouds.elasticstack.binders; import static com.google.common.base.Preconditions.checkArgument; @@ -27,8 +27,8 @@ import javax.inject.Inject; import javax.inject.Singleton; import javax.ws.rs.core.MediaType; -import org.jclouds.elastichosts.domain.DriveData; -import org.jclouds.elastichosts.functions.ListOfMapsToListOfKeyValuesDelimitedByBlankLines; +import org.jclouds.elasticstack.domain.DriveData; +import org.jclouds.elasticstack.functions.ListOfMapsToListOfKeyValuesDelimitedByBlankLines; import org.jclouds.http.HttpRequest; import org.jclouds.rest.Binder; diff --git a/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/binders/BindReadDriveOptionsToPath.java b/sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/binders/BindReadDriveOptionsToPath.java similarity index 95% rename from sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/binders/BindReadDriveOptionsToPath.java rename to sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/binders/BindReadDriveOptionsToPath.java index 367cdfe763..878b4bca3a 100644 --- a/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/binders/BindReadDriveOptionsToPath.java +++ b/sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/binders/BindReadDriveOptionsToPath.java @@ -17,7 +17,7 @@ * ==================================================================== */ -package org.jclouds.elastichosts.binders; +package org.jclouds.elasticstack.binders; import static com.google.common.base.Preconditions.checkArgument; @@ -26,7 +26,7 @@ import javax.inject.Provider; import javax.inject.Singleton; import javax.ws.rs.core.UriBuilder; -import org.jclouds.elastichosts.options.ReadDriveOptions; +import org.jclouds.elasticstack.options.ReadDriveOptions; import org.jclouds.http.HttpRequest; import org.jclouds.rest.Binder; diff --git a/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/config/ElasticHostsRestClientModule.java b/sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/config/ElasticStackRestClientModule.java similarity index 69% rename from sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/config/ElasticHostsRestClientModule.java rename to sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/config/ElasticStackRestClientModule.java index 129ae9d2c0..d8def53140 100644 --- a/sandbox/elastichosts/src/main/java/org/jclouds/elastichosts/config/ElasticHostsRestClientModule.java +++ b/sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/config/ElasticStackRestClientModule.java @@ -17,17 +17,17 @@ * ==================================================================== */ -package org.jclouds.elastichosts.config; +package org.jclouds.elasticstack.config; import java.util.Map; -import org.jclouds.elastichosts.ElasticHostsAsyncClient; -import org.jclouds.elastichosts.ElasticHostsClient; -import org.jclouds.elastichosts.domain.CreateDriveRequest; -import org.jclouds.elastichosts.domain.DriveData; -import org.jclouds.elastichosts.functions.CreateDriveRequestToMap; -import org.jclouds.elastichosts.functions.DriveDataToMap; -import org.jclouds.elastichosts.handlers.ElasticHostsErrorHandler; +import org.jclouds.elasticstack.ElasticStackAsyncClient; +import org.jclouds.elasticstack.ElasticStackClient; +import org.jclouds.elasticstack.domain.CreateDriveRequest; +import org.jclouds.elasticstack.domain.DriveData; +import org.jclouds.elasticstack.functions.CreateDriveRequestToMap; +import org.jclouds.elasticstack.functions.DriveDataToMap; +import org.jclouds.elasticstack.handlers.ElasticStackErrorHandler; import org.jclouds.http.HttpErrorHandler; import org.jclouds.http.RequiresHttp; import org.jclouds.http.annotation.ClientError; @@ -40,16 +40,16 @@ import com.google.common.base.Function; import com.google.inject.TypeLiteral; /** - * Configures the ElasticHosts connection. + * Configures the elasticstack connection. * * @author Adrian Cole */ @RequiresHttp @ConfiguresRestClient -public class ElasticHostsRestClientModule extends RestClientModule { +public class ElasticStackRestClientModule extends RestClientModule { - public ElasticHostsRestClientModule() { - super(ElasticHostsClient.class, ElasticHostsAsyncClient.class); + public ElasticStackRestClientModule() { + super(ElasticStackClient.class, ElasticStackAsyncClient.class); } @Override @@ -63,9 +63,9 @@ public class ElasticHostsRestClientModule extends RestClientModule * - * import static org.jclouds.elastichosts.options.ReadDriveOptions.Builder.*; + * import static org.jclouds.elasticstack.options.ReadDriveOptions.Builder.*; * * * // this will get the first 1024 bytes starting at offset 2048 diff --git a/sandbox/elastichosts/src/test/java/org/jclouds/cloudsigma/CloudSigmaAsyncClientTest.java b/sandbox/elasticstack/src/test/java/org/jclouds/cloudsigma/CloudSigmaAsyncClientTest.java similarity index 98% rename from sandbox/elastichosts/src/test/java/org/jclouds/cloudsigma/CloudSigmaAsyncClientTest.java rename to sandbox/elasticstack/src/test/java/org/jclouds/cloudsigma/CloudSigmaAsyncClientTest.java index 77d23d1103..df788fd86e 100644 --- a/sandbox/elastichosts/src/test/java/org/jclouds/cloudsigma/CloudSigmaAsyncClientTest.java +++ b/sandbox/elasticstack/src/test/java/org/jclouds/cloudsigma/CloudSigmaAsyncClientTest.java @@ -27,9 +27,9 @@ import java.util.Properties; import org.jclouds.cloudsigma.functions.KeyValuesDelimitedByBlankLinesToDriveInfo; import org.jclouds.cloudsigma.functions.ListOfKeyValuesDelimitedByBlankLinesToDriveInfoSet; -import org.jclouds.elastichosts.domain.CreateDriveRequest; -import org.jclouds.elastichosts.domain.DriveData; -import org.jclouds.elastichosts.functions.SplitNewlines; +import org.jclouds.elasticstack.domain.CreateDriveRequest; +import org.jclouds.elasticstack.domain.DriveData; +import org.jclouds.elasticstack.functions.SplitNewlines; import org.jclouds.http.HttpRequest; import org.jclouds.http.filters.BasicAuthentication; import org.jclouds.rest.RestClientTest; diff --git a/sandbox/elastichosts/src/test/java/org/jclouds/cloudsigma/CloudSigmaClientLiveTest.java b/sandbox/elasticstack/src/test/java/org/jclouds/cloudsigma/CloudSigmaClientLiveTest.java similarity index 91% rename from sandbox/elastichosts/src/test/java/org/jclouds/cloudsigma/CloudSigmaClientLiveTest.java rename to sandbox/elasticstack/src/test/java/org/jclouds/cloudsigma/CloudSigmaClientLiveTest.java index bc3fae31a3..223fa37d14 100644 --- a/sandbox/elastichosts/src/test/java/org/jclouds/cloudsigma/CloudSigmaClientLiveTest.java +++ b/sandbox/elasticstack/src/test/java/org/jclouds/cloudsigma/CloudSigmaClientLiveTest.java @@ -26,7 +26,7 @@ import java.util.Set; import org.jclouds.cloudsigma.domain.DriveInfo; import org.jclouds.cloudsigma.domain.DriveType; -import org.jclouds.elastichosts.CommonElasticHostsClientLiveTest; +import org.jclouds.elasticstack.CommonElasticStackClientLiveTest; import org.testng.annotations.Test; /** @@ -35,7 +35,7 @@ import org.testng.annotations.Test; * @author Adrian Cole */ @Test(groups = "live", testName = "cloudsigma.CloudSigmaClientLiveTest") -public class CloudSigmaClientLiveTest extends CommonElasticHostsClientLiveTest { +public class CloudSigmaClientLiveTest extends CommonElasticStackClientLiveTest { public CloudSigmaClientLiveTest() { provider = "cloudsigma"; @@ -59,7 +59,7 @@ public class CloudSigmaClientLiveTest extends CommonElasticHostsClientLiveTest of()), null); diff --git a/sandbox/elastichosts/src/test/java/org/jclouds/elastichosts/CommonElasticHostsClientLiveTest.java b/sandbox/elasticstack/src/test/java/org/jclouds/elasticstack/CommonElasticStackClientLiveTest.java similarity index 91% rename from sandbox/elastichosts/src/test/java/org/jclouds/elastichosts/CommonElasticHostsClientLiveTest.java rename to sandbox/elasticstack/src/test/java/org/jclouds/elasticstack/CommonElasticStackClientLiveTest.java index 835ee12a9d..28c8240a66 100644 --- a/sandbox/elastichosts/src/test/java/org/jclouds/elastichosts/CommonElasticHostsClientLiveTest.java +++ b/sandbox/elasticstack/src/test/java/org/jclouds/elasticstack/CommonElasticStackClientLiveTest.java @@ -17,7 +17,7 @@ * ==================================================================== */ -package org.jclouds.elastichosts; +package org.jclouds.elasticstack; import static com.google.common.base.Preconditions.checkNotNull; import static org.testng.Assert.assertEquals; @@ -27,11 +27,11 @@ import java.util.Properties; import java.util.Set; import org.jclouds.Constants; -import org.jclouds.elastichosts.domain.ClaimType; -import org.jclouds.elastichosts.domain.CreateDriveRequest; -import org.jclouds.elastichosts.domain.DriveData; -import org.jclouds.elastichosts.domain.DriveInfo; -import org.jclouds.elastichosts.domain.DriveStatus; +import org.jclouds.elasticstack.domain.ClaimType; +import org.jclouds.elasticstack.domain.CreateDriveRequest; +import org.jclouds.elasticstack.domain.DriveData; +import org.jclouds.elasticstack.domain.DriveInfo; +import org.jclouds.elasticstack.domain.DriveStatus; import org.jclouds.logging.log4j.config.Log4JLoggingModule; import org.jclouds.rest.RestContext; import org.jclouds.rest.RestContextFactory; @@ -44,17 +44,17 @@ import com.google.common.collect.ImmutableSet; import com.google.inject.Module; /** - * Tests behavior of {@code CommonElasticHostsClient} + * Tests behavior of {@code CommonElasticStackClient} * * @author Adrian Cole */ @Test(groups = "live", sequential = true) -public abstract class CommonElasticHostsClientLiveTest { +public abstract class CommonElasticStackClientLiveTest { protected S client; protected RestContext context; - protected String provider = "elastichosts"; + protected String provider = "elasticstack"; protected String identity; protected String credential; protected String endpoint; diff --git a/sandbox/elastichosts/src/test/java/org/jclouds/elastichosts/ElasticHostsAsyncClientTest.java b/sandbox/elasticstack/src/test/java/org/jclouds/elasticstack/ElasticStackAsyncClientTest.java similarity index 77% rename from sandbox/elastichosts/src/test/java/org/jclouds/elastichosts/ElasticHostsAsyncClientTest.java rename to sandbox/elasticstack/src/test/java/org/jclouds/elasticstack/ElasticStackAsyncClientTest.java index 093f5da40d..0cd9ebf7bf 100644 --- a/sandbox/elastichosts/src/test/java/org/jclouds/elastichosts/ElasticHostsAsyncClientTest.java +++ b/sandbox/elasticstack/src/test/java/org/jclouds/elasticstack/ElasticStackAsyncClientTest.java @@ -17,7 +17,7 @@ * ==================================================================== */ -package org.jclouds.elastichosts; +package org.jclouds.elasticstack; import static org.testng.Assert.assertEquals; @@ -27,14 +27,14 @@ import java.util.Properties; import javax.ws.rs.core.MediaType; -import org.jclouds.elastichosts.domain.CreateDriveRequest; -import org.jclouds.elastichosts.domain.DriveData; -import org.jclouds.elastichosts.domain.ImageConversionType; -import org.jclouds.elastichosts.functions.KeyValuesDelimitedByBlankLinesToDriveInfo; -import org.jclouds.elastichosts.functions.ListOfKeyValuesDelimitedByBlankLinesToDriveInfoSet; -import org.jclouds.elastichosts.functions.ReturnPayload; -import org.jclouds.elastichosts.functions.SplitNewlines; -import org.jclouds.elastichosts.options.ReadDriveOptions; +import org.jclouds.elasticstack.domain.CreateDriveRequest; +import org.jclouds.elasticstack.domain.DriveData; +import org.jclouds.elasticstack.domain.ImageConversionType; +import org.jclouds.elasticstack.functions.KeyValuesDelimitedByBlankLinesToDriveInfo; +import org.jclouds.elasticstack.functions.ListOfKeyValuesDelimitedByBlankLinesToDriveInfoSet; +import org.jclouds.elasticstack.functions.ReturnPayload; +import org.jclouds.elasticstack.functions.SplitNewlines; +import org.jclouds.elasticstack.options.ReadDriveOptions; import org.jclouds.http.HttpRequest; import org.jclouds.http.filters.BasicAuthentication; import org.jclouds.http.functions.ReleasePayloadAndReturn; @@ -54,18 +54,18 @@ import com.google.common.collect.Iterables; import com.google.inject.TypeLiteral; /** - * Tests annotation parsing of {@code ElasticHostsAsyncClient} + * Tests annotation parsing of {@code ElasticStackAsyncClient} * * @author Adrian Cole */ -@Test(groups = "unit", testName = "elastichosts.ElasticHostsAsyncClientTest") -public class ElasticHostsAsyncClientTest extends RestClientTest { +@Test(groups = "unit", testName = "elasticstack.ElasticStackAsyncClientTest") +public class ElasticStackAsyncClientTest extends RestClientTest { public void testListDrives() throws SecurityException, NoSuchMethodException, IOException { - Method method = ElasticHostsAsyncClient.class.getMethod("listDrives"); - GeneratedHttpRequest httpRequest = processor.createRequest(method); + Method method = ElasticStackAsyncClient.class.getMethod("listDrives"); + GeneratedHttpRequest httpRequest = processor.createRequest(method); - assertRequestLineEquals(httpRequest, "GET https://api.elastichosts.com/drives/list HTTP/1.1"); + assertRequestLineEquals(httpRequest, "GET https://api.elasticstack.com/drives/list HTTP/1.1"); assertNonPayloadHeadersEqual(httpRequest, "Accept: text/plain\n"); assertPayloadEquals(httpRequest, null, null, false); @@ -73,7 +73,7 @@ public class ElasticHostsAsyncClientTest extends RestClientTest httpRequest = processor.createRequest(method); + Method method = ElasticStackAsyncClient.class.getMethod("listDriveInfo"); + GeneratedHttpRequest httpRequest = processor.createRequest(method); - assertRequestLineEquals(httpRequest, "GET https://api.elastichosts.com/drives/info HTTP/1.1"); + assertRequestLineEquals(httpRequest, "GET https://api.elasticstack.com/drives/info HTTP/1.1"); assertNonPayloadHeadersEqual(httpRequest, "Accept: text/plain\n"); assertPayloadEquals(httpRequest, null, null, false); @@ -105,10 +105,10 @@ public class ElasticHostsAsyncClientTest extends RestClientTest httpRequest = processor.createRequest(method, "uuid"); + Method method = ElasticStackAsyncClient.class.getMethod("getDriveInfo", String.class); + GeneratedHttpRequest httpRequest = processor.createRequest(method, "uuid"); - assertRequestLineEquals(httpRequest, "GET https://api.elastichosts.com/drives/uuid/info HTTP/1.1"); + assertRequestLineEquals(httpRequest, "GET https://api.elasticstack.com/drives/uuid/info HTTP/1.1"); assertNonPayloadHeadersEqual(httpRequest, "Accept: text/plain\n"); assertPayloadEquals(httpRequest, null, null, false); @@ -121,11 +121,11 @@ public class ElasticHostsAsyncClientTest extends RestClientTest httpRequest = processor.createRequest(method, + Method method = ElasticStackAsyncClient.class.getMethod("createDrive", CreateDriveRequest.class); + GeneratedHttpRequest httpRequest = processor.createRequest(method, new CreateDriveRequest.Builder().name("foo").size(10000l).build()); - assertRequestLineEquals(httpRequest, "POST https://api.elastichosts.com/drives/create HTTP/1.1"); + assertRequestLineEquals(httpRequest, "POST https://api.elasticstack.com/drives/create HTTP/1.1"); assertNonPayloadHeadersEqual(httpRequest, "Accept: text/plain\n"); assertPayloadEquals(httpRequest, "name foo\nsize 10000", "text/plain", false); @@ -138,11 +138,11 @@ public class ElasticHostsAsyncClientTest extends RestClientTest httpRequest = processor.createRequest(method, "100", + Method method = ElasticStackAsyncClient.class.getMethod("setDriveData", String.class, DriveData.class); + GeneratedHttpRequest httpRequest = processor.createRequest(method, "100", new DriveData.Builder().name("foo").size(10000l).tags(ImmutableList.of("production", "candy")).build()); - assertRequestLineEquals(httpRequest, "POST https://api.elastichosts.com/drives/100/set HTTP/1.1"); + assertRequestLineEquals(httpRequest, "POST https://api.elasticstack.com/drives/100/set HTTP/1.1"); assertNonPayloadHeadersEqual(httpRequest, "Accept: text/plain\n"); assertPayloadEquals(httpRequest, "name foo\nsize 10000\ntags production candy", "text/plain", false); @@ -155,10 +155,10 @@ public class ElasticHostsAsyncClientTest extends RestClientTest httpRequest = processor.createRequest(method, "100", "200"); + Method method = ElasticStackAsyncClient.class.getMethod("imageDrive", String.class, String.class); + GeneratedHttpRequest httpRequest = processor.createRequest(method, "100", "200"); - assertRequestLineEquals(httpRequest, "POST https://api.elastichosts.com/drives/200/image/100 HTTP/1.1"); + assertRequestLineEquals(httpRequest, "POST https://api.elasticstack.com/drives/200/image/100 HTTP/1.1"); assertNonPayloadHeadersEqual(httpRequest, "Accept: text/plain\n"); assertPayloadEquals(httpRequest, null, null, false); @@ -171,12 +171,12 @@ public class ElasticHostsAsyncClientTest extends RestClientTest httpRequest = processor.createRequest(method, "100", "200", + GeneratedHttpRequest httpRequest = processor.createRequest(method, "100", "200", ImageConversionType.GUNZIP); - assertRequestLineEquals(httpRequest, "POST https://api.elastichosts.com/drives/200/image/100/gunzip HTTP/1.1"); + assertRequestLineEquals(httpRequest, "POST https://api.elasticstack.com/drives/200/image/100/gunzip HTTP/1.1"); assertNonPayloadHeadersEqual(httpRequest, "Accept: text/plain\n"); assertPayloadEquals(httpRequest, null, null, false); @@ -189,10 +189,10 @@ public class ElasticHostsAsyncClientTest extends RestClientTest httpRequest = processor.createRequest(method, "uuid"); + Method method = ElasticStackAsyncClient.class.getMethod("destroyDrive", String.class); + GeneratedHttpRequest httpRequest = processor.createRequest(method, "uuid"); - assertRequestLineEquals(httpRequest, "POST https://api.elastichosts.com/drives/uuid/destroy HTTP/1.1"); + assertRequestLineEquals(httpRequest, "POST https://api.elasticstack.com/drives/uuid/destroy HTTP/1.1"); assertNonPayloadHeadersEqual(httpRequest, "Accept: text/plain\n"); assertPayloadEquals(httpRequest, null, null, false); @@ -205,10 +205,10 @@ public class ElasticHostsAsyncClientTest extends RestClientTest httpRequest = processor.createRequest(method, "100"); + Method method = ElasticStackAsyncClient.class.getMethod("readDrive", String.class); + GeneratedHttpRequest httpRequest = processor.createRequest(method, "100"); - assertRequestLineEquals(httpRequest, "GET https://api.elastichosts.com/drives/100/read HTTP/1.1"); + assertRequestLineEquals(httpRequest, "GET https://api.elasticstack.com/drives/100/read HTTP/1.1"); assertNonPayloadHeadersEqual(httpRequest, "Accept: application/octet-stream\n"); assertPayloadEquals(httpRequest, null, null, false); @@ -220,11 +220,11 @@ public class ElasticHostsAsyncClientTest extends RestClientTest httpRequest = processor.createRequest(method, "100", + Method method = ElasticStackAsyncClient.class.getMethod("readDrive", String.class, ReadDriveOptions.class); + GeneratedHttpRequest httpRequest = processor.createRequest(method, "100", new ReadDriveOptions().offset(1024).size(2048)); - assertRequestLineEquals(httpRequest, "POST https://api.elastichosts.com/drives/100/read/1024/2048 HTTP/1.1"); + assertRequestLineEquals(httpRequest, "POST https://api.elasticstack.com/drives/100/read/1024/2048 HTTP/1.1"); assertNonPayloadHeadersEqual(httpRequest, "Accept: application/octet-stream\n"); assertPayloadEquals(httpRequest, null, null, false); @@ -236,11 +236,11 @@ public class ElasticHostsAsyncClientTest extends RestClientTest httpRequest = processor.createRequest(method, "100", + Method method = ElasticStackAsyncClient.class.getMethod("writeDrive", String.class, Payload.class); + GeneratedHttpRequest httpRequest = processor.createRequest(method, "100", Payloads.newStringPayload("foo")); - assertRequestLineEquals(httpRequest, "POST https://api.elastichosts.com/drives/100/write HTTP/1.1"); + assertRequestLineEquals(httpRequest, "POST https://api.elasticstack.com/drives/100/write HTTP/1.1"); assertNonPayloadHeadersEqual(httpRequest, "Accept: text/plain\n"); assertPayloadEquals(httpRequest, "", MediaType.APPLICATION_OCTET_STREAM, false); @@ -252,11 +252,11 @@ public class ElasticHostsAsyncClientTest extends RestClientTest httpRequest = processor.createRequest(method, "100", + Method method = ElasticStackAsyncClient.class.getMethod("writeDrive", String.class, Payload.class, long.class); + GeneratedHttpRequest httpRequest = processor.createRequest(method, "100", Payloads.newStringPayload("foo"), 2048); - assertRequestLineEquals(httpRequest, "POST https://api.elastichosts.com/drives/100/write/2048 HTTP/1.1"); + assertRequestLineEquals(httpRequest, "POST https://api.elasticstack.com/drives/100/write/2048 HTTP/1.1"); assertNonPayloadHeadersEqual(httpRequest, "Accept: text/plain\n"); assertPayloadEquals(httpRequest, "", MediaType.APPLICATION_OCTET_STREAM, false); @@ -274,15 +274,15 @@ public class ElasticHostsAsyncClientTest extends RestClientTest> createTypeLiteral() { - return new TypeLiteral>() { + protected TypeLiteral> createTypeLiteral() { + return new TypeLiteral>() { }; } @Override - public RestContextSpec createContextSpec() { + public RestContextSpec createContextSpec() { Properties props = new Properties(); - props.setProperty("elastichosts.endpoint", "https://api.elastichosts.com"); - return new RestContextFactory().createContextSpec("elastichosts", "foo", "bar", props); + props.setProperty("elasticstack.endpoint", "https://api.elasticstack.com"); + return new RestContextFactory().createContextSpec("elasticstack", "foo", "bar", props); } } diff --git a/sandbox/elastichosts/src/test/java/org/jclouds/elastichosts/ElasticHostsClientLiveTest.java b/sandbox/elasticstack/src/test/java/org/jclouds/elasticstack/ElasticStackClientLiveTest.java similarity index 84% rename from sandbox/elastichosts/src/test/java/org/jclouds/elastichosts/ElasticHostsClientLiveTest.java rename to sandbox/elasticstack/src/test/java/org/jclouds/elasticstack/ElasticStackClientLiveTest.java index b037658c95..f669ad7716 100644 --- a/sandbox/elastichosts/src/test/java/org/jclouds/elastichosts/ElasticHostsClientLiveTest.java +++ b/sandbox/elasticstack/src/test/java/org/jclouds/elasticstack/ElasticStackClientLiveTest.java @@ -17,27 +17,27 @@ * ==================================================================== */ -package org.jclouds.elastichosts; +package org.jclouds.elasticstack; import static org.testng.Assert.assertEquals; import java.io.IOException; -import org.jclouds.elastichosts.domain.CreateDriveRequest; -import org.jclouds.elastichosts.domain.DriveInfo; -import org.jclouds.elastichosts.options.ReadDriveOptions; +import org.jclouds.elasticstack.domain.CreateDriveRequest; +import org.jclouds.elasticstack.domain.DriveInfo; +import org.jclouds.elasticstack.options.ReadDriveOptions; import org.jclouds.io.Payloads; import org.jclouds.util.Utils; import org.testng.annotations.Test; /** - * Tests behavior of {@code ElasticHostsClient} + * Tests behavior of {@code ElasticStackClient} * * @author Adrian Cole */ -@Test(groups = "live", testName = "elastichosts.ElasticHostsClientLiveTest") -public class ElasticHostsClientLiveTest extends - CommonElasticHostsClientLiveTest { +@Test(groups = "live", testName = "elasticstack.ElasticStackClientLiveTest") +public class ElasticStackClientLiveTest extends + CommonElasticStackClientLiveTest { private DriveInfo info2; @Override diff --git a/sandbox/elastichosts/src/test/java/org/jclouds/elastichosts/ProvidersInPropertiesTest.java b/sandbox/elasticstack/src/test/java/org/jclouds/elasticstack/ProvidersInPropertiesTest.java similarity index 93% rename from sandbox/elastichosts/src/test/java/org/jclouds/elastichosts/ProvidersInPropertiesTest.java rename to sandbox/elasticstack/src/test/java/org/jclouds/elasticstack/ProvidersInPropertiesTest.java index 28bc7adb37..1ecf6df951 100644 --- a/sandbox/elastichosts/src/test/java/org/jclouds/elastichosts/ProvidersInPropertiesTest.java +++ b/sandbox/elasticstack/src/test/java/org/jclouds/elasticstack/ProvidersInPropertiesTest.java @@ -17,7 +17,7 @@ * ==================================================================== */ -package org.jclouds.elastichosts; +package org.jclouds.elasticstack; import org.jclouds.util.Utils; import org.testng.annotations.Test; @@ -35,7 +35,7 @@ public class ProvidersInPropertiesTest { @Test public void testSupportedProviders() { Iterable providers = Utils.getSupportedProviders(); - assert Iterables.contains(providers, "elastichosts") : providers; + assert Iterables.contains(providers, "elasticstack") : providers; } // // @Test diff --git a/sandbox/elastichosts/src/test/java/org/jclouds/elastichosts/binders/BindCreateDriveRequestToPlainTextStringTest.java b/sandbox/elasticstack/src/test/java/org/jclouds/elasticstack/binders/BindCreateDriveRequestToPlainTextStringTest.java similarity index 91% rename from sandbox/elastichosts/src/test/java/org/jclouds/elastichosts/binders/BindCreateDriveRequestToPlainTextStringTest.java rename to sandbox/elasticstack/src/test/java/org/jclouds/elasticstack/binders/BindCreateDriveRequestToPlainTextStringTest.java index e66810e671..3cc825f713 100644 --- a/sandbox/elastichosts/src/test/java/org/jclouds/elastichosts/binders/BindCreateDriveRequestToPlainTextStringTest.java +++ b/sandbox/elasticstack/src/test/java/org/jclouds/elasticstack/binders/BindCreateDriveRequestToPlainTextStringTest.java @@ -17,7 +17,7 @@ * ==================================================================== */ -package org.jclouds.elastichosts.binders; +package org.jclouds.elasticstack.binders; import static org.testng.Assert.assertEquals; @@ -27,11 +27,11 @@ import java.util.Map; import javax.ws.rs.core.MediaType; -import org.jclouds.elastichosts.domain.ClaimType; -import org.jclouds.elastichosts.domain.CreateDriveRequest; -import org.jclouds.elastichosts.domain.DriveData; -import org.jclouds.elastichosts.functions.CreateDriveRequestToMap; -import org.jclouds.elastichosts.functions.DriveDataToMap; +import org.jclouds.elasticstack.domain.ClaimType; +import org.jclouds.elasticstack.domain.CreateDriveRequest; +import org.jclouds.elasticstack.domain.DriveData; +import org.jclouds.elasticstack.functions.CreateDriveRequestToMap; +import org.jclouds.elasticstack.functions.DriveDataToMap; import org.jclouds.http.HttpRequest; import org.jclouds.util.Utils; import org.testng.annotations.Test; diff --git a/sandbox/elastichosts/src/test/java/org/jclouds/elastichosts/binders/BindDriveDataToPlainTextStringTest.java b/sandbox/elasticstack/src/test/java/org/jclouds/elasticstack/binders/BindDriveDataToPlainTextStringTest.java similarity index 90% rename from sandbox/elastichosts/src/test/java/org/jclouds/elastichosts/binders/BindDriveDataToPlainTextStringTest.java rename to sandbox/elasticstack/src/test/java/org/jclouds/elasticstack/binders/BindDriveDataToPlainTextStringTest.java index 319003d83e..0857dae2c2 100644 --- a/sandbox/elastichosts/src/test/java/org/jclouds/elastichosts/binders/BindDriveDataToPlainTextStringTest.java +++ b/sandbox/elasticstack/src/test/java/org/jclouds/elasticstack/binders/BindDriveDataToPlainTextStringTest.java @@ -17,7 +17,7 @@ * ==================================================================== */ -package org.jclouds.elastichosts.binders; +package org.jclouds.elasticstack.binders; import static org.testng.Assert.assertEquals; @@ -27,11 +27,11 @@ import java.util.Map; import javax.ws.rs.core.MediaType; -import org.jclouds.elastichosts.domain.ClaimType; -import org.jclouds.elastichosts.domain.CreateDriveRequest; -import org.jclouds.elastichosts.domain.DriveData; -import org.jclouds.elastichosts.functions.CreateDriveRequestToMap; -import org.jclouds.elastichosts.functions.DriveDataToMap; +import org.jclouds.elasticstack.domain.ClaimType; +import org.jclouds.elasticstack.domain.CreateDriveRequest; +import org.jclouds.elasticstack.domain.DriveData; +import org.jclouds.elasticstack.functions.CreateDriveRequestToMap; +import org.jclouds.elasticstack.functions.DriveDataToMap; import org.jclouds.http.HttpRequest; import org.jclouds.util.Utils; import org.testng.annotations.Test; diff --git a/sandbox/elastichosts/src/test/java/org/jclouds/elastichosts/binders/BindReadDriveOptionsToPathTest.java b/sandbox/elasticstack/src/test/java/org/jclouds/elasticstack/binders/BindReadDriveOptionsToPathTest.java similarity index 94% rename from sandbox/elastichosts/src/test/java/org/jclouds/elastichosts/binders/BindReadDriveOptionsToPathTest.java rename to sandbox/elasticstack/src/test/java/org/jclouds/elasticstack/binders/BindReadDriveOptionsToPathTest.java index f3e2b6016e..d7d9701b6c 100644 --- a/sandbox/elastichosts/src/test/java/org/jclouds/elastichosts/binders/BindReadDriveOptionsToPathTest.java +++ b/sandbox/elasticstack/src/test/java/org/jclouds/elasticstack/binders/BindReadDriveOptionsToPathTest.java @@ -17,13 +17,13 @@ * ==================================================================== */ -package org.jclouds.elastichosts.binders; +package org.jclouds.elasticstack.binders; import static org.testng.Assert.assertEquals; import java.net.URI; -import org.jclouds.elastichosts.options.ReadDriveOptions; +import org.jclouds.elasticstack.options.ReadDriveOptions; import org.jclouds.http.HttpRequest; import org.jclouds.logging.config.NullLoggingModule; import org.jclouds.rest.BaseRestClientTest.MockModule; diff --git a/sandbox/elastichosts/src/test/java/org/jclouds/elastichosts/functions/BaseDriveToMapTest.java b/sandbox/elasticstack/src/test/java/org/jclouds/elasticstack/functions/BaseDriveToMapTest.java similarity index 93% rename from sandbox/elastichosts/src/test/java/org/jclouds/elastichosts/functions/BaseDriveToMapTest.java rename to sandbox/elasticstack/src/test/java/org/jclouds/elasticstack/functions/BaseDriveToMapTest.java index d4ddc95d81..0bfd3de70c 100644 --- a/sandbox/elastichosts/src/test/java/org/jclouds/elastichosts/functions/BaseDriveToMapTest.java +++ b/sandbox/elasticstack/src/test/java/org/jclouds/elasticstack/functions/BaseDriveToMapTest.java @@ -17,14 +17,14 @@ * ==================================================================== */ -package org.jclouds.elastichosts.functions; +package org.jclouds.elasticstack.functions; import static org.testng.Assert.assertEquals; import java.io.IOException; -import org.jclouds.elastichosts.domain.ClaimType; -import org.jclouds.elastichosts.domain.internal.BaseDrive; +import org.jclouds.elasticstack.domain.ClaimType; +import org.jclouds.elasticstack.domain.internal.BaseDrive; import org.testng.annotations.Test; import com.google.common.collect.ImmutableMap; diff --git a/sandbox/elastichosts/src/test/java/org/jclouds/elastichosts/functions/CreateDriveRequestToMapTest.java b/sandbox/elasticstack/src/test/java/org/jclouds/elasticstack/functions/CreateDriveRequestToMapTest.java similarity index 94% rename from sandbox/elastichosts/src/test/java/org/jclouds/elastichosts/functions/CreateDriveRequestToMapTest.java rename to sandbox/elasticstack/src/test/java/org/jclouds/elasticstack/functions/CreateDriveRequestToMapTest.java index a2c1a6721b..1c40cb90e5 100644 --- a/sandbox/elastichosts/src/test/java/org/jclouds/elastichosts/functions/CreateDriveRequestToMapTest.java +++ b/sandbox/elasticstack/src/test/java/org/jclouds/elasticstack/functions/CreateDriveRequestToMapTest.java @@ -17,14 +17,14 @@ * ==================================================================== */ -package org.jclouds.elastichosts.functions; +package org.jclouds.elasticstack.functions; import static org.testng.Assert.assertEquals; import java.io.IOException; -import org.jclouds.elastichosts.domain.ClaimType; -import org.jclouds.elastichosts.domain.CreateDriveRequest; +import org.jclouds.elasticstack.domain.ClaimType; +import org.jclouds.elasticstack.domain.CreateDriveRequest; import org.testng.annotations.Test; import com.google.common.collect.ImmutableMap; diff --git a/sandbox/elastichosts/src/test/java/org/jclouds/elastichosts/functions/DriveDataToMapTest.java b/sandbox/elasticstack/src/test/java/org/jclouds/elasticstack/functions/DriveDataToMapTest.java similarity index 94% rename from sandbox/elastichosts/src/test/java/org/jclouds/elastichosts/functions/DriveDataToMapTest.java rename to sandbox/elasticstack/src/test/java/org/jclouds/elasticstack/functions/DriveDataToMapTest.java index 5ec2f96c47..041c2dd6d4 100644 --- a/sandbox/elastichosts/src/test/java/org/jclouds/elastichosts/functions/DriveDataToMapTest.java +++ b/sandbox/elasticstack/src/test/java/org/jclouds/elasticstack/functions/DriveDataToMapTest.java @@ -17,14 +17,14 @@ * ==================================================================== */ -package org.jclouds.elastichosts.functions; +package org.jclouds.elasticstack.functions; import static org.testng.Assert.assertEquals; import java.io.IOException; -import org.jclouds.elastichosts.domain.ClaimType; -import org.jclouds.elastichosts.domain.DriveData; +import org.jclouds.elasticstack.domain.ClaimType; +import org.jclouds.elasticstack.domain.DriveData; import org.testng.annotations.Test; import com.google.common.collect.ImmutableMap; diff --git a/sandbox/elastichosts/src/test/java/org/jclouds/elastichosts/functions/KeyValuesDelimitedByBlankLinesToDriveInfoTest.java b/sandbox/elasticstack/src/test/java/org/jclouds/elasticstack/functions/KeyValuesDelimitedByBlankLinesToDriveInfoTest.java similarity index 97% rename from sandbox/elastichosts/src/test/java/org/jclouds/elastichosts/functions/KeyValuesDelimitedByBlankLinesToDriveInfoTest.java rename to sandbox/elasticstack/src/test/java/org/jclouds/elasticstack/functions/KeyValuesDelimitedByBlankLinesToDriveInfoTest.java index e528ab1878..2ad2cf5771 100644 --- a/sandbox/elastichosts/src/test/java/org/jclouds/elastichosts/functions/KeyValuesDelimitedByBlankLinesToDriveInfoTest.java +++ b/sandbox/elasticstack/src/test/java/org/jclouds/elasticstack/functions/KeyValuesDelimitedByBlankLinesToDriveInfoTest.java @@ -17,7 +17,7 @@ * ==================================================================== */ -package org.jclouds.elastichosts.functions; +package org.jclouds.elasticstack.functions; import static org.testng.Assert.assertEquals; diff --git a/sandbox/elastichosts/src/test/java/org/jclouds/elastichosts/functions/ListOfKeyValuesDelimitedByBlankLinesToDriveInfoSetTest.java b/sandbox/elasticstack/src/test/java/org/jclouds/elasticstack/functions/ListOfKeyValuesDelimitedByBlankLinesToDriveInfoSetTest.java similarity index 95% rename from sandbox/elastichosts/src/test/java/org/jclouds/elastichosts/functions/ListOfKeyValuesDelimitedByBlankLinesToDriveInfoSetTest.java rename to sandbox/elasticstack/src/test/java/org/jclouds/elasticstack/functions/ListOfKeyValuesDelimitedByBlankLinesToDriveInfoSetTest.java index 584bd13f4f..dd4b782953 100644 --- a/sandbox/elastichosts/src/test/java/org/jclouds/elastichosts/functions/ListOfKeyValuesDelimitedByBlankLinesToDriveInfoSetTest.java +++ b/sandbox/elasticstack/src/test/java/org/jclouds/elasticstack/functions/ListOfKeyValuesDelimitedByBlankLinesToDriveInfoSetTest.java @@ -17,11 +17,11 @@ * ==================================================================== */ -package org.jclouds.elastichosts.functions; +package org.jclouds.elasticstack.functions; import static org.testng.Assert.assertEquals; -import org.jclouds.elastichosts.domain.DriveInfo; +import org.jclouds.elasticstack.domain.DriveInfo; import org.jclouds.http.HttpResponse; import org.jclouds.io.Payloads; import org.testng.annotations.Test; diff --git a/sandbox/elastichosts/src/test/java/org/jclouds/elastichosts/functions/ListOfKeyValuesDelimitedByBlankLinesToListOfMapsTest.java b/sandbox/elasticstack/src/test/java/org/jclouds/elasticstack/functions/ListOfKeyValuesDelimitedByBlankLinesToListOfMapsTest.java similarity index 98% rename from sandbox/elastichosts/src/test/java/org/jclouds/elastichosts/functions/ListOfKeyValuesDelimitedByBlankLinesToListOfMapsTest.java rename to sandbox/elasticstack/src/test/java/org/jclouds/elasticstack/functions/ListOfKeyValuesDelimitedByBlankLinesToListOfMapsTest.java index 6c50942a0b..62f9552ce3 100644 --- a/sandbox/elastichosts/src/test/java/org/jclouds/elastichosts/functions/ListOfKeyValuesDelimitedByBlankLinesToListOfMapsTest.java +++ b/sandbox/elasticstack/src/test/java/org/jclouds/elasticstack/functions/ListOfKeyValuesDelimitedByBlankLinesToListOfMapsTest.java @@ -17,7 +17,7 @@ * ==================================================================== */ -package org.jclouds.elastichosts.functions; +package org.jclouds.elasticstack.functions; import static org.testng.Assert.assertEquals; diff --git a/sandbox/elastichosts/src/test/java/org/jclouds/elastichosts/functions/ListOfMapsToListOfKeyValuesDelimitedByBlankLinesTest.java b/sandbox/elasticstack/src/test/java/org/jclouds/elasticstack/functions/ListOfMapsToListOfKeyValuesDelimitedByBlankLinesTest.java similarity index 97% rename from sandbox/elastichosts/src/test/java/org/jclouds/elastichosts/functions/ListOfMapsToListOfKeyValuesDelimitedByBlankLinesTest.java rename to sandbox/elasticstack/src/test/java/org/jclouds/elasticstack/functions/ListOfMapsToListOfKeyValuesDelimitedByBlankLinesTest.java index bc6be6d961..8d001af41f 100644 --- a/sandbox/elastichosts/src/test/java/org/jclouds/elastichosts/functions/ListOfMapsToListOfKeyValuesDelimitedByBlankLinesTest.java +++ b/sandbox/elasticstack/src/test/java/org/jclouds/elasticstack/functions/ListOfMapsToListOfKeyValuesDelimitedByBlankLinesTest.java @@ -17,7 +17,7 @@ * ==================================================================== */ -package org.jclouds.elastichosts.functions; +package org.jclouds.elasticstack.functions; import static org.testng.Assert.assertEquals; diff --git a/sandbox/elastichosts/src/test/java/org/jclouds/elastichosts/functions/MapToDriveInfoTest.java b/sandbox/elasticstack/src/test/java/org/jclouds/elasticstack/functions/MapToDriveInfoTest.java similarity index 94% rename from sandbox/elastichosts/src/test/java/org/jclouds/elastichosts/functions/MapToDriveInfoTest.java rename to sandbox/elasticstack/src/test/java/org/jclouds/elasticstack/functions/MapToDriveInfoTest.java index 7b40037446..ef681199fe 100644 --- a/sandbox/elastichosts/src/test/java/org/jclouds/elastichosts/functions/MapToDriveInfoTest.java +++ b/sandbox/elasticstack/src/test/java/org/jclouds/elasticstack/functions/MapToDriveInfoTest.java @@ -17,16 +17,16 @@ * ==================================================================== */ -package org.jclouds.elastichosts.functions; +package org.jclouds.elasticstack.functions; import static org.testng.Assert.assertEquals; import java.io.IOException; import java.util.Map; -import org.jclouds.elastichosts.domain.ClaimType; -import org.jclouds.elastichosts.domain.DriveInfo; -import org.jclouds.elastichosts.domain.DriveStatus; +import org.jclouds.elasticstack.domain.ClaimType; +import org.jclouds.elasticstack.domain.DriveInfo; +import org.jclouds.elasticstack.domain.DriveStatus; import org.jclouds.util.Utils; import org.testng.annotations.Test; diff --git a/sandbox/elastichosts/src/test/java/org/jclouds/elastichosts/functions/SplitNewlinesTest.java b/sandbox/elasticstack/src/test/java/org/jclouds/elasticstack/functions/SplitNewlinesTest.java similarity index 94% rename from sandbox/elastichosts/src/test/java/org/jclouds/elastichosts/functions/SplitNewlinesTest.java rename to sandbox/elasticstack/src/test/java/org/jclouds/elasticstack/functions/SplitNewlinesTest.java index f57e2febe8..2afa9537b6 100644 --- a/sandbox/elastichosts/src/test/java/org/jclouds/elastichosts/functions/SplitNewlinesTest.java +++ b/sandbox/elasticstack/src/test/java/org/jclouds/elasticstack/functions/SplitNewlinesTest.java @@ -17,14 +17,14 @@ * ==================================================================== */ -package org.jclouds.elastichosts.functions; +package org.jclouds.elasticstack.functions; import static org.testng.Assert.assertEquals; import java.io.InputStream; import java.util.Set; -import org.jclouds.elastichosts.functions.SplitNewlines; +import org.jclouds.elasticstack.functions.SplitNewlines; import org.jclouds.http.HttpResponse; import org.jclouds.io.Payloads; import org.testng.annotations.Test; diff --git a/sandbox/elastichosts/src/test/java/org/jclouds/elastichosts/handlers/ElasticHostsErrorHandlerTest.java b/sandbox/elasticstack/src/test/java/org/jclouds/elasticstack/handlers/ElasticStackErrorHandlerTest.java similarity index 87% rename from sandbox/elastichosts/src/test/java/org/jclouds/elastichosts/handlers/ElasticHostsErrorHandlerTest.java rename to sandbox/elasticstack/src/test/java/org/jclouds/elasticstack/handlers/ElasticStackErrorHandlerTest.java index 99a84c8841..0e23584cc0 100644 --- a/sandbox/elastichosts/src/test/java/org/jclouds/elastichosts/handlers/ElasticHostsErrorHandlerTest.java +++ b/sandbox/elasticstack/src/test/java/org/jclouds/elasticstack/handlers/ElasticStackErrorHandlerTest.java @@ -17,7 +17,7 @@ * ==================================================================== */ -package org.jclouds.elastichosts.handlers; +package org.jclouds.elasticstack.handlers; import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.reportMatcher; @@ -44,41 +44,41 @@ import com.google.inject.Guice; * @author Adrian Cole */ @Test(groups = { "unit" }) -public class ElasticHostsErrorHandlerTest { +public class ElasticStackErrorHandlerTest { @Test public void test400MakesIllegalArgumentException() { - assertCodeMakes("GET", URI.create("https://elastichosts.com/foo"), 400, "", "Bad Request", + assertCodeMakes("GET", URI.create("https://elasticstack.com/foo"), 400, "", "Bad Request", IllegalArgumentException.class); } @Test public void test400MakesResourceNotFoundExceptionOnMessageNotFound() { - assertCodeMakes("GET", URI.create("https://elastichosts.com/foo"), 400, "", "errors:system Drive 8f9b42b1-26de-49ad-a3fd-d4fa06524339 could not be found. Please re-validate your entry.", + assertCodeMakes("GET", URI.create("https://elasticstack.com/foo"), 400, "", "errors:system Drive 8f9b42b1-26de-49ad-a3fd-d4fa06524339 could not be found. Please re-validate your entry.", ResourceNotFoundException.class); } @Test public void test401MakesAuthorizationException() { - assertCodeMakes("GET", URI.create("https://elastichosts.com/foo"), 401, "", "Unauthorized", + assertCodeMakes("GET", URI.create("https://elasticstack.com/foo"), 401, "", "Unauthorized", AuthorizationException.class); } @Test public void test404MakesResourceNotFoundException() { - assertCodeMakes("GET", URI.create("https://elastichosts.com/foo"), 404, "", "Not Found", + assertCodeMakes("GET", URI.create("https://elasticstack.com/foo"), 404, "", "Not Found", ResourceNotFoundException.class); } @Test public void test405MakesIllegalArgumentException() { - assertCodeMakes("GET", URI.create("https://elastichosts.com/foo"), 405, "", "Method Not Allowed", + assertCodeMakes("GET", URI.create("https://elasticstack.com/foo"), 405, "", "Method Not Allowed", IllegalArgumentException.class); } @Test public void test409MakesIllegalStateException() { - assertCodeMakes("GET", URI.create("https://elastichosts.com/foo"), 409, "", "Conflict", + assertCodeMakes("GET", URI.create("https://elasticstack.com/foo"), 409, "", "Conflict", IllegalStateException.class); } @@ -90,7 +90,7 @@ public class ElasticHostsErrorHandlerTest { private void assertCodeMakes(String method, URI uri, int statusCode, String message, String contentType, String content, Class expected) { - ElasticHostsErrorHandler function = Guice.createInjector().getInstance(ElasticHostsErrorHandler.class); + ElasticStackErrorHandler function = Guice.createInjector().getInstance(ElasticStackErrorHandler.class); HttpCommand command = createMock(HttpCommand.class); HttpRequest request = new HttpRequest(method, uri); diff --git a/sandbox/elastichosts/src/test/java/org/jclouds/elastichosts/options/ReadDriveOptionsTest.java b/sandbox/elasticstack/src/test/java/org/jclouds/elasticstack/options/ReadDriveOptionsTest.java similarity index 93% rename from sandbox/elastichosts/src/test/java/org/jclouds/elastichosts/options/ReadDriveOptionsTest.java rename to sandbox/elasticstack/src/test/java/org/jclouds/elasticstack/options/ReadDriveOptionsTest.java index 2d1ef43f3d..3e4e4a3a38 100644 --- a/sandbox/elastichosts/src/test/java/org/jclouds/elastichosts/options/ReadDriveOptionsTest.java +++ b/sandbox/elasticstack/src/test/java/org/jclouds/elasticstack/options/ReadDriveOptionsTest.java @@ -17,10 +17,10 @@ * ==================================================================== */ -package org.jclouds.elastichosts.options; +package org.jclouds.elasticstack.options; -import static org.jclouds.elastichosts.options.ReadDriveOptions.Builder.offset; -import static org.jclouds.elastichosts.options.ReadDriveOptions.Builder.size; +import static org.jclouds.elasticstack.options.ReadDriveOptions.Builder.offset; +import static org.jclouds.elasticstack.options.ReadDriveOptions.Builder.size; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNull; diff --git a/sandbox/elastichosts/src/test/resources/cloudsigma/drive.txt b/sandbox/elasticstack/src/test/resources/cloudsigma/drive.txt similarity index 100% rename from sandbox/elastichosts/src/test/resources/cloudsigma/drive.txt rename to sandbox/elasticstack/src/test/resources/cloudsigma/drive.txt diff --git a/sandbox/elastichosts/src/test/resources/create_drive.txt b/sandbox/elasticstack/src/test/resources/create_drive.txt similarity index 100% rename from sandbox/elastichosts/src/test/resources/create_drive.txt rename to sandbox/elasticstack/src/test/resources/create_drive.txt diff --git a/sandbox/elastichosts/src/test/resources/drive.txt b/sandbox/elasticstack/src/test/resources/drive.txt similarity index 100% rename from sandbox/elastichosts/src/test/resources/drive.txt rename to sandbox/elasticstack/src/test/resources/drive.txt diff --git a/sandbox/elastichosts/src/test/resources/drive_data.txt b/sandbox/elasticstack/src/test/resources/drive_data.txt similarity index 100% rename from sandbox/elastichosts/src/test/resources/drive_data.txt rename to sandbox/elasticstack/src/test/resources/drive_data.txt diff --git a/sandbox/elastichosts/src/test/resources/log4j.xml b/sandbox/elasticstack/src/test/resources/log4j.xml similarity index 100% rename from sandbox/elastichosts/src/test/resources/log4j.xml rename to sandbox/elasticstack/src/test/resources/log4j.xml diff --git a/sandbox/elastichosts/src/test/resources/uuids.txt b/sandbox/elasticstack/src/test/resources/uuids.txt similarity index 100% rename from sandbox/elastichosts/src/test/resources/uuids.txt rename to sandbox/elasticstack/src/test/resources/uuids.txt From 69ef3fa7ea922d5128c902611239d3bc5d033e70 Mon Sep 17 00:00:00 2001 From: unknown Date: Fri, 3 Dec 2010 20:08:37 +0100 Subject: [PATCH 20/31] first commit --- sandbox/vsphere/README.txt | 2 + sandbox/vsphere/TODO | 1 + sandbox/vsphere/pom.xml | 138 ++++++++ .../java/org/jclouds/vsphere/Datacenter.java | 56 ++++ .../main/java/org/jclouds/vsphere/Image.java | 56 ++++ .../java/org/jclouds/vsphere/ViConstants.java | 33 ++ .../vsphere/compute/ViComputeService.java | 113 +++++++ .../ViComputeServiceContextBuilder.java | 58 ++++ .../compute/ViComputeServiceContextSpec.java | 43 +++ .../vsphere/compute/ViPropertiesBuilder.java | 58 ++++ .../domain/ViComputeServiceContextModule.java | 151 +++++++++ .../functions/DatacenterToLocation.java | 42 +++ .../functions/LibvirtNodeToLocation.java | 42 +++ .../compute/functions/ViImageToImage.java | 62 ++++ .../functions/VirtualMachineToHardware.java | 98 ++++++ .../VirtualMachineToNodeMetadata.java | 134 ++++++++ .../strategy/ViComputeServiceAdapter.java | 316 ++++++++++++++++++ .../ViComputeServiceContextBuilderTest.java | 33 ++ .../vsphere/compute/ViExperimentLiveTest.java | 97 ++++++ sandbox/vsphere/src/test/resources/log4j.xml | 136 ++++++++ 20 files changed, 1669 insertions(+) create mode 100644 sandbox/vsphere/README.txt create mode 100644 sandbox/vsphere/TODO create mode 100644 sandbox/vsphere/pom.xml create mode 100644 sandbox/vsphere/src/main/java/org/jclouds/vsphere/Datacenter.java create mode 100644 sandbox/vsphere/src/main/java/org/jclouds/vsphere/Image.java create mode 100644 sandbox/vsphere/src/main/java/org/jclouds/vsphere/ViConstants.java create mode 100644 sandbox/vsphere/src/main/java/org/jclouds/vsphere/compute/ViComputeService.java create mode 100644 sandbox/vsphere/src/main/java/org/jclouds/vsphere/compute/ViComputeServiceContextBuilder.java create mode 100644 sandbox/vsphere/src/main/java/org/jclouds/vsphere/compute/ViComputeServiceContextSpec.java create mode 100644 sandbox/vsphere/src/main/java/org/jclouds/vsphere/compute/ViPropertiesBuilder.java create mode 100644 sandbox/vsphere/src/main/java/org/jclouds/vsphere/compute/domain/ViComputeServiceContextModule.java create mode 100644 sandbox/vsphere/src/main/java/org/jclouds/vsphere/compute/functions/DatacenterToLocation.java create mode 100644 sandbox/vsphere/src/main/java/org/jclouds/vsphere/compute/functions/LibvirtNodeToLocation.java create mode 100644 sandbox/vsphere/src/main/java/org/jclouds/vsphere/compute/functions/ViImageToImage.java create mode 100644 sandbox/vsphere/src/main/java/org/jclouds/vsphere/compute/functions/VirtualMachineToHardware.java create mode 100644 sandbox/vsphere/src/main/java/org/jclouds/vsphere/compute/functions/VirtualMachineToNodeMetadata.java create mode 100644 sandbox/vsphere/src/main/java/org/jclouds/vsphere/compute/strategy/ViComputeServiceAdapter.java create mode 100644 sandbox/vsphere/src/test/java/org/jclouds/vsphere/compute/ViComputeServiceContextBuilderTest.java create mode 100644 sandbox/vsphere/src/test/java/org/jclouds/vsphere/compute/ViExperimentLiveTest.java create mode 100644 sandbox/vsphere/src/test/resources/log4j.xml diff --git a/sandbox/vsphere/README.txt b/sandbox/vsphere/README.txt new file mode 100644 index 0000000000..139597f9cb --- /dev/null +++ b/sandbox/vsphere/README.txt @@ -0,0 +1,2 @@ + + diff --git a/sandbox/vsphere/TODO b/sandbox/vsphere/TODO new file mode 100644 index 0000000000..81960b3b76 --- /dev/null +++ b/sandbox/vsphere/TODO @@ -0,0 +1 @@ +runNodesWithTag: when ask for more than 1 node, cloning step fails cause of concurrent access to the originale virtual disk to be cloned. \ No newline at end of file diff --git a/sandbox/vsphere/pom.xml b/sandbox/vsphere/pom.xml new file mode 100644 index 0000000000..b4ff48cc99 --- /dev/null +++ b/sandbox/vsphere/pom.xml @@ -0,0 +1,138 @@ + + + + + 4.0.0 + + org.jclouds + jclouds-project + 1.0-SNAPSHOT + ../../project/pom.xml + + jclouds-vsphere + jclouds example components for a vijava lib for vSphere + + + trmkrun-ccc,test.trmk-924 + test:///default + 1.0 + FIXME + FIXME + + + + org.jvnet.hudson + vijava + 2120100824 + + + com.jamesmurty.utils + java-xmlbuilder + 0.3 + + + ${project.groupId} + jclouds-core + ${project.version} + test-jar + test + + + ${project.groupId} + jclouds-compute + ${project.version} + + + ${project.groupId} + jclouds-compute + ${project.version} + test-jar + test + + + log4j + log4j + 1.2.14 + test + + + ${project.groupId} + jclouds-log4j + ${project.version} + test + + + ${project.groupId} + jclouds-jsch + ${project.version} + test + + + + + + live + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration + integration-test + + test + + + + + test.libvirt.endpoint + ${test.libvirt.endpoint} + + + test.libvirt.apiversion + ${test.libvirt.apiversion} + + + test.libvirt.identity + ${test.libvirt.identity} + + + test.libvirt.credential + ${test.libvirt.credential} + + + jclouds.compute.blacklist.nodes + ${jclouds.compute.blacklist.nodes} + + + + + + + + + + + + diff --git a/sandbox/vsphere/src/main/java/org/jclouds/vsphere/Datacenter.java b/sandbox/vsphere/src/main/java/org/jclouds/vsphere/Datacenter.java new file mode 100644 index 0000000000..4224d9250e --- /dev/null +++ b/sandbox/vsphere/src/main/java/org/jclouds/vsphere/Datacenter.java @@ -0,0 +1,56 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.vsphere; + +import com.google.common.base.Objects; + +/** + * This would be replaced with the real java object related to the underlying data center + * + * @author Adrian Cole + */ +public class Datacenter { + + public int id; + public String name; + + public Datacenter(int id, String name) { + this.id = id; + this.name = name; + } + + @Override + public int hashCode() { + return Objects.hashCode(id, name); + } + + @Override + public boolean equals(Object that) { + if (that == null) + return false; + return Objects.equal(this.toString(), that.toString()); + } + + @Override + public String toString() { + return Objects.toStringHelper(this).add("id", id).add("name", name).toString(); + } + +} diff --git a/sandbox/vsphere/src/main/java/org/jclouds/vsphere/Image.java b/sandbox/vsphere/src/main/java/org/jclouds/vsphere/Image.java new file mode 100644 index 0000000000..0a3f5fbe2e --- /dev/null +++ b/sandbox/vsphere/src/main/java/org/jclouds/vsphere/Image.java @@ -0,0 +1,56 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.vsphere; + +import com.google.common.base.Objects; + +/** + * This would be replaced with the real java object related to the underlying image + * + * @author Adrian Cole + */ +public class Image { + + public int id; + public String name; + + public Image(int id, String name) { + this.id = id; + this.name = name; + } + + @Override + public int hashCode() { + return Objects.hashCode(id, name); + } + + @Override + public boolean equals(Object that) { + if (that == null) + return false; + return Objects.equal(this.toString(), that.toString()); + } + + @Override + public String toString() { + return Objects.toStringHelper(this).add("id", id).add("name", name).toString(); + } + +} diff --git a/sandbox/vsphere/src/main/java/org/jclouds/vsphere/ViConstants.java b/sandbox/vsphere/src/main/java/org/jclouds/vsphere/ViConstants.java new file mode 100644 index 0000000000..d015691241 --- /dev/null +++ b/sandbox/vsphere/src/main/java/org/jclouds/vsphere/ViConstants.java @@ -0,0 +1,33 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.vsphere; + +/** + * Configuration properties and constants used in libvirt local connections. + * + * @author Adrian Cole + */ +public interface ViConstants { + public static final String PROPERTY_LIBVIRT_DOMAIN_DIR = "jclouds.libvirt.domain.dir"; +} + + +//public static final String PROPERTY_AUTH_TAG = "jclouds.aws.auth.tag"; +//public static final String PROPERTY_HEADER_TAG = "jclouds.aws.header.tag"; \ No newline at end of file diff --git a/sandbox/vsphere/src/main/java/org/jclouds/vsphere/compute/ViComputeService.java b/sandbox/vsphere/src/main/java/org/jclouds/vsphere/compute/ViComputeService.java new file mode 100644 index 0000000000..a2531da66f --- /dev/null +++ b/sandbox/vsphere/src/main/java/org/jclouds/vsphere/compute/ViComputeService.java @@ -0,0 +1,113 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.vsphere.compute; + +import java.io.StringReader; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ExecutorService; + +import javax.inject.Inject; +import javax.inject.Named; +import javax.inject.Provider; +import javax.inject.Singleton; + +import org.jclouds.Constants; +import org.jclouds.collect.Memoized; +import org.jclouds.compute.ComputeServiceContext; +import org.jclouds.compute.domain.Hardware; +import org.jclouds.compute.domain.Image; +import org.jclouds.compute.domain.NodeMetadata; +import org.jclouds.compute.domain.TemplateBuilder; +import org.jclouds.compute.internal.BaseComputeService; +import org.jclouds.compute.options.TemplateOptions; +import org.jclouds.compute.reference.ComputeServiceConstants.Timeouts; +import org.jclouds.compute.strategy.DestroyNodeStrategy; +import org.jclouds.compute.strategy.GetNodeMetadataStrategy; +import org.jclouds.compute.strategy.ListNodesStrategy; +import org.jclouds.compute.strategy.RebootNodeStrategy; +import org.jclouds.compute.strategy.ResumeNodeStrategy; +import org.jclouds.compute.strategy.RunNodesAndAddToSetStrategy; +import org.jclouds.compute.strategy.SuspendNodeStrategy; +import org.jclouds.compute.util.ComputeUtils; +import org.jclouds.domain.Credentials; +import org.jclouds.domain.Location; +import org.xml.sax.InputSource; + +import com.google.common.base.Predicate; +import com.google.common.base.Supplier; +import com.google.common.base.Throwables; +import com.jamesmurty.utils.XMLBuilder; +import com.vmware.vim25.mo.ServiceInstance; + +/** + * + * @author andrea.turli + * + */ +@Singleton +public class ViComputeService extends BaseComputeService { + + private final ServiceInstance client; + + @Inject + protected ViComputeService(ComputeServiceContext context, + Map credentialStore, + @Memoized Supplier> images, + @Memoized Supplier> hardwareProfiles, + @Memoized Supplier> locations, + ListNodesStrategy listNodesStrategy, + GetNodeMetadataStrategy getNodeMetadataStrategy, + RunNodesAndAddToSetStrategy runNodesAndAddToSetStrategy, + RebootNodeStrategy rebootNodeStrategy, + DestroyNodeStrategy destroyNodeStrategy, + ResumeNodeStrategy resumeNodeStrategy, + SuspendNodeStrategy suspendNodeStrategy, + Provider templateBuilderProvider, + Provider templateOptionsProvider, + @Named("NODE_RUNNING") Predicate nodeRunning, + @Named("NODE_TERMINATED") Predicate nodeTerminated, + @Named("NODE_SUSPENDED") Predicate nodeSuspended, ComputeUtils utils, + Timeouts timeouts, + @Named(Constants.PROPERTY_USER_THREADS) ExecutorService executor, + ServiceInstance client) { + super(context, credentialStore, images, hardwareProfiles, locations, + listNodesStrategy, getNodeMetadataStrategy, + runNodesAndAddToSetStrategy, rebootNodeStrategy, destroyNodeStrategy, + resumeNodeStrategy, suspendNodeStrategy, templateBuilderProvider, + templateOptionsProvider, nodeRunning, nodeTerminated, nodeSuspended, + utils, timeouts, executor); + + this.client = client; + + } + + @Override + public void destroyNode(String id) { + super.destroyNode(id); + } + + protected T propogate(Exception e) { + Throwables.propagate(e); + assert false; + return null; + } + +} diff --git a/sandbox/vsphere/src/main/java/org/jclouds/vsphere/compute/ViComputeServiceContextBuilder.java b/sandbox/vsphere/src/main/java/org/jclouds/vsphere/compute/ViComputeServiceContextBuilder.java new file mode 100644 index 0000000000..fe6f3b1678 --- /dev/null +++ b/sandbox/vsphere/src/main/java/org/jclouds/vsphere/compute/ViComputeServiceContextBuilder.java @@ -0,0 +1,58 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.vsphere.compute; + +import static org.jclouds.vsphere.ViConstants.PROPERTY_LIBVIRT_DOMAIN_DIR; + +import java.util.List; +import java.util.Properties; + +import org.jclouds.compute.StandaloneComputeServiceContextBuilder; +import org.jclouds.compute.config.StandaloneComputeServiceContextModule; +import org.jclouds.vsphere.Datacenter; +import org.jclouds.vsphere.Image; +import org.jclouds.vsphere.compute.domain.ViComputeServiceContextModule; + +import com.google.inject.Module; +import com.vmware.vim25.mo.VirtualMachine; + +/** + * + * @author Adrian Cole + */ +public class ViComputeServiceContextBuilder extends StandaloneComputeServiceContextBuilder { + + public ViComputeServiceContextBuilder(Properties props) { + super(props); + + if (!properties.containsKey(PROPERTY_LIBVIRT_DOMAIN_DIR)) + properties.setProperty(PROPERTY_LIBVIRT_DOMAIN_DIR, "/etc/libvirt/qemu"); + } + + @Override + protected void addContextModule(List modules) { + modules.add(createContextModule()); + } + + public StandaloneComputeServiceContextModule createContextModule() { + return new ViComputeServiceContextModule(); + } + +} diff --git a/sandbox/vsphere/src/main/java/org/jclouds/vsphere/compute/ViComputeServiceContextSpec.java b/sandbox/vsphere/src/main/java/org/jclouds/vsphere/compute/ViComputeServiceContextSpec.java new file mode 100644 index 0000000000..3108857787 --- /dev/null +++ b/sandbox/vsphere/src/main/java/org/jclouds/vsphere/compute/ViComputeServiceContextSpec.java @@ -0,0 +1,43 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.vsphere.compute; + +import org.jclouds.PropertiesBuilder; +import org.jclouds.compute.ComputeService; +import org.jclouds.rest.RestContextSpec; + +import com.google.common.collect.ImmutableSet; +import com.google.inject.Module; + +/** + * @author Adrian Cole + */ +public class ViComputeServiceContextSpec extends RestContextSpec { + + @SuppressWarnings("unchecked") + public ViComputeServiceContextSpec(String endpoint, String identity, String credential, Iterable modules) { + super("vsphere", endpoint, "1", identity, credential, ComputeService.class, ComputeService.class, + PropertiesBuilder.class, (Class) ViComputeServiceContextBuilder.class, modules); + } + + public ViComputeServiceContextSpec(String endpoint, String identity, String credential) { + this(endpoint, identity, credential, ImmutableSet.of()); + } +} \ No newline at end of file diff --git a/sandbox/vsphere/src/main/java/org/jclouds/vsphere/compute/ViPropertiesBuilder.java b/sandbox/vsphere/src/main/java/org/jclouds/vsphere/compute/ViPropertiesBuilder.java new file mode 100644 index 0000000000..4089ca9b9c --- /dev/null +++ b/sandbox/vsphere/src/main/java/org/jclouds/vsphere/compute/ViPropertiesBuilder.java @@ -0,0 +1,58 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.vsphere.compute; + +import static org.jclouds.Constants.PROPERTY_API_VERSION; +import static org.jclouds.Constants.PROPERTY_ENDPOINT; +import static org.jclouds.vsphere.ViConstants.PROPERTY_LIBVIRT_DOMAIN_DIR; +import static org.jclouds.compute.reference.ComputeServiceConstants.PROPERTY_TIMEOUT_NODE_SUSPENDED; + +import java.util.Properties; + +import org.jclouds.PropertiesBuilder; + +/** + * Builds properties used in Libvirt Clients + * + * @author Andrea Turli + */ +public class ViPropertiesBuilder extends PropertiesBuilder { + @Override + protected Properties defaultProperties() { + Properties properties = super.defaultProperties(); + properties.setProperty(PROPERTY_LIBVIRT_DOMAIN_DIR, "/etc/libvirt/qemu"); + + properties.setProperty(PROPERTY_TIMEOUT_NODE_SUSPENDED, 120 * 1000 + ""); + // auth fail sometimes happens in EC2, as the rc.local script that injects the + // authorized key executes after ssh has started + properties.setProperty("jclouds.ssh.max_retries", "7"); + properties.setProperty("jclouds.ssh.retryable_messages", + "Auth fail,invalid data,End of IO Stream Read,Connection reset,socket is not established"); + return properties; + } + + public ViPropertiesBuilder(Properties properties) { + super(properties); + } + + public ViPropertiesBuilder() { + super(); + } +} diff --git a/sandbox/vsphere/src/main/java/org/jclouds/vsphere/compute/domain/ViComputeServiceContextModule.java b/sandbox/vsphere/src/main/java/org/jclouds/vsphere/compute/domain/ViComputeServiceContextModule.java new file mode 100644 index 0000000000..1e811157c6 --- /dev/null +++ b/sandbox/vsphere/src/main/java/org/jclouds/vsphere/compute/domain/ViComputeServiceContextModule.java @@ -0,0 +1,151 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.vsphere.compute.domain; + +import static org.jclouds.vsphere.ViConstants.PROPERTY_LIBVIRT_DOMAIN_DIR; + +import java.io.File; +import java.io.IOException; +import java.io.StringReader; +import java.net.MalformedURLException; +import java.net.URI; +import java.rmi.RemoteException; +import java.util.Collection; + +import javax.inject.Named; +import javax.inject.Singleton; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.xpath.XPathExpressionException; + +import org.apache.commons.io.FileUtils; +import org.apache.commons.io.filefilter.WildcardFileFilter; +import org.jclouds.Constants; +import org.jclouds.compute.ComputeServiceAdapter; +import org.jclouds.compute.config.StandaloneComputeServiceContextModule; +import org.jclouds.compute.domain.Hardware; +import org.jclouds.compute.domain.NodeMetadata; +import org.jclouds.compute.domain.TemplateBuilder; +import org.jclouds.compute.suppliers.DefaultLocationSupplier; +import org.jclouds.domain.Location; +import org.jclouds.rest.annotations.Provider; +import org.jclouds.vsphere.Datacenter; +import org.jclouds.vsphere.Image; +import org.jclouds.vsphere.compute.functions.DatacenterToLocation; +import org.jclouds.vsphere.compute.functions.ViImageToImage; +import org.jclouds.vsphere.compute.functions.VirtualMachineToHardware; +import org.jclouds.vsphere.compute.functions.VirtualMachineToNodeMetadata; +import org.jclouds.vsphere.compute.strategy.ViComputeServiceAdapter; +import org.xml.sax.InputSource; +import org.xml.sax.SAXException; + +import com.google.common.base.Charsets; +import com.google.common.base.Function; +import com.google.common.base.Supplier; +import com.google.common.collect.Iterables; +import com.google.common.io.Files; +import com.google.inject.Injector; +import com.google.inject.Key; +import com.google.inject.Provides; +import com.google.inject.TypeLiteral; +import com.google.inject.name.Names; +import com.jamesmurty.utils.XMLBuilder; +import com.vmware.vim25.mo.ServiceInstance; +import com.vmware.vim25.mo.VirtualMachine; + +/** + * + * @author Adrian Cole + */ +public class ViComputeServiceContextModule extends +StandaloneComputeServiceContextModule { + @Override + protected void configure() { + super.configure(); + bind(new TypeLiteral>() { + }).to(ViComputeServiceAdapter.class); + bind(new TypeLiteral>() { + }).to(DefaultLocationSupplier.class); + bind(new TypeLiteral>() { + }).to(VirtualMachineToNodeMetadata.class); + bind(new TypeLiteral>() { + }).to(ViImageToImage.class); + bind(new TypeLiteral>() { + }).to(VirtualMachineToHardware.class); + bind(new TypeLiteral>() { + }).to(DatacenterToLocation.class); + } + + @Provides + @Singleton + protected ServiceInstance createConnection(@Provider URI endpoint, @Named(Constants.PROPERTY_IDENTITY) String identity, + @Named(Constants.PROPERTY_CREDENTIAL) String credential) throws RemoteException, MalformedURLException { + System.out.println(endpoint); + System.out.println(identity); + System.out.println(credential); + return new ServiceInstance(endpoint.toURL(), identity, credential, true); + } + + @Override + protected TemplateBuilder provideTemplate(Injector injector, TemplateBuilder template) { + String domainDir = injector.getInstance(Key.get(String.class, Names.named(PROPERTY_LIBVIRT_DOMAIN_DIR))); + String hardwareId = searchForHardwareIdInDomainDir(domainDir); + String image = searchForImageIdInDomainDir(domainDir); + return template.hardwareId(hardwareId).imageId(image) ; + } + + + private String searchForImageIdInDomainDir(String domainDir) { + // TODO + return "1"; + } + + @SuppressWarnings("unchecked") + private String searchForHardwareIdInDomainDir(String domainDir) { + + Collection xmlDomains = FileUtils.listFiles( new File(domainDir), new WildcardFileFilter("*.xml"), null); + String uuid = ""; + try { + String fromXML = Files.toString(Iterables.get(xmlDomains, 0), Charsets.UTF_8); + XMLBuilder builder = XMLBuilder.parse(new InputSource(new StringReader(fromXML))); + uuid = builder.xpathFind("/domain/uuid").getElement().getTextContent(); + } catch (IOException e) { + e.printStackTrace(); + } catch (ParserConfigurationException e) { + e.printStackTrace(); + } catch (SAXException e) { + e.printStackTrace(); + } catch (XPathExpressionException e) { + e.printStackTrace(); + } + return uuid; + } + + /* + * Map regions = newLinkedHashMap(); + for (String region : Splitter.on(',').split(regionString)) { + regions.put( + region, + URI.create(injector.getInstance(Key.get(String.class, + Names.named(Constants.PROPERTY_ENDPOINT + "." + region))))); + } + return regions; + */ + +} \ No newline at end of file diff --git a/sandbox/vsphere/src/main/java/org/jclouds/vsphere/compute/functions/DatacenterToLocation.java b/sandbox/vsphere/src/main/java/org/jclouds/vsphere/compute/functions/DatacenterToLocation.java new file mode 100644 index 0000000000..e949cde848 --- /dev/null +++ b/sandbox/vsphere/src/main/java/org/jclouds/vsphere/compute/functions/DatacenterToLocation.java @@ -0,0 +1,42 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.vsphere.compute.functions; + +import javax.inject.Singleton; + +import org.jclouds.domain.Location; +import org.jclouds.domain.LocationScope; +import org.jclouds.domain.internal.LocationImpl; +import org.jclouds.vsphere.Datacenter; + +import com.google.common.base.Function; + +/** + * @author Adrian Cole + */ +@Singleton +public class DatacenterToLocation implements Function { + + @Override + public Location apply(Datacenter from) { + return new LocationImpl(LocationScope.ZONE, from.id + "", from.name, null); + } + +} diff --git a/sandbox/vsphere/src/main/java/org/jclouds/vsphere/compute/functions/LibvirtNodeToLocation.java b/sandbox/vsphere/src/main/java/org/jclouds/vsphere/compute/functions/LibvirtNodeToLocation.java new file mode 100644 index 0000000000..04d4a80ae1 --- /dev/null +++ b/sandbox/vsphere/src/main/java/org/jclouds/vsphere/compute/functions/LibvirtNodeToLocation.java @@ -0,0 +1,42 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.vsphere.compute.functions; + +import javax.inject.Singleton; + +import org.jclouds.domain.Location; +import org.jclouds.domain.LocationScope; +import org.jclouds.domain.internal.LocationImpl; +import org.jclouds.vsphere.Datacenter; + +import com.google.common.base.Function; + +/** + * @author Adrian Cole + */ +@Singleton +public class LibvirtNodeToLocation implements Function { + + @Override + public Location apply(Datacenter from) { + return new LocationImpl(LocationScope.ZONE, from.id + "", from.name, null); + } + +} diff --git a/sandbox/vsphere/src/main/java/org/jclouds/vsphere/compute/functions/ViImageToImage.java b/sandbox/vsphere/src/main/java/org/jclouds/vsphere/compute/functions/ViImageToImage.java new file mode 100644 index 0000000000..0d7345de7d --- /dev/null +++ b/sandbox/vsphere/src/main/java/org/jclouds/vsphere/compute/functions/ViImageToImage.java @@ -0,0 +1,62 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.vsphere.compute.functions; + +import javax.annotation.Resource; +import javax.inject.Named; +import javax.inject.Singleton; + +import org.jclouds.compute.domain.Image; +import org.jclouds.compute.domain.ImageBuilder; +import org.jclouds.compute.domain.OperatingSystemBuilder; +import org.jclouds.compute.domain.OsFamily; +import org.jclouds.compute.reference.ComputeServiceConstants; +import org.jclouds.logging.Logger; + +import com.google.common.base.Function; + +/** + * @author Adrian Cole + */ +@Singleton +public class ViImageToImage implements Function { + @Resource + @Named(ComputeServiceConstants.COMPUTE_LOGGER) + protected Logger logger = Logger.NULL; + + @Override + public Image apply(org.jclouds.vsphere.Image from) { + + ImageBuilder builder = new ImageBuilder(); + builder.ids(from.id + ""); + builder.name(from.name); + builder.description(from.name); + + OsFamily family = null; + try { + family = OsFamily.fromValue(from.name); + builder.operatingSystem(new OperatingSystemBuilder().name(from.name).family(family).description(from.name).build()); + } catch (IllegalArgumentException e) { + logger.debug("<< didn't match os(%s)", from); + } + return builder.build(); + } + +} diff --git a/sandbox/vsphere/src/main/java/org/jclouds/vsphere/compute/functions/VirtualMachineToHardware.java b/sandbox/vsphere/src/main/java/org/jclouds/vsphere/compute/functions/VirtualMachineToHardware.java new file mode 100644 index 0000000000..33f75aa756 --- /dev/null +++ b/sandbox/vsphere/src/main/java/org/jclouds/vsphere/compute/functions/VirtualMachineToHardware.java @@ -0,0 +1,98 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.vsphere.compute.functions; + +import java.io.IOException; +import java.io.StringReader; +import java.util.List; + +import javax.inject.Singleton; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.xpath.XPathConstants; +import javax.xml.xpath.XPathExpression; +import javax.xml.xpath.XPathExpressionException; +import javax.xml.xpath.XPathFactory; + +import org.jclouds.compute.domain.Hardware; +import org.jclouds.compute.domain.HardwareBuilder; +import org.jclouds.compute.domain.Processor; +import org.jclouds.compute.domain.Volume; +import org.jclouds.compute.domain.internal.VolumeImpl; +import org.w3c.dom.Document; +import org.w3c.dom.NodeList; +import org.xml.sax.InputSource; +import org.xml.sax.SAXException; + +import com.google.common.base.Function; +import com.google.common.base.Throwables; +import com.google.common.collect.Lists; +import com.jamesmurty.utils.XMLBuilder; +import com.vmware.vim25.mo.VirtualMachine; + +/** + * @author Adrian Cole + */ +@Singleton +public class VirtualMachineToHardware implements Function { + + @Override + public Hardware apply(VirtualMachine from) { + HardwareBuilder builder = new HardwareBuilder(); + + builder.id(from.getMOR().get_value() + ""); + builder.providerId(from.getMOR().get_value() + ""); + builder.name(from.getName()); + List processors = Lists.newArrayList(); + for (int i = 0; i < from.getConfig().getHardware().getNumCPU(); i++) { + processors.add(new Processor(i + 1, 1)); + } + builder.processors(processors); + + builder.ram((int) from.getConfig().getHardware().getMemoryMB()); + List volumes = Lists.newArrayList(); + + /* + XMLBuilder xmlBuilder = XMLBuilder.parse(new InputSource(new StringReader(from.getXMLDesc(0)))); + Document doc = xmlBuilder.getDocument(); + XPathExpression expr = XPathFactory.newInstance().newXPath().compile("//devices/disk[@device='disk']/source/@file"); + NodeList nodes = (NodeList) expr.evaluate(doc, XPathConstants.NODESET); + String diskFileName = nodes.item(0).getNodeValue(); + for (int i = 0; i < nodes.getLength(); i++) { + StorageVol storageVol = from.getConnect().storageVolLookupByPath(diskFileName); + String id = storageVol.getKey(); + float size = new Long(storageVol.getInfo().capacity).floatValue(); + volumes.add(new VolumeImpl(id, Volume.Type.LOCAL, size, null, true, false)); + } + */ + + // TODO + builder.volumes((List) volumes); + Float size = new Float(21345); + String id = "dglffdbdflmb"; + volumes.add(new VolumeImpl(id, Volume.Type.LOCAL, size, null, true, false)); + return builder.build(); + } + + protected T propagate(Exception e) { + Throwables.propagate(e); + assert false; + return null; + } +} \ No newline at end of file diff --git a/sandbox/vsphere/src/main/java/org/jclouds/vsphere/compute/functions/VirtualMachineToNodeMetadata.java b/sandbox/vsphere/src/main/java/org/jclouds/vsphere/compute/functions/VirtualMachineToNodeMetadata.java new file mode 100644 index 0000000000..8a0964a7fa --- /dev/null +++ b/sandbox/vsphere/src/main/java/org/jclouds/vsphere/compute/functions/VirtualMachineToNodeMetadata.java @@ -0,0 +1,134 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.vsphere.compute.functions; + +import static com.google.common.base.Preconditions.checkNotNull; +import static org.jclouds.compute.util.ComputeServiceUtils.parseTagFromName; + +import java.util.Map; +import java.util.Set; + +import javax.inject.Inject; +import javax.inject.Singleton; + +import org.jclouds.collect.FindResourceInSet; +import org.jclouds.collect.Memoized; +import org.jclouds.compute.domain.Hardware; +import org.jclouds.compute.domain.Image; +import org.jclouds.compute.domain.NodeMetadata; +import org.jclouds.compute.domain.NodeMetadataBuilder; +import org.jclouds.compute.domain.NodeState; +import org.jclouds.compute.domain.OperatingSystemBuilder; +import org.jclouds.domain.Credentials; +import org.jclouds.domain.Location; + +import com.google.common.base.Function; +import com.google.common.base.Supplier; +import com.google.common.collect.ImmutableMap; +import com.vmware.vim25.VirtualMachinePowerState; +import com.vmware.vim25.mo.VirtualMachine; + +/** + * @author Adrian Cole + */ +@Singleton +public class VirtualMachineToNodeMetadata implements Function { + + public static final Map domainStateToNodeState = + ImmutableMap. builder() + .put(VirtualMachinePowerState.poweredOn, NodeState.RUNNING)// + //.put(VirtualMachinePowerState.suspended, NodeState.PENDING)// + .put(VirtualMachinePowerState.suspended, NodeState.SUSPENDED)// + .put(VirtualMachinePowerState.poweredOff, NodeState.TERMINATED)// + .build(); + + private final Function findHardwareForDomain; + private final FindLocationForDomain findLocationForDomain; + private final FindImageForDomain findImageForDomain; + private final Map credentialStore; + + @Inject + VirtualMachineToNodeMetadata(Map credentialStore, Function findHardwareForDomain, + FindLocationForDomain findLocationForDomain, FindImageForDomain findImageForDomain) { + this.credentialStore = checkNotNull(credentialStore, "credentialStore"); + this.findHardwareForDomain = checkNotNull(findHardwareForDomain, "findHardwareForDomain"); + this.findLocationForDomain = checkNotNull(findLocationForDomain, "findLocationForDomain"); + this.findImageForDomain = checkNotNull(findImageForDomain, "findImageForDomain"); + } + + @Override + public NodeMetadata apply(VirtualMachine from) { + + // convert the result object to a jclouds NodeMetadata + NodeMetadataBuilder builder = new NodeMetadataBuilder(); + try { + builder.id(from.getMOR().get_value() + ""); + builder.providerId(from.getConfig().getLocationId() + ""); + builder.name(from.getName()); + builder.location(findLocationForDomain.apply(from)); + builder.tag(parseTagFromName(from.getName())); + + builder.operatingSystem(new OperatingSystemBuilder().description(from.getConfig().getGuestFullName()).build()); + builder.hardware(findHardwareForDomain.apply(from)); + + builder.state(domainStateToNodeState.get(from.getRuntime().getPowerState())); + // builder.publicAddresses(ImmutableSet. of(from.publicAddress)); + // builder.privateAddresses(ImmutableSet. of(from.privateAddress)); + builder.credentials(credentialStore.get("node#" + from.getMOR().get_value())); + + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + return builder.build(); + } + + @Singleton + public static class FindImageForDomain extends FindResourceInSet { + + @Inject + public FindImageForDomain(@Memoized Supplier> hardware) { + super(hardware); + } + + @Override + public boolean matches(VirtualMachine from, Image input) { + // TODO + // return input.getProviderId().equals(from.imageId + ""); + return true; + } + } + + @Singleton + public static class FindLocationForDomain extends FindResourceInSet { + + @Inject + public FindLocationForDomain(@Memoized Supplier> hardware) { + super(hardware); + } + + @Override + public boolean matches(VirtualMachine from, Location input) { + // TODO + // return input.getId().equals(from.datacenter + ""); + return true; + } + } +} diff --git a/sandbox/vsphere/src/main/java/org/jclouds/vsphere/compute/strategy/ViComputeServiceAdapter.java b/sandbox/vsphere/src/main/java/org/jclouds/vsphere/compute/strategy/ViComputeServiceAdapter.java new file mode 100644 index 0000000000..82bbdffac3 --- /dev/null +++ b/sandbox/vsphere/src/main/java/org/jclouds/vsphere/compute/strategy/ViComputeServiceAdapter.java @@ -0,0 +1,316 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.vsphere.compute.strategy; + +import static com.google.common.base.Preconditions.checkNotNull; +import static org.jclouds.vsphere.ViConstants.PROPERTY_LIBVIRT_DOMAIN_DIR; + +import java.rmi.RemoteException; +import java.util.List; +import java.util.Map; + +import javax.inject.Inject; +import javax.inject.Singleton; + +import org.jclouds.compute.ComputeService; +import org.jclouds.compute.ComputeServiceAdapter; +import org.jclouds.compute.domain.Template; +import org.jclouds.domain.Credentials; +import org.jclouds.vsphere.Datacenter; +import org.jclouds.vsphere.Image; + +import com.google.common.base.Throwables; +import com.google.common.collect.Lists; +import com.google.inject.name.Named; +import com.vmware.vim25.InvalidProperty; +import com.vmware.vim25.RuntimeFault; +import com.vmware.vim25.mo.InventoryNavigator; +import com.vmware.vim25.mo.ManagedEntity; +import com.vmware.vim25.mo.ServiceInstance; +import com.vmware.vim25.mo.VirtualMachine; + +/** + * defines the connection between the {@link Libvirt} implementation and the jclouds + * {@link ComputeService} + * + */ +@Singleton +public class ViComputeServiceAdapter implements ComputeServiceAdapter { + + private final ServiceInstance client; + + @Inject + public ViComputeServiceAdapter(ServiceInstance client) { + this.client = checkNotNull(client, "client"); + } + + @Override + public VirtualMachine runNodeWithTagAndNameAndStoreCredentials(String tag, + String name, Template template, + Map credentialStore) { + // TODO Auto-generated method stub + return null; + } + + /* + @Override + public Domain runNodeWithTagAndNameAndStoreCredentials(String tag, String name, Template template, + Map credentialStore) { + try { + String domainName = tag; + Domain domain = client.domainLookupByName(domainName); + XMLBuilder builder = XMLBuilder.parse(new InputSource(new StringReader(domain.getXMLDesc(0)))); + Document doc = builder.getDocument(); + String xpathString = "//devices/disk[@device='disk']/source/@file"; + XPathExpression expr = XPathFactory.newInstance().newXPath().compile(xpathString); + NodeList nodes = (NodeList) expr.evaluate(doc, XPathConstants.NODESET); + String diskFileName = nodes.item(0).getNodeValue(); + StorageVol storageVol = client.storageVolLookupByPath(diskFileName); + + // cloning volume + String poolName = storageVol.storagePoolLookupByVolume().getName(); + StoragePool storagePool = client.storagePoolLookupByName(poolName); + StorageVol clonedVol = null; + boolean cloned = false; + int retry = 0; + while(!cloned && retry<10) { + try { + clonedVol = cloneVolume(storagePool, storageVol); + cloned = true; + } catch (LibvirtException e) { + retry++; + Thread.sleep(1000); + } + } + // define Domain + String xmlFinal = generateClonedDomainXML(domain.getXMLDesc(0), clonedVol); + Domain newDomain = client.domainDefineXML(xmlFinal); + newDomain.create(); + // store the credentials so that later functions can use them + credentialStore.put(domain.getUUIDString() + "", new Credentials("identity", "credential")); + return newDomain; + } catch (LibvirtException e) { + return propogate(e); + } catch (Exception e) { + return propogate(e); + } + } + */ + + @Override + public Iterable listHardwareProfiles() { + return listNodes(); + } + + @Override + public Iterable listImages() { + /* + int i = 1; + try { + String[] domains = client.listDefinedDomains(); + List images = Lists.newArrayList(); + for (String domainName : domains) { + images.add(new Image(i++, domainName)); + } + return images; + } catch (Exception e) { + return propogate(e); + } + */ + return null; + } + + @Override + public Iterable listNodes() { + try { + ManagedEntity[] vmEntities = new InventoryNavigator(client.getRootFolder()).searchManagedEntities("VirtualMachine"); + List vms = Lists.newArrayList(); + for (ManagedEntity entity : vmEntities) { + System.out.println(entity.getName()); + vms.add((VirtualMachine) entity); + } + return vms; + } catch (InvalidProperty e) { + return propogate(e); + } catch (RuntimeFault e) { + return propogate(e); + } catch (RemoteException e) { + return propogate(e); + } + + } + + @Override + public Iterable listLocations() { + ManagedEntity[] datacenterEntities; + try { + datacenterEntities = new InventoryNavigator(client.getRootFolder()).searchManagedEntities("Datacenter"); + List datacenters = Lists.newArrayList(); + for (int i = 0; i< datacenterEntities.length; i++) { + datacenters.add(new Datacenter(i, datacenterEntities[i].getName())); + } + return datacenters; + } catch (InvalidProperty e) { + return propogate(e); + } catch (RuntimeFault e) { + return propogate(e); + } catch (RemoteException e) { + return propogate(e); + } + + } + + @Override + public VirtualMachine getNode(String id) { + VirtualMachine vm = null; + /* + try { + d = client.domainLookupByUUIDString(id); + } catch (LibvirtException e) { + if (e.getMessage().indexOf("Domain not found: no domain with matching uuid") != -1) + return null; + propogate(e); + } + */ + return vm; + } + + @Override + public void destroyNode(String id) { + /* + try { + client.domainLookupByUUIDString(id).destroy(); + + XMLBuilder builder = XMLBuilder.parse(new InputSource(new StringReader( + client.domainLookupByUUIDString(id).getXMLDesc(0) + ))); + String diskFileName = builder.xpathFind("//devices/disk[@device='disk']/source").getElement().getAttribute("file"); + StorageVol storageVol = client.storageVolLookupByPath(diskFileName); + storageVol.delete(0); + client.domainLookupByUUIDString(id).undefine(); + + } catch (LibvirtException e) { + propogate(e); + } catch (Exception e) { + propogate(e); + } + */ + } + + @Override + public void rebootNode(String id) { + /* + try { + client.domainLookupByUUIDString(id).reboot(0); + } catch (LibvirtException e) { + propogate(e); + } + */ + } + + @Override + public void resumeNode(String id) { + /* + try { + client.domainLookupByUUIDString(id).resume(); + } catch (LibvirtException e) { + propogate(e); + } + */ + } + + @Override + public void suspendNode(String id) { + /* + try { + client.domainLookupByUUIDString(id).suspend(); + } catch (LibvirtException e) { + propogate(e); + } + */ + } + + protected T propogate(Exception e) { + Throwables.propagate(e); + assert false; + return null; + } + + /* + private static StorageVol cloneVolume(StoragePool storagePool, StorageVol from) throws LibvirtException, + XPathExpressionException, ParserConfigurationException, SAXException, IOException, TransformerException { + return storagePool.storageVolCreateXMLFrom(generateClonedVolumeXML(from.getXMLDesc(0)), from, 0); + } + + private static String generateClonedVolumeXML(String fromXML) throws ParserConfigurationException, SAXException, + IOException, XPathExpressionException, TransformerException { + + Properties outputProperties = generateOutputXMLProperties(); + XMLBuilder builder = XMLBuilder.parse(new InputSource(new StringReader(fromXML))); + String nodeNamingConvention = "%s-%s"; + String tag = "-clone"; + String suffix = String.format(nodeNamingConvention, tag, Integer.toHexString(new SecureRandom().nextInt(4095))); + builder.xpathFind("//volume/name").t(suffix); + builder.xpathFind("//volume/key").t(suffix); + builder.xpathFind("//volume/target/path").t(suffix); + + return builder.asString(outputProperties); + } + + private static String generateClonedDomainXML(String fromXML, StorageVol clonedVol) throws ParserConfigurationException, SAXException, + IOException, XPathExpressionException, TransformerException, LibvirtException { + + Properties outputProperties = generateOutputXMLProperties(); + + XMLBuilder builder = XMLBuilder.parse(new InputSource(new StringReader(fromXML))); + + String nodeNamingConvention = "%s-%s"; + String tag = "-clone"; + String suffix = String.format(nodeNamingConvention, tag, Integer.toHexString(new SecureRandom().nextInt(4095))); + builder.xpathFind("//domain/name").t(suffix); + // change uuid domain + Element oldChild = builder.xpathFind("//domain/uuid").getElement(); + Node newNode = oldChild.cloneNode(true); + newNode.getFirstChild().setNodeValue(UUID.randomUUID().toString()); + builder.getDocument().getDocumentElement().replaceChild(newNode, oldChild); + + //String fromVolPath = builder.xpathFind("//domain/devices/disk/source").getElement().getAttribute("file"); + builder.xpathFind("//domain/devices/disk/source").a("file", clonedVol.getPath()); + // generate valid MAC address + String fromMACaddress = builder.xpathFind("//domain/devices/interface/mac").getElement().getAttribute("address"); + String lastMACoctet = Integer.toHexString(new SecureRandom().nextInt(255)); + builder.xpathFind("//domain/devices/interface/mac").a("address", + fromMACaddress.substring(0, fromMACaddress.lastIndexOf(":")+1) + lastMACoctet + ); + return builder.asString(outputProperties); + } + + private static Properties generateOutputXMLProperties() { + Properties outputProperties = new Properties(); + // Explicitly identify the output as an XML document + outputProperties.put(javax.xml.transform.OutputKeys.METHOD, "xml"); + // Pretty-print the XML output (doesn't work in all cases) + outputProperties.put(javax.xml.transform.OutputKeys.INDENT, "yes"); + // Get 2-space indenting when using the Apache transformer + outputProperties.put("{http://xml.apache.org/xslt}indent-amount", "2"); + return outputProperties; + } + */ +} \ No newline at end of file diff --git a/sandbox/vsphere/src/test/java/org/jclouds/vsphere/compute/ViComputeServiceContextBuilderTest.java b/sandbox/vsphere/src/test/java/org/jclouds/vsphere/compute/ViComputeServiceContextBuilderTest.java new file mode 100644 index 0000000000..5c507a97a9 --- /dev/null +++ b/sandbox/vsphere/src/test/java/org/jclouds/vsphere/compute/ViComputeServiceContextBuilderTest.java @@ -0,0 +1,33 @@ +package org.jclouds.vsphere.compute; + +import static org.testng.Assert.assertNotNull; + +import java.util.Properties; + +import org.jclouds.compute.ComputeServiceContext; +import org.jclouds.compute.ComputeServiceContextFactory; +import org.jclouds.vsphere.compute.ViComputeServiceContextBuilder; +import org.jclouds.vsphere.compute.ViComputeServiceContextSpec; +import org.testng.annotations.Test; + +/** + * + * @author andrea.turli + * + */ +@Test(groups = "unit") +public class ViComputeServiceContextBuilderTest { + + @Test + public void testCreateContextModule() { + assertNotNull(new ViComputeServiceContextBuilder(new Properties()).createContextModule()); + } + + @Test + public void testCanBuildWithComputeService() { + ComputeServiceContext context = new ComputeServiceContextFactory() + .createContext(new ViComputeServiceContextSpec("https://10.38.102.196/sdk", "Administrator", "41.U17Sh")); + context.getComputeService().listNodes(); + context.close(); + } +} diff --git a/sandbox/vsphere/src/test/java/org/jclouds/vsphere/compute/ViExperimentLiveTest.java b/sandbox/vsphere/src/test/java/org/jclouds/vsphere/compute/ViExperimentLiveTest.java new file mode 100644 index 0000000000..3674fe6563 --- /dev/null +++ b/sandbox/vsphere/src/test/java/org/jclouds/vsphere/compute/ViExperimentLiveTest.java @@ -0,0 +1,97 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.vsphere.compute; + +import static com.google.common.base.Preconditions.checkNotNull; + +import java.util.Set; + +import org.jclouds.compute.ComputeServiceContext; +import org.jclouds.compute.ComputeServiceContextFactory; +import org.jclouds.compute.domain.NodeMetadata; +import org.jclouds.compute.domain.Template; +import org.jclouds.vsphere.compute.ViComputeServiceContextSpec; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +/** + * + * @author Adrian Cole + */ +@Test(groups = "live", testName = "vsphere.ViExperimentLiveTest") +public class ViExperimentLiveTest { + protected String provider = "vsphere"; + protected String identity; + protected String credential; + protected String endpoint; + protected String apiversion; + + @BeforeClass + protected void setupCredentials() { + identity = checkNotNull(System.getProperty("test." + provider + ".identity"), "test." + provider + ".identity"); + credential = System.getProperty("test." + provider + ".credential"); + endpoint = System.getProperty("test." + provider + ".endpoint"); + apiversion = System.getProperty("test." + provider + ".apiversion"); + } + + @Test + public void testAndExperiment() { + ComputeServiceContext context = null; + try { + context = new ComputeServiceContextFactory().createContext(new ViComputeServiceContextSpec( + endpoint, identity, credential)); + context.getComputeService().listNodes(); + + + /* + * /* System.out.println("images " + context.getComputeService().listImages()); + * System.out.println("nodes " + context.getComputeService().listNodes()); + * System.out.println("hardware profiles " + + * context.getComputeService().listHardwareProfiles()); + */ + + +/* Template defaultTemplate = context.getComputeService().templateBuilder() + .hardwareId("d106ae67-5a1b-8f91-b311-83c93bcb0a1f").imageId("1") //.locationId("") + .build();*/ + + + /* + * We will probably make a default template out of properties at some point You can control + * the default template via overriding a method in standalonecomputeservicexontextmodule + */ + + Set nodeMetadataSet = context.getComputeService().runNodesWithTag("tty", 1); + for (NodeMetadata nodeMetadata : nodeMetadataSet) { + /* + * context.getComputeService().suspendNode(nodeMetadata.getId()); + * context.getComputeService().resumeNode(nodeMetadata.getId()); + */ + context.getComputeService().destroyNode(nodeMetadata.getId()); + } + } catch (Exception e) { + e.printStackTrace(); + } finally { + if (context != null) + context.close(); + } + } + +} \ No newline at end of file diff --git a/sandbox/vsphere/src/test/resources/log4j.xml b/sandbox/vsphere/src/test/resources/log4j.xml new file mode 100644 index 0000000000..a3b1e56934 --- /dev/null +++ b/sandbox/vsphere/src/test/resources/log4j.xml @@ -0,0 +1,136 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file From 5f6cc052ceb4365606906524c16832534a90574d Mon Sep 17 00:00:00 2001 From: andreaturli Date: Sat, 4 Dec 2010 16:21:37 +0100 Subject: [PATCH 21/31] first commit --- .../vsphere/compute/ViComputeServiceContextBuilderTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sandbox/vsphere/src/test/java/org/jclouds/vsphere/compute/ViComputeServiceContextBuilderTest.java b/sandbox/vsphere/src/test/java/org/jclouds/vsphere/compute/ViComputeServiceContextBuilderTest.java index 5c507a97a9..891323bde6 100644 --- a/sandbox/vsphere/src/test/java/org/jclouds/vsphere/compute/ViComputeServiceContextBuilderTest.java +++ b/sandbox/vsphere/src/test/java/org/jclouds/vsphere/compute/ViComputeServiceContextBuilderTest.java @@ -26,7 +26,7 @@ public class ViComputeServiceContextBuilderTest { @Test public void testCanBuildWithComputeService() { ComputeServiceContext context = new ComputeServiceContextFactory() - .createContext(new ViComputeServiceContextSpec("https://10.38.102.196/sdk", "Administrator", "41.U17Sh")); + .createContext(new ViComputeServiceContextSpec("https://localhost/sdk", "Administrator", "password")); context.getComputeService().listNodes(); context.close(); } From 19a8ce4db2109904434f02626ceed64674b96847 Mon Sep 17 00:00:00 2001 From: Adrian Cole Date: Sat, 4 Dec 2010 17:23:38 +0000 Subject: [PATCH 22/31] Issue 310: added simpledb client --- .../java/org/jclouds/aws/domain/Region.java | 46 ++--- .../aws/simpledb/SimpleDBAsyncClient.java | 83 ++++++++ .../jclouds/aws/simpledb/SimpleDBClient.java | 107 ++++++++++ .../aws/simpledb/SimpleDBContextBuilder.java | 56 ++++++ .../simpledb/SimpleDBPropertiesBuilder.java | 69 +++++++ .../config/SimpleDBRestClientModule.java | 41 ++++ .../aws/simpledb/domain/DomainMetadata.java | 190 ++++++++++++++++++ .../simpledb/domain/ListDomainsResponse.java | 37 ++++ .../simpledb/options/ListDomainsOptions.java | 101 ++++++++++ .../jclouds/aws/simpledb/package-info.java | 25 +++ .../reference/SimpleDBParameters.java | 74 +++++++ .../aws/simpledb/reference/package-info.java | 24 +++ .../xml/ListDomainsResponseHandler.java | 83 ++++++++ .../aws/simpledb/SimpleDBAsyncClientTest.java | 126 ++++++++++++ .../aws/simpledb/SimpleDBClientLiveTest.java | 174 ++++++++++++++++ .../config/SimpleDBRestClientModuleTest.java | 93 +++++++++ .../options/ListDomainsOptionsTest.java | 90 +++++++++ .../xml/ListDomainsResponseHandlerTest.java | 51 +++++ .../test/resources/simpledb/list_domains.xml | 11 + aws/pom.xml | 20 ++ core/src/main/resources/rest.properties | 3 + 21 files changed, 1479 insertions(+), 25 deletions(-) create mode 100644 aws/core/src/main/java/org/jclouds/aws/simpledb/SimpleDBAsyncClient.java create mode 100644 aws/core/src/main/java/org/jclouds/aws/simpledb/SimpleDBClient.java create mode 100644 aws/core/src/main/java/org/jclouds/aws/simpledb/SimpleDBContextBuilder.java create mode 100644 aws/core/src/main/java/org/jclouds/aws/simpledb/SimpleDBPropertiesBuilder.java create mode 100644 aws/core/src/main/java/org/jclouds/aws/simpledb/config/SimpleDBRestClientModule.java create mode 100644 aws/core/src/main/java/org/jclouds/aws/simpledb/domain/DomainMetadata.java create mode 100644 aws/core/src/main/java/org/jclouds/aws/simpledb/domain/ListDomainsResponse.java create mode 100644 aws/core/src/main/java/org/jclouds/aws/simpledb/options/ListDomainsOptions.java create mode 100644 aws/core/src/main/java/org/jclouds/aws/simpledb/package-info.java create mode 100644 aws/core/src/main/java/org/jclouds/aws/simpledb/reference/SimpleDBParameters.java create mode 100644 aws/core/src/main/java/org/jclouds/aws/simpledb/reference/package-info.java create mode 100755 aws/core/src/main/java/org/jclouds/aws/simpledb/xml/ListDomainsResponseHandler.java create mode 100644 aws/core/src/test/java/org/jclouds/aws/simpledb/SimpleDBAsyncClientTest.java create mode 100644 aws/core/src/test/java/org/jclouds/aws/simpledb/SimpleDBClientLiveTest.java create mode 100644 aws/core/src/test/java/org/jclouds/aws/simpledb/config/SimpleDBRestClientModuleTest.java create mode 100644 aws/core/src/test/java/org/jclouds/aws/simpledb/options/ListDomainsOptionsTest.java create mode 100644 aws/core/src/test/java/org/jclouds/aws/simpledb/xml/ListDomainsResponseHandlerTest.java create mode 100644 aws/core/src/test/resources/simpledb/list_domains.xml diff --git a/aws/core/src/main/java/org/jclouds/aws/domain/Region.java b/aws/core/src/main/java/org/jclouds/aws/domain/Region.java index e5a0c0408c..a630f3776a 100644 --- a/aws/core/src/main/java/org/jclouds/aws/domain/Region.java +++ b/aws/core/src/main/java/org/jclouds/aws/domain/Region.java @@ -28,7 +28,8 @@ import com.google.common.collect.ImmutableSet; * Regions used for all aws commands. * * @author Adrian Cole - * @see * */ @@ -38,9 +39,8 @@ public class Region { *

*

S3

*

- * In Amazon S3, the EU (Ireland) Region provides read-after-write - * consistency for PUTS of new objects in your Amazon S3 bucket and eventual - * consistency for overwrite PUTS and DELETES. + * In Amazon S3, the EU (Ireland) Region provides read-after-write consistency for PUTS of new + * objects in your Amazon S3 bucket and eventual consistency for overwrite PUTS and DELETES. */ public static final String EU = "EU"; @@ -52,13 +52,11 @@ public class Region { *

*

S3

*

- * This is the default Region. All requests sent to s3.amazonaws.com go to - * this Region unless you specify a LocationConstraint on a bucket. The US - * Standard Region automatically places your data in either Amazon's east or - * west coast data centers depending on what will provide you with the lowest - * latency. To use this region, do not set the LocationConstraint bucket - * parameter. The US Standard Region provides eventual consistency for all - * requests. + * This is the default Region. All requests sent to s3.amazonaws.com go to this Region unless you + * specify a LocationConstraint on a bucket. The US Standard Region automatically places your + * data in either Amazon's east or west coast data centers depending on what will provide you + * with the lowest latency. To use this region, do not set the LocationConstraint bucket + * parameter. The US Standard Region provides eventual consistency for all requests. */ public static final String US_STANDARD = "us-standard"; @@ -68,27 +66,25 @@ public class Region { public static final String US_EAST_1 = "us-east-1"; /** - * US-West (Northern California)

S3

Uses Amazon S3 servers in - * Northern California + * US-West (Northern California)

S3

Uses Amazon S3 servers in Northern California *

- * Optionally, use the endpoint s3-us-west-1.amazonaws.com on all requests to - * this bucket to reduce the latency you might experience after the first - * hour of creating a bucket in this Region. + * Optionally, use the endpoint s3-us-west-1.amazonaws.com on all requests to this bucket to + * reduce the latency you might experience after the first hour of creating a bucket in this + * Region. *

- * In Amazon S3, the US-West (Northern California) Region provides - * read-after-write consistency for PUTS of new objects in your Amazon S3 - * bucket and eventual consistency for overwrite PUTS and DELETES. + * In Amazon S3, the US-West (Northern California) Region provides read-after-write consistency + * for PUTS of new objects in your Amazon S3 bucket and eventual consistency for overwrite PUTS + * and DELETES. */ public static final String US_WEST_1 = "us-west-1"; /** - * Region in Singapore, launched April 28, 2010. This region improves latency - * for Asia-based users + * Region in Singapore, launched April 28, 2010. This region improves latency for Asia-based + * users */ public static final String AP_SOUTHEAST_1 = "ap-southeast-1"; - public static Set ALL_S3 = ImmutableSet.of(EU, US_STANDARD, - US_WEST_1, AP_SOUTHEAST_1); - public static Set ALL_SQS = ImmutableSet.of(EU_WEST_1, US_STANDARD, - US_EAST_1, US_WEST_1, AP_SOUTHEAST_1); + public static Set ALL_SIMPLEDB = ImmutableSet.of(EU_WEST_1, US_EAST_1, US_WEST_1, AP_SOUTHEAST_1); + public static Set ALL_S3 = ImmutableSet.of(EU, US_STANDARD, US_WEST_1, AP_SOUTHEAST_1); + public static Set ALL_SQS = ImmutableSet.of(EU_WEST_1, US_STANDARD, US_EAST_1, US_WEST_1, AP_SOUTHEAST_1); } \ No newline at end of file diff --git a/aws/core/src/main/java/org/jclouds/aws/simpledb/SimpleDBAsyncClient.java b/aws/core/src/main/java/org/jclouds/aws/simpledb/SimpleDBAsyncClient.java new file mode 100644 index 0000000000..f797191579 --- /dev/null +++ b/aws/core/src/main/java/org/jclouds/aws/simpledb/SimpleDBAsyncClient.java @@ -0,0 +1,83 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.aws.simpledb; + +import static org.jclouds.aws.simpledb.reference.SimpleDBParameters.ACTION; +import static org.jclouds.aws.simpledb.reference.SimpleDBParameters.VERSION; + +import javax.annotation.Nullable; +import javax.ws.rs.FormParam; +import javax.ws.rs.POST; +import javax.ws.rs.Path; + +import org.jclouds.aws.filters.FormSigner; +import org.jclouds.aws.functions.RegionToEndpoint; +import org.jclouds.aws.simpledb.domain.ListDomainsResponse; +import org.jclouds.aws.simpledb.options.ListDomainsOptions; +import org.jclouds.aws.simpledb.xml.ListDomainsResponseHandler; +import org.jclouds.rest.annotations.EndpointParam; +import org.jclouds.rest.annotations.FormParams; +import org.jclouds.rest.annotations.RequestFilters; +import org.jclouds.rest.annotations.VirtualHost; +import org.jclouds.rest.annotations.XMLResponseParser; + +import com.google.common.util.concurrent.ListenableFuture; + +/** + * Provides access to SimpleDB via their REST API. + *

+ * + * @author Adrian Cole + */ +@RequestFilters(FormSigner.class) +@FormParams(keys = VERSION, values = SimpleDBAsyncClient.VERSION) +@VirtualHost +public interface SimpleDBAsyncClient { + public static final String VERSION = "2009-04-15"; + + /** + * @see SimpleDBClient#listDomainsInRegion + */ + @POST + @Path("/") + @FormParams(keys = ACTION, values = "ListDomains") + @XMLResponseParser(ListDomainsResponseHandler.class) + ListenableFuture listDomainsInRegion( + @EndpointParam(parser = RegionToEndpoint.class) @Nullable String region, ListDomainsOptions... options); + + /** + * @see SimpleDBClient#createDomainInRegion + */ + @POST + @Path("/") + @FormParams(keys = ACTION, values = "CreateDomain") + ListenableFuture createDomainInRegion(@EndpointParam(parser = RegionToEndpoint.class) @Nullable String region, + @FormParam("DomainName") String domainName); + + /** + * @see SimpleDBClient#deleteDomain + */ + @POST + @Path("/") + @FormParams(keys = ACTION, values = "DeleteDomain") + ListenableFuture deleteDomainInRegion(@EndpointParam(parser = RegionToEndpoint.class) @Nullable String region, + @FormParam("DomainName") String domainName); + +} diff --git a/aws/core/src/main/java/org/jclouds/aws/simpledb/SimpleDBClient.java b/aws/core/src/main/java/org/jclouds/aws/simpledb/SimpleDBClient.java new file mode 100644 index 0000000000..e3d63cc080 --- /dev/null +++ b/aws/core/src/main/java/org/jclouds/aws/simpledb/SimpleDBClient.java @@ -0,0 +1,107 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.aws.simpledb; + +import java.util.concurrent.TimeUnit; + +import javax.annotation.Nullable; + +import org.jclouds.aws.simpledb.domain.ListDomainsResponse; +import org.jclouds.aws.simpledb.options.ListDomainsOptions; +import org.jclouds.concurrent.Timeout; + +/** + * Provides access to SimpleDB via their REST API. + *

+ * + * @author Adrian Cole + */ +@Timeout(duration = 30, timeUnit = TimeUnit.SECONDS) +public interface SimpleDBClient { + + /** + * The ListDomains operation lists all domains associated with the Access Key ID. It returns + * domain names up to the limit set by MaxNumberOfDomains. A NextToken is returned if there are + * more than MaxNumberOfDomains domains. Calling ListDomains successive times with the NextToken + * returns up to MaxNumberOfDomains more domain names each time. + * + * + * @param region + * Domains are Region-specific. + * @param options + * specify result count or other options + * + * @see + */ + ListDomainsResponse listDomainsInRegion(@Nullable String region, ListDomainsOptions... options); + + /** + * The CreateDomain operation creates a new domain. + * + *

+ * The domain name must be unique among the domains associated with the Access Key ID provided in + * the request. The CreateDomain operation might take 10 or more seconds to complete. + * + * + *

Note

+ * CreateDomain is an idempotent operation; running it multiple times using the same domain name + * will not result in an error response. + *

+ * You can create up to 100 domains per account. + *

+ * If you require additional domains, go to + * http://aws.amazon.com/contact-us/simpledb-limit-request/. + * + * @param region + * Domains are Region-specific. + * @param domainName + * The name of the domain to create. The name can range between 3 and 255 characters + * and can contain the following characters: a-z, A-Z, 0-9, '_', '-', and '.'. + * + * @see + */ + void createDomainInRegion(@Nullable String region, String domainName); + + /** + * The DeleteDomain operation deletes a domain. Any items (and their attributes) in the domain + * are deleted as well. The DeleteDomain operation might take 10 or more seconds to complete.

+ * Note

+ * + * Running DeleteDomain on a domain that does not exist or running the function multiple times + * using the same domain name will not result in an error response. + * + * + * @param region + * Domains are Region-specific. + * @param domainName + * The name of the domain to delete. + * + * + * @see + */ + void deleteDomainInRegion(String region, String domainName); + +} diff --git a/aws/core/src/main/java/org/jclouds/aws/simpledb/SimpleDBContextBuilder.java b/aws/core/src/main/java/org/jclouds/aws/simpledb/SimpleDBContextBuilder.java new file mode 100644 index 0000000000..4b210cd866 --- /dev/null +++ b/aws/core/src/main/java/org/jclouds/aws/simpledb/SimpleDBContextBuilder.java @@ -0,0 +1,56 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.aws.simpledb; + +import java.util.List; +import java.util.Properties; + +import org.jclouds.aws.simpledb.config.SimpleDBRestClientModule; +import org.jclouds.http.config.JavaUrlHttpCommandExecutorServiceModule; +import org.jclouds.logging.jdk.config.JDKLoggingModule; +import org.jclouds.rest.RestContextBuilder; + +import com.google.inject.Injector; +import com.google.inject.Module; + +/** + * Creates {@link SimpleDBContext} or {@link Injector} instances based on the most commonly requested + * arguments. + *

+ * Note that Threadsafe objects will be bound as singletons to the Injector or Context provided. + *

+ *

+ * If no Modules are specified, the default {@link JDKLoggingModule logging} and + * {@link JavaUrlHttpCommandExecutorServiceModule http transports} will be installed. + * + * @author Adrian Cole + * @see SimpleDBContext + */ +public class SimpleDBContextBuilder extends RestContextBuilder { + + public SimpleDBContextBuilder(Properties props) { + super(SimpleDBClient.class, SimpleDBAsyncClient.class, props); + } + + @Override + protected void addClientModule(List modules) { + modules.add(new SimpleDBRestClientModule()); + } +} diff --git a/aws/core/src/main/java/org/jclouds/aws/simpledb/SimpleDBPropertiesBuilder.java b/aws/core/src/main/java/org/jclouds/aws/simpledb/SimpleDBPropertiesBuilder.java new file mode 100644 index 0000000000..faa842b5d6 --- /dev/null +++ b/aws/core/src/main/java/org/jclouds/aws/simpledb/SimpleDBPropertiesBuilder.java @@ -0,0 +1,69 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.aws.simpledb; + +import static org.jclouds.Constants.PROPERTY_API_VERSION; +import static org.jclouds.Constants.PROPERTY_ENDPOINT; +import static org.jclouds.aws.reference.AWSConstants.PROPERTY_AUTH_TAG; +import static org.jclouds.aws.reference.AWSConstants.PROPERTY_HEADER_TAG; +import static org.jclouds.aws.reference.AWSConstants.PROPERTY_REGIONS; + +import java.util.Properties; + +import org.jclouds.PropertiesBuilder; +import org.jclouds.aws.domain.Region; + +import com.google.common.base.Joiner; + +/** + * Builds properties used in SimpleDB Clients + * + * @author Adrian Cole + */ +public class SimpleDBPropertiesBuilder extends PropertiesBuilder { + @Override + protected Properties defaultProperties() { + Properties properties = super.defaultProperties(); + properties.setProperty(PROPERTY_AUTH_TAG, "AWS"); + properties.setProperty(PROPERTY_HEADER_TAG, "amz"); + properties.setProperty(PROPERTY_API_VERSION, SimpleDBAsyncClient.VERSION); + properties.setProperty(PROPERTY_REGIONS, Joiner.on(',').join(Region.US_EAST_1, + Region.US_WEST_1, Region.EU_WEST_1, Region.AP_SOUTHEAST_1)); + properties.setProperty(PROPERTY_ENDPOINT, "https://sdb.amazonaws.com"); + properties.setProperty(PROPERTY_ENDPOINT + "." + Region.US_EAST_1, + "https://sdb.amazonaws.com"); + properties.setProperty(PROPERTY_ENDPOINT + "." + Region.US_WEST_1, + "https://sdb.us-west-1.amazonaws.com"); + properties.setProperty(PROPERTY_ENDPOINT + "." + Region.EU_WEST_1, + "https://sdb.eu-west-1.amazonaws.com"); + properties.setProperty(PROPERTY_ENDPOINT + "." + Region.AP_SOUTHEAST_1, + "https://sdb.ap-southeast-1.amazonaws.com"); + return properties; + } + + public SimpleDBPropertiesBuilder() { + super(); + } + + public SimpleDBPropertiesBuilder(Properties properties) { + super(properties); + } + +} diff --git a/aws/core/src/main/java/org/jclouds/aws/simpledb/config/SimpleDBRestClientModule.java b/aws/core/src/main/java/org/jclouds/aws/simpledb/config/SimpleDBRestClientModule.java new file mode 100644 index 0000000000..4870bfcded --- /dev/null +++ b/aws/core/src/main/java/org/jclouds/aws/simpledb/config/SimpleDBRestClientModule.java @@ -0,0 +1,41 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.aws.simpledb.config; + +import org.jclouds.aws.config.AWSFormSigningRestClientModule; +import org.jclouds.aws.simpledb.SimpleDBAsyncClient; +import org.jclouds.aws.simpledb.SimpleDBClient; +import org.jclouds.http.RequiresHttp; +import org.jclouds.rest.ConfiguresRestClient; + +/** + * Configures the SimpleDB connection. + * + * @author Adrian Cole + */ +@RequiresHttp +@ConfiguresRestClient +public class SimpleDBRestClientModule extends AWSFormSigningRestClientModule { + + public SimpleDBRestClientModule() { + super(SimpleDBClient.class, SimpleDBAsyncClient.class); + } + +} diff --git a/aws/core/src/main/java/org/jclouds/aws/simpledb/domain/DomainMetadata.java b/aws/core/src/main/java/org/jclouds/aws/simpledb/domain/DomainMetadata.java new file mode 100644 index 0000000000..90d5a9c3f2 --- /dev/null +++ b/aws/core/src/main/java/org/jclouds/aws/simpledb/domain/DomainMetadata.java @@ -0,0 +1,190 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.aws.simpledb.domain; + +import java.util.Date; + +/** + * + * @see + * @author Adrian Cole + */ +public class DomainMetadata { + private final String region; + private final String name; + private final Date timestamp; + private final long itemCount; + private final long attributeValueCount; + private final long attributeNameCount; + private final long itemNamesSizeBytes; + private final long attributeValuesSizeBytes; + private final long attributeNamesSizeBytes; + + public DomainMetadata(String region, String name, Date timestamp, long itemCount, long attributeValueCount, + long attributeNameCount, long itemNamesSizeBytes, long attributeValuesSizeBytes, long attributeNamesSizeBytes) { + this.region = region; + this.name = name; + this.timestamp = timestamp; + this.itemCount = itemCount; + this.attributeValueCount = attributeValueCount; + this.attributeNameCount = attributeNameCount; + this.itemNamesSizeBytes = itemNamesSizeBytes; + this.attributeValuesSizeBytes = attributeValuesSizeBytes; + this.attributeNamesSizeBytes = attributeNamesSizeBytes; + } + + /** + * + * @return region the domain belongs to + */ + public String getRegion() { + return region; + } + + /** + * + * @return name of the domain + */ + public String getName() { + return name; + } + + /** + * + * @return The number of all items in the domain. + */ + public Date getTimestamp() { + return timestamp; + } + + /** + * + * @return + */ + public long getItemCount() { + return itemCount; + } + + /** + * + * @return The number of all attribute name/value pairs in the domain. + */ + public long getAttributeValueCount() { + return attributeValueCount; + } + + /** + * + * @return The number of unique attribute names in the domain. + */ + public long getAttributeNameCount() { + return attributeNameCount; + } + + /** + * + * @return The total size of all item names in the domain, in bytes. + */ + public long getItemNamesSizeBytes() { + return itemNamesSizeBytes; + } + + /** + * + * @return The total size of all attribute values, in bytes. + */ + public long getAttributeValuesSizeBytes() { + return attributeValuesSizeBytes; + } + + /** + * + * @return The total size of all unique attribute names, in bytes. + */ + public long getAttributeNamesSizeBytes() { + return attributeNamesSizeBytes; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + (int) (attributeNameCount ^ (attributeNameCount >>> 32)); + result = prime * result + (int) (attributeNamesSizeBytes ^ (attributeNamesSizeBytes >>> 32)); + result = prime * result + (int) (attributeValueCount ^ (attributeValueCount >>> 32)); + result = prime * result + (int) (attributeValuesSizeBytes ^ (attributeValuesSizeBytes >>> 32)); + result = prime * result + (int) (itemCount ^ (itemCount >>> 32)); + result = prime * result + (int) (itemNamesSizeBytes ^ (itemNamesSizeBytes >>> 32)); + result = prime * result + ((name == null) ? 0 : name.hashCode()); + result = prime * result + ((region == null) ? 0 : region.hashCode()); + result = prime * result + ((timestamp == null) ? 0 : timestamp.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; + DomainMetadata other = (DomainMetadata) obj; + if (attributeNameCount != other.attributeNameCount) + return false; + if (attributeNamesSizeBytes != other.attributeNamesSizeBytes) + return false; + if (attributeValueCount != other.attributeValueCount) + return false; + if (attributeValuesSizeBytes != other.attributeValuesSizeBytes) + return false; + if (itemCount != other.itemCount) + return false; + if (itemNamesSizeBytes != other.itemNamesSizeBytes) + return false; + if (name == null) { + if (other.name != null) + return false; + } else if (!name.equals(other.name)) + return false; + if (region == null) { + if (other.region != null) + return false; + } else if (!region.equals(other.region)) + return false; + if (timestamp == null) { + if (other.timestamp != null) + return false; + } else if (!timestamp.equals(other.timestamp)) + return false; + return true; + } + + @Override + public String toString() { + return "[region=" + region + ", name=" + name + ", timestamp=" + timestamp + ", itemCount=" + itemCount + + ", attributeValueCount=" + attributeValueCount + ", attributeNameCount=" + attributeNameCount + + ", itemNamesSizeBytes=" + itemNamesSizeBytes + ", attributeValuesSizeBytes=" + attributeValuesSizeBytes + + ", attributeNamesSizeBytes=" + attributeNamesSizeBytes + "]"; + } + +} diff --git a/aws/core/src/main/java/org/jclouds/aws/simpledb/domain/ListDomainsResponse.java b/aws/core/src/main/java/org/jclouds/aws/simpledb/domain/ListDomainsResponse.java new file mode 100644 index 0000000000..4fa1ba9339 --- /dev/null +++ b/aws/core/src/main/java/org/jclouds/aws/simpledb/domain/ListDomainsResponse.java @@ -0,0 +1,37 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.aws.simpledb.domain; + +import java.util.Set; + +/** + * + * @author Adrian Cole + * @see + */ +public interface ListDomainsResponse extends Set { + + /** + * An opaque token indicating that there are more than MaxNumberOfDomains domains still + * available. + */ + String getNextToken(); + +} \ No newline at end of file diff --git a/aws/core/src/main/java/org/jclouds/aws/simpledb/options/ListDomainsOptions.java b/aws/core/src/main/java/org/jclouds/aws/simpledb/options/ListDomainsOptions.java new file mode 100644 index 0000000000..4db2c3453f --- /dev/null +++ b/aws/core/src/main/java/org/jclouds/aws/simpledb/options/ListDomainsOptions.java @@ -0,0 +1,101 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.aws.simpledb.options; + +import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.base.Preconditions.checkNotNull; + +import org.jclouds.http.options.BaseHttpRequestOptions; + +/** + * Contains options supported in the Form API for the ListDomains operation.

+ * Usage

The recommended way to instantiate a ListDomainsOptions object is to statically import + * ListDomainsOptions.Builder.* and invoke a static creation method followed by an instance mutator + * (if needed): + *

+ * + * import static org.jclouds.aws.simpledb.options.ListDomainsOptions.Builder.* + *

+ * SimpleDBClient connection = // get connection + * Set domains = connection.listDomainsInRegion(maxNumberOfDomains(1)); + * + * + * @author Adrian Cole + * @see + */ +public class ListDomainsOptions extends BaseHttpRequestOptions { + + /** + * The maximum number of domain names you want returned. + * + * @param maxNumberOfDomains + * Maximum 100 + */ + public ListDomainsOptions maxNumberOfDomains(int maxNumberOfDomains) { + checkArgument(maxNumberOfDomains > 0 && maxNumberOfDomains <= 100, "must be between 1-100"); + formParameters.put("MaxNumberOfDomains", maxNumberOfDomains + ""); + return this; + } + + public String getMaxNumberOfDomains() { + return getFirstFormOrNull("MaxNumberOfDomains"); + } + + /** + * + * @param nextToken + * tells Amazon SimpleDB where to start the next list of domain names. + */ + public ListDomainsOptions nextToken(String nextToken) { + checkNotNull(nextToken, "nextToken"); + formParameters.put("NextToken", nextToken); + return this; + } + + /** + * + * @return String that tells Amazon SimpleDB where to start the next list of domain names. + */ + public String getNextToken() { + return getFirstFormOrNull("NextToken"); + } + + public static class Builder { + + /** + * @see ListDomainsOptions#nextToken + */ + public static ListDomainsOptions nextToken(String nextToken) { + ListDomainsOptions options = new ListDomainsOptions(); + return options.nextToken(nextToken); + } + + /** + * @see ListDomainsOptions#maxNumberOfDomains + */ + public static ListDomainsOptions maxNumberOfDomains(int maxNumberOfDomains) { + ListDomainsOptions options = new ListDomainsOptions(); + return options.maxNumberOfDomains(maxNumberOfDomains); + } + + } +} diff --git a/aws/core/src/main/java/org/jclouds/aws/simpledb/package-info.java b/aws/core/src/main/java/org/jclouds/aws/simpledb/package-info.java new file mode 100644 index 0000000000..12a98f4bdd --- /dev/null +++ b/aws/core/src/main/java/org/jclouds/aws/simpledb/package-info.java @@ -0,0 +1,25 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +/** + * + * @see + * @author Adrian Cole + */ +package org.jclouds.aws.simpledb; diff --git a/aws/core/src/main/java/org/jclouds/aws/simpledb/reference/SimpleDBParameters.java b/aws/core/src/main/java/org/jclouds/aws/simpledb/reference/SimpleDBParameters.java new file mode 100644 index 0000000000..afd6e8e638 --- /dev/null +++ b/aws/core/src/main/java/org/jclouds/aws/simpledb/reference/SimpleDBParameters.java @@ -0,0 +1,74 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.aws.simpledb.reference; + +/** + * Configuration properties and constants used in SimpleDB connections. + * + * @see + * @author Adrian Cole + */ +public interface SimpleDBParameters { + + /** + * The action to perform. For example: CreateDomain. + */ + public static final String ACTION = "Action"; + + /** + * The API version to use, as specified in the WSDL. For example: 2009-02-01. + */ + public static final String VERSION = "Version"; + + /** + * Your Access Key ID. For example: 0AS7253JW73RRM652K02. For more information, see Your AWS + * Identifiers in the Amazon SimpleDB Developer Guide. + */ + public static final String AWS_ACCESS_KEY_ID = "AWSAccessKeyId"; + + /** + * The date and time the request is signed, in the format YYYY-MM-DDThh:mm:ssZ, as specified in + * the ISO 8601 standard. Query requests must include either Timestamp or Expires, but not both. + * + */ + public static final String TIMESTAMP = "Timestamp"; + + /** + * The date and time at which the signature included in the request expires, in the format + * YYYY-MM-DDThh:mm:ssZ, as specified in the ISO 8601 standard. Query requests must include + * either Timestamp or Expires, but not both. + */ + public static final String EXPIRES = "Expires"; + /** + * A request signature (for information, see Request Authentication in the Amazon SimpleDB Developer + * Guide). For example: Qnpl4Qk/7tINHzfXCiT7VbBatDA=. + */ + public static final String SIGNATURE = "Signature"; + /** + *Required when you use signature version 2 with Query requests. For more information, see Query + * Request Authentication in the Amazon SimpleDB Developer Guide. + */ + public static final String SIGNATURE_METHOD = "SignatureMethod"; + /** + * For more information, see Query Request Authentication in the Amazon SimpleDB Developer Guide. + */ + public static final String SIGNATURE_VERSION = "SignatureVersion"; +} diff --git a/aws/core/src/main/java/org/jclouds/aws/simpledb/reference/package-info.java b/aws/core/src/main/java/org/jclouds/aws/simpledb/reference/package-info.java new file mode 100644 index 0000000000..e59d873f8e --- /dev/null +++ b/aws/core/src/main/java/org/jclouds/aws/simpledb/reference/package-info.java @@ -0,0 +1,24 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +/** + * This package contains properties and reference data used in SimpleDB. + * @author Adrian Cole + */ +package org.jclouds.aws.simpledb.reference; diff --git a/aws/core/src/main/java/org/jclouds/aws/simpledb/xml/ListDomainsResponseHandler.java b/aws/core/src/main/java/org/jclouds/aws/simpledb/xml/ListDomainsResponseHandler.java new file mode 100755 index 0000000000..5b4b4063f1 --- /dev/null +++ b/aws/core/src/main/java/org/jclouds/aws/simpledb/xml/ListDomainsResponseHandler.java @@ -0,0 +1,83 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.aws.simpledb.xml; + +import java.util.LinkedHashSet; +import java.util.Set; + +import org.jclouds.aws.simpledb.domain.ListDomainsResponse; +import org.jclouds.http.functions.ParseSax; + +import com.google.common.collect.Iterables; +import com.google.common.collect.Sets; + +/** + * Parses the following XML document: + *

+ * ListDomainsResponse + * + * @author Adrian Cole + * @see + */ +public class ListDomainsResponseHandler extends ParseSax.HandlerWithResult { + private StringBuilder currentText = new StringBuilder(); + + private Set domains = Sets.newLinkedHashSet(); + private String nextToken; + + @Override + public ListDomainsResponse getResult() { + return new ListDomainsResponseImpl(domains, nextToken); + } + + public static class ListDomainsResponseImpl extends LinkedHashSet implements ListDomainsResponse { + + private static final long serialVersionUID = 1L; + private final String nextToken; + + public ListDomainsResponseImpl(Iterable domains, String nextToken) { + Iterables.addAll(this, domains); + this.nextToken = nextToken; + } + + @Override + public String getNextToken() { + return nextToken; + } + + } + + public void endElement(String uri, String name, String qName) { + if (qName.equals("DomainName")) { + domains.add(currentText.toString().trim()); + } else if (qName.equals("NextToken")) { + if (!currentText.toString().equals("")) + this.nextToken = currentText.toString().trim(); + } + currentText = new StringBuilder(); + } + + public void characters(char ch[], int start, int length) { + currentText.append(ch, start, length); + } + +} diff --git a/aws/core/src/test/java/org/jclouds/aws/simpledb/SimpleDBAsyncClientTest.java b/aws/core/src/test/java/org/jclouds/aws/simpledb/SimpleDBAsyncClientTest.java new file mode 100644 index 0000000000..47e8d470b5 --- /dev/null +++ b/aws/core/src/test/java/org/jclouds/aws/simpledb/SimpleDBAsyncClientTest.java @@ -0,0 +1,126 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.aws.simpledb; + +import static org.testng.Assert.assertEquals; + +import java.io.IOException; +import java.lang.reflect.Method; +import java.util.Properties; + +import org.jclouds.aws.domain.Region; +import org.jclouds.aws.filters.FormSigner; +import org.jclouds.aws.simpledb.config.SimpleDBRestClientModule; +import org.jclouds.aws.simpledb.options.ListDomainsOptions; +import org.jclouds.aws.simpledb.xml.ListDomainsResponseHandler; +import org.jclouds.http.HttpRequest; +import org.jclouds.http.RequiresHttp; +import org.jclouds.http.functions.ParseSax; +import org.jclouds.http.functions.ReleasePayloadAndReturn; +import org.jclouds.rest.ConfiguresRestClient; +import org.jclouds.rest.RestClientTest; +import org.jclouds.rest.RestContextFactory; +import org.jclouds.rest.RestContextSpec; +import org.jclouds.rest.internal.RestAnnotationProcessor; +import org.testng.annotations.Test; + +import com.google.inject.Module; +import com.google.inject.TypeLiteral; + +/** + * Tests behavior of {@code SimpleDBAsyncClient} + * + * @author Adrian Cole + */ +@Test(groups = "unit", testName = "simpledb.SimpleDBAsyncClientTest") +public class SimpleDBAsyncClientTest extends RestClientTest { + + @RequiresHttp + @ConfiguresRestClient + private static final class TestSimpleDBRestClientModule extends SimpleDBRestClientModule { + @Override + protected void configure() { + super.configure(); + } + + } + + public void testListDomainsInRegion() throws SecurityException, NoSuchMethodException, IOException { + Method method = SimpleDBAsyncClient.class.getMethod("listDomainsInRegion", String.class, + ListDomainsOptions[].class); + HttpRequest request = processor.createRequest(method); + + assertRequestLineEquals(request, "POST https://sdb.amazonaws.com/ HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Host: sdb.amazonaws.com\n"); + assertPayloadEquals(request, "Version=2009-04-15&Action=ListDomains", "application/x-www-form-urlencoded", false); + + assertResponseParserClassEquals(method, request, ParseSax.class); + assertSaxResponseParserClassEquals(method, ListDomainsResponseHandler.class); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testCreateDomainInRegion() throws SecurityException, NoSuchMethodException, IOException { + Method method = SimpleDBAsyncClient.class.getMethod("createDomainInRegion", String.class, String.class); + HttpRequest request = processor.createRequest(method, null, "domainName"); + + assertRequestLineEquals(request, "POST https://sdb.amazonaws.com/ HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Host: sdb.amazonaws.com\n"); + assertPayloadEquals(request, "Version=2009-04-15&Action=CreateDomain&DomainName=domainName", + "application/x-www-form-urlencoded", false); + + assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testAllRegions() throws SecurityException, NoSuchMethodException, IOException { + Method method = SimpleDBAsyncClient.class.getMethod("createDomainInRegion", String.class, String.class); + for (String region : Region.ALL_SIMPLEDB) { + processor.createRequest(method, region, "domainName"); + } + } + + @Override + protected void checkFilters(HttpRequest request) { + assertEquals(request.getFilters().size(), 1); + assertEquals(request.getFilters().get(0).getClass(), FormSigner.class); + } + + @Override + protected TypeLiteral> createTypeLiteral() { + return new TypeLiteral>() { + }; + } + + @Override + protected Module createModule() { + return new TestSimpleDBRestClientModule(); + } + + @Override + public RestContextSpec createContextSpec() { + return new RestContextFactory().createContextSpec("simpledb", "identity", "credential", new Properties()); + } + +} diff --git a/aws/core/src/test/java/org/jclouds/aws/simpledb/SimpleDBClientLiveTest.java b/aws/core/src/test/java/org/jclouds/aws/simpledb/SimpleDBClientLiveTest.java new file mode 100644 index 0000000000..cfb5ae5d21 --- /dev/null +++ b/aws/core/src/test/java/org/jclouds/aws/simpledb/SimpleDBClientLiveTest.java @@ -0,0 +1,174 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.aws.simpledb; + +import static com.google.common.base.Preconditions.checkNotNull; +import static org.testng.Assert.assertNotNull; + +import java.util.Properties; +import java.util.Set; +import java.util.SortedSet; + +import org.jclouds.Constants; +import org.jclouds.aws.domain.Region; +import org.jclouds.aws.simpledb.domain.ListDomainsResponse; +import org.jclouds.logging.log4j.config.Log4JLoggingModule; +import org.jclouds.rest.RestContext; +import org.jclouds.rest.RestContextFactory; +import org.testng.annotations.AfterTest; +import org.testng.annotations.BeforeGroups; +import org.testng.annotations.Test; + +import com.google.common.collect.ImmutableSet; +import com.google.common.collect.Lists; +import com.google.common.collect.Sets; +import com.google.inject.Module; + +/** + * Tests behavior of {@code SimpleDBClient} + * + * @author Adrian Cole + */ +@Test(groups = "live", sequential = true, testName = "simpledb.SimpleDBClientLiveTest") +public class SimpleDBClientLiveTest { + + private SimpleDBClient client; + + private RestContext context; + + private Set domains = Sets.newHashSet(); + protected String provider = "simpledb"; + protected String identity; + protected String credential; + protected String endpoint; + protected String apiversion; + + protected void setupCredentials() { + identity = checkNotNull(System.getProperty("test." + provider + ".identity"), "test." + provider + ".identity"); + credential = checkNotNull(System.getProperty("test." + provider + ".credential"), "test." + provider + + ".credential"); + endpoint = System.getProperty("test." + provider + ".endpoint"); + apiversion = System.getProperty("test." + provider + ".apiversion"); + } + + protected Properties setupProperties() { + Properties overrides = new Properties(); + overrides.setProperty(Constants.PROPERTY_TRUST_ALL_CERTS, "true"); + overrides.setProperty(Constants.PROPERTY_RELAX_HOSTNAME, "true"); + overrides.setProperty(provider + ".identity", identity); + if (credential != null) + overrides.setProperty(provider + ".credential", credential); + if (endpoint != null) + overrides.setProperty(provider + ".endpoint", endpoint); + if (apiversion != null) + overrides.setProperty(provider + ".apiversion", apiversion); + return overrides; + } + + @BeforeGroups(groups = { "live" }) + public void setupClient() { + setupCredentials(); + Properties overrides = setupProperties(); + context = new RestContextFactory().createContext(provider, ImmutableSet. of(new Log4JLoggingModule()), + overrides); + this.client = context.getApi(); + } + + @Test + void testListDomainsInRegion() throws InterruptedException { + for (String region : Lists.newArrayList(null, Region.EU_WEST_1, Region.US_EAST_1, Region.US_WEST_1, + Region.AP_SOUTHEAST_1)) { + SortedSet allResults = Sets.newTreeSet(client.listDomainsInRegion(region)); + assertNotNull(allResults); + if (allResults.size() >= 1) { + String domain = allResults.last(); + assertDomainInList(region, domain); + } + } + } + + public static final String PREFIX = System.getProperty("user.name") + "-simpledb"; + + @Test + void testCreateDomain() throws InterruptedException { + String domainName = PREFIX + "1"; + + for (final String region : Lists.newArrayList(null, Region.EU_WEST_1, Region.US_EAST_1, Region.US_WEST_1, + Region.AP_SOUTHEAST_1)) { + try { + SortedSet result = Sets.newTreeSet(client.listDomainsInRegion(region)); + if (result.size() >= 1) { + client.deleteDomainInRegion(region, result.last()); + domainName += 1;// cannot recreate a domain within 60 seconds + } + } catch (Exception e) { + + } + client.createDomainInRegion(region, domainName); + + // TODO get the domain metadata and ensure the region is correct + + // if (region != null) + // assertEquals(domain.getRegion(), region); + // assertEquals(domain.getName(), domainName); + assertDomainInList(region, domainName); + domains.add(domainName); + } + } + + private void assertDomainInList(final String region, final String domain) throws InterruptedException { + assertEventually(new Runnable() { + public void run() { + ListDomainsResponse domains = client.listDomainsInRegion(region); + assert domains.contains(domain) : domain + " not in " + domains; + } + }); + } + + private static final int INCONSISTENCY_WINDOW = 10000; + + /** + * Due to eventual consistency, container commands may not return correctly immediately. Hence, + * we will try up to the inconsistency window to see if the assertion completes. + */ + protected static void assertEventually(Runnable assertion) throws InterruptedException { + long start = System.currentTimeMillis(); + AssertionError error = null; + for (int i = 0; i < 30; i++) { + try { + assertion.run(); + if (i > 0) + System.err.printf("%d attempts and %dms asserting %s%n", i + 1, System.currentTimeMillis() - start, + assertion.getClass().getSimpleName()); + return; + } catch (AssertionError e) { + error = e; + } + Thread.sleep(INCONSISTENCY_WINDOW / 30); + } + if (error != null) + throw error; + } + + @AfterTest + public void shutdown() { + context.close(); + } +} diff --git a/aws/core/src/test/java/org/jclouds/aws/simpledb/config/SimpleDBRestClientModuleTest.java b/aws/core/src/test/java/org/jclouds/aws/simpledb/config/SimpleDBRestClientModuleTest.java new file mode 100644 index 0000000000..e7ada93906 --- /dev/null +++ b/aws/core/src/test/java/org/jclouds/aws/simpledb/config/SimpleDBRestClientModuleTest.java @@ -0,0 +1,93 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.aws.simpledb.config; + +import static org.testng.Assert.assertEquals; + +import java.net.URI; +import java.util.Map; + +import org.jclouds.aws.domain.Region; +import org.jclouds.aws.handlers.AWSClientErrorRetryHandler; +import org.jclouds.aws.handlers.AWSRedirectionRetryHandler; +import org.jclouds.aws.handlers.ParseAWSErrorFromXmlContent; +import org.jclouds.http.handlers.DelegatingErrorHandler; +import org.jclouds.http.handlers.DelegatingRetryHandler; +import org.jclouds.logging.config.NullLoggingModule; +import org.jclouds.rest.RestContextFactory; +import org.jclouds.rest.BaseRestClientTest.MockModule; +import org.testng.annotations.Test; + +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.ImmutableSet; +import com.google.inject.Injector; +import com.google.inject.Key; +import com.google.inject.Module; + +/** + * @author Adrian Cole + */ +@Test(groups = "unit", testName = "simpledb.SimpleDBRestClientModuleTest") +public class SimpleDBRestClientModuleTest { + + Injector createInjector() { + return new RestContextFactory().createContextBuilder("simpledb", "uid", "key", + ImmutableSet. of(new MockModule(), new NullLoggingModule())).buildInjector(); + } + + @Test + void testServerErrorHandler() { + DelegatingErrorHandler handler = createInjector().getInstance(DelegatingErrorHandler.class); + assertEquals(handler.getServerErrorHandler().getClass(), ParseAWSErrorFromXmlContent.class); + } + + @Test + void testRegions() { + Map regionMap = createInjector().getInstance( + new Key>(org.jclouds.aws.Region.class) { + }); + assertEquals(regionMap, ImmutableMap. of(Region.US_EAST_1, URI + .create("https://sdb.amazonaws.com"), Region.US_WEST_1, URI + .create("https://sdb.us-west-1.amazonaws.com"), Region.EU_WEST_1, URI + .create("https://sdb.eu-west-1.amazonaws.com"), Region.AP_SOUTHEAST_1, URI + .create("https://sdb.ap-southeast-1.amazonaws.com"))); + } + + @Test + void testClientErrorHandler() { + DelegatingErrorHandler handler = createInjector().getInstance(DelegatingErrorHandler.class); + assertEquals(handler.getClientErrorHandler().getClass(), ParseAWSErrorFromXmlContent.class); + } + + @Test + void testClientRetryHandler() { + DelegatingRetryHandler handler = createInjector().getInstance(DelegatingRetryHandler.class); + assertEquals(handler.getClientErrorRetryHandler().getClass(), + AWSClientErrorRetryHandler.class); + } + + @Test + void testRedirectionRetryHandler() { + DelegatingRetryHandler handler = createInjector().getInstance(DelegatingRetryHandler.class); + assertEquals(handler.getRedirectionRetryHandler().getClass(), + AWSRedirectionRetryHandler.class); + } + +} diff --git a/aws/core/src/test/java/org/jclouds/aws/simpledb/options/ListDomainsOptionsTest.java b/aws/core/src/test/java/org/jclouds/aws/simpledb/options/ListDomainsOptionsTest.java new file mode 100644 index 0000000000..d929949b6e --- /dev/null +++ b/aws/core/src/test/java/org/jclouds/aws/simpledb/options/ListDomainsOptionsTest.java @@ -0,0 +1,90 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.aws.simpledb.options; + +import static org.jclouds.aws.simpledb.options.ListDomainsOptions.Builder.maxNumberOfDomains; +import static org.jclouds.aws.simpledb.options.ListDomainsOptions.Builder.nextToken; +import static org.testng.Assert.assertEquals; + +import java.util.Collections; + +import org.jclouds.http.options.HttpRequestOptions; +import org.testng.annotations.Test; + +/** + * Tests possible uses of ListDomainsOptions and ListDomainsOptions.Builder.* + * + * @author Adrian Cole + */ +public class ListDomainsOptionsTest { + + @Test + public void testAssignability() { + assert HttpRequestOptions.class.isAssignableFrom(ListDomainsOptions.class); + assert !String.class.isAssignableFrom(ListDomainsOptions.class); + } + + @Test + public void testNextToken() { + ListDomainsOptions options = new ListDomainsOptions(); + options.nextToken("test"); + assertEquals(options.buildFormParameters().get("NextToken"), Collections.singletonList("test")); + } + + @Test + public void testNullNextToken() { + ListDomainsOptions options = new ListDomainsOptions(); + assertEquals(options.buildFormParameters().get("NextToken"), Collections.EMPTY_LIST); + } + + @Test + public void testNextTokenStatic() { + ListDomainsOptions options = nextToken("test"); + assertEquals(options.buildFormParameters().get("NextToken"), Collections.singletonList("test")); + } + + public void testInvalidMaxNumberOfDomainsZero() { + maxNumberOfDomains(0); + } + + public void testInvalidMaxNumberOfDomainsOver100() { + maxNumberOfDomains(101); + } + + @Test + public void testMaxNumberOfDomains() { + ListDomainsOptions options = new ListDomainsOptions(); + options.maxNumberOfDomains(1); + assertEquals(options.buildFormParameters().get("MaxNumberOfDomains"), Collections.singletonList("1")); + } + + @Test + public void testNullMaxNumberOfDomains() { + ListDomainsOptions options = new ListDomainsOptions(); + assertEquals(options.buildFormParameters().get("MaxNumberOfDomains"), Collections.EMPTY_LIST); + } + + @Test + public void testMaxNumberOfDomainsStatic() { + ListDomainsOptions options = maxNumberOfDomains(1); + assertEquals(options.buildFormParameters().get("MaxNumberOfDomains"), Collections.singletonList("1")); + } + +} diff --git a/aws/core/src/test/java/org/jclouds/aws/simpledb/xml/ListDomainsResponseHandlerTest.java b/aws/core/src/test/java/org/jclouds/aws/simpledb/xml/ListDomainsResponseHandlerTest.java new file mode 100644 index 0000000000..2dbc2517be --- /dev/null +++ b/aws/core/src/test/java/org/jclouds/aws/simpledb/xml/ListDomainsResponseHandlerTest.java @@ -0,0 +1,51 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.aws.simpledb.xml; + +import static org.testng.Assert.assertEquals; + +import java.io.InputStream; + +import org.jclouds.aws.simpledb.domain.ListDomainsResponse; +import org.jclouds.http.functions.BaseHandlerTest; +import org.testng.annotations.Test; + +import com.google.common.collect.ImmutableSet; + +/** + * Tests behavior of {@code ListDomainsResponseHandler} + * + * @author Adrian Cole + */ +@Test(groups = "unit", sequential = true, testName = "simpledb.ListDomainsResponseHandlerTest") +public class ListDomainsResponseHandlerTest extends BaseHandlerTest { + + public void test() { + InputStream is = getClass().getResourceAsStream("/simpledb/list_domains.xml"); + + ListDomainsResponse result = factory.create(injector.getInstance(ListDomainsResponseHandler.class)).parse(is); + + assertEquals( + result, + new ListDomainsResponseHandler.ListDomainsResponseImpl(ImmutableSet.of("Domain1-200706011651", + "Domain2-200706011652"), "TWV0ZXJpbmdUZXN0RG9tYWluMS0yMDA3MDYwMTE2NTY")); + + } +} diff --git a/aws/core/src/test/resources/simpledb/list_domains.xml b/aws/core/src/test/resources/simpledb/list_domains.xml new file mode 100644 index 0000000000..bd5595c2c4 --- /dev/null +++ b/aws/core/src/test/resources/simpledb/list_domains.xml @@ -0,0 +1,11 @@ + + + Domain1-200706011651 + Domain2-200706011652 + TWV0ZXJpbmdUZXN0RG9tYWluMS0yMDA3MDYwMTE2NTY= + + + eb13162f-1b95-4511-8b12-489b86acfd28 + 0.0000219907 + + \ No newline at end of file diff --git a/aws/pom.xml b/aws/pom.xml index 2b2e620caf..4622ff396f 100644 --- a/aws/pom.xml +++ b/aws/pom.xml @@ -42,6 +42,10 @@ FIXME trmkrun-ccc,test.trmk-924 + https://sdb.amazonaws.com + 2009-04-15 + ${test.aws.identity} + ${test.aws.credential} https://s3.amazonaws.com 2006-03-01 ${test.aws.identity} @@ -187,6 +191,22 @@ jclouds.compute.blacklist.nodes ${jclouds.compute.blacklist.nodes} + + test.simpledb.endpoint + ${test.simpledb.endpoint} + + + test.simpledb.apiversion + ${test.simpledb.apiversion} + + + test.simpledb.identity + ${test.simpledb.identity} + + + test.simpledb.credential + ${test.simpledb.credential} + test.sqs.endpoint ${test.sqs.endpoint} diff --git a/core/src/main/resources/rest.properties b/core/src/main/resources/rest.properties index 65ce7ab602..465c817ad4 100644 --- a/core/src/main/resources/rest.properties +++ b/core/src/main/resources/rest.properties @@ -35,6 +35,9 @@ sdn.propertiesbuilder=org.jclouds.nirvanix.sdn.SDNPropertiesBuilder sqs.contextbuilder=org.jclouds.aws.sqs.SQSContextBuilder sqs.propertiesbuilder=org.jclouds.aws.sqs.SQSPropertiesBuilder +simpledb.contextbuilder=org.jclouds.aws.simpledb.SimpleDBContextBuilder +simpledb.propertiesbuilder=org.jclouds.aws.simpledb.SimpleDBPropertiesBuilder + elb.contextbuilder=org.jclouds.aws.elb.ELBContextBuilder elb.propertiesbuilder=org.jclouds.aws.elb.ELBPropertiesBuilder From 92a9e2f562dc492e59e0d4d6b088db9a2d21cb60 Mon Sep 17 00:00:00 2001 From: Adrian Cole Date: Sat, 4 Dec 2010 17:47:16 +0000 Subject: [PATCH 23/31] Issue 419 separated elasticstack and cloudsigma drivers --- .../org/jclouds/cloudsigma/CloudSigmaAsyncClient.java | 0 .../java/org/jclouds/cloudsigma/CloudSigmaClient.java | 0 .../org/jclouds/cloudsigma/CloudSigmaContextBuilder.java | 0 .../jclouds/cloudsigma/CloudSigmaPropertiesBuilder.java | 0 .../cloudsigma/config/CloudSigmaRestClientModule.java | 0 .../java/org/jclouds/cloudsigma/domain/DriveInfo.java | 0 .../java/org/jclouds/cloudsigma/domain/DriveType.java | 0 .../cloudsigma/functions/CreateDriveRequestToMap.java | 0 .../org/jclouds/cloudsigma/functions/DriveDataToMap.java | 0 .../KeyValuesDelimitedByBlankLinesToDriveInfo.java | 0 ...istOfKeyValuesDelimitedByBlankLinesToDriveInfoSet.java | 0 .../org/jclouds/cloudsigma/functions/MapToDriveInfo.java | 0 .../org/jclouds/cloudsigma/CloudSigmaAsyncClientTest.java | 0 .../org/jclouds/cloudsigma/CloudSigmaClientLiveTest.java | 0 .../org/jclouds/cloudsigma/ProvidersInPropertiesTest.java | 0 .../KeyValuesDelimitedByBlankLinesToDriveInfoTest.java | 4 ++-- ...fKeyValuesDelimitedByBlankLinesToDriveInfoSetTest.java | 4 ++-- .../jclouds/cloudsigma/functions/MapToDriveInfoTest.java | 4 ++-- .../src/test/resources}/drive.txt | 0 sandbox/elasticstack/pom.xml | 8 +------- 20 files changed, 7 insertions(+), 13 deletions(-) rename sandbox/{elasticstack => cloudsigma}/src/main/java/org/jclouds/cloudsigma/CloudSigmaAsyncClient.java (100%) rename sandbox/{elasticstack => cloudsigma}/src/main/java/org/jclouds/cloudsigma/CloudSigmaClient.java (100%) rename sandbox/{elasticstack => cloudsigma}/src/main/java/org/jclouds/cloudsigma/CloudSigmaContextBuilder.java (100%) rename sandbox/{elasticstack => cloudsigma}/src/main/java/org/jclouds/cloudsigma/CloudSigmaPropertiesBuilder.java (100%) rename sandbox/{elasticstack => cloudsigma}/src/main/java/org/jclouds/cloudsigma/config/CloudSigmaRestClientModule.java (100%) rename sandbox/{elasticstack => cloudsigma}/src/main/java/org/jclouds/cloudsigma/domain/DriveInfo.java (100%) rename sandbox/{elasticstack => cloudsigma}/src/main/java/org/jclouds/cloudsigma/domain/DriveType.java (100%) rename sandbox/{elasticstack => cloudsigma}/src/main/java/org/jclouds/cloudsigma/functions/CreateDriveRequestToMap.java (100%) rename sandbox/{elasticstack => cloudsigma}/src/main/java/org/jclouds/cloudsigma/functions/DriveDataToMap.java (100%) rename sandbox/{elasticstack => cloudsigma}/src/main/java/org/jclouds/cloudsigma/functions/KeyValuesDelimitedByBlankLinesToDriveInfo.java (100%) rename sandbox/{elasticstack => cloudsigma}/src/main/java/org/jclouds/cloudsigma/functions/ListOfKeyValuesDelimitedByBlankLinesToDriveInfoSet.java (100%) rename sandbox/{elasticstack => cloudsigma}/src/main/java/org/jclouds/cloudsigma/functions/MapToDriveInfo.java (100%) rename sandbox/{elasticstack => cloudsigma}/src/test/java/org/jclouds/cloudsigma/CloudSigmaAsyncClientTest.java (100%) rename sandbox/{elasticstack => cloudsigma}/src/test/java/org/jclouds/cloudsigma/CloudSigmaClientLiveTest.java (100%) rename sandbox/{elasticstack => cloudsigma}/src/test/java/org/jclouds/cloudsigma/ProvidersInPropertiesTest.java (100%) rename sandbox/{elasticstack => cloudsigma}/src/test/java/org/jclouds/cloudsigma/functions/KeyValuesDelimitedByBlankLinesToDriveInfoTest.java (95%) rename sandbox/{elasticstack => cloudsigma}/src/test/java/org/jclouds/cloudsigma/functions/ListOfKeyValuesDelimitedByBlankLinesToDriveInfoSetTest.java (94%) rename sandbox/{elasticstack => cloudsigma}/src/test/java/org/jclouds/cloudsigma/functions/MapToDriveInfoTest.java (98%) rename sandbox/{elasticstack/src/test/resources/cloudsigma => cloudsigma/src/test/resources}/drive.txt (100%) diff --git a/sandbox/elasticstack/src/main/java/org/jclouds/cloudsigma/CloudSigmaAsyncClient.java b/sandbox/cloudsigma/src/main/java/org/jclouds/cloudsigma/CloudSigmaAsyncClient.java similarity index 100% rename from sandbox/elasticstack/src/main/java/org/jclouds/cloudsigma/CloudSigmaAsyncClient.java rename to sandbox/cloudsigma/src/main/java/org/jclouds/cloudsigma/CloudSigmaAsyncClient.java diff --git a/sandbox/elasticstack/src/main/java/org/jclouds/cloudsigma/CloudSigmaClient.java b/sandbox/cloudsigma/src/main/java/org/jclouds/cloudsigma/CloudSigmaClient.java similarity index 100% rename from sandbox/elasticstack/src/main/java/org/jclouds/cloudsigma/CloudSigmaClient.java rename to sandbox/cloudsigma/src/main/java/org/jclouds/cloudsigma/CloudSigmaClient.java diff --git a/sandbox/elasticstack/src/main/java/org/jclouds/cloudsigma/CloudSigmaContextBuilder.java b/sandbox/cloudsigma/src/main/java/org/jclouds/cloudsigma/CloudSigmaContextBuilder.java similarity index 100% rename from sandbox/elasticstack/src/main/java/org/jclouds/cloudsigma/CloudSigmaContextBuilder.java rename to sandbox/cloudsigma/src/main/java/org/jclouds/cloudsigma/CloudSigmaContextBuilder.java diff --git a/sandbox/elasticstack/src/main/java/org/jclouds/cloudsigma/CloudSigmaPropertiesBuilder.java b/sandbox/cloudsigma/src/main/java/org/jclouds/cloudsigma/CloudSigmaPropertiesBuilder.java similarity index 100% rename from sandbox/elasticstack/src/main/java/org/jclouds/cloudsigma/CloudSigmaPropertiesBuilder.java rename to sandbox/cloudsigma/src/main/java/org/jclouds/cloudsigma/CloudSigmaPropertiesBuilder.java diff --git a/sandbox/elasticstack/src/main/java/org/jclouds/cloudsigma/config/CloudSigmaRestClientModule.java b/sandbox/cloudsigma/src/main/java/org/jclouds/cloudsigma/config/CloudSigmaRestClientModule.java similarity index 100% rename from sandbox/elasticstack/src/main/java/org/jclouds/cloudsigma/config/CloudSigmaRestClientModule.java rename to sandbox/cloudsigma/src/main/java/org/jclouds/cloudsigma/config/CloudSigmaRestClientModule.java diff --git a/sandbox/elasticstack/src/main/java/org/jclouds/cloudsigma/domain/DriveInfo.java b/sandbox/cloudsigma/src/main/java/org/jclouds/cloudsigma/domain/DriveInfo.java similarity index 100% rename from sandbox/elasticstack/src/main/java/org/jclouds/cloudsigma/domain/DriveInfo.java rename to sandbox/cloudsigma/src/main/java/org/jclouds/cloudsigma/domain/DriveInfo.java diff --git a/sandbox/elasticstack/src/main/java/org/jclouds/cloudsigma/domain/DriveType.java b/sandbox/cloudsigma/src/main/java/org/jclouds/cloudsigma/domain/DriveType.java similarity index 100% rename from sandbox/elasticstack/src/main/java/org/jclouds/cloudsigma/domain/DriveType.java rename to sandbox/cloudsigma/src/main/java/org/jclouds/cloudsigma/domain/DriveType.java diff --git a/sandbox/elasticstack/src/main/java/org/jclouds/cloudsigma/functions/CreateDriveRequestToMap.java b/sandbox/cloudsigma/src/main/java/org/jclouds/cloudsigma/functions/CreateDriveRequestToMap.java similarity index 100% rename from sandbox/elasticstack/src/main/java/org/jclouds/cloudsigma/functions/CreateDriveRequestToMap.java rename to sandbox/cloudsigma/src/main/java/org/jclouds/cloudsigma/functions/CreateDriveRequestToMap.java diff --git a/sandbox/elasticstack/src/main/java/org/jclouds/cloudsigma/functions/DriveDataToMap.java b/sandbox/cloudsigma/src/main/java/org/jclouds/cloudsigma/functions/DriveDataToMap.java similarity index 100% rename from sandbox/elasticstack/src/main/java/org/jclouds/cloudsigma/functions/DriveDataToMap.java rename to sandbox/cloudsigma/src/main/java/org/jclouds/cloudsigma/functions/DriveDataToMap.java diff --git a/sandbox/elasticstack/src/main/java/org/jclouds/cloudsigma/functions/KeyValuesDelimitedByBlankLinesToDriveInfo.java b/sandbox/cloudsigma/src/main/java/org/jclouds/cloudsigma/functions/KeyValuesDelimitedByBlankLinesToDriveInfo.java similarity index 100% rename from sandbox/elasticstack/src/main/java/org/jclouds/cloudsigma/functions/KeyValuesDelimitedByBlankLinesToDriveInfo.java rename to sandbox/cloudsigma/src/main/java/org/jclouds/cloudsigma/functions/KeyValuesDelimitedByBlankLinesToDriveInfo.java diff --git a/sandbox/elasticstack/src/main/java/org/jclouds/cloudsigma/functions/ListOfKeyValuesDelimitedByBlankLinesToDriveInfoSet.java b/sandbox/cloudsigma/src/main/java/org/jclouds/cloudsigma/functions/ListOfKeyValuesDelimitedByBlankLinesToDriveInfoSet.java similarity index 100% rename from sandbox/elasticstack/src/main/java/org/jclouds/cloudsigma/functions/ListOfKeyValuesDelimitedByBlankLinesToDriveInfoSet.java rename to sandbox/cloudsigma/src/main/java/org/jclouds/cloudsigma/functions/ListOfKeyValuesDelimitedByBlankLinesToDriveInfoSet.java diff --git a/sandbox/elasticstack/src/main/java/org/jclouds/cloudsigma/functions/MapToDriveInfo.java b/sandbox/cloudsigma/src/main/java/org/jclouds/cloudsigma/functions/MapToDriveInfo.java similarity index 100% rename from sandbox/elasticstack/src/main/java/org/jclouds/cloudsigma/functions/MapToDriveInfo.java rename to sandbox/cloudsigma/src/main/java/org/jclouds/cloudsigma/functions/MapToDriveInfo.java diff --git a/sandbox/elasticstack/src/test/java/org/jclouds/cloudsigma/CloudSigmaAsyncClientTest.java b/sandbox/cloudsigma/src/test/java/org/jclouds/cloudsigma/CloudSigmaAsyncClientTest.java similarity index 100% rename from sandbox/elasticstack/src/test/java/org/jclouds/cloudsigma/CloudSigmaAsyncClientTest.java rename to sandbox/cloudsigma/src/test/java/org/jclouds/cloudsigma/CloudSigmaAsyncClientTest.java diff --git a/sandbox/elasticstack/src/test/java/org/jclouds/cloudsigma/CloudSigmaClientLiveTest.java b/sandbox/cloudsigma/src/test/java/org/jclouds/cloudsigma/CloudSigmaClientLiveTest.java similarity index 100% rename from sandbox/elasticstack/src/test/java/org/jclouds/cloudsigma/CloudSigmaClientLiveTest.java rename to sandbox/cloudsigma/src/test/java/org/jclouds/cloudsigma/CloudSigmaClientLiveTest.java diff --git a/sandbox/elasticstack/src/test/java/org/jclouds/cloudsigma/ProvidersInPropertiesTest.java b/sandbox/cloudsigma/src/test/java/org/jclouds/cloudsigma/ProvidersInPropertiesTest.java similarity index 100% rename from sandbox/elasticstack/src/test/java/org/jclouds/cloudsigma/ProvidersInPropertiesTest.java rename to sandbox/cloudsigma/src/test/java/org/jclouds/cloudsigma/ProvidersInPropertiesTest.java diff --git a/sandbox/elasticstack/src/test/java/org/jclouds/cloudsigma/functions/KeyValuesDelimitedByBlankLinesToDriveInfoTest.java b/sandbox/cloudsigma/src/test/java/org/jclouds/cloudsigma/functions/KeyValuesDelimitedByBlankLinesToDriveInfoTest.java similarity index 95% rename from sandbox/elasticstack/src/test/java/org/jclouds/cloudsigma/functions/KeyValuesDelimitedByBlankLinesToDriveInfoTest.java rename to sandbox/cloudsigma/src/test/java/org/jclouds/cloudsigma/functions/KeyValuesDelimitedByBlankLinesToDriveInfoTest.java index 8af9256de7..aeff757ebf 100644 --- a/sandbox/elasticstack/src/test/java/org/jclouds/cloudsigma/functions/KeyValuesDelimitedByBlankLinesToDriveInfoTest.java +++ b/sandbox/cloudsigma/src/test/java/org/jclouds/cloudsigma/functions/KeyValuesDelimitedByBlankLinesToDriveInfoTest.java @@ -45,6 +45,6 @@ public class KeyValuesDelimitedByBlankLinesToDriveInfoTest { public void testOne() { assertEquals(FN.apply(new HttpResponse(200, "", Payloads.newInputStreamPayload(MapToDriveInfoTest.class - .getResourceAsStream("/cloudsigma/drive.txt")))), MapToDriveInfoTest.ONE); + .getResourceAsStream("/drive.txt")))), MapToDriveInfoTest.ONE); } -} \ No newline at end of file +} diff --git a/sandbox/elasticstack/src/test/java/org/jclouds/cloudsigma/functions/ListOfKeyValuesDelimitedByBlankLinesToDriveInfoSetTest.java b/sandbox/cloudsigma/src/test/java/org/jclouds/cloudsigma/functions/ListOfKeyValuesDelimitedByBlankLinesToDriveInfoSetTest.java similarity index 94% rename from sandbox/elasticstack/src/test/java/org/jclouds/cloudsigma/functions/ListOfKeyValuesDelimitedByBlankLinesToDriveInfoSetTest.java rename to sandbox/cloudsigma/src/test/java/org/jclouds/cloudsigma/functions/ListOfKeyValuesDelimitedByBlankLinesToDriveInfoSetTest.java index 82b5631e98..28e6f2ab3a 100644 --- a/sandbox/elasticstack/src/test/java/org/jclouds/cloudsigma/functions/ListOfKeyValuesDelimitedByBlankLinesToDriveInfoSetTest.java +++ b/sandbox/cloudsigma/src/test/java/org/jclouds/cloudsigma/functions/ListOfKeyValuesDelimitedByBlankLinesToDriveInfoSetTest.java @@ -47,6 +47,6 @@ public class ListOfKeyValuesDelimitedByBlankLinesToDriveInfoSetTest { public void testOne() { assertEquals(FN.apply(new HttpResponse(200, "", Payloads.newInputStreamPayload(MapToDriveInfoTest.class - .getResourceAsStream("/cloudsigma/drive.txt")))), ImmutableSet. of(MapToDriveInfoTest.ONE)); + .getResourceAsStream("/drive.txt")))), ImmutableSet. of(MapToDriveInfoTest.ONE)); } -} \ No newline at end of file +} diff --git a/sandbox/elasticstack/src/test/java/org/jclouds/cloudsigma/functions/MapToDriveInfoTest.java b/sandbox/cloudsigma/src/test/java/org/jclouds/cloudsigma/functions/MapToDriveInfoTest.java similarity index 98% rename from sandbox/elasticstack/src/test/java/org/jclouds/cloudsigma/functions/MapToDriveInfoTest.java rename to sandbox/cloudsigma/src/test/java/org/jclouds/cloudsigma/functions/MapToDriveInfoTest.java index bcb2419a6c..14327bd7d4 100644 --- a/sandbox/elasticstack/src/test/java/org/jclouds/cloudsigma/functions/MapToDriveInfoTest.java +++ b/sandbox/cloudsigma/src/test/java/org/jclouds/cloudsigma/functions/MapToDriveInfoTest.java @@ -89,9 +89,9 @@ public class MapToDriveInfoTest { public void testComplete() throws IOException { Map input = new ListOfKeyValuesDelimitedByBlankLinesToListOfMaps().apply( - Utils.toStringAndClose(MapToDriveInfoTest.class.getResourceAsStream("/cloudsigma/drive.txt"))).get(0); + Utils.toStringAndClose(MapToDriveInfoTest.class.getResourceAsStream("/drive.txt"))).get(0); assertEquals(MAP_TO_DRIVE.apply(input), ONE); } -} \ No newline at end of file +} diff --git a/sandbox/elasticstack/src/test/resources/cloudsigma/drive.txt b/sandbox/cloudsigma/src/test/resources/drive.txt similarity index 100% rename from sandbox/elasticstack/src/test/resources/cloudsigma/drive.txt rename to sandbox/cloudsigma/src/test/resources/drive.txt diff --git a/sandbox/elasticstack/pom.xml b/sandbox/elasticstack/pom.xml index 9e3d3d15dd..d56c26367f 100644 --- a/sandbox/elasticstack/pom.xml +++ b/sandbox/elasticstack/pom.xml @@ -34,12 +34,6 @@ jclouds-elasticstack jclouds elasticstack core jclouds components to access elasticstack - - - scm:svn:http://jclouds.googlecode.com/svn/trunk/elasticstack - scm:svn:https://jclouds.googlecode.com/svn/trunk/elasticstack - http://jclouds.googlecode.com/svn/trunk/elasticstack - @@ -59,7 +53,7 @@ trmkrun-ccc,test.trmk-924 - https://api.cloudsigma.com + https://api.lon-p.elastichosts.com 1.0 FIXME FIXME From 6e975662c1a841135274075f8c52bde34b647e7e Mon Sep 17 00:00:00 2001 From: Adrian Cole Date: Sat, 4 Dec 2010 23:26:16 +0000 Subject: [PATCH 24/31] Issue 412: added elasticstack read-only commands for servers --- sandbox/cloudsigma/pom.xml | 140 +++++++++++++++++ .../config/CloudSigmaRestClientModule.java | 10 ++ .../CommonElasticStackAsyncClient.java | 28 ++++ .../CommonElasticStackClient.java | 23 ++- .../config/ElasticStackRestClientModule.java | 10 ++ .../elasticstack/domain/BlockDevice.java | 22 ++- .../jclouds/elasticstack/domain/Device.java | 99 +++++++++++- .../elasticstack/domain/IDEDevice.java | 28 +++- .../org/jclouds/elasticstack/domain/NIC.java | 58 ++++++- .../elasticstack/domain/SCSIDevice.java | 26 ++- .../domain/{Server.java => ServerInfo.java} | 148 ++++++++++++++---- .../elasticstack/domain/ServerStatus.java | 47 ++++++ ...luesDelimitedByBlankLinesToServerInfo.java | 53 +++++++ ...sDelimitedByBlankLinesToServerInfoSet.java | 60 +++++++ .../elasticstack/functions/MapToDevices.java | 95 +++++++++++ .../elasticstack/functions/MapToNICs.java | 59 +++++++ .../functions/MapToServerInfo.java | 101 ++++++++++++ .../CommonElasticStackClientLiveTest.java | 21 +++ .../ElasticStackAsyncClientTest.java | 62 +++++++- ...DelimitedByBlankLinesToServerInfoTest.java | 68 ++++++++ ...imitedByBlankLinesToServerInfoSetTest.java | 73 +++++++++ .../functions/MapToServerInfoTest.java | 110 +++++++++++++ .../src/test/resources/servers.txt | 40 +++++ 23 files changed, 1328 insertions(+), 53 deletions(-) create mode 100644 sandbox/cloudsigma/pom.xml rename sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/domain/{Server.java => ServerInfo.java} (68%) create mode 100644 sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/domain/ServerStatus.java create mode 100644 sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/functions/KeyValuesDelimitedByBlankLinesToServerInfo.java create mode 100644 sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/functions/ListOfKeyValuesDelimitedByBlankLinesToServerInfoSet.java create mode 100644 sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/functions/MapToDevices.java create mode 100644 sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/functions/MapToNICs.java create mode 100644 sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/functions/MapToServerInfo.java create mode 100644 sandbox/elasticstack/src/test/java/org/jclouds/elasticstack/functions/KeyValuesDelimitedByBlankLinesToServerInfoTest.java create mode 100644 sandbox/elasticstack/src/test/java/org/jclouds/elasticstack/functions/ListOfKeyValuesDelimitedByBlankLinesToServerInfoSetTest.java create mode 100644 sandbox/elasticstack/src/test/java/org/jclouds/elasticstack/functions/MapToServerInfoTest.java create mode 100644 sandbox/elasticstack/src/test/resources/servers.txt diff --git a/sandbox/cloudsigma/pom.xml b/sandbox/cloudsigma/pom.xml new file mode 100644 index 0000000000..0b6be3bd0d --- /dev/null +++ b/sandbox/cloudsigma/pom.xml @@ -0,0 +1,140 @@ + + + + 4.0.0 + + org.jclouds + jclouds-project + 1.0-SNAPSHOT + ../../project/pom.xml + + org.jclouds + jclouds-cloudsigma + jclouds cloudsigma core + jclouds components to access cloudsigma + + + + + jclouds-googlecode-deploy + http://jclouds.googlecode.com/svn/repo + + + jclouds-rimu-snapshots-nexus + https://oss.sonatype.org/content/repositories/snapshots + + true + + + + + + + trmkrun-ccc,test.trmk-924 + https://api.cloudsigma.com + 1.0 + FIXME + FIXME + + + + ${project.groupId} + jclouds-elasticstack + ${project.version} + + + ${project.groupId} + jclouds-core + ${project.version} + test-jar + test + + + ${project.groupId} + jclouds-elasticstack + ${project.version} + test-jar + test + + + log4j + log4j + 1.2.14 + test + + + ${project.groupId} + jclouds-log4j + ${project.version} + test + + + + + live + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration + integration-test + + test + + + + + test.cloudsigma.endpoint + ${test.cloudsigma.endpoint} + + + test.cloudsigma.apiversion + ${test.cloudsigma.apiversion} + + + test.cloudsigma.identity + ${test.cloudsigma.identity} + + + test.cloudsigma.credential + ${test.cloudsigma.credential} + + + jclouds.compute.blacklist-nodes + ${jclouds.compute.blacklist-nodes} + + + + + + + + + + + diff --git a/sandbox/cloudsigma/src/main/java/org/jclouds/cloudsigma/config/CloudSigmaRestClientModule.java b/sandbox/cloudsigma/src/main/java/org/jclouds/cloudsigma/config/CloudSigmaRestClientModule.java index 453362e8ae..0a0d4509d8 100644 --- a/sandbox/cloudsigma/src/main/java/org/jclouds/cloudsigma/config/CloudSigmaRestClientModule.java +++ b/sandbox/cloudsigma/src/main/java/org/jclouds/cloudsigma/config/CloudSigmaRestClientModule.java @@ -19,14 +19,20 @@ package org.jclouds.cloudsigma.config; +import java.util.List; import java.util.Map; +import java.util.Set; import org.jclouds.cloudsigma.CloudSigmaAsyncClient; import org.jclouds.cloudsigma.CloudSigmaClient; import org.jclouds.cloudsigma.functions.CreateDriveRequestToMap; import org.jclouds.cloudsigma.functions.DriveDataToMap; import org.jclouds.elasticstack.domain.CreateDriveRequest; +import org.jclouds.elasticstack.domain.Device; import org.jclouds.elasticstack.domain.DriveData; +import org.jclouds.elasticstack.domain.NIC; +import org.jclouds.elasticstack.functions.MapToDevices; +import org.jclouds.elasticstack.functions.MapToNICs; import org.jclouds.elasticstack.handlers.ElasticStackErrorHandler; import org.jclouds.http.HttpErrorHandler; import org.jclouds.http.RequiresHttp; @@ -66,6 +72,10 @@ public class CloudSigmaRestClientModule extends RestClientModule>>() { }).to(DriveDataToMap.class); + bind(new TypeLiteral, List>>() { + }).to(MapToNICs.class); + bind(new TypeLiteral, Set>>() { + }).to(MapToDevices.class); } @Override diff --git a/sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/CommonElasticStackAsyncClient.java b/sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/CommonElasticStackAsyncClient.java index 193b155b72..e5f72ec460 100644 --- a/sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/CommonElasticStackAsyncClient.java +++ b/sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/CommonElasticStackAsyncClient.java @@ -33,8 +33,11 @@ import org.jclouds.elasticstack.binders.BindDriveDataToPlainTextString; import org.jclouds.elasticstack.domain.CreateDriveRequest; import org.jclouds.elasticstack.domain.DriveData; import org.jclouds.elasticstack.domain.DriveInfo; +import org.jclouds.elasticstack.domain.ServerInfo; import org.jclouds.elasticstack.functions.KeyValuesDelimitedByBlankLinesToDriveInfo; +import org.jclouds.elasticstack.functions.KeyValuesDelimitedByBlankLinesToServerInfo; import org.jclouds.elasticstack.functions.ListOfKeyValuesDelimitedByBlankLinesToDriveInfoSet; +import org.jclouds.elasticstack.functions.ListOfKeyValuesDelimitedByBlankLinesToServerInfoSet; import org.jclouds.elasticstack.functions.SplitNewlines; import org.jclouds.http.filters.BasicAuthentication; import org.jclouds.rest.annotations.BinderParam; @@ -58,6 +61,31 @@ import com.google.common.util.concurrent.ListenableFuture; @Consumes(MediaType.TEXT_PLAIN) public interface CommonElasticStackAsyncClient { + /** + * @see ElasticStackClient#listServers() + */ + @GET + @Path("/servers/list") + @ResponseParser(SplitNewlines.class) + ListenableFuture> listServers(); + + /** + * @see ElasticStackClient#listServerInfo() + */ + @GET + @Path("/servers/info") + @ResponseParser(ListOfKeyValuesDelimitedByBlankLinesToServerInfoSet.class) + ListenableFuture> listServerInfo(); + + /** + * @see ElasticStackClient#getServerInfo + */ + @GET + @ExceptionParser(ReturnNullOnNotFoundOr404.class) + @ResponseParser(KeyValuesDelimitedByBlankLinesToServerInfo.class) + @Path("/servers/{uuid}/info") + ListenableFuture getServerInfo(@PathParam("uuid") String uuid); + /** * @see ElasticStackClient#listDrives() */ diff --git a/sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/CommonElasticStackClient.java b/sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/CommonElasticStackClient.java index 0f0acad24f..081c9979d0 100644 --- a/sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/CommonElasticStackClient.java +++ b/sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/CommonElasticStackClient.java @@ -26,6 +26,7 @@ import org.jclouds.concurrent.Timeout; import org.jclouds.elasticstack.domain.CreateDriveRequest; import org.jclouds.elasticstack.domain.DriveData; import org.jclouds.elasticstack.domain.DriveInfo; +import org.jclouds.elasticstack.domain.ServerInfo; /** * Provides synchronous access to elasticstack. @@ -37,6 +38,27 @@ import org.jclouds.elasticstack.domain.DriveInfo; */ @Timeout(duration = 60, timeUnit = TimeUnit.SECONDS) public interface CommonElasticStackClient { + /** + * list of server uuids in your account + * + * @return or empty set if no servers are found + */ + Set listServers(); + + /** + * Get all servers info + * + * @return or empty set if no servers are found + */ + Set listServerInfo(); + + /** + * @param uuid + * what to get + * @return null, if not found + */ + ServerInfo getServerInfo(String uuid); + /** * list of drive uuids in your account * @@ -86,5 +108,4 @@ public interface CommonElasticStackClient { */ void destroyDrive(String uuid); - } diff --git a/sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/config/ElasticStackRestClientModule.java b/sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/config/ElasticStackRestClientModule.java index d8def53140..92e778fa46 100644 --- a/sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/config/ElasticStackRestClientModule.java +++ b/sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/config/ElasticStackRestClientModule.java @@ -19,14 +19,20 @@ package org.jclouds.elasticstack.config; +import java.util.List; import java.util.Map; +import java.util.Set; import org.jclouds.elasticstack.ElasticStackAsyncClient; import org.jclouds.elasticstack.ElasticStackClient; import org.jclouds.elasticstack.domain.CreateDriveRequest; +import org.jclouds.elasticstack.domain.Device; import org.jclouds.elasticstack.domain.DriveData; +import org.jclouds.elasticstack.domain.NIC; import org.jclouds.elasticstack.functions.CreateDriveRequestToMap; import org.jclouds.elasticstack.functions.DriveDataToMap; +import org.jclouds.elasticstack.functions.MapToDevices; +import org.jclouds.elasticstack.functions.MapToNICs; import org.jclouds.elasticstack.handlers.ElasticStackErrorHandler; import org.jclouds.http.HttpErrorHandler; import org.jclouds.http.RequiresHttp; @@ -59,6 +65,10 @@ public class ElasticStackRestClientModule extends RestClientModule>>() { }).to(DriveDataToMap.class); + bind(new TypeLiteral, List>>() { + }).to(MapToNICs.class); + bind(new TypeLiteral, Set>>() { + }).to(MapToDevices.class); } @Override diff --git a/sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/domain/BlockDevice.java b/sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/domain/BlockDevice.java index 757732c2f3..661377fe6a 100644 --- a/sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/domain/BlockDevice.java +++ b/sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/domain/BlockDevice.java @@ -26,11 +26,25 @@ import static com.google.common.base.Preconditions.checkArgument; * @author Adrian Cole */ public class BlockDevice extends Device { + public static class Builder extends Device.Builder { + private final int index; - private final char index; + public Builder(int index) { + this.index = index; + } - public BlockDevice(String driveUuid, MediaType mediaType, char index) { - super(driveUuid, mediaType); + @Override + public Device build() { + return new BlockDevice(uuid, mediaType, index, readBytes, readRequests, writeBytes, writeRequests); + } + + } + + private final int index; + + public BlockDevice(String driveUuid, MediaType mediaType, int index, long readBytes, long readRequests, + long writeBytes, long writeRequests) { + super(driveUuid, mediaType, readBytes, readRequests, writeBytes, writeRequests); checkArgument(index >= 0 && index < 8, "index must be between 0 and 7"); this.index = index; } @@ -62,7 +76,7 @@ public class BlockDevice extends Device { return String.format("block:%d", index); } - public char getIndex() { + public int getIndex() { return index; } diff --git a/sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/domain/Device.java b/sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/domain/Device.java index 3085647581..8216e00db0 100644 --- a/sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/domain/Device.java +++ b/sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/domain/Device.java @@ -26,12 +26,62 @@ import static com.google.common.base.Preconditions.checkNotNull; * @author Adrian Cole */ public abstract class Device { + public static abstract class Builder { + protected String uuid; + protected MediaType mediaType = MediaType.DISK; + protected long readBytes; + protected long readRequests; + protected long writeBytes; + protected long writeRequests; + + public Builder mediaType(MediaType mediaType) { + this.mediaType = mediaType; + return this; + } + + public Builder readBytes(long readBytes) { + this.readBytes = readBytes; + return this; + } + + public Builder readRequests(long readRequests) { + this.readRequests = readRequests; + return this; + } + + public Builder writeBytes(long writeBytes) { + this.writeBytes = writeBytes; + return this; + } + + public Builder writeRequests(long writeRequests) { + this.writeRequests = writeRequests; + return this; + } + + public Builder uuid(String uuid) { + this.uuid = uuid; + return this; + } + + public abstract Device build(); + } + protected final String driveUuid; protected final MediaType mediaType; + protected final long readBytes; + protected final long readRequests; + protected final long writeBytes; + protected final long writeRequests; - public Device(String driveUuid, MediaType mediaType) { + public Device(String driveUuid, MediaType mediaType, long readBytes, long readRequests, long writeBytes, + long writeRequests) { this.driveUuid = checkNotNull(driveUuid, "driveUuid"); this.mediaType = checkNotNull(mediaType, "mediaType"); + this.readBytes = readBytes; + this.readRequests = readRequests; + this.writeBytes = writeBytes; + this.writeRequests = writeRequests; } /** @@ -56,12 +106,48 @@ public abstract class Device { return mediaType; } + /** + * + * @return Cumulative i/o byte/request count for each drive + */ + public long getReadBytes() { + return readBytes; + } + + /** + * + * @return Cumulative i/o byte/request count for each drive + */ + public long getReadRequests() { + return readRequests; + } + + /** + * + * @return Cumulative i/o byte/request count for each drive + */ + public long getWriteBytes() { + return writeBytes; + } + + /** + * + * @return Cumulative i/o byte/request count for each drive + */ + public long getWriteRequests() { + return writeRequests; + } + @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((driveUuid == null) ? 0 : driveUuid.hashCode()); result = prime * result + ((mediaType == null) ? 0 : mediaType.hashCode()); + result = prime * result + (int) (readBytes ^ (readBytes >>> 32)); + result = prime * result + (int) (readRequests ^ (readRequests >>> 32)); + result = prime * result + (int) (writeBytes ^ (writeBytes >>> 32)); + result = prime * result + (int) (writeRequests ^ (writeRequests >>> 32)); return result; } @@ -81,11 +167,20 @@ public abstract class Device { return false; if (mediaType != other.mediaType) return false; + if (readBytes != other.readBytes) + return false; + if (readRequests != other.readRequests) + return false; + if (writeBytes != other.writeBytes) + return false; + if (writeRequests != other.writeRequests) + return false; return true; } @Override public String toString() { - return "[driveUuid=" + driveUuid + ", mediaType=" + mediaType + "]"; + return "[driveUuid=" + driveUuid + ", mediaType=" + mediaType + ", readBytes=" + readBytes + ", readRequests=" + + readRequests + ", writeBytes=" + writeBytes + ", writeRequests=" + writeRequests + "]"; } } \ No newline at end of file diff --git a/sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/domain/IDEDevice.java b/sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/domain/IDEDevice.java index dda18b9f8b..651c467a2d 100644 --- a/sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/domain/IDEDevice.java +++ b/sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/domain/IDEDevice.java @@ -26,12 +26,28 @@ import static com.google.common.base.Preconditions.checkArgument; * @author Adrian Cole */ public class IDEDevice extends Device { + public static class Builder extends Device.Builder { + private final int bus; + private final int unit; - private final char bus; - private final char unit; + public Builder(int bus, int unit) { + this.bus = bus; + this.unit = unit; + } - public IDEDevice(String driveUuid, MediaType mediaType, char bus, char unit) { - super(driveUuid, mediaType); + @Override + public Device build() { + return new IDEDevice(uuid, mediaType, bus, unit, readBytes, readRequests, writeBytes, writeRequests); + } + + } + + private final int bus; + private final int unit; + + public IDEDevice(String driveUuid, MediaType mediaType, int bus, int unit, long readBytes, long readRequests, + long writeBytes, long writeRequests) { + super(driveUuid, mediaType, readBytes, readRequests, writeBytes, writeRequests); checkArgument(bus == 0 || bus == 1, "bus must be 0 or 1"); checkArgument(unit == 0 || unit == 1, "unit must be 0 or 1"); this.bus = bus; @@ -68,11 +84,11 @@ public class IDEDevice extends Device { return String.format("ide:%d:%d", bus, unit); } - public char getBus() { + public int getBus() { return bus; } - public char getUnit() { + public int getUnit() { return unit; } diff --git a/sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/domain/NIC.java b/sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/domain/NIC.java index b08625786c..c553edd6de 100644 --- a/sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/domain/NIC.java +++ b/sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/domain/NIC.java @@ -21,23 +21,66 @@ package org.jclouds.elasticstack.domain; import static com.google.common.base.Preconditions.checkNotNull; +import java.util.Set; + import javax.annotation.Nullable; +import com.google.common.collect.ImmutableSet; + /** * * @author Adrian Cole */ public class NIC { + public static class Builder { + private String dhcp; + private Model model; + private String vlan; + private String mac; + private Set block = ImmutableSet.of(); + + public Builder dhcp(String dhcp) { + this.dhcp = dhcp; + return this; + } + + public Builder model(Model model) { + this.model = model; + return this; + } + + public Builder vlan(String vlan) { + this.vlan = vlan; + return this; + } + + public Builder mac(String mac) { + this.mac = mac; + return this; + } + + public Builder block(Iterable block) { + this.block = ImmutableSet.copyOf(checkNotNull(block, "block")); + return this; + } + + public NIC build() { + return new NIC(dhcp, model, vlan, mac, block); + } + } + private final String dhcp; private final Model model; private final String vlan; private final String mac; + private final Set block; - public NIC(@Nullable String dhcp, Model model, @Nullable String vlan, @Nullable String mac) { + public NIC(@Nullable String dhcp, Model model, @Nullable String vlan, @Nullable String mac, Iterable block) { this.dhcp = dhcp; this.model = checkNotNull(model, "model"); this.vlan = vlan; this.mac = mac; + this.block = ImmutableSet.copyOf(checkNotNull(block, "block")); } /** @@ -75,10 +118,16 @@ public class NIC { return mac; } + // TODO undocumented + public Set getBlock() { + return block; + } + @Override public int hashCode() { final int prime = 31; int result = 1; + result = prime * result + ((block == null) ? 0 : block.hashCode()); result = prime * result + ((dhcp == null) ? 0 : dhcp.hashCode()); result = prime * result + ((mac == null) ? 0 : mac.hashCode()); result = prime * result + ((model == null) ? 0 : model.hashCode()); @@ -95,6 +144,11 @@ public class NIC { if (getClass() != obj.getClass()) return false; NIC other = (NIC) obj; + if (block == null) { + if (other.block != null) + return false; + } else if (!block.equals(other.block)) + return false; if (dhcp == null) { if (other.dhcp != null) return false; @@ -117,6 +171,6 @@ public class NIC { @Override public String toString() { - return "[dhcp=" + dhcp + ", model=" + model + ", vlan=" + vlan + ", mac=" + mac + "]"; + return "[dhcp=" + dhcp + ", model=" + model + ", vlan=" + vlan + ", mac=" + mac + ", block=" + block + "]"; } } \ No newline at end of file diff --git a/sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/domain/SCSIDevice.java b/sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/domain/SCSIDevice.java index 56bd535294..665b7cdeb2 100644 --- a/sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/domain/SCSIDevice.java +++ b/sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/domain/SCSIDevice.java @@ -26,12 +26,26 @@ import static com.google.common.base.Preconditions.checkArgument; * @author Adrian Cole */ public class SCSIDevice extends Device { + public static class Builder extends Device.Builder { + private final int unit; - private final char bus = 0; - private final char unit; + public Builder(int unit) { + this.unit = unit; + } - public SCSIDevice(String driveUuid, MediaType mediaType, char unit) { - super(driveUuid, mediaType); + @Override + public Device build() { + return new SCSIDevice(uuid, mediaType, unit, readBytes, readRequests, writeBytes, writeRequests); + } + + } + + private final int bus = 0; + private final int unit; + + public SCSIDevice(String driveUuid, MediaType mediaType, int unit, long readBytes, long readRequests, + long writeBytes, long writeRequests) { + super(driveUuid, mediaType, readBytes, readRequests, writeBytes, writeRequests); checkArgument(unit >= 0 && unit < 8, "unit must be between 0 and 7"); this.unit = unit; } @@ -61,11 +75,11 @@ public class SCSIDevice extends Device { return true; } - public char getBus() { + public int getBus() { return bus; } - public char getUnit() { + public int getUnit() { return unit; } diff --git a/sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/domain/Server.java b/sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/domain/ServerInfo.java similarity index 68% rename from sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/domain/Server.java rename to sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/domain/ServerInfo.java index ad85f45e84..9f0ecf2d64 100644 --- a/sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/domain/Server.java +++ b/sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/domain/ServerInfo.java @@ -21,6 +21,7 @@ package org.jclouds.elasticstack.domain; import static com.google.common.base.Preconditions.checkNotNull; +import java.util.Date; import java.util.List; import java.util.Map; import java.util.Set; @@ -34,31 +35,15 @@ import com.google.common.collect.ImmutableSet; * * @author Adrian Cole */ -public class Server extends Item { - // - // user UUID - // status active|stopped - // cpu CPU - // smp SMP - // mem MEM - // bootDeviceIds UUID - // description DESCRIPTION - // ide:0:0 UUID - // ide:0:1 UUID - // ide:1:0 UUID - // ide:1:1 UUID - // nic:0:model NIC_0_MODEL - // nic:0:dhcp NIC_0_DHCP - // nic:1:model NIC_1_MODEL - // nic:1:vlan NIC_1_VLAN - // vnc:ip VNC_IP - // vnc:password VNC_PASS +public class ServerInfo extends Item { public static class Builder extends Item.Builder { protected int cpu; protected Integer smp; + protected ServerStatus status; protected int mem; protected boolean persistent; + protected Date started; protected Set devices = ImmutableSet.of(); protected Set bootDeviceIds = ImmutableSet.of(); protected List nics = ImmutableList.of(); @@ -66,6 +51,15 @@ public class Server extends Item { protected VNC vnc; // TODO undocumented protected String description; + protected long txPackets; + protected long tx; + protected long rxPackets; + protected long rx; + + public Builder status(ServerStatus status) { + this.status = status; + return this; + } public Builder cpu(int cpu) { this.cpu = cpu; @@ -87,6 +81,11 @@ public class Server extends Item { return this; } + public Builder started(Date started) { + this.started = started; + return this; + } + public Builder devices(Iterable devices) { this.devices = ImmutableSet.copyOf(checkNotNull(devices, "devices")); return this; @@ -117,6 +116,26 @@ public class Server extends Item { return this; } + public Builder txPackets(long txPackets) { + this.txPackets = txPackets; + return this; + } + + public Builder tx(long tx) { + this.tx = tx; + return this; + } + + public Builder rxPackets(long rxPackets) { + this.rxPackets = rxPackets; + return this; + } + + public Builder rx(long rx) { + this.rx = rx; + return this; + } + /** * {@inheritDoc} */ @@ -149,16 +168,19 @@ public class Server extends Item { return Builder.class.cast(super.userMetadata(userMetadata)); } - public Server build() { - return new Server(uuid, name, cpu, smp, mem, persistent, devices, tags, bootDeviceIds, userMetadata, nics, - user, vnc, description); + public ServerInfo build() { + return new ServerInfo(uuid, name, cpu, smp, mem, status, persistent, started, devices, tags, bootDeviceIds, + userMetadata, nics, user, vnc, description, tx, txPackets, rx, rxPackets); } } protected final int cpu; protected final Integer smp; protected final int mem; + protected final ServerStatus status; protected final boolean persistent; + @Nullable + protected final Date started; protected final Set devices; protected final Set bootDeviceIds; @Nullable @@ -167,21 +189,32 @@ public class Server extends Item { protected final VNC vnc; @Nullable private final String description; + protected final long txPackets; + protected final long tx; + protected final long rxPackets; + protected final long rx; - public Server(@Nullable String uuid, String name, int cpu, @Nullable Integer smp, int mem, boolean persistent, - Iterable devices, Iterable bootDeviceIds, Iterable tags, - Map userMetadata, Iterable nics, @Nullable String user, VNC vnc, String description) { + public ServerInfo(@Nullable String uuid, String name, int cpu, @Nullable Integer smp, int mem, ServerStatus status, + boolean persistent, @Nullable Date started, Iterable devices, + Iterable bootDeviceIds, Iterable tags, Map userMetadata, Iterable nics, + @Nullable String user, VNC vnc, String description, long tx, long txPackets, long rx, long rxPackets) { super(uuid, name, tags, userMetadata); this.cpu = cpu; this.smp = smp; this.mem = mem; + this.status = status; this.persistent = persistent; + this.started = started; this.devices = ImmutableSet.copyOf(checkNotNull(devices, "devices")); this.bootDeviceIds = ImmutableSet.copyOf(checkNotNull(bootDeviceIds, "bootDeviceIds")); this.nics = ImmutableList.copyOf(checkNotNull(nics, "nics")); this.user = user; this.vnc = checkNotNull(vnc, "vnc"); this.description = description; + this.txPackets = txPackets; + this.tx = tx; + this.rxPackets = rxPackets; + this.rx = rx; } /** @@ -208,6 +241,14 @@ public class Server extends Item { return mem; } + /** + * + * @return active | stopped | paused | dumped | dead + */ + public ServerStatus getStatus() { + return status; + } + /** * * @return 'true' means that server will revert to a 'stopped' status on server stop or shutdown, @@ -238,6 +279,31 @@ public class Server extends Item { return nics; } + // TODO undocumented + public Date getStarted() { + return started; + } + + // TODO undocumented + public long getTxPackets() { + return txPackets; + } + + // TODO undocumented + public long getTx() { + return tx; + } + + // TODO undocumented + public long getRxPackets() { + return rxPackets; + } + + // TODO undocumented + public long getRx() { + return rx; + } + // TODO undocumented /** * @@ -267,7 +333,13 @@ public class Server extends Item { result = prime * result + mem; result = prime * result + ((nics == null) ? 0 : nics.hashCode()); result = prime * result + (persistent ? 1231 : 1237); + result = prime * result + (int) (rx ^ (rx >>> 32)); + result = prime * result + (int) (rxPackets ^ (rxPackets >>> 32)); result = prime * result + ((smp == null) ? 0 : smp.hashCode()); + result = prime * result + ((started == null) ? 0 : started.hashCode()); + result = prime * result + ((status == null) ? 0 : status.hashCode()); + result = prime * result + (int) (tx ^ (tx >>> 32)); + result = prime * result + (int) (txPackets ^ (txPackets >>> 32)); result = prime * result + ((user == null) ? 0 : user.hashCode()); result = prime * result + ((vnc == null) ? 0 : vnc.hashCode()); return result; @@ -281,7 +353,7 @@ public class Server extends Item { return false; if (getClass() != obj.getClass()) return false; - Server other = (Server) obj; + ServerInfo other = (ServerInfo) obj; if (bootDeviceIds == null) { if (other.bootDeviceIds != null) return false; @@ -308,11 +380,26 @@ public class Server extends Item { return false; if (persistent != other.persistent) return false; + if (rx != other.rx) + return false; + if (rxPackets != other.rxPackets) + return false; if (smp == null) { if (other.smp != null) return false; } else if (!smp.equals(other.smp)) return false; + if (started == null) { + if (other.started != null) + return false; + } else if (!started.equals(other.started)) + return false; + if (status != other.status) + return false; + if (tx != other.tx) + return false; + if (txPackets != other.txPackets) + return false; if (user == null) { if (other.user != null) return false; @@ -328,10 +415,11 @@ public class Server extends Item { @Override public String toString() { - return "[uuid=" + uuid + ", name=" + name + ", tags=" + tags + ", userMetadata=" + userMetadata + ", cpu=" + cpu - + ", smp=" + smp + ", mem=" + mem + ", persistent=" + persistent + ", devices=" + devices - + ", bootDeviceIds=" + bootDeviceIds + ", user=" + user + ", nics=" + nics + ", vnc=" + vnc - + ", description=" + description + "]"; + return "[uuid=" + uuid + ", name=" + name + ", tags=" + tags + ", userMetadata=" + userMetadata + + ", cpu=" + cpu + ", smp=" + smp + ", mem=" + mem + ", status=" + status + ", persistent=" + persistent + + ", started=" + started + ", devices=" + devices + ", bootDeviceIds=" + bootDeviceIds + ", user=" + user + + ", nics=" + nics + ", vnc=" + vnc + ", description=" + description + ", txPackets=" + txPackets + ", tx=" + + tx + ", rxPackets=" + rxPackets + ", rx=" + rx + "]"; } } \ No newline at end of file diff --git a/sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/domain/ServerStatus.java b/sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/domain/ServerStatus.java new file mode 100644 index 0000000000..2a53c67fd4 --- /dev/null +++ b/sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/domain/ServerStatus.java @@ -0,0 +1,47 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.elasticstack.domain; + +import static com.google.common.base.Preconditions.checkNotNull; + +/** + * + * @author Adrian Cole + */ +public enum ServerStatus { + ACTIVE, STOPPED, PAUSED, DUMPED, DEAD, UNRECOGNIZED; + public String value() { + return name().toLowerCase(); + } + + @Override + public String toString() { + return value(); + } + + public static ServerStatus fromValue(String status) { + try { + return valueOf(checkNotNull(status, "status").toUpperCase()); + } catch (IllegalArgumentException e) { + return UNRECOGNIZED; + } + } + +} \ No newline at end of file diff --git a/sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/functions/KeyValuesDelimitedByBlankLinesToServerInfo.java b/sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/functions/KeyValuesDelimitedByBlankLinesToServerInfo.java new file mode 100644 index 0000000000..027f79ff2b --- /dev/null +++ b/sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/functions/KeyValuesDelimitedByBlankLinesToServerInfo.java @@ -0,0 +1,53 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.elasticstack.functions; + +import java.util.Set; + +import javax.inject.Inject; +import javax.inject.Singleton; + +import org.jclouds.elasticstack.domain.ServerInfo; +import org.jclouds.http.HttpResponse; + +import com.google.common.base.Function; +import com.google.common.collect.Iterables; + +/** + * + * @author Adrian Cole + */ +@Singleton +public class KeyValuesDelimitedByBlankLinesToServerInfo implements Function { + private final ListOfKeyValuesDelimitedByBlankLinesToServerInfoSet setParser; + + @Inject + public KeyValuesDelimitedByBlankLinesToServerInfo(ListOfKeyValuesDelimitedByBlankLinesToServerInfoSet setParser) { + this.setParser = setParser; + } + + @Override + public ServerInfo apply(HttpResponse response) { + Set drives = setParser.apply(response); + if (drives.size() == 0) + return null; + return Iterables.get(drives, 0); + } +} \ No newline at end of file diff --git a/sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/functions/ListOfKeyValuesDelimitedByBlankLinesToServerInfoSet.java b/sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/functions/ListOfKeyValuesDelimitedByBlankLinesToServerInfoSet.java new file mode 100644 index 0000000000..5047b43085 --- /dev/null +++ b/sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/functions/ListOfKeyValuesDelimitedByBlankLinesToServerInfoSet.java @@ -0,0 +1,60 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.elasticstack.functions; + +import java.util.Set; + +import javax.inject.Inject; +import javax.inject.Singleton; + +import org.jclouds.elasticstack.domain.ServerInfo; +import org.jclouds.http.HttpResponse; +import org.jclouds.http.functions.ReturnStringIf2xx; + +import com.google.common.base.Function; +import com.google.common.collect.ImmutableSet; +import com.google.common.collect.Iterables; + +/** + * + * @author Adrian Cole + */ +@Singleton +public class ListOfKeyValuesDelimitedByBlankLinesToServerInfoSet implements Function> { + private final ReturnStringIf2xx returnStringIf200; + private final ListOfKeyValuesDelimitedByBlankLinesToListOfMaps mapConverter; + private final MapToServerInfo mapToServer; + + @Inject + ListOfKeyValuesDelimitedByBlankLinesToServerInfoSet(ReturnStringIf2xx returnStringIf200, + ListOfKeyValuesDelimitedByBlankLinesToListOfMaps mapConverter, MapToServerInfo mapToServer) { + this.returnStringIf200 = returnStringIf200; + this.mapConverter = mapConverter; + this.mapToServer = mapToServer; + } + + @Override + public Set apply(HttpResponse response) { + String text = returnStringIf200.apply(response); + if (text == null || text.trim().equals("")) + return ImmutableSet. of(); + return ImmutableSet.copyOf(Iterables.transform(mapConverter.apply(text), mapToServer)); + } +} \ No newline at end of file diff --git a/sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/functions/MapToDevices.java b/sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/functions/MapToDevices.java new file mode 100644 index 0000000000..f7c9e64bcd --- /dev/null +++ b/sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/functions/MapToDevices.java @@ -0,0 +1,95 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.elasticstack.functions; + +import java.util.Map; +import java.util.Set; + +import javax.inject.Singleton; + +import org.jclouds.elasticstack.domain.BlockDevice; +import org.jclouds.elasticstack.domain.Device; +import org.jclouds.elasticstack.domain.IDEDevice; +import org.jclouds.elasticstack.domain.MediaType; +import org.jclouds.elasticstack.domain.SCSIDevice; + +import com.google.common.base.Function; +import com.google.common.collect.ImmutableSet; +import com.google.common.collect.ImmutableSet.Builder; + +/** + * + * @author Adrian Cole + */ +@Singleton +public class MapToDevices implements Function, Set> { + + public Set apply(Map from) { + Builder devices = ImmutableSet.builder(); + addIDEDevices(from, devices); + addSCSIDevices(from, devices); + addBlockDevices(from, devices); + Set devicess = devices.build(); + return devicess; + } + + protected void addBlockDevices(Map from, Builder devices) { + BLOCK: for (int index : new int[] { 0, 1, 2, 3, 4, 5, 6, 7 }) { + String key = String.format("block:0:%d", index); + if (!from.containsKey(key)) + break BLOCK; + devices.add(populateBuilder(new BlockDevice.Builder(index), key, from).build()); + } + } + + protected void addSCSIDevices(Map from, Builder devices) { + SCSI: for (int unit : new int[] { 0, 1, 2, 3, 4, 5, 6, 7 }) { + String key = String.format("scsi:0:%d", unit); + if (!from.containsKey(key)) + break SCSI; + devices.add(populateBuilder(new SCSIDevice.Builder(unit), key, from).build()); + } + } + + protected void addIDEDevices(Map from, Builder devices) { + IDE: for (int bus : new int[] { 0, 1 }) + for (int unit : new int[] { 0, 1 }) { + String key = String.format("ide:%d:%d", bus, unit); + if (!from.containsKey(key)) + break IDE; + devices.add(populateBuilder(new IDEDevice.Builder(bus, unit), key, from).build()); + } + } + + protected Device.Builder populateBuilder(Device.Builder deviceBuilder, String key, Map from) { + deviceBuilder.uuid(from.get(key)); + if (from.containsKey(key + ":read:bytes")) + deviceBuilder.readBytes(new Long(from.get(key + ":read:bytes"))); + if (from.containsKey(key + ":read:requests")) + deviceBuilder.readRequests(new Long(from.get(key + ":read:requests"))); + if (from.containsKey(key + ":write:bytes")) + deviceBuilder.writeBytes(new Long(from.get(key + ":write:bytes"))); + if (from.containsKey(key + ":write:requests")) + deviceBuilder.writeRequests(new Long(from.get(key + ":write:requests"))); + if (from.containsKey(key + ":media")) + deviceBuilder.mediaType(MediaType.fromValue(from.get(key + ":media"))); + return deviceBuilder; + } +} \ No newline at end of file diff --git a/sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/functions/MapToNICs.java b/sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/functions/MapToNICs.java new file mode 100644 index 0000000000..4303da4d10 --- /dev/null +++ b/sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/functions/MapToNICs.java @@ -0,0 +1,59 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.elasticstack.functions; + +import java.util.List; +import java.util.Map; + +import javax.inject.Singleton; + +import org.jclouds.elasticstack.domain.Model; +import org.jclouds.elasticstack.domain.NIC; + +import com.google.common.base.Function; +import com.google.common.base.Splitter; +import com.google.common.collect.ImmutableList; + +/** + * + * @author Adrian Cole + */ +@Singleton +public class MapToNICs implements Function, List> { + + @Override + public List apply(Map from) { + ImmutableList.Builder nics = ImmutableList.builder(); + NIC: for (int id : new int[] { 0, 1 }) { + String key = String.format("nic:%d", id); + if (!from.containsKey(key + ":model")) + break NIC; + NIC.Builder nicBuilder = new NIC.Builder(); + nicBuilder.dhcp(from.get(key + ":dhcp")); + nicBuilder.model(Model.fromValue(from.get(key + ":model"))); + nicBuilder.vlan(from.get(key + ":vlan")); + nicBuilder.mac(from.get(key + ":mac")); + if (from.containsKey(key + ":block")) + nicBuilder.block(Splitter.on(' ').split(from.get(key + ":block"))); + nics.add(nicBuilder.build()); + } + return nics.build(); + } +} \ No newline at end of file diff --git a/sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/functions/MapToServerInfo.java b/sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/functions/MapToServerInfo.java new file mode 100644 index 0000000000..20221c82de --- /dev/null +++ b/sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/functions/MapToServerInfo.java @@ -0,0 +1,101 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.elasticstack.functions; + +import java.util.Date; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +import javax.inject.Inject; +import javax.inject.Singleton; + +import org.jclouds.elasticstack.domain.Device; +import org.jclouds.elasticstack.domain.NIC; +import org.jclouds.elasticstack.domain.ServerInfo; +import org.jclouds.elasticstack.domain.ServerStatus; +import org.jclouds.elasticstack.domain.VNC; + +import com.google.common.base.Function; +import com.google.common.base.Splitter; +import com.google.common.collect.Maps; + +/** + * + * @author Adrian Cole + */ +@Singleton +public class MapToServerInfo implements Function, ServerInfo> { + private final Function, Set> mapToDevices; + private final Function, List> mapToNICs; + + @Inject + public MapToServerInfo(Function, Set> mapToDevices, + Function, List> mapToNICs) { + this.mapToDevices = mapToDevices; + this.mapToNICs = mapToNICs; + } + + @Override + public ServerInfo apply(Map from) { + if (from.size() == 0) + return null; + ServerInfo.Builder builder = new ServerInfo.Builder(); + builder.name(from.get("name")); + builder.description(from.get("description")); + builder.persistent(Boolean.parseBoolean(from.get("persistent"))); + if (from.containsKey("tags")) + builder.tags(Splitter.on(' ').split(from.get("tags"))); + if (from.containsKey("status")) + builder.status(ServerStatus.fromValue(from.get("status"))); + if (from.containsKey("tx:packets")) + builder.txPackets(new Long(from.get("tx:packets"))); + if (from.containsKey("tx")) + builder.tx(new Long(from.get("tx"))); + if (from.containsKey("smp") && !"auto".equals(from.get("smp"))) + builder.smp(new Integer(from.get("smp"))); + builder.cpu(Integer.parseInt(from.get("cpu"))); + builder.mem(Integer.parseInt(from.get("mem"))); + builder.user(from.get("user")); + if (from.containsKey("started")) + builder.started(new Date(new Long(from.get("started")))); + builder.uuid(from.get("server")); + builder.vnc(new VNC(from.get("vnc:ip"), from.get("vnc:password"), from.containsKey("vnc:tls") + && Boolean.valueOf(from.get("vnc:tls")))); + if (from.containsKey("rx:packets")) + builder.rxPackets(new Long(from.get("rx:packets"))); + if (from.containsKey("rx")) + builder.rx(new Long(from.get("rx"))); + if (from.containsKey("boot")) + builder.bootDeviceIds(Splitter.on(' ').split(from.get("boot"))); + + Map metadata = Maps.newLinkedHashMap(); + for (Entry entry : from.entrySet()) { + if (entry.getKey().startsWith("user:")) + metadata.put(entry.getKey().substring(entry.getKey().indexOf(':') + 1), entry.getValue()); + } + builder.userMetadata(metadata); + + builder.nics(mapToNICs.apply(from)); + builder.devices(mapToDevices.apply(from)); + return builder.build(); + } +} \ No newline at end of file diff --git a/sandbox/elasticstack/src/test/java/org/jclouds/elasticstack/CommonElasticStackClientLiveTest.java b/sandbox/elasticstack/src/test/java/org/jclouds/elasticstack/CommonElasticStackClientLiveTest.java index 28c8240a66..cf2afcc2e7 100644 --- a/sandbox/elasticstack/src/test/java/org/jclouds/elasticstack/CommonElasticStackClientLiveTest.java +++ b/sandbox/elasticstack/src/test/java/org/jclouds/elasticstack/CommonElasticStackClientLiveTest.java @@ -32,6 +32,7 @@ import org.jclouds.elasticstack.domain.CreateDriveRequest; import org.jclouds.elasticstack.domain.DriveData; import org.jclouds.elasticstack.domain.DriveInfo; import org.jclouds.elasticstack.domain.DriveStatus; +import org.jclouds.elasticstack.domain.ServerInfo; import org.jclouds.logging.log4j.config.Log4JLoggingModule; import org.jclouds.rest.RestContext; import org.jclouds.rest.RestContextFactory; @@ -97,6 +98,26 @@ public abstract class CommonElasticStackClientLiveTest servers = client.listServers(); + assertNotNull(servers); + } + + @Test + public void testListServerInfo() throws Exception { + Set servers = client.listServerInfo(); + assertNotNull(servers); + } + + @Test + public void testGetServer() throws Exception { + for (String serverUUID : client.listServers()) { + assert !"".equals(serverUUID); + assertNotNull(client.getServerInfo(serverUUID)); + } + } + @Test public void testListDrives() throws Exception { Set drives = client.listDrives(); diff --git a/sandbox/elasticstack/src/test/java/org/jclouds/elasticstack/ElasticStackAsyncClientTest.java b/sandbox/elasticstack/src/test/java/org/jclouds/elasticstack/ElasticStackAsyncClientTest.java index 0cd9ebf7bf..b3ab118918 100644 --- a/sandbox/elasticstack/src/test/java/org/jclouds/elasticstack/ElasticStackAsyncClientTest.java +++ b/sandbox/elasticstack/src/test/java/org/jclouds/elasticstack/ElasticStackAsyncClientTest.java @@ -31,7 +31,9 @@ import org.jclouds.elasticstack.domain.CreateDriveRequest; import org.jclouds.elasticstack.domain.DriveData; import org.jclouds.elasticstack.domain.ImageConversionType; import org.jclouds.elasticstack.functions.KeyValuesDelimitedByBlankLinesToDriveInfo; +import org.jclouds.elasticstack.functions.KeyValuesDelimitedByBlankLinesToServerInfo; import org.jclouds.elasticstack.functions.ListOfKeyValuesDelimitedByBlankLinesToDriveInfoSet; +import org.jclouds.elasticstack.functions.ListOfKeyValuesDelimitedByBlankLinesToServerInfoSet; import org.jclouds.elasticstack.functions.ReturnPayload; import org.jclouds.elasticstack.functions.SplitNewlines; import org.jclouds.elasticstack.options.ReadDriveOptions; @@ -60,6 +62,63 @@ import com.google.inject.TypeLiteral; */ @Test(groups = "unit", testName = "elasticstack.ElasticStackAsyncClientTest") public class ElasticStackAsyncClientTest extends RestClientTest { + public void testListServers() throws SecurityException, NoSuchMethodException, IOException { + Method method = ElasticStackAsyncClient.class.getMethod("listServers"); + GeneratedHttpRequest httpRequest = processor.createRequest(method); + + assertRequestLineEquals(httpRequest, "GET https://api.elasticstack.com/servers/list HTTP/1.1"); + assertNonPayloadHeadersEqual(httpRequest, "Accept: text/plain\n"); + assertPayloadEquals(httpRequest, null, null, false); + + // now make sure request filters apply by replaying + Iterables.getOnlyElement(httpRequest.getFilters()).filter(httpRequest); + Iterables.getOnlyElement(httpRequest.getFilters()).filter(httpRequest); + + assertRequestLineEquals(httpRequest, "GET https://api.elasticstack.com/servers/list HTTP/1.1"); + // for example, using basic authentication, we should get "only one" + // header + assertNonPayloadHeadersEqual(httpRequest, "Accept: text/plain\nAuthorization: Basic Zm9vOmJhcg==\n"); + assertPayloadEquals(httpRequest, null, null, false); + + // TODO: insert expected response class, which probably extends ParseJson + assertResponseParserClassEquals(method, httpRequest, SplitNewlines.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(httpRequest); + + } + + public void testListServerInfo() throws SecurityException, NoSuchMethodException, IOException { + Method method = ElasticStackAsyncClient.class.getMethod("listServerInfo"); + GeneratedHttpRequest httpRequest = processor.createRequest(method); + + assertRequestLineEquals(httpRequest, "GET https://api.elasticstack.com/servers/info HTTP/1.1"); + assertNonPayloadHeadersEqual(httpRequest, "Accept: text/plain\n"); + assertPayloadEquals(httpRequest, null, null, false); + + assertResponseParserClassEquals(method, httpRequest, ListOfKeyValuesDelimitedByBlankLinesToServerInfoSet.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(httpRequest); + } + + public void testGetServerInfo() throws SecurityException, NoSuchMethodException, IOException { + Method method = ElasticStackAsyncClient.class.getMethod("getServerInfo", String.class); + GeneratedHttpRequest httpRequest = processor.createRequest(method, "uuid"); + + assertRequestLineEquals(httpRequest, "GET https://api.elasticstack.com/servers/uuid/info HTTP/1.1"); + assertNonPayloadHeadersEqual(httpRequest, "Accept: text/plain\n"); + assertPayloadEquals(httpRequest, null, null, false); + + assertResponseParserClassEquals(method, httpRequest, KeyValuesDelimitedByBlankLinesToServerInfo.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, ReturnNullOnNotFoundOr404.class); + + checkFilters(httpRequest); + + } public void testListDrives() throws SecurityException, NoSuchMethodException, IOException { Method method = ElasticStackAsyncClient.class.getMethod("listDrives"); @@ -76,8 +135,7 @@ public class ElasticStackAsyncClientTest extends RestClientTest + * + * ==================================================================== + * 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.elasticstack.functions; + +import static org.testng.Assert.assertEquals; + +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.jclouds.elasticstack.domain.Device; +import org.jclouds.elasticstack.domain.NIC; +import org.jclouds.http.HttpResponse; +import org.jclouds.io.Payloads; +import org.testng.annotations.Test; + +import com.google.common.base.Function; +import com.google.inject.AbstractModule; +import com.google.inject.Guice; +import com.google.inject.TypeLiteral; + +/** + * + * @author Adrian Cole + */ +@Test(groups = { "unit" }) +public class KeyValuesDelimitedByBlankLinesToServerInfoTest { + + private static final KeyValuesDelimitedByBlankLinesToServerInfo FN = Guice.createInjector(new AbstractModule() { + + @Override + protected void configure() { + bind(new TypeLiteral, List>>() { + }).to(MapToNICs.class); + bind(new TypeLiteral, Set>>() { + }).to(MapToDevices.class); + } + + }).getInstance(KeyValuesDelimitedByBlankLinesToServerInfo.class); + + public void testNone() { + assertEquals(FN.apply(new HttpResponse(200, "", Payloads.newStringPayload(""))), null); + assertEquals(FN.apply(new HttpResponse(200, "", Payloads.newStringPayload("\n\n"))), null); + assertEquals(FN.apply(new HttpResponse(200, "", null)), null); + } + + public void testOne() { + assertEquals(FN.apply(new HttpResponse(200, "", Payloads.newInputStreamPayload(MapToServerInfoTest.class + .getResourceAsStream("/servers.txt")))), MapToServerInfoTest.ONE); + } +} \ No newline at end of file diff --git a/sandbox/elasticstack/src/test/java/org/jclouds/elasticstack/functions/ListOfKeyValuesDelimitedByBlankLinesToServerInfoSetTest.java b/sandbox/elasticstack/src/test/java/org/jclouds/elasticstack/functions/ListOfKeyValuesDelimitedByBlankLinesToServerInfoSetTest.java new file mode 100644 index 0000000000..3741230731 --- /dev/null +++ b/sandbox/elasticstack/src/test/java/org/jclouds/elasticstack/functions/ListOfKeyValuesDelimitedByBlankLinesToServerInfoSetTest.java @@ -0,0 +1,73 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.elasticstack.functions; + +import static org.testng.Assert.assertEquals; + +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.jclouds.elasticstack.domain.Device; +import org.jclouds.elasticstack.domain.NIC; +import org.jclouds.elasticstack.domain.ServerInfo; +import org.jclouds.http.HttpResponse; +import org.jclouds.io.Payloads; +import org.testng.annotations.Test; + +import com.google.common.base.Function; +import com.google.common.collect.ImmutableSet; +import com.google.inject.AbstractModule; +import com.google.inject.Guice; +import com.google.inject.TypeLiteral; + +/** + * + * @author Adrian Cole + */ +@Test(groups = { "unit" }) +public class ListOfKeyValuesDelimitedByBlankLinesToServerInfoSetTest { + + private static final ListOfKeyValuesDelimitedByBlankLinesToServerInfoSet FN = Guice.createInjector( + new AbstractModule() { + + @Override + protected void configure() { + bind(new TypeLiteral, List>>() { + }).to(MapToNICs.class); + bind(new TypeLiteral, Set>>() { + }).to(MapToDevices.class); + } + + }).getInstance(ListOfKeyValuesDelimitedByBlankLinesToServerInfoSet.class); + + public void testNone() { + assertEquals(FN.apply(new HttpResponse(200, "", Payloads.newStringPayload(""))), ImmutableSet. of()); + assertEquals(FN.apply(new HttpResponse(200, "", Payloads.newStringPayload("\n\n"))), + ImmutableSet. of()); + assertEquals(FN.apply(new HttpResponse(200, "", null)), ImmutableSet. of()); + } + + public void testOne() { + assertEquals(FN.apply(new HttpResponse(200, "", Payloads.newInputStreamPayload(MapToServerInfoTest.class + .getResourceAsStream("/servers.txt")))), ImmutableSet. of(MapToServerInfoTest.ONE, + MapToServerInfoTest.TWO)); + } +} \ No newline at end of file diff --git a/sandbox/elasticstack/src/test/java/org/jclouds/elasticstack/functions/MapToServerInfoTest.java b/sandbox/elasticstack/src/test/java/org/jclouds/elasticstack/functions/MapToServerInfoTest.java new file mode 100644 index 0000000000..6e446c5cd4 --- /dev/null +++ b/sandbox/elasticstack/src/test/java/org/jclouds/elasticstack/functions/MapToServerInfoTest.java @@ -0,0 +1,110 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.elasticstack.functions; + +import static org.testng.Assert.assertEquals; + +import java.io.IOException; +import java.util.Date; +import java.util.Map; + +import org.jclouds.elasticstack.domain.IDEDevice; +import org.jclouds.elasticstack.domain.MediaType; +import org.jclouds.elasticstack.domain.Model; +import org.jclouds.elasticstack.domain.NIC; +import org.jclouds.elasticstack.domain.ServerInfo; +import org.jclouds.elasticstack.domain.ServerStatus; +import org.jclouds.elasticstack.domain.VNC; +import org.jclouds.util.Utils; +import org.testng.annotations.Test; + +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.ImmutableSet; + +/** + * + * @author Adrian Cole + */ +@Test(groups = { "unit" }) +public class MapToServerInfoTest { + public static ServerInfo ONE = new ServerInfo.Builder() + .persistent(true) + .uuid("f8bee9cd-8e4b-4a05-8593-1314e3bfe49b") + .cpu(2000) + .bootDeviceIds(ImmutableSet.of("ide:0:0")) + .smp(1) + .mem(1024) + .status(ServerStatus.ACTIVE) + .started(new Date(1291493868l)) + .user("2f6244eb-50bc-4403-847e-f03cc3706a1f") + .name("jo") + .vnc(new VNC("46.20.114.124", "HfHzVmLT", false)) + .nics(ImmutableSet.of(new NIC.Builder() + .model(Model.E1000) + .dhcp("46.20.114.124") + .block( + ImmutableList.of("tcp/43594", "tcp/5902", "udp/5060", "tcp/5900", "tcp/5901", "tcp/21", "tcp/22", + "tcp/23", "tcp/25", "tcp/110", "tcp/143", "tcp/43595")).build())) + .devices( + ImmutableSet.of(new IDEDevice.Builder((int) 0, (int) 0).uuid("4af85ed3-0caa-4736-8a26-a33d7de0a122") + .readRequests(11154).readBytes(45686784).writeRequests(3698).writeBytes(15147008).build() + + )).tx(2550).txPackets(31).rx(455530).rxPackets(7583).build(); + + public static ServerInfo TWO = new ServerInfo.Builder() + .status(ServerStatus.STOPPED) + .name("Demo") + .mem(1024) + .cpu(2000) + .persistent(true) + .uuid("0f962616-2071-4173-be79-7dd084271edf") + .bootDeviceIds(ImmutableSet.of("ide:0:0")) + .user("2f6244eb-50bc-4403-847e-f03cc3706a1f") + .vnc(new VNC("auto", "HWbjvrg2", false)) + .nics(ImmutableSet.of(new NIC.Builder().model(Model.E1000).dhcp("auto").build())) + .devices( + ImmutableSet.of(new IDEDevice.Builder((int) 0, (int) 0).uuid("853bb98a-4fff-4c2f-a265-97c363f19ea5") + .mediaType(MediaType.CDROM).build() + + )).build(); + + private static final MapToServerInfo MAP_TO_DRIVE = new MapToServerInfo(new MapToDevices(), new MapToNICs()); + + public void testEmptyMapReturnsNull() { + assertEquals(MAP_TO_DRIVE.apply(ImmutableMap. of()), null); + } + + public void testBasics() { + ServerInfo expects = new ServerInfo.Builder().name("foo").uuid("hello").vnc(new VNC("auto", null, false)) + .cpu(1000).mem(2048).build(); + assertEquals(MAP_TO_DRIVE.apply(ImmutableMap.of("name", "foo", "server", "hello", "vnc:ip", "auto", "cpu", + "1000", "mem", "2048")), expects); + } + + public void testComplete() throws IOException { + + Map input = new ListOfKeyValuesDelimitedByBlankLinesToListOfMaps().apply( + Utils.toStringAndClose(MapToServerInfoTest.class.getResourceAsStream("/servers.txt"))).get(0); + + assertEquals(MAP_TO_DRIVE.apply(input), ONE); + + } +} \ No newline at end of file diff --git a/sandbox/elasticstack/src/test/resources/servers.txt b/sandbox/elasticstack/src/test/resources/servers.txt new file mode 100644 index 0000000000..a3d1ff1b46 --- /dev/null +++ b/sandbox/elasticstack/src/test/resources/servers.txt @@ -0,0 +1,40 @@ +ide:0:0:write:requests 3698 +boot ide:0:0 +vnc:password HfHzVmLT +ide:0:0 4af85ed3-0caa-4736-8a26-a33d7de0a122 +ide:0:0:read:requests 11154 +ide:0:0:read:bytes 45686784 +vnc:ip 46.20.114.124 +tx:packets 31 +tx 2550 +rx 455530 +smp 1 +mem 1024 +nic:0:model e1000 +status active +started 1291493868 +rx:packets 7583 +user 2f6244eb-50bc-4403-847e-f03cc3706a1f +name jo +persistent true +nic:0:block tcp/43594 tcp/5902 udp/5060 tcp/5900 tcp/5901 tcp/21 tcp/22 tcp/23 tcp/25 tcp/110 tcp/143 tcp/43595 +server f8bee9cd-8e4b-4a05-8593-1314e3bfe49b +nic:0:dhcp 46.20.114.124 +ide:0:0:write:bytes 15147008 +cpu 2000 + +status stopped +name Demo +mem 1024 +boot ide:0:0 +vnc:password HWbjvrg2 +persistent true +server 0f962616-2071-4173-be79-7dd084271edf +smp auto +nic:0:dhcp auto +user 2f6244eb-50bc-4403-847e-f03cc3706a1f +nic:0:model e1000 +vnc:ip auto +ide:0:0 853bb98a-4fff-4c2f-a265-97c363f19ea5 +cpu 2000 +ide:0:0:media cdrom From 1063924f6a906df5416eee248c1a17fad44ee427 Mon Sep 17 00:00:00 2001 From: Adrian Cole Date: Sat, 4 Dec 2010 23:45:03 +0000 Subject: [PATCH 25/31] fixed issue where body of a Payload arg wasn't being added to the http request --- .../internal/RestAnnotationProcessor.java | 119 +++---- .../internal/RestAnnotationProcessorTest.java | 311 +++++++++--------- .../ElasticStackAsyncClientTest.java | 4 +- .../ElasticStackClientLiveTest.java | 3 +- 4 files changed, 226 insertions(+), 211 deletions(-) diff --git a/core/src/main/java/org/jclouds/rest/internal/RestAnnotationProcessor.java b/core/src/main/java/org/jclouds/rest/internal/RestAnnotationProcessor.java index 3b61dd877a..725f0c5b43 100755 --- a/core/src/main/java/org/jclouds/rest/internal/RestAnnotationProcessor.java +++ b/core/src/main/java/org/jclouds/rest/internal/RestAnnotationProcessor.java @@ -166,7 +166,7 @@ public class RestAnnotationProcessor { static final Map delegationMap = newHashMap(); static Map>> createMethodToIndexOfParamToAnnotation( - final Class annotation) { + final Class annotation) { return new MapMaker().makeComputingMap(new Function>>() { public Map> apply(final Method method) { return new MapMaker().makeComputingMap(new GetAnnotationsForMethodParameterIndex(method, annotation)); @@ -200,7 +200,7 @@ public class RestAnnotationProcessor { } private static final Class optionsVarArgsClass = new HttpRequestOptions[] {} - .getClass(); + .getClass(); private static final Function, ? extends Part> ENTRY_TO_PART = new Function, Part>() { @@ -212,17 +212,17 @@ public class RestAnnotationProcessor { }; private final Map> methodToIndexesOfOptions = new MapMaker() - .makeComputingMap(new Function>() { - public Set apply(final Method method) { - Set toReturn = newHashSet(); - for (int index = 0; index < method.getParameterTypes().length; index++) { - Class type = method.getParameterTypes()[index]; - if (HttpRequestOptions.class.isAssignableFrom(type) || optionsVarArgsClass.isAssignableFrom(type)) - toReturn.add(index); - } - return toReturn; + .makeComputingMap(new Function>() { + public Set apply(final Method method) { + Set toReturn = newHashSet(); + for (int index = 0; index < method.getParameterTypes().length; index++) { + Class type = method.getParameterTypes()[index]; + if (HttpRequestOptions.class.isAssignableFrom(type) || optionsVarArgsClass.isAssignableFrom(type)) + toReturn.add(index); } - }); + return toReturn; + } + }); private final ParseSax.Factory parserFactory; private final HttpUtils utils; @@ -240,7 +240,7 @@ public class RestAnnotationProcessor { @VisibleForTesting public static Function createResponseParser(ParseSax.Factory parserFactory, Injector injector, - Method method, HttpRequest request) { + Method method, HttpRequest request) { Function transformer; Class> handler = getSaxResponseParserClassOrNull(method); if (handler != null) { @@ -261,7 +261,7 @@ public class RestAnnotationProcessor { @VisibleForTesting public static Function createExceptionParserOrThrowResourceNotFoundOn404IfNoAnnotation( - Injector injector, Method method) { + Injector injector, Method method) { ExceptionParser annotation = method.getAnnotation(ExceptionParser.class); if (annotation != null) { return injector.getInstance(annotation.value()); @@ -272,7 +272,7 @@ public class RestAnnotationProcessor { @SuppressWarnings("unchecked") @Inject public RestAnnotationProcessor(Injector injector, ParseSax.Factory parserFactory, HttpUtils utils, - TypeLiteral typeLiteral) { + TypeLiteral typeLiteral) { this.declaring = (Class) typeLiteral.getRawType(); this.injector = injector; this.parserFactory = parserFactory; @@ -387,7 +387,7 @@ public class RestAnnotationProcessor { public GeneratedHttpRequest createRequest(Method method, Object... args) { inputParamValidator.validateMethodParametersOrThrow(method, args); ClassMethodArgs cma = logger.isTraceEnabled() ? new ClassMethodArgs(method.getDeclaringClass(), method, args) - : null; + : null; URI endpoint = callerEndpoint; try { @@ -457,7 +457,7 @@ public class RestAnnotationProcessor { } GeneratedHttpRequest request = new GeneratedHttpRequest(httpMethod, endpoint, skips, declaring, method, - args); + args); addHostHeaderIfAnnotatedWithVirtualHost(headers, request.getEndpoint().getHost(), method); addFiltersIfAnnotated(method, request); @@ -472,8 +472,9 @@ public class RestAnnotationProcessor { } else if (formParams.size() > 0) { payload = Payloads.newUrlEncodedFormPayload(formParams, skips); } else if (headers.containsKey(CONTENT_TYPE)) { - payload = Payloads.newByteArrayPayload(new byte[]{}); - payload.getContentMetadata().setContentType(Iterables.get(headers.get(CONTENT_TYPE),0)); + if (payload == null) + payload = Payloads.newByteArrayPayload(new byte[] {}); + payload.getContentMetadata().setContentType(Iterables.get(headers.get(CONTENT_TYPE), 0)); } if (payload != null) { request.setPayload(payload); @@ -496,14 +497,14 @@ public class RestAnnotationProcessor { } public static URI replaceQuery(Provider uriBuilderProvider, URI in, String newQuery, - @Nullable Comparator> sorter, char... skips) { + @Nullable Comparator> sorter, char... skips) { UriBuilder builder = uriBuilderProvider.get().uri(in); builder.replaceQuery(makeQueryLine(parseQueryToMap(newQuery), sorter, skips)); return builder.build(); } private void addMatrixParams(UriBuilder builder, Collection> tokenValues, Method method, - Object... args) { + Object... args) { if (declaring.isAnnotationPresent(MatrixParams.class)) { MatrixParams matrix = declaring.getAnnotation(MatrixParams.class); addMatrix(builder, matrix, tokenValues); @@ -520,7 +521,7 @@ public class RestAnnotationProcessor { } private Multimap addFormParams(Collection> tokenValues, Method method, - Object... args) { + Object... args) { Multimap formMap = LinkedListMultimap.create(); if (declaring.isAnnotationPresent(FormParams.class)) { FormParams form = declaring.getAnnotation(FormParams.class); @@ -539,7 +540,7 @@ public class RestAnnotationProcessor { } private Multimap addQueryParams(Collection> tokenValues, Method method, - Object... args) { + Object... args) { Multimap queryMap = LinkedListMultimap.create(); if (declaring.isAnnotationPresent(QueryParams.class)) { QueryParams query = declaring.getAnnotation(QueryParams.class); @@ -558,7 +559,7 @@ public class RestAnnotationProcessor { } private void addForm(Multimap formParams, FormParams form, - Collection> tokenValues) { + Collection> tokenValues) { for (int i = 0; i < form.keys().length; i++) { if (form.values()[i].equals(FormParams.NULL)) { formParams.removeAll(form.keys()[i]); @@ -570,7 +571,7 @@ public class RestAnnotationProcessor { } private void addMapPayload(Map postParams, MapPayloadParams mapDefaults, - Collection> tokenValues) { + Collection> tokenValues) { for (int i = 0; i < mapDefaults.keys().length; i++) { if (mapDefaults.values()[i].equals(MapPayloadParams.NULL)) { postParams.put(mapDefaults.keys()[i], null); @@ -581,7 +582,7 @@ public class RestAnnotationProcessor { } private void addQuery(Multimap queryParams, QueryParams query, - Collection> tokenValues) { + Collection> tokenValues) { for (int i = 0; i < query.keys().length; i++) { if (query.values()[i].equals(QueryParams.NULL)) { queryParams.removeAll(query.keys()[i]); @@ -624,7 +625,7 @@ public class RestAnnotationProcessor { @VisibleForTesting public static URI getEndpointInParametersOrNull(Method method, final Object[] args, Injector injector) { Map> map = indexWithAtLeastOneAnnotation(method, - methodToIndexOfParamToEndpointParamAnnotations); + methodToIndexOfParamToEndpointParamAnnotations); if (map.size() >= 1 && args.length > 0) { EndpointParam firstAnnotation = (EndpointParam) get(get(map.values(), 0), 0); Function parser = injector.getInstance(firstAnnotation.parser()); @@ -633,8 +634,8 @@ public class RestAnnotationProcessor { int index = map.keySet().iterator().next(); try { URI returnVal = parser.apply(args[index]); - checkArgument(returnVal != null, String.format("endpoint for [%s] not configured for %s", args[index], - method)); + checkArgument(returnVal != null, + String.format("endpoint for [%s] not configured for %s", args[index], method)); return returnVal; } catch (NullPointerException e) { throw new IllegalArgumentException(String.format("argument at index %d on method %s", index, method), e); @@ -651,12 +652,12 @@ public class RestAnnotationProcessor { }); try { URI returnVal = parser.apply(argsToParse); - checkArgument(returnVal != null, String.format("endpoint for [%s] not configured for %s", argsToParse, - method)); + checkArgument(returnVal != null, + String.format("endpoint for [%s] not configured for %s", argsToParse, method)); return returnVal; } catch (NullPointerException e) { throw new IllegalArgumentException(String.format("argument at indexes %s on method %s", map.keySet(), - method), e); + method), e); } } } @@ -697,13 +698,13 @@ public class RestAnnotationProcessor { ResponseParser annotation = method.getAnnotation(ResponseParser.class); if (annotation == null) { if (method.getReturnType().equals(void.class) - || TypeLiteral.get(method.getGenericReturnType()).equals(futureVoidLiteral)) { + || TypeLiteral.get(method.getGenericReturnType()).equals(futureVoidLiteral)) { return Key.get(ReleasePayloadAndReturn.class); } else if (method.getReturnType().equals(boolean.class) || method.getReturnType().equals(Boolean.class) - || TypeLiteral.get(method.getGenericReturnType()).equals(futureBooleanLiteral)) { + || TypeLiteral.get(method.getGenericReturnType()).equals(futureBooleanLiteral)) { return Key.get(ReturnTrueIf2xx.class); } else if (method.getReturnType().equals(InputStream.class) - || TypeLiteral.get(method.getGenericReturnType()).equals(futureInputStreamLiteral)) { + || TypeLiteral.get(method.getGenericReturnType()).equals(futureInputStreamLiteral)) { return Key.get(ReturnInputStream.class); } else if (getAcceptHeadersOrNull(method).contains(MediaType.APPLICATION_JSON)) { Type returnVal; @@ -724,10 +725,10 @@ public class RestAnnotationProcessor { parserType = Types.newParameterizedType(ParseJson.class, returnVal); return (Key>) Key.get(parserType); } else if (method.getReturnType().equals(String.class) - || TypeLiteral.get(method.getGenericReturnType()).equals(futureStringLiteral)) { + || TypeLiteral.get(method.getGenericReturnType()).equals(futureStringLiteral)) { return Key.get(ReturnStringIf2xx.class); } else if (method.getReturnType().equals(URI.class) - || TypeLiteral.get(method.getGenericReturnType()).equals(futureURILiteral)) { + || TypeLiteral.get(method.getGenericReturnType()).equals(futureURILiteral)) { return Key.get(ParseURIFromListOrLocationHeaderIf20x.class); } else { throw new IllegalStateException("You must specify a ResponseParser annotation on: " + method.toString()); @@ -759,7 +760,7 @@ public class RestAnnotationProcessor { } else { if (postBinders[0] instanceof org.jclouds.rest.MapBinder) { throw new IllegalArgumentException("we currently do not support multiple varargs postBinders in: " - + method.getName()); + + method.getName()); } } } else if (arg instanceof org.jclouds.rest.MapBinder) { @@ -808,8 +809,8 @@ public class RestAnnotationProcessor { Set requests = getHttpMethods(method); if (requests == null || requests.size() != 1) { throw new IllegalStateException( - "You must use at least one, but no more than one http method or pathparam annotation on: " - + method.toString()); + "You must use at least one, but no more than one http method or pathparam annotation on: " + + method.toString()); } return requests.iterator().next(); } @@ -831,12 +832,12 @@ public class RestAnnotationProcessor { mapBinder.bindToRequest(request, mapParams); } else { OUTER: for (Entry> entry : filterValues( - methodToIndexOfParamToDecoratorParamAnnotation.get(request.getJavaMethod()), - new Predicate>() { - public boolean apply(Set input) { - return input.size() >= 1; - } - }).entrySet()) { + methodToIndexOfParamToDecoratorParamAnnotation.get(request.getJavaMethod()), + new Predicate>() { + public boolean apply(Set input) { + return input.size() >= 1; + } + }).entrySet()) { boolean shouldBreak = false; BinderParam payloadAnnotation = (BinderParam) entry.getValue().iterator().next(); Binder binder = injector.getInstance(payloadAnnotation.value()); @@ -872,24 +873,24 @@ public class RestAnnotationProcessor { } public static Map> indexWithOnlyOneAnnotation(Method method, String description, - Map>> toRefine) { + Map>> toRefine) { Map> indexToPayloadAnnotation = indexWithAtLeastOneAnnotation(method, toRefine); if (indexToPayloadAnnotation.size() > 1) { throw new IllegalStateException(String.format( - "You must not specify more than one %s annotation on: %s; found %s", description, method.toString(), - indexToPayloadAnnotation)); + "You must not specify more than one %s annotation on: %s; found %s", description, method.toString(), + indexToPayloadAnnotation)); } return indexToPayloadAnnotation; } private static Map> indexWithAtLeastOneAnnotation(Method method, - Map>> toRefine) { + Map>> toRefine) { Map> indexToPayloadAnnotation = filterValues(toRefine.get(method), - new Predicate>() { - public boolean apply(Set input) { - return input.size() == 1; - } - }); + new Predicate>() { + public boolean apply(Set input) { + return input.size() == 1; + } + }); return indexToPayloadAnnotation; } @@ -908,7 +909,7 @@ public class RestAnnotationProcessor { } else { if (options[0] instanceof HttpRequestOptions) { throw new IllegalArgumentException("we currently do not support multiple varargs options in: " - + method.getName()); + + method.getName()); } } } else { @@ -920,7 +921,7 @@ public class RestAnnotationProcessor { } public Multimap buildHeaders(Collection> tokenValues, Method method, - final Object... args) { + final Object... args) { Multimap headers = LinkedHashMultimap.create(); addHeaderIfAnnotationPresentOnMethod(headers, method, tokenValues); Map> indexToHeaderParam = methodToIndexOfParamToHeaderParamAnnotations.get(method); @@ -967,7 +968,7 @@ public class RestAnnotationProcessor { } public void addHeaderIfAnnotationPresentOnMethod(Multimap headers, Method method, - Collection> tokenValues) { + Collection> tokenValues) { if (declaring.isAnnotationPresent(Headers.class)) { Headers header = declaring.getAnnotation(Headers.class); addHeader(headers, header, tokenValues); @@ -979,7 +980,7 @@ public class RestAnnotationProcessor { } private void addHeader(Multimap headers, Headers header, - Collection> tokenValues) { + Collection> tokenValues) { for (int i = 0; i < header.keys().length; i++) { String value = header.values()[i]; value = replaceTokens(value, tokenValues); diff --git a/core/src/test/java/org/jclouds/rest/internal/RestAnnotationProcessorTest.java b/core/src/test/java/org/jclouds/rest/internal/RestAnnotationProcessorTest.java index b107347cb6..b0bf75a07a 100755 --- a/core/src/test/java/org/jclouds/rest/internal/RestAnnotationProcessorTest.java +++ b/core/src/test/java/org/jclouds/rest/internal/RestAnnotationProcessorTest.java @@ -104,6 +104,7 @@ import org.jclouds.http.options.GetOptions; import org.jclouds.http.options.HttpRequestOptions; import org.jclouds.io.Payload; import org.jclouds.io.PayloadEnclosing; +import org.jclouds.io.Payloads; import org.jclouds.logging.config.NullLoggingModule; import org.jclouds.rest.BaseRestClientTest; import org.jclouds.rest.ConfiguresRestClient; @@ -208,7 +209,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { @SuppressWarnings("unchecked") public void testDelegateAsync() throws SecurityException, NoSuchMethodException, InterruptedException, - ExecutionException { + ExecutionException { Injector child = injectorForClient(); TransformingHttpCommandExecutorService mock = child.getInstance(TransformingHttpCommandExecutorService.class); @@ -223,7 +224,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { AsyncCaller caller = child.getInstance(AsyncCaller.class); expect(mock.submit(requestLineEquals("GET http://localhost:9999/client/foo HTTP/1.1"), eq(function))).andReturn( - createNiceMock(ListenableFuture.class)).atLeastOnce(); + createNiceMock(ListenableFuture.class)).atLeastOnce(); replay(mock); caller.getCallee().onePath("foo"); @@ -252,7 +253,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { } public void testDelegateWithOverridingEndpoint() throws SecurityException, NoSuchMethodException, - InterruptedException, ExecutionException { + InterruptedException, ExecutionException { Injector child = injectorForClient(); TransformingHttpCommandExecutorService mock = child.getInstance(TransformingHttpCommandExecutorService.class); @@ -267,7 +268,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { Caller caller = child.getInstance(Caller.class); expect(mock.submit(requestLineEquals("GET http://localhost:1111/client/foo HTTP/1.1"), eq(function))).andReturn( - Futures. immediateFuture(null)).atLeastOnce(); + Futures. immediateFuture(null)).atLeastOnce(); replay(mock); caller.getCallee().onePath("foo"); @@ -278,9 +279,9 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { private Injector injectorForClient() { - RestContextSpec contextSpec = contextSpec("test", "http://localhost:9999", "1", "userfoo", null, - Caller.class, AsyncCaller.class, ImmutableSet. of(new MockModule(), new NullLoggingModule(), - new CallerCalleeModule())); + RestContextSpec contextSpec = contextSpec("test", "http://localhost:9999", "1", "userfoo", + null, Caller.class, AsyncCaller.class, + ImmutableSet. of(new MockModule(), new NullLoggingModule(), new CallerCalleeModule())); return createContextBuilder(contextSpec).buildInjector(); @@ -295,7 +296,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { }; - @Target( { ElementType.METHOD }) + @Target({ ElementType.METHOD }) @Retention(RetentionPolicy.RUNTIME) @javax.ws.rs.HttpMethod("FOO") public @interface FOO { @@ -330,10 +331,10 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { public void testUnEncodeQuery() { URI expects = URI - .create("http://services.nirvanix.com/ws/Metadata/SetMetadata.ashx?output=json&path=adriancole-compute.testObjectOperations&metadata=chef:sushi&metadata=foo:bar&sessionToken=775ef26e-0740-4707-ad92-afe9814bc436"); + .create("http://services.nirvanix.com/ws/Metadata/SetMetadata.ashx?output=json&path=adriancole-compute.testObjectOperations&metadata=chef:sushi&metadata=foo:bar&sessionToken=775ef26e-0740-4707-ad92-afe9814bc436"); URI start = URI - .create("http://services.nirvanix.com/ws/Metadata/SetMetadata.ashx?output=json&path=adriancole-compute.testObjectOperations&metadata=chef%3Asushi&metadata=foo%3Abar&sessionToken=775ef26e-0740-4707-ad92-afe9814bc436"); + .create("http://services.nirvanix.com/ws/Metadata/SetMetadata.ashx?output=json&path=adriancole-compute.testObjectOperations&metadata=chef%3Asushi&metadata=foo%3Abar&sessionToken=775ef26e-0740-4707-ad92-afe9814bc436"); URI value = RestAnnotationProcessor.replaceQuery(uriBuilderProvider, start, start.getQuery(), null, '/', ':'); assertEquals(value, expects); } @@ -373,21 +374,34 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { @POST @Path("") public void post(HttpRequestOptions options); - + @POST @Path("") @Produces(MediaType.APPLICATION_OCTET_STREAM) public void post(); + + @POST + @Path("") + @Produces(MediaType.APPLICATION_OCTET_STREAM) + public void post(Payload payload); } - public void testHttpRequestOptionsPayloadParam() throws SecurityException, NoSuchMethodException, IOException { + public void testHttpRequestOptionsNoPayloadParam() throws SecurityException, NoSuchMethodException, IOException { Method method = TestPayloadParamVarargs.class.getMethod("post"); HttpRequest request = factory(TestQuery.class).createRequest(method); assertRequestLineEquals(request, "POST http://localhost:9999?x-ms-version=2009-07-17 HTTP/1.1"); assertNonPayloadHeadersEqual(request, ""); assertPayloadEquals(request, "", "application/octet-stream", false); } - + + public void testHttpRequestOptionsPayloadParam() throws SecurityException, NoSuchMethodException, IOException { + Method method = TestPayloadParamVarargs.class.getMethod("post", Payload.class); + HttpRequest request = factory(TestQuery.class).createRequest(method, Payloads.newStringPayload("foo")); + assertRequestLineEquals(request, "POST http://localhost:9999?x-ms-version=2009-07-17 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, ""); + assertPayloadEquals(request, "foo", "application/octet-stream", false); + } + public void testHttpRequestWithOnlyContentType() throws SecurityException, NoSuchMethodException, IOException { Method method = TestPayloadParamVarargs.class.getMethod("post", HttpRequestOptions.class); verifyTestPostOptions(method); @@ -395,7 +409,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { public void testPayloadParamVarargs() throws SecurityException, NoSuchMethodException, IOException { Method method = TestPayloadParamVarargs.class.getMethod("varargs", Array.newInstance(HttpRequestOptions.class, 0) - .getClass()); + .getClass()); verifyTestPostOptions(method); } @@ -492,7 +506,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { public void testOverriddenEndpointParameter() throws SecurityException, NoSuchMethodException { Method method = TestOverriddenEndpoint.class.getMethod("foo", URI.class); HttpRequest request = factory(TestOverriddenEndpoint.class).createRequest(method, - new Object[] { URI.create("http://wowsa:8001") }); + new Object[] { URI.create("http://wowsa:8001") }); assertEquals(request.getEndpoint().getHost(), "wowsa"); assertEquals(request.getEndpoint().getPort(), 8001); assertEquals(request.getEndpoint().getPath(), ""); @@ -600,45 +614,45 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { @POST @Path("") void withParamFileBinaryPart(@FormParam("name") String name, - @PartParam(name = "file", contentType = MediaType.APPLICATION_OCTET_STREAM) File path); + @PartParam(name = "file", contentType = MediaType.APPLICATION_OCTET_STREAM) File path); @POST @Path("") void withParamByteArrayBinaryPart( - @FormParam("name") String name, - @PartParam(name = "file", contentType = MediaType.APPLICATION_OCTET_STREAM, filename = "{name}.tar.gz") byte[] content); + @FormParam("name") String name, + @PartParam(name = "file", contentType = MediaType.APPLICATION_OCTET_STREAM, filename = "{name}.tar.gz") byte[] content); } public void testMultipartWithStringPart() throws SecurityException, NoSuchMethodException, IOException { Method method = TestMultipartForm.class.getMethod("withStringPart", String.class); GeneratedHttpRequest httpRequest = factory(TestMultipartForm.class).createRequest(method, - "foobledata"); + "foobledata"); assertRequestLineEquals(httpRequest, "POST http://localhost:9999 HTTP/1.1"); assertNonPayloadHeadersEqual(httpRequest, ""); assertPayloadEquals(httpRequest,// - "----JCLOUDS--\r\n" + // - "Content-Disposition: form-data; name=\"fooble\"\r\n" + // - "\r\n" + // - "foobledata\r\n" + // - "----JCLOUDS----\r\n", "multipart/form-data; boundary=--JCLOUDS--", false); + "----JCLOUDS--\r\n" + // + "Content-Disposition: form-data; name=\"fooble\"\r\n" + // + "\r\n" + // + "foobledata\r\n" + // + "----JCLOUDS----\r\n", "multipart/form-data; boundary=--JCLOUDS--", false); } public void testMultipartWithParamStringPart() throws SecurityException, NoSuchMethodException, IOException { Method method = TestMultipartForm.class.getMethod("withParamStringPart", String.class, String.class); GeneratedHttpRequest httpRequest = factory(TestMultipartForm.class).createRequest(method, - "name", "foobledata"); + "name", "foobledata"); assertRequestLineEquals(httpRequest, "POST http://localhost:9999 HTTP/1.1"); assertNonPayloadHeadersEqual(httpRequest, ""); assertPayloadEquals(httpRequest,// - "----JCLOUDS--\r\n" + // - "Content-Disposition: form-data; name=\"name\"\r\n" + // - "\r\n" + // - "name\r\n" + // / - "----JCLOUDS--\r\n" + // - "Content-Disposition: form-data; name=\"file\"\r\n" + // - "\r\n" + // - "foobledata\r\n" + // - "----JCLOUDS----\r\n", "multipart/form-data; boundary=--JCLOUDS--", false); + "----JCLOUDS--\r\n" + // + "Content-Disposition: form-data; name=\"name\"\r\n" + // + "\r\n" + // + "name\r\n" + // / + "----JCLOUDS--\r\n" + // + "Content-Disposition: form-data; name=\"file\"\r\n" + // + "\r\n" + // + "foobledata\r\n" + // + "----JCLOUDS----\r\n", "multipart/form-data; boundary=--JCLOUDS--", false); } public void testMultipartWithParamFilePart() throws SecurityException, NoSuchMethodException, IOException { @@ -648,38 +662,38 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { file.deleteOnExit(); GeneratedHttpRequest httpRequest = factory(TestMultipartForm.class).createRequest(method, - "name", file); + "name", file); assertRequestLineEquals(httpRequest, "POST http://localhost:9999 HTTP/1.1"); assertNonPayloadHeadersEqual(httpRequest, ""); assertPayloadEquals(httpRequest,// - "----JCLOUDS--\r\n" + // - "Content-Disposition: form-data; name=\"name\"\r\n" + // - "\r\n" + // - "name\r\n" + // / - "----JCLOUDS--\r\n" + // - "Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getName() + "\"\r\n" + // - "\r\n" + // - "foobledata\r\n" + // - "----JCLOUDS----\r\n", "multipart/form-data; boundary=--JCLOUDS--", false); + "----JCLOUDS--\r\n" + // + "Content-Disposition: form-data; name=\"name\"\r\n" + // + "\r\n" + // + "name\r\n" + // / + "----JCLOUDS--\r\n" + // + "Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getName() + "\"\r\n" + // + "\r\n" + // + "foobledata\r\n" + // + "----JCLOUDS----\r\n", "multipart/form-data; boundary=--JCLOUDS--", false); } public void testMultipartWithParamByteArrayPart() throws SecurityException, NoSuchMethodException, IOException { Method method = TestMultipartForm.class.getMethod("withParamByteArrayBinaryPart", String.class, byte[].class); GeneratedHttpRequest httpRequest = factory(TestMultipartForm.class).createRequest(method, - "name", "goo".getBytes()); + "name", "goo".getBytes()); assertRequestLineEquals(httpRequest, "POST http://localhost:9999 HTTP/1.1"); assertNonPayloadHeadersEqual(httpRequest, ""); assertPayloadEquals(httpRequest,// - "----JCLOUDS--\r\n" + // - "Content-Disposition: form-data; name=\"name\"\r\n" + // - "\r\n" + // - "name\r\n" + // / - "----JCLOUDS--\r\n" + // - "Content-Disposition: form-data; name=\"file\"; filename=\"name.tar.gz\"\r\n" + // - "Content-Type: application/octet-stream\r\n" + // - "\r\n" + // - "goo\r\n" + // - "----JCLOUDS----\r\n", "multipart/form-data; boundary=--JCLOUDS--", false); + "----JCLOUDS--\r\n" + // + "Content-Disposition: form-data; name=\"name\"\r\n" + // + "\r\n" + // + "name\r\n" + // / + "----JCLOUDS--\r\n" + // + "Content-Disposition: form-data; name=\"file\"; filename=\"name.tar.gz\"\r\n" + // + "Content-Type: application/octet-stream\r\n" + // + "\r\n" + // + "goo\r\n" + // + "----JCLOUDS----\r\n", "multipart/form-data; boundary=--JCLOUDS--", false); }; public void testMultipartWithParamFileBinaryPart() throws SecurityException, NoSuchMethodException, IOException { @@ -689,20 +703,20 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { file.deleteOnExit(); GeneratedHttpRequest httpRequest = factory(TestMultipartForm.class).createRequest(method, - "name", file); + "name", file); assertRequestLineEquals(httpRequest, "POST http://localhost:9999 HTTP/1.1"); assertNonPayloadHeadersEqual(httpRequest, ""); assertPayloadEquals(httpRequest,// - "----JCLOUDS--\r\n" + // - "Content-Disposition: form-data; name=\"name\"\r\n" + // - "\r\n" + // - "name\r\n" + // / - "----JCLOUDS--\r\n" + // - "Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getName() + "\"\r\n" + // - "Content-Type: application/octet-stream\r\n" + // - "\r\n" + // - "'(2\r\n" + // - "----JCLOUDS----\r\n", "multipart/form-data; boundary=--JCLOUDS--", false); + "----JCLOUDS--\r\n" + // + "Content-Disposition: form-data; name=\"name\"\r\n" + // + "\r\n" + // + "name\r\n" + // / + "----JCLOUDS--\r\n" + // + "Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getName() + "\"\r\n" + // + "Content-Type: application/octet-stream\r\n" + // + "\r\n" + // + "'(2\r\n" + // + "----JCLOUDS----\r\n", "multipart/form-data; boundary=--JCLOUDS--", false); } public interface TestPut { @@ -761,7 +775,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { @Consumes(MediaType.APPLICATION_JSON) ListenableFuture> testUnwrap4(); - @Target( { ElementType.METHOD }) + @Target({ ElementType.METHOD }) @Retention(RetentionPolicy.RUNTIME) @HttpMethod("ROWDY") public @interface ROWDY { @@ -816,7 +830,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { // now test that it works! Function parser = (Function) RestAnnotationProcessor - .createResponseParser(parserFactory, injector, method, request); + .createResponseParser(parserFactory, injector, method, request); assertEquals(parser.apply(new HttpResponse(200, "ok", newStringPayload("{ foo:\"bar\"}"))).foo, "bar"); @@ -831,10 +845,10 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { // now test that it works! Function> parser = (Function>) RestAnnotationProcessor - .createResponseParser(parserFactory, injector, method, request); + .createResponseParser(parserFactory, injector, method, request); - assertEquals(parser.apply(new HttpResponse(200, "ok", newStringPayload("{ foo:\"bar\"}"))), ImmutableMap.of( - "foo", "bar")); + assertEquals(parser.apply(new HttpResponse(200, "ok", newStringPayload("{ foo:\"bar\"}"))), + ImmutableMap.of("foo", "bar")); } @@ -847,10 +861,10 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { // now test that it works! Function> parser = (Function>) RestAnnotationProcessor - .createResponseParser(parserFactory, injector, method, request); + .createResponseParser(parserFactory, injector, method, request); - assertEquals(parser.apply(new HttpResponse(200, "ok", newStringPayload("{ foo:\"bar\"}"))), ImmutableMap.of( - "foo", "bar")); + assertEquals(parser.apply(new HttpResponse(200, "ok", newStringPayload("{ foo:\"bar\"}"))), + ImmutableMap.of("foo", "bar")); } @@ -863,10 +877,10 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { // now test that it works! Function> parser = (Function>) RestAnnotationProcessor - .createResponseParser(parserFactory, injector, method, request); + .createResponseParser(parserFactory, injector, method, request); - assertEquals(parser.apply(new HttpResponse(200, "ok", newStringPayload("{ foo:\"bar\"}"))), ImmutableMap.of( - "foo", "bar")); + assertEquals(parser.apply(new HttpResponse(200, "ok", newStringPayload("{ foo:\"bar\"}"))), + ImmutableMap.of("foo", "bar")); } @@ -879,7 +893,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { // now test that it works! Function> parser = (Function>) RestAnnotationProcessor - .createResponseParser(parserFactory, injector, method, request); + .createResponseParser(parserFactory, injector, method, request); assertEquals(parser.apply(new HttpResponse(200, "ok", newStringPayload("{ foo:\"bar\"}"))), "bar"); @@ -894,7 +908,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { // now test that it works! Function> parser = (Function>) RestAnnotationProcessor - .createResponseParser(parserFactory, injector, method, request); + .createResponseParser(parserFactory, injector, method, request); assertEquals(parser.apply(new HttpResponse(200, "ok", newStringPayload("{ foo:\"bar\"}"))), "bar"); @@ -909,10 +923,10 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { // now test that it works! Function> parser = (Function>) RestAnnotationProcessor - .createResponseParser(parserFactory, injector, method, request); + .createResponseParser(parserFactory, injector, method, request); assertEquals(parser.apply(new HttpResponse(200, "ok", newStringPayload("{\"runit\":[\"0.7.0\",\"0.7.1\"]}"))), - ImmutableSet.of("0.7.0", "0.7.1")); + ImmutableSet.of("0.7.0", "0.7.1")); } @SuppressWarnings("unchecked") @@ -924,10 +938,10 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { // now test that it works! Function> parser = (Function>) RestAnnotationProcessor - .createResponseParser(parserFactory, injector, method, request); + .createResponseParser(parserFactory, injector, method, request); assertEquals(parser.apply(new HttpResponse(200, "ok", newStringPayload("{\"runit\":[\"0.7.0\",\"0.7.1\"]}"))), - ImmutableSet.of("0.7.0", "0.7.1")); + ImmutableSet.of("0.7.0", "0.7.1")); } static class TestRequestFilter1 implements HttpRequestFilter { @@ -1014,7 +1028,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { public void testConstantPathParam() throws SecurityException, NoSuchMethodException, IOException { Method method = TestConstantPathParam.class.getMethod("twoPaths", String.class, String.class); HttpRequest request = factory(TestConstantPathParam.class).createRequest(method, - new Object[] { "1", "localhost" }); + new Object[] { "1", "localhost" }); assertRequestLineEquals(request, "GET http://localhost:9999/v1/ralphie/1/localhost HTTP/1.1"); assertNonPayloadHeadersEqual(request, ""); assertPayloadEquals(request, null, null, false); @@ -1151,7 +1165,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { public void testBuildTwoHeader() throws SecurityException, NoSuchMethodException, UnsupportedEncodingException { Method oneHeader = TestHeader.class.getMethod("twoHeader", String.class); Multimap headers = factory(TestHeader.class).createRequest(oneHeader, new Object[] { "robot" }) - .getHeaders(); + .getHeaders(); assertEquals(headers.size(), 2); assertEquals(headers.get("slash"), Collections.singletonList("/robot")); assertEquals(headers.get("hyphen"), Collections.singletonList("-robot")); @@ -1169,7 +1183,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { public void testBuildOneClassHeader() throws SecurityException, NoSuchMethodException, UnsupportedEncodingException { Method oneHeader = TestClassHeader.class.getMethod("oneHeader", String.class); Multimap headers = factory(TestClassHeader.class).createRequest(oneHeader, - new Object[] { "robot" }).getHeaders(); + new Object[] { "robot" }).getHeaders(); assertEquals(headers.size(), 1); assertEquals(headers.get("x-amz-copy-source"), Collections.singletonList("/robot")); } @@ -1178,7 +1192,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { public void testBuildOneHeader() throws SecurityException, NoSuchMethodException, UnsupportedEncodingException { Method oneHeader = TestHeader.class.getMethod("oneHeader", String.class); Multimap headers = factory(TestHeader.class).createRequest(oneHeader, new Object[] { "robot" }) - .getHeaders(); + .getHeaders(); assertEquals(headers.size(), 1); assertEquals(headers.get("x-amz-copy-source"), Collections.singletonList("/robot")); } @@ -1187,17 +1201,17 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { public void testBuildTwoHeaders() throws SecurityException, NoSuchMethodException, UnsupportedEncodingException { Method twoHeaders = TestHeader.class.getMethod("twoHeaders", String.class, String.class); Multimap headers = factory(TestHeader.class).createRequest(twoHeaders, - new Object[] { "robot", "eggs" }).getHeaders(); + new Object[] { "robot", "eggs" }).getHeaders(); assertEquals(headers.size(), 1); assertEquals(headers.get("x-amz-copy-source"), Collections.singletonList("/robot/eggs")); } @Test public void testBuildTwoHeadersOutOfOrder() throws SecurityException, NoSuchMethodException, - UnsupportedEncodingException { + UnsupportedEncodingException { Method twoHeadersOutOfOrder = TestHeader.class.getMethod("twoHeadersOutOfOrder", String.class, String.class); Multimap headers = factory(TestHeader.class).createRequest(twoHeadersOutOfOrder, - new Object[] { "robot", "eggs" }).getHeaders(); + new Object[] { "robot", "eggs" }).getHeaders(); assertEquals(headers.size(), 1); assertEquals(headers.get("x-amz-copy-source"), Collections.singletonList("/eggs/robot")); } @@ -1211,8 +1225,8 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { @Test public void testQueryInOptions() throws SecurityException, NoSuchMethodException, UnsupportedEncodingException { Method oneQuery = TestQueryReplace.class.getMethod("queryInOptions", String.class, TestReplaceQueryOptions.class); - String query = factory(TestQueryReplace.class).createRequest(oneQuery, - new Object[] { "robot", new TestReplaceQueryOptions() }).getEndpoint().getQuery(); + String query = factory(TestQueryReplace.class) + .createRequest(oneQuery, new Object[] { "robot", new TestReplaceQueryOptions() }).getEndpoint().getQuery(); assertEquals(query, "x-amz-copy-source=/robot"); } @@ -1220,13 +1234,13 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { @POST @Path("/objects/{id}/action/{action}") ListenableFuture action(@PathParam("id") String id, @PathParam("action") String action, - @BinderParam(BindMapToMatrixParams.class) Map options); + @BinderParam(BindMapToMatrixParams.class) Map options); } public void testTestMapMatrixParams() throws SecurityException, NoSuchMethodException, UnsupportedEncodingException { Method method = TestMapMatrixParams.class.getMethod("action", String.class, String.class, Map.class); HttpRequest request = factory(TestMapMatrixParams.class).createRequest(method, - new Object[] { "robot", "kill", ImmutableMap.of("death", "slow") }); + new Object[] { "robot", "kill", ImmutableMap.of("death", "slow") }); assertRequestLineEquals(request, "POST http://localhost:9999/objects/robot/action/kill;death=slow HTTP/1.1"); assertEquals(request.getHeaders().size(), 0); } @@ -1268,7 +1282,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { public void testBuildTwoQuery() throws SecurityException, NoSuchMethodException, UnsupportedEncodingException { Method oneQuery = TestQueryReplace.class.getMethod("twoQuery", String.class); String query = factory(TestQueryReplace.class).createRequest(oneQuery, new Object[] { "robot" }).getEndpoint() - .getQuery(); + .getQuery(); assertEquals(query, "slash=/robot&hyphen=-robot"); } @@ -1284,7 +1298,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { public void testBuildOneClassQuery() throws SecurityException, NoSuchMethodException, UnsupportedEncodingException { Method oneQuery = TestClassQuery.class.getMethod("oneQuery", String.class); String query = factory(TestClassQuery.class).createRequest(oneQuery, new Object[] { "robot" }).getEndpoint() - .getQuery(); + .getQuery(); assertEquals(query, "x-amz-copy-source=/robot"); } @@ -1292,7 +1306,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { public void testBuildOneQuery() throws SecurityException, NoSuchMethodException, UnsupportedEncodingException { Method oneQuery = TestQueryReplace.class.getMethod("oneQuery", String.class); String query = factory(TestQueryReplace.class).createRequest(oneQuery, new Object[] { "robot" }).getEndpoint() - .getQuery(); + .getQuery(); assertEquals(query, "x-amz-copy-source=/robot"); } @@ -1300,16 +1314,16 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { public void testBuildTwoQuerys() throws SecurityException, NoSuchMethodException, UnsupportedEncodingException { Method twoQuerys = TestQueryReplace.class.getMethod("twoQuerys", String.class, String.class); String query = factory(TestQueryReplace.class).createRequest(twoQuerys, new Object[] { "robot", "eggs" }) - .getEndpoint().getQuery(); + .getEndpoint().getQuery(); assertEquals(query, "x-amz-copy-source=/robot/eggs"); } @Test public void testBuildTwoQuerysOutOfOrder() throws SecurityException, NoSuchMethodException, - UnsupportedEncodingException { + UnsupportedEncodingException { Method twoQuerysOutOfOrder = TestQueryReplace.class.getMethod("twoQuerysOutOfOrder", String.class, String.class); - String query = factory(TestQueryReplace.class).createRequest(twoQuerysOutOfOrder, - new Object[] { "robot", "eggs" }).getEndpoint().getQuery(); + String query = factory(TestQueryReplace.class) + .createRequest(twoQuerysOutOfOrder, new Object[] { "robot", "eggs" }).getEndpoint().getQuery(); assertEquals(query, "x-amz-copy-source=/eggs/robot"); } @@ -1322,9 +1336,9 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { @Test public void testMatrixInOptions() throws SecurityException, NoSuchMethodException, UnsupportedEncodingException { Method oneMatrix = TestMatrixReplace.class.getMethod("matrixInOptions", String.class, - TestReplaceMatrixOptions.class); - String path = factory(TestMatrixReplace.class).createRequest(oneMatrix, - new Object[] { "robot", new TestReplaceMatrixOptions() }).getEndpoint().getPath(); + TestReplaceMatrixOptions.class); + String path = factory(TestMatrixReplace.class) + .createRequest(oneMatrix, new Object[] { "robot", new TestReplaceMatrixOptions() }).getEndpoint().getPath(); assertEquals(path, "/;x-amz-copy-source=/robot"); } @@ -1365,7 +1379,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { public void testBuildTwoMatrix() throws SecurityException, NoSuchMethodException, UnsupportedEncodingException { Method oneMatrix = TestMatrixReplace.class.getMethod("twoMatrix", String.class); String path = factory(TestMatrixReplace.class).createRequest(oneMatrix, new Object[] { "robot" }).getEndpoint() - .getPath(); + .getPath(); assertEquals(path, "/;slash=/robot;hyphen=-robot"); } @@ -1382,7 +1396,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { public void testBuildOneClassMatrix() throws SecurityException, NoSuchMethodException, UnsupportedEncodingException { Method oneMatrix = TestClassMatrix.class.getMethod("oneMatrix", String.class); String path = factory(TestClassMatrix.class).createRequest(oneMatrix, new Object[] { "robot" }).getEndpoint() - .getPath(); + .getPath(); assertEquals(path, "/;x-amz-copy-source=/robot"); } @@ -1390,7 +1404,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { public void testBuildOneMatrix() throws SecurityException, NoSuchMethodException, UnsupportedEncodingException { Method oneMatrix = TestMatrixReplace.class.getMethod("oneMatrix", String.class); String path = factory(TestMatrixReplace.class).createRequest(oneMatrix, new Object[] { "robot" }).getEndpoint() - .getPath(); + .getPath(); assertEquals(path, "/;x-amz-copy-source=/robot"); } @@ -1398,17 +1412,17 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { public void testBuildTwoMatrixs() throws SecurityException, NoSuchMethodException, UnsupportedEncodingException { Method twoMatrixs = TestMatrixReplace.class.getMethod("twoMatrixs", String.class, String.class); String path = factory(TestMatrixReplace.class).createRequest(twoMatrixs, new Object[] { "robot", "eggs" }) - .getEndpoint().getPath(); + .getEndpoint().getPath(); assertEquals(path, "/;x-amz-copy-source=/robot/eggs"); } @Test public void testBuildTwoMatrixsOutOfOrder() throws SecurityException, NoSuchMethodException, - UnsupportedEncodingException { + UnsupportedEncodingException { Method twoMatrixsOutOfOrder = TestMatrixReplace.class.getMethod("twoMatrixsOutOfOrder", String.class, - String.class); - String path = factory(TestMatrixReplace.class).createRequest(twoMatrixsOutOfOrder, - new Object[] { "robot", "eggs" }).getEndpoint().getPath(); + String.class); + String path = factory(TestMatrixReplace.class) + .createRequest(twoMatrixsOutOfOrder, new Object[] { "robot", "eggs" }).getEndpoint().getPath(); assertEquals(path, "/;x-amz-copy-source=/eggs/robot"); } @@ -1460,7 +1474,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { public void testPutPayloadEnclosing() throws SecurityException, NoSuchMethodException, IOException { Method method = TestTransformers.class.getMethod("put", PayloadEnclosing.class); HttpRequest request = factory(TestQuery.class).createRequest(method, - new PayloadEnclosingImpl(newStringPayload("whoops"))); + new PayloadEnclosingImpl(newStringPayload("whoops"))); assertRequestLineEquals(request, "PUT http://localhost:9999?x-ms-version=2009-07-17 HTTP/1.1"); assertNonPayloadHeadersEqual(request, ""); assertPayloadEquals(request, "whoops", "application/unknown", false); @@ -1478,7 +1492,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { } public void testPutInputStreamPayloadEnclosingGenerateMD5() throws SecurityException, NoSuchMethodException, - IOException { + IOException { Method method = TestTransformers.class.getMethod("put", PayloadEnclosing.class); PayloadEnclosing payloadEnclosing = new PayloadEnclosingImpl(newInputStreamPayload(toInputStream("whoops"))); @@ -1537,7 +1551,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { } public void testPutPayloadWithGeneratedMD5AndNoContentType() throws SecurityException, NoSuchMethodException, - IOException { + IOException { Payload payload = newStringPayload("whoops"); calculateMD5(payload, crypto.md5()); Method method = TestTransformers.class.getMethod("put", Payload.class); @@ -1558,7 +1572,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { } public void testPutInputStreamPayloadWithMD5() throws NoSuchAlgorithmException, IOException, SecurityException, - NoSuchMethodException { + NoSuchMethodException { Payload payload = newStringPayload("whoops"); calculateMD5(payload, crypto.md5()); Method method = TestTransformers.class.getMethod("put", Payload.class); @@ -1582,9 +1596,9 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { @SuppressWarnings("unchecked") public static Class> unwrap(RestAnnotationProcessor processor, - Method method) { + Method method) { return (Class>) RestAnnotationProcessor.getParserOrThrowException(method) - .getTypeLiteral().getRawType(); + .getTypeLiteral().getRawType(); } public void testURI() throws SecurityException, NoSuchMethodException { @@ -1620,8 +1634,8 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { public void oneTransformerWithContext() throws SecurityException, NoSuchMethodException { RestAnnotationProcessor processor = factory(TestTransformers.class); Method method = TestTransformers.class.getMethod("oneTransformerWithContext"); - GeneratedHttpRequest request = new GeneratedHttpRequest("GET", URI - .create("http://localhost"), TestTransformers.class, method); + GeneratedHttpRequest request = new GeneratedHttpRequest("GET", + URI.create("http://localhost"), TestTransformers.class, method); Function transformer = processor.createResponseParser(method, request); assertEquals(transformer.getClass(), ReturnStringIf200Context.class); assertEquals(((ReturnStringIf200Context) transformer).request, request); @@ -1662,7 +1676,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { @PUT @Path("/{id}") ListenableFuture put(@PathParam("id") @ParamParser(FirstCharacter.class) String id, - @BinderParam(BindToStringPayload.class) String payload); + @BinderParam(BindToStringPayload.class) String payload); @PUT @Path("/{id}") @@ -1674,7 +1688,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { @Headers(keys = "foo", values = "--{id}--") @ResponseParser(ReturnTrueIf2xx.class) ListenableFuture putHeader(@PathParam("id") String id, - @BinderParam(BindToStringPayload.class) String payload); + @BinderParam(BindToStringPayload.class) String payload); } public void testCreateGetVarArgOptionsThatProducesHeaders() throws SecurityException, NoSuchMethodException { @@ -1688,8 +1702,8 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { assertEquals(request.getMethod(), HttpMethod.GET); assertEquals(request.getHeaders().size(), 2); assertEquals(request.getHeaders().get(HttpHeaders.HOST), Collections.singletonList("localhost")); - assertEquals(request.getHeaders().get(HttpHeaders.IF_MODIFIED_SINCE), Collections.singletonList(dateService - .rfc822DateFormat(date))); + assertEquals(request.getHeaders().get(HttpHeaders.IF_MODIFIED_SINCE), + Collections.singletonList(dateService.rfc822DateFormat(date))); } public void testCreateGetOptionsThatProducesHeaders() throws SecurityException, NoSuchMethodException { @@ -1702,8 +1716,8 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { assertEquals(request.getMethod(), HttpMethod.GET); assertEquals(request.getHeaders().size(), 2); assertEquals(request.getHeaders().get(HttpHeaders.HOST), Collections.singletonList("localhost")); - assertEquals(request.getHeaders().get(HttpHeaders.IF_MODIFIED_SINCE), Collections.singletonList(dateService - .rfc822DateFormat(date))); + assertEquals(request.getHeaders().get(HttpHeaders.IF_MODIFIED_SINCE), + Collections.singletonList(dateService.rfc822DateFormat(date))); } public class PrefixOptions extends BaseHttpRequestOptions { @@ -1766,7 +1780,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { @Test(dataProvider = "strings") public void testCreateGetRequest(String key) throws SecurityException, NoSuchMethodException, - UnsupportedEncodingException { + UnsupportedEncodingException { Method method = TestRequest.class.getMethod("get", String.class, String.class); HttpRequest request = factory(TestRequest.class).createRequest(method, new Object[] { key, "localhost" }); assertEquals(request.getEndpoint().getHost(), "localhost"); @@ -1809,7 +1823,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { public void testVirtualHostMethod() throws SecurityException, NoSuchMethodException { Method method = TestVirtualHostMethod.class.getMethod("get", String.class, String.class); HttpRequest request = factory(TestVirtualHostMethod.class).createRequest(method, - new Object[] { "1", "localhost" }); + new Object[] { "1", "localhost" }); assertEquals(request.getEndpoint().getHost(), "localhost"); assertEquals(request.getEndpoint().getPath(), "/1"); assertEquals(request.getMethod(), HttpMethod.GET); @@ -1874,7 +1888,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { public void testOneHeader() throws SecurityException, NoSuchMethodException { Method method = TestHeaders.class.getMethod("oneHeader", String.class); Multimap headers = factory(TestHeaders.class).buildHeaders( - ImmutableMultimap. of().entries(), method, "robot"); + ImmutableMultimap. of().entries(), method, "robot"); assertEquals(headers.size(), 1); assertEquals(headers.get("header"), Collections.singletonList("robot")); } @@ -1883,7 +1897,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { public void testOneIntHeader() throws SecurityException, NoSuchMethodException { Method method = TestHeaders.class.getMethod("oneIntHeader", int.class); Multimap headers = factory(TestHeaders.class).buildHeaders( - ImmutableMultimap. of().entries(), method, 1); + ImmutableMultimap. of().entries(), method, 1); assertEquals(headers.size(), 1); assertEquals(headers.get("header"), Collections.singletonList("1")); } @@ -1892,7 +1906,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { public void testTwoDifferentHeaders() throws SecurityException, NoSuchMethodException { Method method = TestHeaders.class.getMethod("twoDifferentHeaders", String.class, String.class); Multimap headers = factory(TestHeaders.class).buildHeaders( - ImmutableMultimap. of().entries(), method, "robot", "egg"); + ImmutableMultimap. of().entries(), method, "robot", "egg"); assertEquals(headers.size(), 2); assertEquals(headers.get("header1"), Collections.singletonList("robot")); assertEquals(headers.get("header2"), Collections.singletonList("egg")); @@ -1902,7 +1916,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { public void testTwoSameHeaders() throws SecurityException, NoSuchMethodException { Method method = TestHeaders.class.getMethod("twoSameHeaders", String.class, String.class); Multimap headers = factory(TestHeaders.class).buildHeaders( - ImmutableMultimap. of().entries(), method, "robot", "egg"); + ImmutableMultimap. of().entries(), method, "robot", "egg"); assertEquals(headers.size(), 2); Collection values = headers.get("header"); assert values.contains("robot"); @@ -1925,7 +1939,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { @GET void twoEndpointParams(@EndpointParam(parser = ConvertTwoToURI.class) String EndpointParam1, - @EndpointParam(parser = ConvertTwoToURI.class) String EndpointParam2); + @EndpointParam(parser = ConvertTwoToURI.class) String EndpointParam2); @Singleton public static class ConvertTwoToURI implements Function { @@ -1945,7 +1959,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { public void testOneEndpointParam() throws SecurityException, NoSuchMethodException { Method method = TestEndpointParams.class.getMethod("oneEndpointParam", String.class); URI uri = factory(TestEndpointParams.class).getEndpointInParametersOrNull(method, new Object[] { "robot" }, - injector); + injector); assertEquals(uri, URI.create("robot")); } @@ -1955,7 +1969,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { public void testTwoDifferentEndpointParams() throws SecurityException, NoSuchMethodException { Method method = TestEndpointParams.class.getMethod("twoEndpointParams", String.class, String.class); URI uri = factory(TestEndpointParams.class).getEndpointInParametersOrNull(method, - new Object[] { "robot", "egg" }, injector); + new Object[] { "robot", "egg" }, injector); assertEquals(uri, URI.create("robot/egg")); } @@ -1967,12 +1981,12 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { @PUT @Path("/{foo}") public ListenableFuture putWithPath(@PathParam("foo") String path, - @BinderParam(BindToStringPayload.class) String content); + @BinderParam(BindToStringPayload.class) String content); @PUT @Path("") public void twoEntities(@BinderParam(BindToStringPayload.class) String payload1, - @BinderParam(BindToStringPayload.class) String payload2); + @BinderParam(BindToStringPayload.class) String payload2); } @Test @@ -2070,23 +2084,23 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { public void testBuildTwoForms() throws SecurityException, NoSuchMethodException, UnsupportedEncodingException { Method twoForms = TestFormReplace.class.getMethod("twoForms", String.class, String.class); Object form = factory(TestFormReplace.class).createRequest(twoForms, "robot", "eggs").getPayload() - .getRawContent(); + .getRawContent(); assertEquals(form, "x-amz-copy-source=/robot/eggs"); } @Test public void testBuildTwoFormsOutOfOrder() throws SecurityException, NoSuchMethodException, - UnsupportedEncodingException { + UnsupportedEncodingException { Method twoFormsOutOfOrder = TestFormReplace.class.getMethod("twoFormsOutOfOrder", String.class, String.class); Object form = factory(TestFormReplace.class).createRequest(twoFormsOutOfOrder, "robot", "eggs").getPayload() - .getRawContent(); + .getRawContent(); assertEquals(form, "x-amz-copy-source=/eggs/robot"); } @SuppressWarnings("unchecked") private RestAnnotationProcessor factory(Class clazz) { return ((RestAnnotationProcessor) injector.getInstance(Key.get(newParameterizedType( - RestAnnotationProcessor.class, clazz)))); + RestAnnotationProcessor.class, clazz)))); } DateService dateService = new SimpleDateFormatDateService(); @@ -2094,16 +2108,15 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { @BeforeClass void setupFactory() { RestContextSpec contextSpec = contextSpec("test", "http://localhost:9999", "1", "userfoo", null, - String.class, Integer.class, ImmutableSet. of(new MockModule(), new NullLoggingModule(), - new AbstractModule() { + String.class, Integer.class, + ImmutableSet. of(new MockModule(), new NullLoggingModule(), new AbstractModule() { - @Override - protected void configure() { - bind(URI.class).annotatedWith(Localhost2.class).toInstance( - URI.create("http://localhost:1111")); - } + @Override + protected void configure() { + bind(URI.class).annotatedWith(Localhost2.class).toInstance(URI.create("http://localhost:1111")); + } - })); + })); injector = createContextBuilder(contextSpec).buildInjector(); parserFactory = injector.getInstance(ParseSax.Factory.class); diff --git a/sandbox/elasticstack/src/test/java/org/jclouds/elasticstack/ElasticStackAsyncClientTest.java b/sandbox/elasticstack/src/test/java/org/jclouds/elasticstack/ElasticStackAsyncClientTest.java index b3ab118918..ae372f4216 100644 --- a/sandbox/elasticstack/src/test/java/org/jclouds/elasticstack/ElasticStackAsyncClientTest.java +++ b/sandbox/elasticstack/src/test/java/org/jclouds/elasticstack/ElasticStackAsyncClientTest.java @@ -300,7 +300,7 @@ public class ElasticStackAsyncClientTest extends RestClientTest Date: Sun, 5 Dec 2010 12:46:34 +0000 Subject: [PATCH 26/31] Issue 385: exposed underlying client and means to test --- ...tandaloneComputeServiceContextBuilder.java | 9 +- .../StandaloneComputeServiceContextSpec.java | 26 ++- ...StandaloneComputeServiceContextModule.java | 24 ++- .../StubComputeServiceContextBuilder.java | 6 +- .../StubComputeServiceContextModule.java | 15 ++ .../compute/BaseComputeServiceLiveTest.java | 7 +- .../ComputeServiceContextFactoryTest.java | 11 +- .../src/main/java/org/jclouds/util/Utils.java | 10 +- .../test/java/org/jclouds/util/UtilsTest.java | 6 + .../LibvirtComputeServiceContextBuilder.java | 20 +-- ...bvirtComputeServiceContextBuilderTest.java | 39 ++++- .../LibvirtComputeServiceLiveTest.java | 55 +++++++ .../jclouds/{vsphere => vi}/Datacenter.java | 2 +- .../org/jclouds/{vsphere => vi}/Image.java | 2 +- .../jclouds/{vsphere => vi}/ViConstants.java | 2 +- .../compute/ViComputeService.java | 2 +- .../ViComputeServiceContextBuilder.java | 25 ++- .../compute/ViComputeServiceContextSpec.java | 2 +- .../compute/ViPropertiesBuilder.java | 4 +- .../config/ViComputeServiceContextModule.java | 147 +++++++++++++++++ .../functions/DatacenterToLocation.java | 4 +- .../functions/LibvirtNodeToLocation.java | 4 +- .../compute/functions/ViImageToImage.java | 6 +- .../functions/VirtualMachineToHardware.java | 2 +- .../VirtualMachineToNodeMetadata.java | 2 +- .../strategy/ViComputeServiceAdapter.java | 8 +- .../domain/ViComputeServiceContextModule.java | 151 ------------------ .../ViComputeServiceContextBuilderTest.java | 53 ++++++ .../vi/compute/ViComputeServiceLiveTest.java | 56 +++++++ .../compute/ViExperimentLiveTest.java | 4 +- .../ViComputeServiceContextBuilderTest.java | 33 ---- ...erManagerComputeServiceContextBuilder.java | 49 +----- ...verManagerComputeServiceContextModule.java | 63 ++++++++ ...nagerComputeServiceContextBuilderTest.java | 60 +++++-- .../ServerManagerComputeServiceLiveTest.java | 56 +++++++ .../ServerManagerExperimentLiveTest.java | 7 +- 36 files changed, 648 insertions(+), 324 deletions(-) create mode 100644 sandbox/libvirt/src/test/java/org/jclouds/libvirt/compute/LibvirtComputeServiceLiveTest.java rename sandbox/vsphere/src/main/java/org/jclouds/{vsphere => vi}/Datacenter.java (98%) rename sandbox/vsphere/src/main/java/org/jclouds/{vsphere => vi}/Image.java (98%) rename sandbox/vsphere/src/main/java/org/jclouds/{vsphere => vi}/ViConstants.java (97%) rename sandbox/vsphere/src/main/java/org/jclouds/{vsphere => vi}/compute/ViComputeService.java (99%) rename sandbox/vsphere/src/main/java/org/jclouds/{vsphere => vi}/compute/ViComputeServiceContextBuilder.java (62%) rename sandbox/vsphere/src/main/java/org/jclouds/{vsphere => vi}/compute/ViComputeServiceContextSpec.java (97%) rename sandbox/vsphere/src/main/java/org/jclouds/{vsphere => vi}/compute/ViPropertiesBuilder.java (94%) create mode 100644 sandbox/vsphere/src/main/java/org/jclouds/vi/compute/config/ViComputeServiceContextModule.java rename sandbox/vsphere/src/main/java/org/jclouds/{vsphere => vi}/compute/functions/DatacenterToLocation.java (93%) rename sandbox/vsphere/src/main/java/org/jclouds/{vsphere => vi}/compute/functions/LibvirtNodeToLocation.java (93%) rename sandbox/vsphere/src/main/java/org/jclouds/{vsphere => vi}/compute/functions/ViImageToImage.java (90%) rename sandbox/vsphere/src/main/java/org/jclouds/{vsphere => vi}/compute/functions/VirtualMachineToHardware.java (98%) rename sandbox/vsphere/src/main/java/org/jclouds/{vsphere => vi}/compute/functions/VirtualMachineToNodeMetadata.java (99%) rename sandbox/vsphere/src/main/java/org/jclouds/{vsphere => vi}/compute/strategy/ViComputeServiceAdapter.java (98%) delete mode 100644 sandbox/vsphere/src/main/java/org/jclouds/vsphere/compute/domain/ViComputeServiceContextModule.java create mode 100644 sandbox/vsphere/src/test/java/org/jclouds/vi/compute/ViComputeServiceContextBuilderTest.java create mode 100644 sandbox/vsphere/src/test/java/org/jclouds/vi/compute/ViComputeServiceLiveTest.java rename sandbox/vsphere/src/test/java/org/jclouds/{vsphere => vi}/compute/ViExperimentLiveTest.java (97%) delete mode 100644 sandbox/vsphere/src/test/java/org/jclouds/vsphere/compute/ViComputeServiceContextBuilderTest.java create mode 100644 skeletons/standalone-compute/src/main/java/org/jclouds/servermanager/compute/config/ServerManagerComputeServiceContextModule.java create mode 100644 skeletons/standalone-compute/src/test/java/org/jclouds/servermanager/compute/ServerManagerComputeServiceLiveTest.java diff --git a/compute/src/main/java/org/jclouds/compute/StandaloneComputeServiceContextBuilder.java b/compute/src/main/java/org/jclouds/compute/StandaloneComputeServiceContextBuilder.java index 7c18b05c9b..b805ad9310 100644 --- a/compute/src/main/java/org/jclouds/compute/StandaloneComputeServiceContextBuilder.java +++ b/compute/src/main/java/org/jclouds/compute/StandaloneComputeServiceContextBuilder.java @@ -35,11 +35,10 @@ import com.google.inject.Module; * * @author Adrian Cole */ -public class StandaloneComputeServiceContextBuilder extends - ComputeServiceContextBuilder { +public class StandaloneComputeServiceContextBuilder extends ComputeServiceContextBuilder { - public StandaloneComputeServiceContextBuilder(Properties props) { - super(ComputeService.class, ComputeService.class, props); + public StandaloneComputeServiceContextBuilder(Class driverClass, Properties props) { + super(driverClass, driverClass, props); if (properties.size() == 0) properties.putAll(new PropertiesBuilder().build()); if (!properties.containsKey("jclouds.provider")) @@ -54,7 +53,7 @@ public class StandaloneComputeServiceContextBuilder extends @Override protected void addClientModule(List modules) { - modules.add(new StandaloneComputeServiceClientModule(ComputeService.class)); + modules.add(new StandaloneComputeServiceClientModule(syncClientType)); } } \ No newline at end of file diff --git a/compute/src/main/java/org/jclouds/compute/StandaloneComputeServiceContextSpec.java b/compute/src/main/java/org/jclouds/compute/StandaloneComputeServiceContextSpec.java index 0dc354a0e2..9d0ab8c5f4 100644 --- a/compute/src/main/java/org/jclouds/compute/StandaloneComputeServiceContextSpec.java +++ b/compute/src/main/java/org/jclouds/compute/StandaloneComputeServiceContextSpec.java @@ -20,24 +20,34 @@ package org.jclouds.compute; import org.jclouds.PropertiesBuilder; -import org.jclouds.compute.config.StandaloneComputeServiceContextModule; import org.jclouds.rest.RestContextSpec; import com.google.common.collect.ImmutableSet; -import com.google.common.collect.Iterables; import com.google.inject.Module; /** * @author Adrian Cole */ -public class StandaloneComputeServiceContextSpec extends RestContextSpec { +public class StandaloneComputeServiceContextSpec extends RestContextSpec { + public StandaloneComputeServiceContextSpec(String provider, String endpoint, String apiVersion, String identity, + String credential, Class driverClass, + Class> contextBuilderClass) { + this(provider, endpoint, apiVersion, identity, credential, driverClass, contextBuilderClass, ImmutableSet + . of()); + } + + public StandaloneComputeServiceContextSpec(String provider, String endpoint, String apiVersion, String identity, + String credential, Class driverClass, + Class> contextBuilderClass, Iterable modules) { + this(provider, endpoint, apiVersion, identity, credential, driverClass, PropertiesBuilder.class, + contextBuilderClass, modules); + } @SuppressWarnings({ "unchecked", "rawtypes" }) public StandaloneComputeServiceContextSpec(String provider, String endpoint, String apiVersion, String identity, - String credential, StandaloneComputeServiceContextModule contextModule, Iterable modules) { - super(provider, endpoint, apiVersion, identity, credential, ComputeService.class, ComputeService.class, - PropertiesBuilder.class, (Class) StandaloneComputeServiceContextBuilder.class, Iterables.concat( - ImmutableSet.of(contextModule), modules)); + String credential, Class driverClass, Class propertiesBuilderClass, + Class> contextBuilderClass, Iterable modules) { + super(provider, endpoint, apiVersion, identity, credential, driverClass, driverClass, + (Class) propertiesBuilderClass, (Class) contextBuilderClass, modules); } - } \ No newline at end of file diff --git a/compute/src/main/java/org/jclouds/compute/config/JCloudsNativeStandaloneComputeServiceContextModule.java b/compute/src/main/java/org/jclouds/compute/config/JCloudsNativeStandaloneComputeServiceContextModule.java index 1ef63a6ec6..48502b3c89 100644 --- a/compute/src/main/java/org/jclouds/compute/config/JCloudsNativeStandaloneComputeServiceContextModule.java +++ b/compute/src/main/java/org/jclouds/compute/config/JCloudsNativeStandaloneComputeServiceContextModule.java @@ -1,7 +1,25 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + package org.jclouds.compute.config; import org.jclouds.compute.ComputeServiceAdapter; -import org.jclouds.compute.config.StandaloneComputeServiceContextModule; import org.jclouds.compute.domain.Hardware; import org.jclouds.compute.domain.Image; import org.jclouds.compute.domain.NodeMetadata; @@ -10,6 +28,10 @@ import org.jclouds.domain.Location; import com.google.common.base.Function; import com.google.inject.TypeLiteral; +/** + * + * @author Adrian Cole + */ public class JCloudsNativeStandaloneComputeServiceContextModule extends StandaloneComputeServiceContextModule { private final Class> adapter; diff --git a/compute/src/main/java/org/jclouds/compute/stub/StubComputeServiceContextBuilder.java b/compute/src/main/java/org/jclouds/compute/stub/StubComputeServiceContextBuilder.java index d9b614c3cd..bc9af50837 100644 --- a/compute/src/main/java/org/jclouds/compute/stub/StubComputeServiceContextBuilder.java +++ b/compute/src/main/java/org/jclouds/compute/stub/StubComputeServiceContextBuilder.java @@ -21,6 +21,7 @@ package org.jclouds.compute.stub; import java.util.List; import java.util.Properties; +import java.util.concurrent.ConcurrentMap; import org.jclouds.compute.StandaloneComputeServiceContextBuilder; import org.jclouds.compute.stub.config.StubComputeServiceContextModule; @@ -31,10 +32,11 @@ import com.google.inject.Module; * * @author Adrian Cole */ -public class StubComputeServiceContextBuilder extends StandaloneComputeServiceContextBuilder { +@SuppressWarnings("rawtypes") +public class StubComputeServiceContextBuilder extends StandaloneComputeServiceContextBuilder { public StubComputeServiceContextBuilder(Properties props) { - super(props); + super(ConcurrentMap.class, props); } @Override diff --git a/compute/src/main/java/org/jclouds/compute/stub/config/StubComputeServiceContextModule.java b/compute/src/main/java/org/jclouds/compute/stub/config/StubComputeServiceContextModule.java index a298e6c6a1..fe61f1df32 100644 --- a/compute/src/main/java/org/jclouds/compute/stub/config/StubComputeServiceContextModule.java +++ b/compute/src/main/java/org/jclouds/compute/stub/config/StubComputeServiceContextModule.java @@ -19,9 +19,16 @@ package org.jclouds.compute.stub.config; +import java.util.concurrent.ConcurrentMap; + +import javax.inject.Singleton; + import org.jclouds.compute.config.JCloudsNativeStandaloneComputeServiceContextModule; +import org.jclouds.compute.domain.NodeMetadata; import org.jclouds.concurrent.SingleThreaded; +import com.google.inject.Provides; + /** * * @author Adrian Cole @@ -33,6 +40,14 @@ public class StubComputeServiceContextModule extends JCloudsNativeStandaloneComp super(StubComputeServiceAdapter.class); } + // Ensure that a plain class is able to be bound as getProviderSpecificContext.getApi() + @SuppressWarnings("rawtypes") + @Provides + @Singleton + ConcurrentMap provideApi(ConcurrentMap in) { + return in; + } + @Override protected void configure() { install(new StubComputeServiceDependenciesModule()); diff --git a/compute/src/test/java/org/jclouds/compute/BaseComputeServiceLiveTest.java b/compute/src/test/java/org/jclouds/compute/BaseComputeServiceLiveTest.java index d01e7d5244..72b376e831 100755 --- a/compute/src/test/java/org/jclouds/compute/BaseComputeServiceLiveTest.java +++ b/compute/src/test/java/org/jclouds/compute/BaseComputeServiceLiveTest.java @@ -74,6 +74,7 @@ import org.jclouds.net.IPSocket; import org.jclouds.predicates.RetryablePredicate; import org.jclouds.predicates.SocketOpen; import org.jclouds.rest.AuthorizationException; +import org.jclouds.rest.RestContextFactory; import org.jclouds.scriptbuilder.domain.OsFamily; import org.jclouds.ssh.ExecResponse; import org.jclouds.ssh.SshClient; @@ -161,11 +162,15 @@ public abstract class BaseComputeServiceLiveTest { if (context != null) context.close(); Properties props = setupProperties(); - context = new ComputeServiceContextFactory().createContext(provider, + context = new ComputeServiceContextFactory(getRestProperties()).createContext(provider, ImmutableSet.of(new Log4JLoggingModule(), getSshModule()), props); client = context.getComputeService(); } + protected Properties getRestProperties() { + return RestContextFactory.getPropertiesFromResource("/rest.properties"); + } + abstract protected Module getSshModule(); // wait up to 5 seconds for an auth exception diff --git a/compute/src/test/java/org/jclouds/compute/ComputeServiceContextFactoryTest.java b/compute/src/test/java/org/jclouds/compute/ComputeServiceContextFactoryTest.java index c3a72d6917..a13843e384 100644 --- a/compute/src/test/java/org/jclouds/compute/ComputeServiceContextFactoryTest.java +++ b/compute/src/test/java/org/jclouds/compute/ComputeServiceContextFactoryTest.java @@ -19,10 +19,12 @@ package org.jclouds.compute; +import java.util.concurrent.ConcurrentMap; + import org.jclouds.compute.domain.Hardware; import org.jclouds.compute.domain.Image; import org.jclouds.compute.domain.NodeMetadata; -import org.jclouds.compute.stub.config.StubComputeServiceContextModule; +import org.jclouds.compute.stub.StubComputeServiceContextBuilder; import org.jclouds.domain.Location; import org.testng.annotations.Test; @@ -39,10 +41,11 @@ public class ComputeServiceContextFactoryTest { @Test public void testStandalone() { + @SuppressWarnings("rawtypes") ComputeServiceContext context = new ComputeServiceContextFactory() - .createContext(new StandaloneComputeServiceContextSpec("stub", - "stub", "1", "identity", "credential", new StubComputeServiceContextModule(), ImmutableSet - . of())); + .createContext(new StandaloneComputeServiceContextSpec( + "stub", "stub", "1", "identity", "credential", ConcurrentMap.class, + StubComputeServiceContextBuilder.class, ImmutableSet. of())); context.getComputeService().listNodes(); } diff --git a/core/src/main/java/org/jclouds/util/Utils.java b/core/src/main/java/org/jclouds/util/Utils.java index fabf3de3e3..c0a745367a 100644 --- a/core/src/main/java/org/jclouds/util/Utils.java +++ b/core/src/main/java/org/jclouds/util/Utils.java @@ -195,10 +195,12 @@ public class Utils { public static T getFirstThrowableOfType(ProvisionException e, Class clazz) { for (Message message : e.getErrorMessages()) { - T cause = getFirstThrowableOfType(message.getCause(), clazz); - if (cause instanceof ProvisionException) - return getFirstThrowableOfType(ProvisionException.class.cast(cause), clazz); - return cause; + if (message.getCause() != null) { + T cause = getFirstThrowableOfType(message.getCause(), clazz); + if (cause instanceof ProvisionException) + return getFirstThrowableOfType(ProvisionException.class.cast(cause), clazz); + return cause; + } } return null; } diff --git a/core/src/test/java/org/jclouds/util/UtilsTest.java b/core/src/test/java/org/jclouds/util/UtilsTest.java index 8a5de24518..3e8704cd92 100644 --- a/core/src/test/java/org/jclouds/util/UtilsTest.java +++ b/core/src/test/java/org/jclouds/util/UtilsTest.java @@ -105,6 +105,12 @@ public class UtilsTest { ProvisionException pex = new ProvisionException(ImmutableSet.of(message)); assertEquals(Utils.getFirstThrowableOfType(pex, AuthorizationException.class), null); } + + public void testGetFirstThrowableOfTypeWhenCauseIsNull() { + Message message = new Message(ImmutableList.of(), "test", null); + ProvisionException pex = new ProvisionException(ImmutableSet.of(message)); + assertEquals(Utils.getFirstThrowableOfType(pex, AuthorizationException.class), null); + } public void testReplaceTokens() throws UnsupportedEncodingException { assertEquals(Utils.replaceTokens("hello {where}", ImmutableMap.of("where", "world")), "hello world"); diff --git a/sandbox/libvirt/src/main/java/org/jclouds/libvirt/compute/LibvirtComputeServiceContextBuilder.java b/sandbox/libvirt/src/main/java/org/jclouds/libvirt/compute/LibvirtComputeServiceContextBuilder.java index 0aa12766b5..110cddaac2 100644 --- a/sandbox/libvirt/src/main/java/org/jclouds/libvirt/compute/LibvirtComputeServiceContextBuilder.java +++ b/sandbox/libvirt/src/main/java/org/jclouds/libvirt/compute/LibvirtComputeServiceContextBuilder.java @@ -25,11 +25,8 @@ import java.util.List; import java.util.Properties; import org.jclouds.compute.StandaloneComputeServiceContextBuilder; -import org.jclouds.compute.config.StandaloneComputeServiceContextModule; -import org.jclouds.libvirt.Datacenter; -import org.jclouds.libvirt.Image; import org.jclouds.libvirt.compute.domain.LibvirtComputeServiceContextModule; -import org.libvirt.Domain; +import org.libvirt.Connect; import com.google.inject.Module; @@ -37,22 +34,17 @@ import com.google.inject.Module; * * @author Adrian Cole */ -public class LibvirtComputeServiceContextBuilder extends StandaloneComputeServiceContextBuilder { +public class LibvirtComputeServiceContextBuilder extends StandaloneComputeServiceContextBuilder { public LibvirtComputeServiceContextBuilder(Properties props) { - super(props); - + super(Connect.class, props); + if (!properties.containsKey(PROPERTY_LIBVIRT_DOMAIN_DIR)) - properties.setProperty(PROPERTY_LIBVIRT_DOMAIN_DIR, "/etc/libvirt/qemu"); + properties.setProperty(PROPERTY_LIBVIRT_DOMAIN_DIR, "/etc/libvirt/qemu"); } @Override protected void addContextModule(List modules) { - modules.add(createContextModule()); + modules.add(new LibvirtComputeServiceContextModule()); } - - public StandaloneComputeServiceContextModule createContextModule() { - return new LibvirtComputeServiceContextModule(); - } - } diff --git a/sandbox/libvirt/src/test/java/org/jclouds/libvirt/compute/LibvirtComputeServiceContextBuilderTest.java b/sandbox/libvirt/src/test/java/org/jclouds/libvirt/compute/LibvirtComputeServiceContextBuilderTest.java index 60e094a5fc..9b7732630a 100644 --- a/sandbox/libvirt/src/test/java/org/jclouds/libvirt/compute/LibvirtComputeServiceContextBuilderTest.java +++ b/sandbox/libvirt/src/test/java/org/jclouds/libvirt/compute/LibvirtComputeServiceContextBuilderTest.java @@ -1,11 +1,13 @@ package org.jclouds.libvirt.compute; -import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.assertEquals; import java.util.Properties; import org.jclouds.compute.ComputeServiceContext; import org.jclouds.compute.ComputeServiceContextFactory; +import org.jclouds.rest.RestContext; +import org.libvirt.Connect; import org.testng.annotations.Test; /** @@ -16,11 +18,6 @@ import org.testng.annotations.Test; @Test(groups = "unit") public class LibvirtComputeServiceContextBuilderTest { - @Test - public void testCreateContextModule() { - assertNotNull(new LibvirtComputeServiceContextBuilder(new Properties()).createContextModule()); - } - @Test public void testCanBuildWithComputeService() { ComputeServiceContext context = new ComputeServiceContextFactory() @@ -28,4 +25,34 @@ public class LibvirtComputeServiceContextBuilderTest { // System.err.println(context.getComputeService(). context.close(); } + + @Test + public void testCanBuildWithRestProperties() { + Properties restProperties = new Properties(); + restProperties.setProperty("libvirt.contextbuilder", LibvirtComputeServiceContextBuilder.class.getName()); + restProperties.setProperty("libvirt.propertiesbuilder", LibvirtPropertiesBuilder.class.getName()); + restProperties.setProperty("libvirt.endpoint", "test:///default"); + + ComputeServiceContext context = new ComputeServiceContextFactory(restProperties).createContext("libvirt", + "identity", "credential"); + + context.close(); + } + + @Test + public void testProviderSpecificContextIsCorrectType() { + Properties restProperties = new Properties(); + restProperties.setProperty("libvirt.contextbuilder", LibvirtComputeServiceContextBuilder.class.getName()); + restProperties.setProperty("libvirt.propertiesbuilder", LibvirtPropertiesBuilder.class.getName()); + restProperties.setProperty("libvirt.endpoint", "test:///default"); + + ComputeServiceContext context = new ComputeServiceContextFactory(restProperties).createContext("libvirt", + "identity", "credential"); + + RestContext providerContext = context.getProviderSpecificContext(); + + assertEquals(providerContext.getApi().getClass(), Connect.class); + + context.close(); + } } diff --git a/sandbox/libvirt/src/test/java/org/jclouds/libvirt/compute/LibvirtComputeServiceLiveTest.java b/sandbox/libvirt/src/test/java/org/jclouds/libvirt/compute/LibvirtComputeServiceLiveTest.java new file mode 100644 index 0000000000..8bac5ef16a --- /dev/null +++ b/sandbox/libvirt/src/test/java/org/jclouds/libvirt/compute/LibvirtComputeServiceLiveTest.java @@ -0,0 +1,55 @@ +package org.jclouds.libvirt.compute; + +import static org.jclouds.compute.util.ComputeServiceUtils.getCores; +import static org.testng.Assert.assertEquals; + +import java.util.Properties; + +import org.jclouds.compute.BaseComputeServiceLiveTest; +import org.jclouds.compute.ComputeServiceContextFactory; +import org.jclouds.compute.domain.OsFamily; +import org.jclouds.compute.domain.Template; +import org.jclouds.rest.RestContext; +import org.jclouds.ssh.jsch.config.JschSshClientModule; +import org.libvirt.Connect; +import org.testng.annotations.Test; + +/** + * @author Adrian Cole + */ +@Test(groups = "live", enabled = true, sequential = true, testName = "libvirt.LibvirtComputeServiceLiveTest") +public class LibvirtComputeServiceLiveTest extends BaseComputeServiceLiveTest { + public LibvirtComputeServiceLiveTest() { + provider = "libvirt"; + } + + @Override + protected Properties getRestProperties() { + Properties restProperties = new Properties(); + restProperties.setProperty("libvirt.contextbuilder", LibvirtComputeServiceContextBuilder.class.getName()); + restProperties.setProperty("libvirt.propertiesbuilder", LibvirtPropertiesBuilder.class.getName()); + restProperties.setProperty("libvirt.endpoint", "test:///default"); + return restProperties; + } + + @Test + public void testTemplateBuilder() { + Template defaultTemplate = client.templateBuilder().build(); + assertEquals(defaultTemplate.getImage().getOperatingSystem().is64Bit(), true); + assertEquals(defaultTemplate.getImage().getOperatingSystem().getVersion(), "5.3"); + assertEquals(defaultTemplate.getImage().getOperatingSystem().getFamily(), OsFamily.CENTOS); + assertEquals(defaultTemplate.getLocation().getId(), "1"); + assertEquals(getCores(defaultTemplate.getHardware()), 0.5d); + } + + @Override + protected JschSshClientModule getSshModule() { + return new JschSshClientModule(); + } + + public void testAssignability() throws Exception { + @SuppressWarnings("unused") + RestContext goGridContext = new ComputeServiceContextFactory().createContext(provider, + identity, credential).getProviderSpecificContext(); + } +} diff --git a/sandbox/vsphere/src/main/java/org/jclouds/vsphere/Datacenter.java b/sandbox/vsphere/src/main/java/org/jclouds/vi/Datacenter.java similarity index 98% rename from sandbox/vsphere/src/main/java/org/jclouds/vsphere/Datacenter.java rename to sandbox/vsphere/src/main/java/org/jclouds/vi/Datacenter.java index 4224d9250e..b1312ab871 100644 --- a/sandbox/vsphere/src/main/java/org/jclouds/vsphere/Datacenter.java +++ b/sandbox/vsphere/src/main/java/org/jclouds/vi/Datacenter.java @@ -17,7 +17,7 @@ * ==================================================================== */ -package org.jclouds.vsphere; +package org.jclouds.vi; import com.google.common.base.Objects; diff --git a/sandbox/vsphere/src/main/java/org/jclouds/vsphere/Image.java b/sandbox/vsphere/src/main/java/org/jclouds/vi/Image.java similarity index 98% rename from sandbox/vsphere/src/main/java/org/jclouds/vsphere/Image.java rename to sandbox/vsphere/src/main/java/org/jclouds/vi/Image.java index 0a3f5fbe2e..069b5bfd67 100644 --- a/sandbox/vsphere/src/main/java/org/jclouds/vsphere/Image.java +++ b/sandbox/vsphere/src/main/java/org/jclouds/vi/Image.java @@ -17,7 +17,7 @@ * ==================================================================== */ -package org.jclouds.vsphere; +package org.jclouds.vi; import com.google.common.base.Objects; diff --git a/sandbox/vsphere/src/main/java/org/jclouds/vsphere/ViConstants.java b/sandbox/vsphere/src/main/java/org/jclouds/vi/ViConstants.java similarity index 97% rename from sandbox/vsphere/src/main/java/org/jclouds/vsphere/ViConstants.java rename to sandbox/vsphere/src/main/java/org/jclouds/vi/ViConstants.java index d015691241..98804ca8c0 100644 --- a/sandbox/vsphere/src/main/java/org/jclouds/vsphere/ViConstants.java +++ b/sandbox/vsphere/src/main/java/org/jclouds/vi/ViConstants.java @@ -17,7 +17,7 @@ * ==================================================================== */ -package org.jclouds.vsphere; +package org.jclouds.vi; /** * Configuration properties and constants used in libvirt local connections. diff --git a/sandbox/vsphere/src/main/java/org/jclouds/vsphere/compute/ViComputeService.java b/sandbox/vsphere/src/main/java/org/jclouds/vi/compute/ViComputeService.java similarity index 99% rename from sandbox/vsphere/src/main/java/org/jclouds/vsphere/compute/ViComputeService.java rename to sandbox/vsphere/src/main/java/org/jclouds/vi/compute/ViComputeService.java index a2531da66f..f5b240a3fa 100644 --- a/sandbox/vsphere/src/main/java/org/jclouds/vsphere/compute/ViComputeService.java +++ b/sandbox/vsphere/src/main/java/org/jclouds/vi/compute/ViComputeService.java @@ -17,7 +17,7 @@ * ==================================================================== */ -package org.jclouds.vsphere.compute; +package org.jclouds.vi.compute; import java.io.StringReader; import java.util.Map; diff --git a/sandbox/vsphere/src/main/java/org/jclouds/vsphere/compute/ViComputeServiceContextBuilder.java b/sandbox/vsphere/src/main/java/org/jclouds/vi/compute/ViComputeServiceContextBuilder.java similarity index 62% rename from sandbox/vsphere/src/main/java/org/jclouds/vsphere/compute/ViComputeServiceContextBuilder.java rename to sandbox/vsphere/src/main/java/org/jclouds/vi/compute/ViComputeServiceContextBuilder.java index fe6f3b1678..8baff48f3d 100644 --- a/sandbox/vsphere/src/main/java/org/jclouds/vsphere/compute/ViComputeServiceContextBuilder.java +++ b/sandbox/vsphere/src/main/java/org/jclouds/vi/compute/ViComputeServiceContextBuilder.java @@ -17,42 +17,35 @@ * ==================================================================== */ -package org.jclouds.vsphere.compute; +package org.jclouds.vi.compute; -import static org.jclouds.vsphere.ViConstants.PROPERTY_LIBVIRT_DOMAIN_DIR; +import static org.jclouds.vi.ViConstants.PROPERTY_LIBVIRT_DOMAIN_DIR; import java.util.List; import java.util.Properties; import org.jclouds.compute.StandaloneComputeServiceContextBuilder; -import org.jclouds.compute.config.StandaloneComputeServiceContextModule; -import org.jclouds.vsphere.Datacenter; -import org.jclouds.vsphere.Image; -import org.jclouds.vsphere.compute.domain.ViComputeServiceContextModule; +import org.jclouds.vi.compute.config.ViComputeServiceContextModule; import com.google.inject.Module; -import com.vmware.vim25.mo.VirtualMachine; +import com.vmware.vim25.mo.ServiceInstance; /** * * @author Adrian Cole */ -public class ViComputeServiceContextBuilder extends StandaloneComputeServiceContextBuilder { +public class ViComputeServiceContextBuilder extends StandaloneComputeServiceContextBuilder { public ViComputeServiceContextBuilder(Properties props) { - super(props); - + super(ServiceInstance.class, props); + if (!properties.containsKey(PROPERTY_LIBVIRT_DOMAIN_DIR)) - properties.setProperty(PROPERTY_LIBVIRT_DOMAIN_DIR, "/etc/libvirt/qemu"); + properties.setProperty(PROPERTY_LIBVIRT_DOMAIN_DIR, "/etc/libvirt/qemu"); } @Override protected void addContextModule(List modules) { - modules.add(createContextModule()); - } - - public StandaloneComputeServiceContextModule createContextModule() { - return new ViComputeServiceContextModule(); + modules.add(new ViComputeServiceContextModule()); } } diff --git a/sandbox/vsphere/src/main/java/org/jclouds/vsphere/compute/ViComputeServiceContextSpec.java b/sandbox/vsphere/src/main/java/org/jclouds/vi/compute/ViComputeServiceContextSpec.java similarity index 97% rename from sandbox/vsphere/src/main/java/org/jclouds/vsphere/compute/ViComputeServiceContextSpec.java rename to sandbox/vsphere/src/main/java/org/jclouds/vi/compute/ViComputeServiceContextSpec.java index 3108857787..c28e15f75c 100644 --- a/sandbox/vsphere/src/main/java/org/jclouds/vsphere/compute/ViComputeServiceContextSpec.java +++ b/sandbox/vsphere/src/main/java/org/jclouds/vi/compute/ViComputeServiceContextSpec.java @@ -17,7 +17,7 @@ * ==================================================================== */ -package org.jclouds.vsphere.compute; +package org.jclouds.vi.compute; import org.jclouds.PropertiesBuilder; import org.jclouds.compute.ComputeService; diff --git a/sandbox/vsphere/src/main/java/org/jclouds/vsphere/compute/ViPropertiesBuilder.java b/sandbox/vsphere/src/main/java/org/jclouds/vi/compute/ViPropertiesBuilder.java similarity index 94% rename from sandbox/vsphere/src/main/java/org/jclouds/vsphere/compute/ViPropertiesBuilder.java rename to sandbox/vsphere/src/main/java/org/jclouds/vi/compute/ViPropertiesBuilder.java index 4089ca9b9c..98a154751f 100644 --- a/sandbox/vsphere/src/main/java/org/jclouds/vsphere/compute/ViPropertiesBuilder.java +++ b/sandbox/vsphere/src/main/java/org/jclouds/vi/compute/ViPropertiesBuilder.java @@ -17,11 +17,11 @@ * ==================================================================== */ -package org.jclouds.vsphere.compute; +package org.jclouds.vi.compute; import static org.jclouds.Constants.PROPERTY_API_VERSION; import static org.jclouds.Constants.PROPERTY_ENDPOINT; -import static org.jclouds.vsphere.ViConstants.PROPERTY_LIBVIRT_DOMAIN_DIR; +import static org.jclouds.vi.ViConstants.PROPERTY_LIBVIRT_DOMAIN_DIR; import static org.jclouds.compute.reference.ComputeServiceConstants.PROPERTY_TIMEOUT_NODE_SUSPENDED; import java.util.Properties; diff --git a/sandbox/vsphere/src/main/java/org/jclouds/vi/compute/config/ViComputeServiceContextModule.java b/sandbox/vsphere/src/main/java/org/jclouds/vi/compute/config/ViComputeServiceContextModule.java new file mode 100644 index 0000000000..981bf94052 --- /dev/null +++ b/sandbox/vsphere/src/main/java/org/jclouds/vi/compute/config/ViComputeServiceContextModule.java @@ -0,0 +1,147 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.vi.compute.config; + +import static org.jclouds.vi.ViConstants.PROPERTY_LIBVIRT_DOMAIN_DIR; + +import java.io.File; +import java.io.IOException; +import java.io.StringReader; +import java.net.MalformedURLException; +import java.net.URI; +import java.rmi.RemoteException; +import java.util.Collection; + +import javax.inject.Named; +import javax.inject.Singleton; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.xpath.XPathExpressionException; + +import org.apache.commons.io.FileUtils; +import org.apache.commons.io.filefilter.WildcardFileFilter; +import org.jclouds.Constants; +import org.jclouds.compute.ComputeServiceAdapter; +import org.jclouds.compute.config.StandaloneComputeServiceContextModule; +import org.jclouds.compute.domain.Hardware; +import org.jclouds.compute.domain.NodeMetadata; +import org.jclouds.compute.domain.TemplateBuilder; +import org.jclouds.compute.suppliers.DefaultLocationSupplier; +import org.jclouds.domain.Location; +import org.jclouds.rest.annotations.Provider; +import org.jclouds.vi.Datacenter; +import org.jclouds.vi.Image; +import org.jclouds.vi.compute.functions.DatacenterToLocation; +import org.jclouds.vi.compute.functions.ViImageToImage; +import org.jclouds.vi.compute.functions.VirtualMachineToHardware; +import org.jclouds.vi.compute.functions.VirtualMachineToNodeMetadata; +import org.jclouds.vi.compute.strategy.ViComputeServiceAdapter; +import org.xml.sax.InputSource; +import org.xml.sax.SAXException; + +import com.google.common.base.Charsets; +import com.google.common.base.Function; +import com.google.common.base.Supplier; +import com.google.common.collect.Iterables; +import com.google.common.io.Files; +import com.google.inject.Injector; +import com.google.inject.Key; +import com.google.inject.Provides; +import com.google.inject.TypeLiteral; +import com.google.inject.name.Names; +import com.jamesmurty.utils.XMLBuilder; +import com.vmware.vim25.mo.ServiceInstance; +import com.vmware.vim25.mo.VirtualMachine; + +/** + * + * @author Adrian Cole + */ +public class ViComputeServiceContextModule extends + StandaloneComputeServiceContextModule { + @Override + protected void configure() { + super.configure(); + bind(new TypeLiteral>() { + }).to(ViComputeServiceAdapter.class); + bind(new TypeLiteral>() { + }).to(DefaultLocationSupplier.class); + bind(new TypeLiteral>() { + }).to(VirtualMachineToNodeMetadata.class); + bind(new TypeLiteral>() { + }).to(ViImageToImage.class); + bind(new TypeLiteral>() { + }).to(VirtualMachineToHardware.class); + bind(new TypeLiteral>() { + }).to(DatacenterToLocation.class); + } + + @Provides + @Singleton + protected ServiceInstance createConnection(@Provider URI endpoint, + @Named(Constants.PROPERTY_IDENTITY) String identity, @Named(Constants.PROPERTY_CREDENTIAL) String credential) + throws RemoteException, MalformedURLException { + System.out.println(endpoint); + System.out.println(identity); + System.out.println(credential); + return new ServiceInstance(endpoint.toURL(), identity, credential, true); + } + + @Override + protected TemplateBuilder provideTemplate(Injector injector, TemplateBuilder template) { + String domainDir = injector.getInstance(Key.get(String.class, Names.named(PROPERTY_LIBVIRT_DOMAIN_DIR))); + String hardwareId = searchForHardwareIdInDomainDir(domainDir); + String image = searchForImageIdInDomainDir(domainDir); + return template.hardwareId(hardwareId).imageId(image); + } + + private String searchForImageIdInDomainDir(String domainDir) { + // TODO + return "1"; + } + + @SuppressWarnings("unchecked") + private String searchForHardwareIdInDomainDir(String domainDir) { + + Collection xmlDomains = FileUtils.listFiles(new File(domainDir), new WildcardFileFilter("*.xml"), null); + String uuid = ""; + try { + String fromXML = Files.toString(Iterables.get(xmlDomains, 0), Charsets.UTF_8); + XMLBuilder builder = XMLBuilder.parse(new InputSource(new StringReader(fromXML))); + uuid = builder.xpathFind("/domain/uuid").getElement().getTextContent(); + } catch (IOException e) { + e.printStackTrace(); + } catch (ParserConfigurationException e) { + e.printStackTrace(); + } catch (SAXException e) { + e.printStackTrace(); + } catch (XPathExpressionException e) { + e.printStackTrace(); + } + return uuid; + } + + /* + * Map regions = newLinkedHashMap(); for (String region : + * Splitter.on(',').split(regionString)) { regions.put( region, + * URI.create(injector.getInstance(Key.get(String.class, Names.named(Constants.PROPERTY_ENDPOINT + * + "." + region))))); } return regions; + */ + +} \ No newline at end of file diff --git a/sandbox/vsphere/src/main/java/org/jclouds/vsphere/compute/functions/DatacenterToLocation.java b/sandbox/vsphere/src/main/java/org/jclouds/vi/compute/functions/DatacenterToLocation.java similarity index 93% rename from sandbox/vsphere/src/main/java/org/jclouds/vsphere/compute/functions/DatacenterToLocation.java rename to sandbox/vsphere/src/main/java/org/jclouds/vi/compute/functions/DatacenterToLocation.java index e949cde848..d5ac03464d 100644 --- a/sandbox/vsphere/src/main/java/org/jclouds/vsphere/compute/functions/DatacenterToLocation.java +++ b/sandbox/vsphere/src/main/java/org/jclouds/vi/compute/functions/DatacenterToLocation.java @@ -17,14 +17,14 @@ * ==================================================================== */ -package org.jclouds.vsphere.compute.functions; +package org.jclouds.vi.compute.functions; import javax.inject.Singleton; import org.jclouds.domain.Location; import org.jclouds.domain.LocationScope; import org.jclouds.domain.internal.LocationImpl; -import org.jclouds.vsphere.Datacenter; +import org.jclouds.vi.Datacenter; import com.google.common.base.Function; diff --git a/sandbox/vsphere/src/main/java/org/jclouds/vsphere/compute/functions/LibvirtNodeToLocation.java b/sandbox/vsphere/src/main/java/org/jclouds/vi/compute/functions/LibvirtNodeToLocation.java similarity index 93% rename from sandbox/vsphere/src/main/java/org/jclouds/vsphere/compute/functions/LibvirtNodeToLocation.java rename to sandbox/vsphere/src/main/java/org/jclouds/vi/compute/functions/LibvirtNodeToLocation.java index 04d4a80ae1..9482ec7220 100644 --- a/sandbox/vsphere/src/main/java/org/jclouds/vsphere/compute/functions/LibvirtNodeToLocation.java +++ b/sandbox/vsphere/src/main/java/org/jclouds/vi/compute/functions/LibvirtNodeToLocation.java @@ -17,14 +17,14 @@ * ==================================================================== */ -package org.jclouds.vsphere.compute.functions; +package org.jclouds.vi.compute.functions; import javax.inject.Singleton; import org.jclouds.domain.Location; import org.jclouds.domain.LocationScope; import org.jclouds.domain.internal.LocationImpl; -import org.jclouds.vsphere.Datacenter; +import org.jclouds.vi.Datacenter; import com.google.common.base.Function; diff --git a/sandbox/vsphere/src/main/java/org/jclouds/vsphere/compute/functions/ViImageToImage.java b/sandbox/vsphere/src/main/java/org/jclouds/vi/compute/functions/ViImageToImage.java similarity index 90% rename from sandbox/vsphere/src/main/java/org/jclouds/vsphere/compute/functions/ViImageToImage.java rename to sandbox/vsphere/src/main/java/org/jclouds/vi/compute/functions/ViImageToImage.java index 0d7345de7d..7fdedf6538 100644 --- a/sandbox/vsphere/src/main/java/org/jclouds/vsphere/compute/functions/ViImageToImage.java +++ b/sandbox/vsphere/src/main/java/org/jclouds/vi/compute/functions/ViImageToImage.java @@ -17,7 +17,7 @@ * ==================================================================== */ -package org.jclouds.vsphere.compute.functions; +package org.jclouds.vi.compute.functions; import javax.annotation.Resource; import javax.inject.Named; @@ -36,13 +36,13 @@ import com.google.common.base.Function; * @author Adrian Cole */ @Singleton -public class ViImageToImage implements Function { +public class ViImageToImage implements Function { @Resource @Named(ComputeServiceConstants.COMPUTE_LOGGER) protected Logger logger = Logger.NULL; @Override - public Image apply(org.jclouds.vsphere.Image from) { + public Image apply(org.jclouds.vi.Image from) { ImageBuilder builder = new ImageBuilder(); builder.ids(from.id + ""); diff --git a/sandbox/vsphere/src/main/java/org/jclouds/vsphere/compute/functions/VirtualMachineToHardware.java b/sandbox/vsphere/src/main/java/org/jclouds/vi/compute/functions/VirtualMachineToHardware.java similarity index 98% rename from sandbox/vsphere/src/main/java/org/jclouds/vsphere/compute/functions/VirtualMachineToHardware.java rename to sandbox/vsphere/src/main/java/org/jclouds/vi/compute/functions/VirtualMachineToHardware.java index 33f75aa756..281de80a11 100644 --- a/sandbox/vsphere/src/main/java/org/jclouds/vsphere/compute/functions/VirtualMachineToHardware.java +++ b/sandbox/vsphere/src/main/java/org/jclouds/vi/compute/functions/VirtualMachineToHardware.java @@ -17,7 +17,7 @@ * ==================================================================== */ -package org.jclouds.vsphere.compute.functions; +package org.jclouds.vi.compute.functions; import java.io.IOException; import java.io.StringReader; diff --git a/sandbox/vsphere/src/main/java/org/jclouds/vsphere/compute/functions/VirtualMachineToNodeMetadata.java b/sandbox/vsphere/src/main/java/org/jclouds/vi/compute/functions/VirtualMachineToNodeMetadata.java similarity index 99% rename from sandbox/vsphere/src/main/java/org/jclouds/vsphere/compute/functions/VirtualMachineToNodeMetadata.java rename to sandbox/vsphere/src/main/java/org/jclouds/vi/compute/functions/VirtualMachineToNodeMetadata.java index 8a0964a7fa..6fd5d2d3d7 100644 --- a/sandbox/vsphere/src/main/java/org/jclouds/vsphere/compute/functions/VirtualMachineToNodeMetadata.java +++ b/sandbox/vsphere/src/main/java/org/jclouds/vi/compute/functions/VirtualMachineToNodeMetadata.java @@ -17,7 +17,7 @@ * ==================================================================== */ -package org.jclouds.vsphere.compute.functions; +package org.jclouds.vi.compute.functions; import static com.google.common.base.Preconditions.checkNotNull; import static org.jclouds.compute.util.ComputeServiceUtils.parseTagFromName; diff --git a/sandbox/vsphere/src/main/java/org/jclouds/vsphere/compute/strategy/ViComputeServiceAdapter.java b/sandbox/vsphere/src/main/java/org/jclouds/vi/compute/strategy/ViComputeServiceAdapter.java similarity index 98% rename from sandbox/vsphere/src/main/java/org/jclouds/vsphere/compute/strategy/ViComputeServiceAdapter.java rename to sandbox/vsphere/src/main/java/org/jclouds/vi/compute/strategy/ViComputeServiceAdapter.java index 82bbdffac3..a0ac47bec2 100644 --- a/sandbox/vsphere/src/main/java/org/jclouds/vsphere/compute/strategy/ViComputeServiceAdapter.java +++ b/sandbox/vsphere/src/main/java/org/jclouds/vi/compute/strategy/ViComputeServiceAdapter.java @@ -17,10 +17,10 @@ * ==================================================================== */ -package org.jclouds.vsphere.compute.strategy; +package org.jclouds.vi.compute.strategy; import static com.google.common.base.Preconditions.checkNotNull; -import static org.jclouds.vsphere.ViConstants.PROPERTY_LIBVIRT_DOMAIN_DIR; +import static org.jclouds.vi.ViConstants.PROPERTY_LIBVIRT_DOMAIN_DIR; import java.rmi.RemoteException; import java.util.List; @@ -33,8 +33,8 @@ import org.jclouds.compute.ComputeService; import org.jclouds.compute.ComputeServiceAdapter; import org.jclouds.compute.domain.Template; import org.jclouds.domain.Credentials; -import org.jclouds.vsphere.Datacenter; -import org.jclouds.vsphere.Image; +import org.jclouds.vi.Datacenter; +import org.jclouds.vi.Image; import com.google.common.base.Throwables; import com.google.common.collect.Lists; diff --git a/sandbox/vsphere/src/main/java/org/jclouds/vsphere/compute/domain/ViComputeServiceContextModule.java b/sandbox/vsphere/src/main/java/org/jclouds/vsphere/compute/domain/ViComputeServiceContextModule.java deleted file mode 100644 index 1e811157c6..0000000000 --- a/sandbox/vsphere/src/main/java/org/jclouds/vsphere/compute/domain/ViComputeServiceContextModule.java +++ /dev/null @@ -1,151 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.vsphere.compute.domain; - -import static org.jclouds.vsphere.ViConstants.PROPERTY_LIBVIRT_DOMAIN_DIR; - -import java.io.File; -import java.io.IOException; -import java.io.StringReader; -import java.net.MalformedURLException; -import java.net.URI; -import java.rmi.RemoteException; -import java.util.Collection; - -import javax.inject.Named; -import javax.inject.Singleton; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.xpath.XPathExpressionException; - -import org.apache.commons.io.FileUtils; -import org.apache.commons.io.filefilter.WildcardFileFilter; -import org.jclouds.Constants; -import org.jclouds.compute.ComputeServiceAdapter; -import org.jclouds.compute.config.StandaloneComputeServiceContextModule; -import org.jclouds.compute.domain.Hardware; -import org.jclouds.compute.domain.NodeMetadata; -import org.jclouds.compute.domain.TemplateBuilder; -import org.jclouds.compute.suppliers.DefaultLocationSupplier; -import org.jclouds.domain.Location; -import org.jclouds.rest.annotations.Provider; -import org.jclouds.vsphere.Datacenter; -import org.jclouds.vsphere.Image; -import org.jclouds.vsphere.compute.functions.DatacenterToLocation; -import org.jclouds.vsphere.compute.functions.ViImageToImage; -import org.jclouds.vsphere.compute.functions.VirtualMachineToHardware; -import org.jclouds.vsphere.compute.functions.VirtualMachineToNodeMetadata; -import org.jclouds.vsphere.compute.strategy.ViComputeServiceAdapter; -import org.xml.sax.InputSource; -import org.xml.sax.SAXException; - -import com.google.common.base.Charsets; -import com.google.common.base.Function; -import com.google.common.base.Supplier; -import com.google.common.collect.Iterables; -import com.google.common.io.Files; -import com.google.inject.Injector; -import com.google.inject.Key; -import com.google.inject.Provides; -import com.google.inject.TypeLiteral; -import com.google.inject.name.Names; -import com.jamesmurty.utils.XMLBuilder; -import com.vmware.vim25.mo.ServiceInstance; -import com.vmware.vim25.mo.VirtualMachine; - -/** - * - * @author Adrian Cole - */ -public class ViComputeServiceContextModule extends -StandaloneComputeServiceContextModule { - @Override - protected void configure() { - super.configure(); - bind(new TypeLiteral>() { - }).to(ViComputeServiceAdapter.class); - bind(new TypeLiteral>() { - }).to(DefaultLocationSupplier.class); - bind(new TypeLiteral>() { - }).to(VirtualMachineToNodeMetadata.class); - bind(new TypeLiteral>() { - }).to(ViImageToImage.class); - bind(new TypeLiteral>() { - }).to(VirtualMachineToHardware.class); - bind(new TypeLiteral>() { - }).to(DatacenterToLocation.class); - } - - @Provides - @Singleton - protected ServiceInstance createConnection(@Provider URI endpoint, @Named(Constants.PROPERTY_IDENTITY) String identity, - @Named(Constants.PROPERTY_CREDENTIAL) String credential) throws RemoteException, MalformedURLException { - System.out.println(endpoint); - System.out.println(identity); - System.out.println(credential); - return new ServiceInstance(endpoint.toURL(), identity, credential, true); - } - - @Override - protected TemplateBuilder provideTemplate(Injector injector, TemplateBuilder template) { - String domainDir = injector.getInstance(Key.get(String.class, Names.named(PROPERTY_LIBVIRT_DOMAIN_DIR))); - String hardwareId = searchForHardwareIdInDomainDir(domainDir); - String image = searchForImageIdInDomainDir(domainDir); - return template.hardwareId(hardwareId).imageId(image) ; - } - - - private String searchForImageIdInDomainDir(String domainDir) { - // TODO - return "1"; - } - - @SuppressWarnings("unchecked") - private String searchForHardwareIdInDomainDir(String domainDir) { - - Collection xmlDomains = FileUtils.listFiles( new File(domainDir), new WildcardFileFilter("*.xml"), null); - String uuid = ""; - try { - String fromXML = Files.toString(Iterables.get(xmlDomains, 0), Charsets.UTF_8); - XMLBuilder builder = XMLBuilder.parse(new InputSource(new StringReader(fromXML))); - uuid = builder.xpathFind("/domain/uuid").getElement().getTextContent(); - } catch (IOException e) { - e.printStackTrace(); - } catch (ParserConfigurationException e) { - e.printStackTrace(); - } catch (SAXException e) { - e.printStackTrace(); - } catch (XPathExpressionException e) { - e.printStackTrace(); - } - return uuid; - } - - /* - * Map regions = newLinkedHashMap(); - for (String region : Splitter.on(',').split(regionString)) { - regions.put( - region, - URI.create(injector.getInstance(Key.get(String.class, - Names.named(Constants.PROPERTY_ENDPOINT + "." + region))))); - } - return regions; - */ - -} \ No newline at end of file diff --git a/sandbox/vsphere/src/test/java/org/jclouds/vi/compute/ViComputeServiceContextBuilderTest.java b/sandbox/vsphere/src/test/java/org/jclouds/vi/compute/ViComputeServiceContextBuilderTest.java new file mode 100644 index 0000000000..f5f982a3e3 --- /dev/null +++ b/sandbox/vsphere/src/test/java/org/jclouds/vi/compute/ViComputeServiceContextBuilderTest.java @@ -0,0 +1,53 @@ +package org.jclouds.vi.compute; + +import static org.testng.Assert.assertEquals; + +import java.util.Properties; + +import org.jclouds.compute.ComputeServiceContext; +import org.jclouds.compute.ComputeServiceContextFactory; +import org.jclouds.rest.RestContext; +import org.testng.annotations.Test; + +import com.vmware.vim25.mo.ServiceInstance; + +/** + * + * @author andrea.turli + * + */ +@Test(groups = "unit") +public class ViComputeServiceContextBuilderTest { + + @Test + public void testCanBuildWithContextSpec() { + ComputeServiceContext context = new ComputeServiceContextFactory().createContext(new ViComputeServiceContextSpec( + "https://localhost/sdk", "Administrator", "password")); + context.getComputeService().listNodes(); + + context.close(); + } + + @Test + public void testCanBuildWithRestProperties() { + Properties restProperties = new Properties(); + restProperties.setProperty("vi.contextbuilder", ViComputeServiceContextBuilder.class.getName()); + restProperties.setProperty("vi.propertiesbuilder", ViPropertiesBuilder.class.getName()); + restProperties.setProperty("vi.endpoint", "https://localhost/sdk"); + + ComputeServiceContext context = new ComputeServiceContextFactory(restProperties).createContext("vi", + "identity", "credential"); + + context.close(); + } + + @Test + public void testProviderSpecificContextIsCorrectType() { + ComputeServiceContext context = new ViComputeServiceContextBuilder(new Properties()).buildComputeServiceContext(); + RestContext providerContext = context.getProviderSpecificContext(); + + assertEquals(providerContext.getApi().getClass(), ServiceInstance.class); + + context.close(); + } +} diff --git a/sandbox/vsphere/src/test/java/org/jclouds/vi/compute/ViComputeServiceLiveTest.java b/sandbox/vsphere/src/test/java/org/jclouds/vi/compute/ViComputeServiceLiveTest.java new file mode 100644 index 0000000000..fdb9e45d58 --- /dev/null +++ b/sandbox/vsphere/src/test/java/org/jclouds/vi/compute/ViComputeServiceLiveTest.java @@ -0,0 +1,56 @@ +package org.jclouds.vi.compute; + +import static org.jclouds.compute.util.ComputeServiceUtils.getCores; +import static org.testng.Assert.assertEquals; + +import java.util.Properties; + +import org.jclouds.compute.BaseComputeServiceLiveTest; +import org.jclouds.compute.ComputeServiceContextFactory; +import org.jclouds.compute.domain.OsFamily; +import org.jclouds.compute.domain.Template; +import org.jclouds.rest.RestContext; +import org.jclouds.ssh.jsch.config.JschSshClientModule; +import org.testng.annotations.Test; + +import com.vmware.vim25.mo.ServiceInstance; + +/** + * @author Adrian Cole + */ +@Test(groups = "live", enabled = true, sequential = true, testName = "vi.ViComputeServiceLiveTest") +public class ViComputeServiceLiveTest extends BaseComputeServiceLiveTest { + public ViComputeServiceLiveTest() { + provider = "vi"; + } + + @Override + protected Properties getRestProperties() { + Properties restProperties = new Properties(); + restProperties.setProperty("vi.contextbuilder", ViComputeServiceContextBuilder.class.getName()); + restProperties.setProperty("vi.propertiesbuilder", ViPropertiesBuilder.class.getName()); + restProperties.setProperty("vi.endpoint", "https://localhost/sdk"); + return restProperties; + } + + @Test + public void testTemplateBuilder() { + Template defaultTemplate = client.templateBuilder().build(); + assertEquals(defaultTemplate.getImage().getOperatingSystem().is64Bit(), true); + assertEquals(defaultTemplate.getImage().getOperatingSystem().getVersion(), "5.3"); + assertEquals(defaultTemplate.getImage().getOperatingSystem().getFamily(), OsFamily.CENTOS); + assertEquals(defaultTemplate.getLocation().getId(), "1"); + assertEquals(getCores(defaultTemplate.getHardware()), 0.5d); + } + + @Override + protected JschSshClientModule getSshModule() { + return new JschSshClientModule(); + } + + public void testAssignability() throws Exception { + @SuppressWarnings("unused") + RestContext goGridContext = new ComputeServiceContextFactory().createContext( + provider, identity, credential).getProviderSpecificContext(); + } +} diff --git a/sandbox/vsphere/src/test/java/org/jclouds/vsphere/compute/ViExperimentLiveTest.java b/sandbox/vsphere/src/test/java/org/jclouds/vi/compute/ViExperimentLiveTest.java similarity index 97% rename from sandbox/vsphere/src/test/java/org/jclouds/vsphere/compute/ViExperimentLiveTest.java rename to sandbox/vsphere/src/test/java/org/jclouds/vi/compute/ViExperimentLiveTest.java index 3674fe6563..c9bb37b772 100644 --- a/sandbox/vsphere/src/test/java/org/jclouds/vsphere/compute/ViExperimentLiveTest.java +++ b/sandbox/vsphere/src/test/java/org/jclouds/vi/compute/ViExperimentLiveTest.java @@ -17,7 +17,7 @@ * ==================================================================== */ -package org.jclouds.vsphere.compute; +package org.jclouds.vi.compute; import static com.google.common.base.Preconditions.checkNotNull; @@ -27,7 +27,7 @@ import org.jclouds.compute.ComputeServiceContext; import org.jclouds.compute.ComputeServiceContextFactory; import org.jclouds.compute.domain.NodeMetadata; import org.jclouds.compute.domain.Template; -import org.jclouds.vsphere.compute.ViComputeServiceContextSpec; +import org.jclouds.vi.compute.ViComputeServiceContextSpec; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; diff --git a/sandbox/vsphere/src/test/java/org/jclouds/vsphere/compute/ViComputeServiceContextBuilderTest.java b/sandbox/vsphere/src/test/java/org/jclouds/vsphere/compute/ViComputeServiceContextBuilderTest.java deleted file mode 100644 index 891323bde6..0000000000 --- a/sandbox/vsphere/src/test/java/org/jclouds/vsphere/compute/ViComputeServiceContextBuilderTest.java +++ /dev/null @@ -1,33 +0,0 @@ -package org.jclouds.vsphere.compute; - -import static org.testng.Assert.assertNotNull; - -import java.util.Properties; - -import org.jclouds.compute.ComputeServiceContext; -import org.jclouds.compute.ComputeServiceContextFactory; -import org.jclouds.vsphere.compute.ViComputeServiceContextBuilder; -import org.jclouds.vsphere.compute.ViComputeServiceContextSpec; -import org.testng.annotations.Test; - -/** - * - * @author andrea.turli - * - */ -@Test(groups = "unit") -public class ViComputeServiceContextBuilderTest { - - @Test - public void testCreateContextModule() { - assertNotNull(new ViComputeServiceContextBuilder(new Properties()).createContextModule()); - } - - @Test - public void testCanBuildWithComputeService() { - ComputeServiceContext context = new ComputeServiceContextFactory() - .createContext(new ViComputeServiceContextSpec("https://localhost/sdk", "Administrator", "password")); - context.getComputeService().listNodes(); - context.close(); - } -} diff --git a/skeletons/standalone-compute/src/main/java/org/jclouds/servermanager/compute/ServerManagerComputeServiceContextBuilder.java b/skeletons/standalone-compute/src/main/java/org/jclouds/servermanager/compute/ServerManagerComputeServiceContextBuilder.java index e03059a9dd..7062a76d81 100644 --- a/skeletons/standalone-compute/src/main/java/org/jclouds/servermanager/compute/ServerManagerComputeServiceContextBuilder.java +++ b/skeletons/standalone-compute/src/main/java/org/jclouds/servermanager/compute/ServerManagerComputeServiceContextBuilder.java @@ -22,63 +22,24 @@ package org.jclouds.servermanager.compute; import java.util.List; import java.util.Properties; -import org.jclouds.compute.ComputeServiceAdapter; import org.jclouds.compute.StandaloneComputeServiceContextBuilder; -import org.jclouds.compute.config.StandaloneComputeServiceContextModule; -import org.jclouds.compute.domain.NodeMetadata; -import org.jclouds.compute.suppliers.DefaultLocationSupplier; -import org.jclouds.domain.Location; -import org.jclouds.servermanager.Datacenter; -import org.jclouds.servermanager.Hardware; -import org.jclouds.servermanager.Image; -import org.jclouds.servermanager.Server; -import org.jclouds.servermanager.compute.functions.DatacenterToLocation; -import org.jclouds.servermanager.compute.functions.ServerManagerHardwareToHardware; -import org.jclouds.servermanager.compute.functions.ServerManagerImageToImage; -import org.jclouds.servermanager.compute.functions.ServerToNodeMetadata; -import org.jclouds.servermanager.compute.strategy.ServerManagerComputeServiceAdapter; +import org.jclouds.servermanager.ServerManager; +import org.jclouds.servermanager.compute.config.ServerManagerComputeServiceContextModule; -import com.google.common.base.Function; -import com.google.common.base.Supplier; import com.google.inject.Module; -import com.google.inject.TypeLiteral; /** * * @author Adrian Cole */ -public class ServerManagerComputeServiceContextBuilder extends StandaloneComputeServiceContextBuilder { +public class ServerManagerComputeServiceContextBuilder extends StandaloneComputeServiceContextBuilder { public ServerManagerComputeServiceContextBuilder(Properties props) { - super(props); + super(ServerManager.class, props); } @Override protected void addContextModule(List modules) { - modules.add(createContextModule()); + modules.add(new ServerManagerComputeServiceContextModule()); } - - public static StandaloneComputeServiceContextModule createContextModule() { - return new StandaloneComputeServiceContextModule() { - - @Override - protected void configure() { - super.configure(); - bind(new TypeLiteral>() { - }).to(ServerManagerComputeServiceAdapter.class); - bind(new TypeLiteral>() { - }).to(DefaultLocationSupplier.class); - bind(new TypeLiteral>() { - }).to(ServerToNodeMetadata.class); - bind(new TypeLiteral>() { - }).to(ServerManagerImageToImage.class); - bind(new TypeLiteral>() { - }).to(ServerManagerHardwareToHardware.class); - bind(new TypeLiteral>() { - }).to(DatacenterToLocation.class); - } - - }; - } - } diff --git a/skeletons/standalone-compute/src/main/java/org/jclouds/servermanager/compute/config/ServerManagerComputeServiceContextModule.java b/skeletons/standalone-compute/src/main/java/org/jclouds/servermanager/compute/config/ServerManagerComputeServiceContextModule.java new file mode 100644 index 0000000000..82f434858f --- /dev/null +++ b/skeletons/standalone-compute/src/main/java/org/jclouds/servermanager/compute/config/ServerManagerComputeServiceContextModule.java @@ -0,0 +1,63 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.servermanager.compute.config; + +import org.jclouds.compute.ComputeServiceAdapter; +import org.jclouds.compute.config.StandaloneComputeServiceContextModule; +import org.jclouds.compute.domain.NodeMetadata; +import org.jclouds.compute.suppliers.DefaultLocationSupplier; +import org.jclouds.domain.Location; +import org.jclouds.servermanager.Datacenter; +import org.jclouds.servermanager.Hardware; +import org.jclouds.servermanager.Image; +import org.jclouds.servermanager.Server; +import org.jclouds.servermanager.compute.functions.DatacenterToLocation; +import org.jclouds.servermanager.compute.functions.ServerManagerHardwareToHardware; +import org.jclouds.servermanager.compute.functions.ServerManagerImageToImage; +import org.jclouds.servermanager.compute.functions.ServerToNodeMetadata; +import org.jclouds.servermanager.compute.strategy.ServerManagerComputeServiceAdapter; + +import com.google.common.base.Function; +import com.google.common.base.Supplier; +import com.google.inject.TypeLiteral; + +/** + * + * @author Adrian Cole + */ +public class ServerManagerComputeServiceContextModule extends + StandaloneComputeServiceContextModule { + @Override + protected void configure() { + super.configure(); + bind(new TypeLiteral>() { + }).to(ServerManagerComputeServiceAdapter.class); + bind(new TypeLiteral>() { + }).to(DefaultLocationSupplier.class); + bind(new TypeLiteral>() { + }).to(ServerToNodeMetadata.class); + bind(new TypeLiteral>() { + }).to(ServerManagerImageToImage.class); + bind(new TypeLiteral>() { + }).to(ServerManagerHardwareToHardware.class); + bind(new TypeLiteral>() { + }).to(DatacenterToLocation.class); + } +} \ No newline at end of file diff --git a/skeletons/standalone-compute/src/test/java/org/jclouds/servermanager/compute/ServerManagerComputeServiceContextBuilderTest.java b/skeletons/standalone-compute/src/test/java/org/jclouds/servermanager/compute/ServerManagerComputeServiceContextBuilderTest.java index 2538a36a72..c1d002c50a 100644 --- a/skeletons/standalone-compute/src/test/java/org/jclouds/servermanager/compute/ServerManagerComputeServiceContextBuilderTest.java +++ b/skeletons/standalone-compute/src/test/java/org/jclouds/servermanager/compute/ServerManagerComputeServiceContextBuilderTest.java @@ -1,16 +1,37 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + package org.jclouds.servermanager.compute; -import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.assertEquals; import java.util.Properties; import org.jclouds.compute.ComputeServiceContext; import org.jclouds.compute.ComputeServiceContextFactory; import org.jclouds.compute.StandaloneComputeServiceContextSpec; +import org.jclouds.rest.RestContext; import org.jclouds.servermanager.Datacenter; import org.jclouds.servermanager.Hardware; import org.jclouds.servermanager.Image; import org.jclouds.servermanager.Server; +import org.jclouds.servermanager.ServerManager; import org.testng.annotations.Test; import com.google.common.collect.ImmutableSet; @@ -24,11 +45,6 @@ import com.google.inject.Module; @Test(groups = "unit") public class ServerManagerComputeServiceContextBuilderTest { - @Test - public void testCreateContextModule() { - assertNotNull(ServerManagerComputeServiceContextBuilder.createContextModule()); - } - @Test public void testCanBuildDirectly() { ComputeServiceContext context = new ServerManagerComputeServiceContextBuilder(new Properties()) @@ -37,13 +53,37 @@ public class ServerManagerComputeServiceContextBuilderTest { } @Test - public void testCanBuildWithComputeService() { + public void testCanBuildWithContextSpec() { ComputeServiceContext context = new ComputeServiceContextFactory() - .createContext(new StandaloneComputeServiceContextSpec( - "servermanager", "http://host", "1", "identity", "credential", - ServerManagerComputeServiceContextBuilder.createContextModule(), ImmutableSet. of())); + .createContext(new StandaloneComputeServiceContextSpec( + "servermanager", "http://host", "1", "identity", "credential", ServerManager.class, + ServerManagerComputeServiceContextBuilder.class, ImmutableSet. of())); context.close(); + } + @Test + public void testCanBuildWithRestProperties() { + Properties restProperties = new Properties(); + restProperties.setProperty("servermanager.contextbuilder", + ServerManagerComputeServiceContextBuilder.class.getName()); + restProperties.setProperty("servermanager.endpoint", "http://host"); + restProperties.setProperty("servermanager.apiversion", "1"); + + ComputeServiceContext context = new ComputeServiceContextFactory(restProperties).createContext("servermanager", + "identity", "credential"); + + context.close(); + } + + @Test + public void testProviderSpecificContextIsCorrectType() { + ComputeServiceContext context = new ServerManagerComputeServiceContextBuilder(new Properties()) + .buildComputeServiceContext(); + RestContext providerContext = context.getProviderSpecificContext(); + + assertEquals(providerContext.getApi().getClass(), ServerManager.class); + + context.close(); } } diff --git a/skeletons/standalone-compute/src/test/java/org/jclouds/servermanager/compute/ServerManagerComputeServiceLiveTest.java b/skeletons/standalone-compute/src/test/java/org/jclouds/servermanager/compute/ServerManagerComputeServiceLiveTest.java new file mode 100644 index 0000000000..092fd82406 --- /dev/null +++ b/skeletons/standalone-compute/src/test/java/org/jclouds/servermanager/compute/ServerManagerComputeServiceLiveTest.java @@ -0,0 +1,56 @@ +package org.jclouds.servermanager.compute; + +import static org.jclouds.compute.util.ComputeServiceUtils.getCores; +import static org.testng.Assert.assertEquals; + +import java.util.Properties; + +import org.jclouds.compute.BaseComputeServiceLiveTest; +import org.jclouds.compute.ComputeServiceContextFactory; +import org.jclouds.compute.domain.OsFamily; +import org.jclouds.compute.domain.Template; +import org.jclouds.rest.RestContext; +import org.jclouds.servermanager.ServerManager; +import org.jclouds.ssh.jsch.config.JschSshClientModule; +import org.testng.annotations.Test; + +/** + * @author Adrian Cole + */ +@Test(groups = "live", enabled = true, sequential = true, testName = "servermanager.ServerManagerComputeServiceLiveTest") +public class ServerManagerComputeServiceLiveTest extends BaseComputeServiceLiveTest { + public ServerManagerComputeServiceLiveTest() { + provider = "servermanager"; + } + + @Override + protected Properties getRestProperties() { + Properties restProperties = new Properties(); + restProperties.setProperty("servermanager.contextbuilder", + ServerManagerComputeServiceContextBuilder.class.getName()); + restProperties.setProperty("servermanager.endpoint", "http://host"); + restProperties.setProperty("servermanager.apiversion", "1"); + return restProperties; + } + + @Test + public void testTemplateBuilder() { + Template defaultTemplate = client.templateBuilder().build(); + assertEquals(defaultTemplate.getImage().getOperatingSystem().is64Bit(), true); + assertEquals(defaultTemplate.getImage().getOperatingSystem().getVersion(), "5.3"); + assertEquals(defaultTemplate.getImage().getOperatingSystem().getFamily(), OsFamily.CENTOS); + assertEquals(defaultTemplate.getLocation().getId(), "1"); + assertEquals(getCores(defaultTemplate.getHardware()), 0.5d); + } + + @Override + protected JschSshClientModule getSshModule() { + return new JschSshClientModule(); + } + + public void testAssignability() throws Exception { + @SuppressWarnings("unused") + RestContext goGridContext = new ComputeServiceContextFactory().createContext( + provider, identity, credential).getProviderSpecificContext(); + } +} diff --git a/skeletons/standalone-compute/src/test/java/org/jclouds/servermanager/compute/ServerManagerExperimentLiveTest.java b/skeletons/standalone-compute/src/test/java/org/jclouds/servermanager/compute/ServerManagerExperimentLiveTest.java index fa3716e3da..4d4923797e 100644 --- a/skeletons/standalone-compute/src/test/java/org/jclouds/servermanager/compute/ServerManagerExperimentLiveTest.java +++ b/skeletons/standalone-compute/src/test/java/org/jclouds/servermanager/compute/ServerManagerExperimentLiveTest.java @@ -28,6 +28,7 @@ import org.jclouds.servermanager.Datacenter; import org.jclouds.servermanager.Hardware; import org.jclouds.servermanager.Image; import org.jclouds.servermanager.Server; +import org.jclouds.servermanager.ServerManager; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; @@ -59,9 +60,9 @@ public class ServerManagerExperimentLiveTest { ComputeServiceContext context = null; try { context = new ComputeServiceContextFactory() - .createContext(new StandaloneComputeServiceContextSpec( - "servermanager", endpoint, apiversion, identity, credential, - ServerManagerComputeServiceContextBuilder.createContextModule(), ImmutableSet. of())); + .createContext(new StandaloneComputeServiceContextSpec( + "servermanager", endpoint, apiversion, identity, credential, ServerManager.class, + ServerManagerComputeServiceContextBuilder.class, ImmutableSet. of())); context.getComputeService().listNodes(); From bf325b1126012d72d761e738303c607c6a6086b2 Mon Sep 17 00:00:00 2001 From: Adrian Cole Date: Sun, 5 Dec 2010 20:52:43 +0000 Subject: [PATCH 27/31] separated runtime metadata from normal domain objects in elasticstack api --- .../binders/BindDriveToPlainTextString.java | 61 ++++ .../jclouds/elasticstack/domain/Drive.java | 219 +++++++++++++ .../elasticstack/domain/DriveMetrics.java | 139 ++++++++ .../jclouds/elasticstack/domain/Server.java | 297 ++++++++++++++++++ .../elasticstack/domain/ServerMetrics.java | 156 +++++++++ .../functions/MapToDriveMetrics.java | 87 +++++ .../functions/MapToServerMetrics.java | 60 ++++ .../BindDriveToPlainTextStringTest.java | 92 ++++++ 8 files changed, 1111 insertions(+) create mode 100644 sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/binders/BindDriveToPlainTextString.java create mode 100644 sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/domain/Drive.java create mode 100644 sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/domain/DriveMetrics.java create mode 100644 sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/domain/Server.java create mode 100644 sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/domain/ServerMetrics.java create mode 100644 sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/functions/MapToDriveMetrics.java create mode 100644 sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/functions/MapToServerMetrics.java create mode 100644 sandbox/elasticstack/src/test/java/org/jclouds/elasticstack/binders/BindDriveToPlainTextStringTest.java diff --git a/sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/binders/BindDriveToPlainTextString.java b/sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/binders/BindDriveToPlainTextString.java new file mode 100644 index 0000000000..9db28769f3 --- /dev/null +++ b/sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/binders/BindDriveToPlainTextString.java @@ -0,0 +1,61 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.elasticstack.binders; + +import static com.google.common.base.Preconditions.checkArgument; + +import java.util.Map; + +import javax.inject.Inject; +import javax.inject.Singleton; +import javax.ws.rs.core.MediaType; + +import org.jclouds.elasticstack.domain.Drive; +import org.jclouds.elasticstack.functions.ListOfMapsToListOfKeyValuesDelimitedByBlankLines; +import org.jclouds.http.HttpRequest; +import org.jclouds.rest.Binder; + +import com.google.common.base.Function; +import com.google.common.collect.ImmutableSet; + +/** + * + * @author Adrian Cole + */ +@Singleton +public class BindDriveToPlainTextString implements Binder { + private final Function> createDriveRequestToMap; + private final ListOfMapsToListOfKeyValuesDelimitedByBlankLines listOfMapsToListOfKeyValuesDelimitedByBlankLines; + + @Inject + public BindDriveToPlainTextString(Function> createDriveRequestToMap, + ListOfMapsToListOfKeyValuesDelimitedByBlankLines listOfMapsToListOfKeyValuesDelimitedByBlankLines) { + this.createDriveRequestToMap = createDriveRequestToMap; + this.listOfMapsToListOfKeyValuesDelimitedByBlankLines = listOfMapsToListOfKeyValuesDelimitedByBlankLines; + } + + public void bindToRequest(HttpRequest request, Object payload) { + checkArgument(payload instanceof Drive, "this binder is only valid for Drive!"); + Drive create = Drive.class.cast(payload); + Map map = createDriveRequestToMap.apply(create); + request.setPayload(listOfMapsToListOfKeyValuesDelimitedByBlankLines.apply(ImmutableSet.of(map))); + request.getPayload().getContentMetadata().setContentType(MediaType.TEXT_PLAIN); + } +} diff --git a/sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/domain/Drive.java b/sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/domain/Drive.java new file mode 100644 index 0000000000..da54f37be7 --- /dev/null +++ b/sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/domain/Drive.java @@ -0,0 +1,219 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.elasticstack.domain; + +import static com.google.common.base.Preconditions.checkNotNull; + +import java.util.Map; +import java.util.Set; + +import javax.annotation.Nullable; + + +import com.google.common.collect.ImmutableSet; + +/** + * + * @author Adrian Cole + */ +public class Drive extends Item { + public static class Builder extends Item.Builder { + protected long size; + protected ClaimType claimType = ClaimType.EXCLUSIVE; + protected Set readers = ImmutableSet.of(); + + public Builder claimType(ClaimType claimType) { + this.claimType = claimType; + return this; + } + + public Builder readers(Iterable readers) { + this.readers = ImmutableSet.copyOf(checkNotNull(readers, "readers")); + return this; + } + + public Builder size(long size) { + this.size = size; + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public Builder uuid(String uuid) { + return Builder.class.cast(super.uuid(uuid)); + } + + /** + * {@inheritDoc} + */ + @Override + public Builder name(String name) { + return Builder.class.cast(super.name(name)); + } + + /** + * {@inheritDoc} + */ + @Override + public Builder tags(Iterable tags) { + return Builder.class.cast(super.tags(tags)); + } + + /** + * {@inheritDoc} + */ + @Override + public Builder userMetadata(Map userMetadata) { + return Builder.class.cast(super.userMetadata(userMetadata)); + } + + public Drive build() { + return new Drive(uuid, name, size, claimType, readers, tags, userMetadata); + } + + @Override + public int hashCode() { + final int prime = 31; + int result = super.hashCode(); + result = prime * result + ((claimType == null) ? 0 : claimType.hashCode()); + result = prime * result + ((readers == null) ? 0 : readers.hashCode()); + result = prime * result + (int) (size ^ (size >>> 32)); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (!super.equals(obj)) + return false; + if (getClass() != obj.getClass()) + return false; + Builder other = (Builder) obj; + if (claimType != other.claimType) + return false; + if (readers == null) { + if (other.readers != null) + return false; + } else if (!readers.equals(other.readers)) + return false; + if (size != other.size) + return false; + return true; + } + } + + protected final long size; + protected final ClaimType claimType; + protected final Set readers; + + public Drive(@Nullable String uuid, String name, long size, @Nullable ClaimType claimType, + Iterable readers, Iterable tags, Map userMetadata) { + super(uuid, name, tags, userMetadata); + this.size = size; + this.claimType = checkNotNull(claimType, "set claimType to exclusive, not null"); + this.readers = ImmutableSet.copyOf(checkNotNull(readers, "readers")); + } + + /** + * + * @return either 'exclusive' (the default) or 'shared' to allow multiple servers to access a + * drive simultaneously + */ + @Nullable + public ClaimType getClaimType() { + return claimType; + } + + /** + * + * @return list of users allowed to read from a drive or 'ffffffff-ffff-ffff-ffff-ffffffffffff' + * for all users + */ + public Set getReaders() { + return readers; + } + + /** + * + * @return size of drive in bytes + */ + public long getSize() { + return size; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((claimType == null) ? 0 : claimType.hashCode()); + result = prime * result + ((name == null) ? 0 : name.hashCode()); + result = prime * result + ((readers == null) ? 0 : readers.hashCode()); + result = prime * result + (int) (size ^ (size >>> 32)); + result = prime * result + ((tags == null) ? 0 : tags.hashCode()); + result = prime * result + ((userMetadata == null) ? 0 : userMetadata.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; + Drive other = (Drive) obj; + if (claimType != other.claimType) + return false; + if (name == null) { + if (other.name != null) + return false; + } else if (!name.equals(other.name)) + return false; + if (readers == null) { + if (other.readers != null) + return false; + } else if (!readers.equals(other.readers)) + return false; + if (size != other.size) + return false; + if (tags == null) { + if (other.tags != null) + return false; + } else if (!tags.equals(other.tags)) + return false; + if (userMetadata == null) { + if (other.userMetadata != null) + return false; + } else if (!userMetadata.equals(other.userMetadata)) + return false; + return true; + } + + @Override + public String toString() { + return "[uuid=" + uuid + ", name=" + name + ", tags=" + tags + ", userMetadata=" + userMetadata + ", size=" + + size + ", claimType=" + claimType + ", readers=" + readers + "]"; + } + +} \ No newline at end of file diff --git a/sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/domain/DriveMetrics.java b/sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/domain/DriveMetrics.java new file mode 100644 index 0000000000..913a547ea6 --- /dev/null +++ b/sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/domain/DriveMetrics.java @@ -0,0 +1,139 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.elasticstack.domain; + + +/** + * + * @author Adrian Cole + */ +public class DriveMetrics { + public static class Builder { + protected long readBytes; + protected long readRequests; + protected long writeBytes; + protected long writeRequests; + + public Builder readBytes(long readBytes) { + this.readBytes = readBytes; + return this; + } + + public Builder readRequests(long readRequests) { + this.readRequests = readRequests; + return this; + } + + public Builder writeBytes(long writeBytes) { + this.writeBytes = writeBytes; + return this; + } + + public Builder writeRequests(long writeRequests) { + this.writeRequests = writeRequests; + return this; + } + + public DriveMetrics build() { + return new DriveMetrics(readBytes, readRequests, writeBytes, writeRequests); + } + } + + protected final long readBytes; + protected final long readRequests; + protected final long writeBytes; + protected final long writeRequests; + + public DriveMetrics(long readBytes, long readRequests, long writeBytes, long writeRequests) { + this.readBytes = readBytes; + this.readRequests = readRequests; + this.writeBytes = writeBytes; + this.writeRequests = writeRequests; + } + + /** + * + * @return Cumulative i/o byte/request count for each drive + */ + public long getReadBytes() { + return readBytes; + } + + /** + * + * @return Cumulative i/o byte/request count for each drive + */ + public long getReadRequests() { + return readRequests; + } + + /** + * + * @return Cumulative i/o byte/request count for each drive + */ + public long getWriteBytes() { + return writeBytes; + } + + /** + * + * @return Cumulative i/o byte/request count for each drive + */ + public long getWriteRequests() { + return writeRequests; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + (int) (readBytes ^ (readBytes >>> 32)); + result = prime * result + (int) (readRequests ^ (readRequests >>> 32)); + result = prime * result + (int) (writeBytes ^ (writeBytes >>> 32)); + result = prime * result + (int) (writeRequests ^ (writeRequests >>> 32)); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + DriveMetrics other = (DriveMetrics) obj; + if (readBytes != other.readBytes) + return false; + if (readRequests != other.readRequests) + return false; + if (writeBytes != other.writeBytes) + return false; + if (writeRequests != other.writeRequests) + return false; + return true; + } + + @Override + public String toString() { + return "[readBytes=" + readBytes + ", readRequests=" + readRequests + ", writeBytes=" + writeBytes + + ", writeRequests=" + writeRequests + "]"; + } +} \ No newline at end of file diff --git a/sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/domain/Server.java b/sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/domain/Server.java new file mode 100644 index 0000000000..dc50aa7b91 --- /dev/null +++ b/sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/domain/Server.java @@ -0,0 +1,297 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.elasticstack.domain; + +import static com.google.common.base.Preconditions.checkNotNull; + +import java.util.List; +import java.util.Map; +import java.util.Set; + +import javax.annotation.Nullable; + +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.ImmutableSet; + +/** + * + * @author Adrian Cole + */ +public class Server extends Item { + + public static class Builder extends Item.Builder { + protected int cpu; + protected Integer smp; + protected int mem; + protected boolean persistent; + protected Map devices = ImmutableMap.of(); + protected Set bootDeviceIds = ImmutableSet.of(); + protected List nics = ImmutableList.of(); + protected VNC vnc; + // TODO undocumented + protected String description; + + public Builder cpu(int cpu) { + this.cpu = cpu; + return this; + } + + public Builder smp(Integer smp) { + this.smp = smp; + return this; + } + + public Builder mem(int mem) { + this.mem = mem; + return this; + } + + public Builder persistent(boolean persistent) { + this.persistent = persistent; + return this; + } + + public Builder devices(Map devices) { + this.devices = ImmutableMap.copyOf(checkNotNull(devices, "devices")); + return this; + } + + public Builder bootDeviceIds(Iterable bootDeviceIds) { + this.bootDeviceIds = ImmutableSet.copyOf(checkNotNull(bootDeviceIds, "bootDeviceIds")); + return this; + } + + public Builder nics(Iterable nics) { + this.nics = ImmutableList.copyOf(checkNotNull(nics, "nics")); + return this; + } + + public Builder vnc(VNC vnc) { + this.vnc = vnc; + return this; + } + + public Builder description(String description) { + this.description = description; + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public Builder uuid(String uuid) { + return Builder.class.cast(super.uuid(uuid)); + } + + /** + * {@inheritDoc} + */ + @Override + public Builder name(String name) { + return Builder.class.cast(super.name(name)); + } + + /** + * {@inheritDoc} + */ + @Override + public Builder tags(Iterable tags) { + return Builder.class.cast(super.tags(tags)); + } + + /** + * {@inheritDoc} + */ + @Override + public Builder userMetadata(Map userMetadata) { + return Builder.class.cast(super.userMetadata(userMetadata)); + } + + public Server build() { + return new Server(uuid, name, cpu, smp, mem, persistent, devices, tags, bootDeviceIds, userMetadata, nics, + vnc, description); + } + } + + protected final int cpu; + protected final Integer smp; + protected final int mem; + protected final boolean persistent; + @Nullable + protected final Map devices; + protected final Set bootDeviceIds; + protected final List nics; + protected final VNC vnc; + @Nullable + private final String description; + + public Server(@Nullable String uuid, String name, int cpu, @Nullable Integer smp, int mem, boolean persistent, + Map devices, Iterable bootDeviceIds, Iterable tags, + Map userMetadata, Iterable nics, VNC vnc, String description) { + super(uuid, name, tags, userMetadata); + this.cpu = cpu; + this.smp = smp; + this.mem = mem; + this.persistent = persistent; + this.devices = ImmutableMap.copyOf(checkNotNull(devices, "devices")); + this.bootDeviceIds = ImmutableSet.copyOf(checkNotNull(bootDeviceIds, "bootDeviceIds")); + this.nics = ImmutableList.copyOf(checkNotNull(nics, "nics")); + this.vnc = checkNotNull(vnc, "vnc"); + this.description = description; + } + + /** + * + * @return CPU quota in core MHz. + */ + public int getCpu() { + return cpu; + } + + /** + * + * @return number of virtual processors or null if calculated based on cpu. + */ + public Integer getSmp() { + return smp; + } + + /** + * + * @return virtual memory size in MB. + */ + public int getMem() { + return mem; + } + + /** + * + * @return 'true' means that server will revert to a 'stopped' status on server stop or shutdown, + * rather than being destroyed automatically. + */ + public boolean isPersistent() { + return persistent; + } + + /** + * + * @return devices present, mapped by id + */ + public Map getDevices() { + return devices; + } + + /** + * + * @return ids of the devices to boot, e.g. ide:0:0 or ide:1:0 + * @see Device#getId() + */ + public Set getBootDeviceIds() { + return bootDeviceIds; + } + + public List getNics() { + return nics; + } + + public VNC getVnc() { + return vnc; + } + + // TODO undocumented + public String getDescription() { + return description; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = super.hashCode(); + result = prime * result + ((bootDeviceIds == null) ? 0 : bootDeviceIds.hashCode()); + result = prime * result + cpu; + result = prime * result + ((description == null) ? 0 : description.hashCode()); + result = prime * result + ((devices == null) ? 0 : devices.hashCode()); + result = prime * result + mem; + result = prime * result + ((nics == null) ? 0 : nics.hashCode()); + result = prime * result + (persistent ? 1231 : 1237); + result = prime * result + ((smp == null) ? 0 : smp.hashCode()); + result = prime * result + ((vnc == null) ? 0 : vnc.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (!super.equals(obj)) + return false; + if (getClass() != obj.getClass()) + return false; + Server other = (Server) obj; + if (bootDeviceIds == null) { + if (other.bootDeviceIds != null) + return false; + } else if (!bootDeviceIds.equals(other.bootDeviceIds)) + return false; + if (cpu != other.cpu) + return false; + if (description == null) { + if (other.description != null) + return false; + } else if (!description.equals(other.description)) + return false; + if (devices == null) { + if (other.devices != null) + return false; + } else if (!devices.equals(other.devices)) + return false; + if (mem != other.mem) + return false; + if (nics == null) { + if (other.nics != null) + return false; + } else if (!nics.equals(other.nics)) + return false; + if (persistent != other.persistent) + return false; + if (smp == null) { + if (other.smp != null) + return false; + } else if (!smp.equals(other.smp)) + return false; + if (vnc == null) { + if (other.vnc != null) + return false; + } else if (!vnc.equals(other.vnc)) + return false; + return true; + } + + @Override + public String toString() { + return "[uuid=" + uuid + ", name=" + name + ", tags=" + tags + ", userMetadata=" + userMetadata + ", cpu=" + cpu + + ", smp=" + smp + ", mem=" + mem + ", persistent=" + persistent + ", devices=" + devices + + ", bootDeviceIds=" + bootDeviceIds + ", nics=" + nics + ", vnc=" + vnc + ", description=" + description + + "]"; + } + +} \ No newline at end of file diff --git a/sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/domain/ServerMetrics.java b/sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/domain/ServerMetrics.java new file mode 100644 index 0000000000..48a079bcb3 --- /dev/null +++ b/sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/domain/ServerMetrics.java @@ -0,0 +1,156 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.elasticstack.domain; + +import static com.google.common.base.Preconditions.checkNotNull; + +import java.util.Map; + +import com.google.common.collect.ImmutableMap; + +/** + * + * @author Adrian Cole + */ +public class ServerMetrics { + + public static class Builder { + protected long txPackets; + protected long tx; + protected long rxPackets; + protected long rx; + protected Map driveMetrics = ImmutableMap. of(); + + public Builder txPackets(long txPackets) { + this.txPackets = txPackets; + return this; + } + + public Builder tx(long tx) { + this.tx = tx; + return this; + } + + public Builder rxPackets(long rxPackets) { + this.rxPackets = rxPackets; + return this; + } + + public Builder rx(long rx) { + this.rx = rx; + return this; + } + + public Builder driveMetrics(Map driveMetrics) { + this.driveMetrics = ImmutableMap.copyOf(checkNotNull(driveMetrics, "driveMetrics")); + return this; + } + + public ServerMetrics build() { + return new ServerMetrics(tx, txPackets, rx, rxPackets, driveMetrics); + } + } + + protected final long txPackets; + protected final long tx; + protected final long rxPackets; + protected final long rx; + protected final Map driveMetrics; + + public ServerMetrics(long tx, long txPackets, long rx, long rxPackets, Map driveMetrics) { + this.txPackets = txPackets; + this.tx = tx; + this.rxPackets = rxPackets; + this.rx = rx; + this.driveMetrics = ImmutableMap.copyOf(checkNotNull(driveMetrics, "driveMetrics")); + } + + // TODO undocumented + public long getTxPackets() { + return txPackets; + } + + // TODO undocumented + public long getTx() { + return tx; + } + + // TODO undocumented + public long getRxPackets() { + return rxPackets; + } + + // TODO undocumented + public long getRx() { + return rx; + } + + /** + * + * @return metrics keyed on device id ex. {@code ide:0:0} + */ + public Map getDriveMetrics() { + return driveMetrics; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((driveMetrics == null) ? 0 : driveMetrics.hashCode()); + result = prime * result + (int) (rx ^ (rx >>> 32)); + result = prime * result + (int) (rxPackets ^ (rxPackets >>> 32)); + result = prime * result + (int) (tx ^ (tx >>> 32)); + result = prime * result + (int) (txPackets ^ (txPackets >>> 32)); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + ServerMetrics other = (ServerMetrics) obj; + if (driveMetrics == null) { + if (other.driveMetrics != null) + return false; + } else if (!driveMetrics.equals(other.driveMetrics)) + return false; + if (rx != other.rx) + return false; + if (rxPackets != other.rxPackets) + return false; + if (tx != other.tx) + return false; + if (txPackets != other.txPackets) + return false; + return true; + } + + @Override + public String toString() { + return "[ txPackets=" + txPackets + ", tx=" + tx + ", rxPackets=" + rxPackets + ", rx=" + rx + ", driveMetrics=" + + driveMetrics + "]"; + } + +} \ No newline at end of file diff --git a/sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/functions/MapToDriveMetrics.java b/sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/functions/MapToDriveMetrics.java new file mode 100644 index 0000000000..e7a84950ff --- /dev/null +++ b/sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/functions/MapToDriveMetrics.java @@ -0,0 +1,87 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.elasticstack.functions; + +import java.util.Map; + +import javax.inject.Singleton; + +import org.jclouds.elasticstack.domain.DriveMetrics; + +import com.google.common.base.Function; +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.ImmutableMap.Builder; + +/** + * + * @author Adrian Cole + */ +@Singleton +public class MapToDriveMetrics implements Function, Map> { + + public Map apply(Map from) { + Builder builder = ImmutableMap. builder(); + addIDEDevices(from, builder); + addSCSIDevices(from, builder); + addBlockDevices(from, builder); + return builder.build(); + } + + protected void addBlockDevices(Map from, Builder devices) { + BLOCK: for (int index : new int[] { 0, 1, 2, 3, 4, 5, 6, 7 }) { + String key = String.format("block:0:%d", index); + if (!from.containsKey(key)) + break BLOCK; + devices.put(key, buildMetrics(key, from)); + } + } + + protected void addSCSIDevices(Map from, Builder devices) { + SCSI: for (int unit : new int[] { 0, 1, 2, 3, 4, 5, 6, 7 }) { + String key = String.format("scsi:0:%d", unit); + if (!from.containsKey(key)) + break SCSI; + devices.put(key, buildMetrics(key, from)); + } + } + + protected void addIDEDevices(Map from, Builder devices) { + IDE: for (int bus : new int[] { 0, 1 }) + for (int unit : new int[] { 0, 1 }) { + String key = String.format("ide:%d:%d", bus, unit); + if (!from.containsKey(key)) + break IDE; + devices.put(key, buildMetrics(key, from)); + } + } + + protected DriveMetrics buildMetrics(String key, Map from) { + DriveMetrics.Builder builder = new DriveMetrics.Builder(); + if (from.containsKey(key + ":read:bytes")) + builder.readBytes(new Long(from.get(key + ":read:bytes"))); + if (from.containsKey(key + ":read:requests")) + builder.readRequests(new Long(from.get(key + ":read:requests"))); + if (from.containsKey(key + ":write:bytes")) + builder.writeBytes(new Long(from.get(key + ":write:bytes"))); + if (from.containsKey(key + ":write:requests")) + builder.writeRequests(new Long(from.get(key + ":write:requests"))); + return builder.build(); + } +} \ No newline at end of file diff --git a/sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/functions/MapToServerMetrics.java b/sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/functions/MapToServerMetrics.java new file mode 100644 index 0000000000..283d56e522 --- /dev/null +++ b/sandbox/elasticstack/src/main/java/org/jclouds/elasticstack/functions/MapToServerMetrics.java @@ -0,0 +1,60 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.elasticstack.functions; + +import java.util.Map; + +import javax.inject.Inject; +import javax.inject.Singleton; + +import org.jclouds.elasticstack.domain.DriveMetrics; +import org.jclouds.elasticstack.domain.ServerMetrics; + +import com.google.common.base.Function; + +/** + * + * @author Adrian Cole + */ +@Singleton +public class MapToServerMetrics implements Function, ServerMetrics> { + private final Function, Map> mapToDriveMetrics; + + @Inject + public MapToServerMetrics(Function, Map> mapToDriveMetrics) { + this.mapToDriveMetrics = mapToDriveMetrics; + } + + public ServerMetrics apply(Map from) { + ServerMetrics.Builder metricsBuilder = new ServerMetrics.Builder(); + if (from.containsKey("tx:packets")) + metricsBuilder.txPackets(new Long(from.get("tx:packets"))); + if (from.containsKey("tx")) + metricsBuilder.tx(new Long(from.get("tx"))); + if (from.containsKey("rx:packets")) + metricsBuilder.rxPackets(new Long(from.get("rx:packets"))); + if (from.containsKey("rx")) + metricsBuilder.rx(new Long(from.get("rx"))); + metricsBuilder.driveMetrics(mapToDriveMetrics.apply(from)); + + ServerMetrics metrics = metricsBuilder.build(); + return metrics; + } +} \ No newline at end of file diff --git a/sandbox/elasticstack/src/test/java/org/jclouds/elasticstack/binders/BindDriveToPlainTextStringTest.java b/sandbox/elasticstack/src/test/java/org/jclouds/elasticstack/binders/BindDriveToPlainTextStringTest.java new file mode 100644 index 0000000000..6482fa87bf --- /dev/null +++ b/sandbox/elasticstack/src/test/java/org/jclouds/elasticstack/binders/BindDriveToPlainTextStringTest.java @@ -0,0 +1,92 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.elasticstack.binders; + +import static org.testng.Assert.assertEquals; + +import java.io.IOException; +import java.net.URI; +import java.util.Map; + +import javax.ws.rs.core.MediaType; + +import org.jclouds.elasticstack.domain.ClaimType; +import org.jclouds.elasticstack.domain.CreateDriveRequest; +import org.jclouds.elasticstack.domain.Drive; +import org.jclouds.elasticstack.domain.DriveData; +import org.jclouds.elasticstack.functions.CreateDriveRequestToMap; +import org.jclouds.elasticstack.functions.DriveDataToMap; +import org.jclouds.http.HttpRequest; +import org.jclouds.util.Utils; +import org.testng.annotations.Test; + +import com.google.common.base.Function; +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.ImmutableSet; +import com.google.inject.AbstractModule; +import com.google.inject.Guice; +import com.google.inject.TypeLiteral; + +/** + * + * @author Adrian Cole + */ +@Test(groups = { "unit" }) +public class BindDriveToPlainTextStringTest { + + private static final BindDriveToPlainTextString FN = Guice.createInjector(new AbstractModule() { + + @Override + protected void configure() { + bind(new TypeLiteral>>() { + }).to(CreateDriveRequestToMap.class); + bind(new TypeLiteral>>() { + }).to(DriveDataToMap.class); + } + + }).getInstance(BindDriveToPlainTextString.class); + + public void testSimple() { + HttpRequest request = new HttpRequest("POST", URI.create("https://host/drives/create")); + FN.bindToRequest(request, new CreateDriveRequest.Builder().name("foo").size(100l).build()); + assertEquals(request.getPayload().getContentMetadata().getContentType(), MediaType.TEXT_PLAIN); + assertEquals(request.getPayload().getRawContent(), "name foo\nsize 100"); + } + + public void testComplete() throws IOException { + CreateDriveRequest input = new CreateDriveRequest.Builder() + .name("Ubuntu 10.10 Server Edition Linux 64bit Preinstalled System") + // + .size(8589934592l)// + .claimType(ClaimType.SHARED)// + .readers(ImmutableSet.of("ffffffff-ffff-ffff-ffff-ffffffffffff"))// + .tags(ImmutableSet.of("tag1", "tag2")).userMetadata(ImmutableMap.of("foo", "bar", "baz", "raz"))// + .encryptionCipher("aes-xts-plain").avoid(ImmutableSet.of("avoid1")).build(); + + HttpRequest request = new HttpRequest("POST", URI.create("https://host/drives/create")); + FN.bindToRequest(request, input); + assertEquals(request.getPayload().getContentMetadata().getContentType(), MediaType.TEXT_PLAIN); + assertEquals(request.getPayload().getRawContent(), + Utils.toStringAndClose(BindDriveToPlainTextStringTest.class + .getResourceAsStream("/create_drive.txt"))); + + } + +} \ No newline at end of file From 84b76c060602fb5b5512a9c4f8eb3f4ade958a07 Mon Sep 17 00:00:00 2001 From: Adrian Cole Date: Mon, 6 Dec 2010 21:32:34 +0000 Subject: [PATCH 28/31] Issue 421: Updated to google gson 1.6, and patched their classes to support natural parsing of Map --- core/pom.xml | 2 +- .../google/gson/JcloudsCompactFormatter.java | 182 ---- .../gson/JcloudsDefaultTypeAdapters.java | 928 ------------------ .../com/google/gson/JcloudsGsonBuilder.java | 591 ----------- .../gson/JcloudsGsonPackageAccessor.java | 33 + .../com/google/gson/JcloudsTreeNavigator.java | 138 --- .../java/com/google/gson/MapTypeAdapter.java | 71 ++ .../main/java/com/google/gson/Streams.java | 192 ++++ .../com/google/gson/stream/JsonWriter.java | 568 +++++++++++ core/src/main/java/org/jclouds/Constants.java | 4 - .../org/jclouds/json/config/GsonModule.java | 67 +- .../EnumTypeAdapterThatReturnsFromValue.java | 82 ++ .../json/internal/JsonObjectAsMap.java | 59 ++ .../json/internal/ParseObjectFromElement.java | 59 ++ .../java/org/jclouds/domain/JsonBallTest.java | 14 +- .../org/jclouds/domain/JsonObjectTest.java | 98 ++ .../test/java/org/jclouds/json/JsonTest.java | 41 + .../gogrid/config/GoGridParserModule.java | 3 - .../ParseCredentialsFromJsonResponseTest.java | 2 - .../ParseJobsFromJsonResponseTest.java | 2 - ...arseLoadBalancersFromJsonResponseTest.java | 2 - ...eToCredentialsMapFromJsonResponseTest.java | 2 - .../ParseServersFromJsonResponseTest.java | 2 - 23 files changed, 1239 insertions(+), 1903 deletions(-) delete mode 100644 core/src/main/java/com/google/gson/JcloudsCompactFormatter.java delete mode 100644 core/src/main/java/com/google/gson/JcloudsDefaultTypeAdapters.java delete mode 100644 core/src/main/java/com/google/gson/JcloudsGsonBuilder.java create mode 100644 core/src/main/java/com/google/gson/JcloudsGsonPackageAccessor.java delete mode 100644 core/src/main/java/com/google/gson/JcloudsTreeNavigator.java create mode 100644 core/src/main/java/com/google/gson/MapTypeAdapter.java create mode 100644 core/src/main/java/com/google/gson/Streams.java create mode 100644 core/src/main/java/com/google/gson/stream/JsonWriter.java create mode 100644 core/src/main/java/org/jclouds/json/internal/EnumTypeAdapterThatReturnsFromValue.java create mode 100644 core/src/main/java/org/jclouds/json/internal/JsonObjectAsMap.java create mode 100644 core/src/main/java/org/jclouds/json/internal/ParseObjectFromElement.java create mode 100644 core/src/test/java/org/jclouds/domain/JsonObjectTest.java diff --git a/core/pom.xml b/core/pom.xml index 372ab3e87b..aa4156ab2e 100644 --- a/core/pom.xml +++ b/core/pom.xml @@ -101,7 +101,7 @@ com.google.code.gson gson - 1.5 + 1.6 com.google.guava diff --git a/core/src/main/java/com/google/gson/JcloudsCompactFormatter.java b/core/src/main/java/com/google/gson/JcloudsCompactFormatter.java deleted file mode 100644 index 52670be44c..0000000000 --- a/core/src/main/java/com/google/gson/JcloudsCompactFormatter.java +++ /dev/null @@ -1,182 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -/* - * Copyright (C) 2010 Google Inc. - * - * 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 com.google.gson; - -import java.io.IOException; - -/** - * The only reason I am pasting this class and changing 2 lines is because the - * gson project uses abstract classes and final otherwise for every part one - * might want to extend. We simply need to control the formatting of json - * literals, and hopefully one day gson will allow us to subclass something. - * - * @author Adrian Cole - * @author Inderjeet Singh - */ -public class JcloudsCompactFormatter implements JsonFormatter { - - static class FormattingVisitor implements JsonElementVisitor { - private final Appendable writer; - private final Escaper escaper; - private final boolean serializeNulls; - - FormattingVisitor(Appendable writer, Escaper escaper, boolean serializeNulls) { - this.writer = writer; - this.escaper = escaper; - this.serializeNulls = serializeNulls; - } - - public void visitLiteral(JsonLiteral primitive) throws IOException { - primitive.toString(writer, escaper); - } - - public void visitPrimitive(JsonPrimitive primitive) throws IOException { - primitive.toString(writer, escaper); - } - - public void visitNull() throws IOException { - writer.append("null"); - } - - public void startArray(JsonArray array) throws IOException { - writer.append('['); - } - - public void visitArrayMember(JsonArray parent, JsonPrimitive member, boolean isFirst) throws IOException { - if (!isFirst) { - writer.append(','); - } - member.toString(writer, escaper); - } - - public void visitArrayMember(JsonArray parent, JsonArray member, boolean isFirst) throws IOException { - if (!isFirst) { - writer.append(','); - } - } - - public void visitArrayMember(JsonArray parent, JsonObject member, boolean isFirst) throws IOException { - if (!isFirst) { - writer.append(','); - } - } - - public void visitNullArrayMember(JsonArray parent, boolean isFirst) throws IOException { - if (!isFirst) { - writer.append(','); - } - } - - public void endArray(JsonArray array) throws IOException { - writer.append(']'); - } - - public void startObject(JsonObject object) throws IOException { - writer.append('{'); - } - - public void visitObjectMember(JsonObject parent, String memberName, JsonLiteral member, boolean isFirst) - throws IOException { - if (!isFirst) { - writer.append(','); - } - writer.append('"'); - writer.append(memberName); - writer.append("\":"); - member.toString(writer, escaper); - } - - public void visitObjectMember(JsonObject parent, String memberName, JsonPrimitive member, boolean isFirst) - throws IOException { - if (!isFirst) { - writer.append(','); - } - writer.append('"'); - writer.append(memberName); - writer.append("\":"); - member.toString(writer, escaper); - } - - public void visitObjectMember(JsonObject parent, String memberName, JsonArray member, boolean isFirst) - throws IOException { - if (!isFirst) { - writer.append(','); - } - writer.append('"'); - writer.append(memberName); - writer.append("\":"); - } - - public void visitObjectMember(JsonObject parent, String memberName, JsonObject member, boolean isFirst) - throws IOException { - if (!isFirst) { - writer.append(','); - } - writer.append('"'); - writer.append(memberName); - writer.append("\":"); - } - - public void visitNullObjectMember(JsonObject parent, String memberName, boolean isFirst) throws IOException { - if (serializeNulls) { - visitObjectMember(parent, memberName, (JsonObject) null, isFirst); - } - } - - public void endObject(JsonObject object) throws IOException { - writer.append('}'); - } - } - - private final boolean escapeHtmlChars; - - public JcloudsCompactFormatter() { - this(true); - } - - JcloudsCompactFormatter(boolean escapeHtmlChars) { - this.escapeHtmlChars = escapeHtmlChars; - } - - public void format(JsonElement root, Appendable writer, boolean serializeNulls) throws IOException { - if (root == null) { - return; - } - FormattingVisitor visitor = new FormattingVisitor(writer, new Escaper(escapeHtmlChars), serializeNulls); - JcloudsTreeNavigator navigator = new JcloudsTreeNavigator(visitor, serializeNulls); - navigator.navigate(root); - } -} diff --git a/core/src/main/java/com/google/gson/JcloudsDefaultTypeAdapters.java b/core/src/main/java/com/google/gson/JcloudsDefaultTypeAdapters.java deleted file mode 100644 index 39fdc04c80..0000000000 --- a/core/src/main/java/com/google/gson/JcloudsDefaultTypeAdapters.java +++ /dev/null @@ -1,928 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -/* - * Copyright (C) 2008 Google Inc. - * - * 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 com.google.gson; - -import java.lang.reflect.Method; -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.Type; -import java.math.BigDecimal; -import java.math.BigInteger; -import java.net.MalformedURLException; -import java.net.URI; -import java.net.URISyntaxException; -import java.net.URL; -import java.sql.Time; -import java.sql.Timestamp; -import java.text.DateFormat; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.Calendar; -import java.util.Collection; -import java.util.Date; -import java.util.GregorianCalendar; -import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.LinkedList; -import java.util.Locale; -import java.util.Map; -import java.util.Properties; -import java.util.Set; -import java.util.SortedSet; -import java.util.StringTokenizer; -import java.util.TreeSet; -import java.util.UUID; - -import com.google.common.base.Function; -import com.google.common.collect.MapMaker; - -/** - * List of all the default type adapters ({@link JsonSerializer}s, {@link JsonDeserializer}s, and - * {@link InstanceCreator}s. - * - *

Note!

- * changed to edit the default behaviour of enum parsing by Adrian Cole - * - * @author Inderjeet Singh - * @author Joel Leitch - */ -final class JcloudsDefaultTypeAdapters { - - private static final DefaultDateTypeAdapter DATE_TYPE_ADAPTER = new DefaultDateTypeAdapter(); - private static final DefaultJavaSqlDateTypeAdapter JAVA_SQL_DATE_TYPE_ADAPTER = new DefaultJavaSqlDateTypeAdapter(); - private static final DefaultTimeTypeAdapter TIME_TYPE_ADAPTER = new DefaultTimeTypeAdapter(); - private static final DefaultTimestampDeserializer TIMESTAMP_DESERIALIZER = new DefaultTimestampDeserializer(); - - @SuppressWarnings({ "rawtypes" }) - private static final EnumTypeAdapter ENUM_TYPE_ADAPTER = new EnumTypeAdapter(); - private static final UrlTypeAdapter URL_TYPE_ADAPTER = new UrlTypeAdapter(); - private static final UriTypeAdapter URI_TYPE_ADAPTER = new UriTypeAdapter(); - private static final UuidTypeAdapter UUUID_TYPE_ADAPTER = new UuidTypeAdapter(); - private static final LocaleTypeAdapter LOCALE_TYPE_ADAPTER = new LocaleTypeAdapter(); - private static final CollectionTypeAdapter COLLECTION_TYPE_ADAPTER = new CollectionTypeAdapter(); - private static final MapTypeAdapter MAP_TYPE_ADAPTER = new MapTypeAdapter(); - private static final BigDecimalTypeAdapter BIG_DECIMAL_TYPE_ADAPTER = new BigDecimalTypeAdapter(); - private static final BigIntegerTypeAdapter BIG_INTEGER_TYPE_ADAPTER = new BigIntegerTypeAdapter(); - - private static final BooleanTypeAdapter BOOLEAN_TYPE_ADAPTER = new BooleanTypeAdapter(); - private static final ByteTypeAdapter BYTE_TYPE_ADAPTER = new ByteTypeAdapter(); - private static final CharacterTypeAdapter CHARACTER_TYPE_ADAPTER = new CharacterTypeAdapter(); - private static final DoubleDeserializer DOUBLE_TYPE_ADAPTER = new DoubleDeserializer(); - private static final FloatDeserializer FLOAT_TYPE_ADAPTER = new FloatDeserializer(); - private static final IntegerTypeAdapter INTEGER_TYPE_ADAPTER = new IntegerTypeAdapter(); - private static final LongDeserializer LONG_DESERIALIZER = new LongDeserializer(); - private static final NumberTypeAdapter NUMBER_TYPE_ADAPTER = new NumberTypeAdapter(); - private static final ShortTypeAdapter SHORT_TYPE_ADAPTER = new ShortTypeAdapter(); - private static final StringTypeAdapter STRING_TYPE_ADAPTER = new StringTypeAdapter(); - - private static final PropertiesCreator PROPERTIES_CREATOR = new PropertiesCreator(); - private static final TreeSetCreator TREE_SET_CREATOR = new TreeSetCreator(); - private static final HashSetCreator HASH_SET_CREATOR = new HashSetCreator(); - private static final GregorianCalendarTypeAdapter GREGORIAN_CALENDAR_TYPE_ADAPTER = new GregorianCalendarTypeAdapter(); - - // The constants DEFAULT_SERIALIZERS, DEFAULT_DESERIALIZERS, and DEFAULT_INSTANCE_CREATORS - // must be defined after the constants for the type adapters. Otherwise, the type adapter - // constants will appear as nulls. - private static final ParameterizedTypeHandlerMap> DEFAULT_SERIALIZERS = createDefaultSerializers(); - private static final ParameterizedTypeHandlerMap> DEFAULT_DESERIALIZERS = createDefaultDeserializers(); - private static final ParameterizedTypeHandlerMap> DEFAULT_INSTANCE_CREATORS = createDefaultInstanceCreators(); - - private static ParameterizedTypeHandlerMap> createDefaultSerializers() { - ParameterizedTypeHandlerMap> map = new ParameterizedTypeHandlerMap>(); - - map.registerForTypeHierarchy(Enum.class, ENUM_TYPE_ADAPTER); - map.register(URL.class, URL_TYPE_ADAPTER); - map.register(URI.class, URI_TYPE_ADAPTER); - map.register(UUID.class, UUUID_TYPE_ADAPTER); - map.register(Locale.class, LOCALE_TYPE_ADAPTER); - map.registerForTypeHierarchy(Collection.class, COLLECTION_TYPE_ADAPTER); - map.registerForTypeHierarchy(Map.class, MAP_TYPE_ADAPTER); - map.register(Date.class, DATE_TYPE_ADAPTER); - map.register(java.sql.Date.class, JAVA_SQL_DATE_TYPE_ADAPTER); - map.register(Timestamp.class, DATE_TYPE_ADAPTER); - map.register(Time.class, TIME_TYPE_ADAPTER); - map.register(Calendar.class, GREGORIAN_CALENDAR_TYPE_ADAPTER); - map.register(GregorianCalendar.class, GREGORIAN_CALENDAR_TYPE_ADAPTER); - map.register(BigDecimal.class, BIG_DECIMAL_TYPE_ADAPTER); - map.register(BigInteger.class, BIG_INTEGER_TYPE_ADAPTER); - - // Add primitive serializers - map.register(Boolean.class, BOOLEAN_TYPE_ADAPTER); - map.register(boolean.class, BOOLEAN_TYPE_ADAPTER); - map.register(Byte.class, BYTE_TYPE_ADAPTER); - map.register(byte.class, BYTE_TYPE_ADAPTER); - map.register(Character.class, CHARACTER_TYPE_ADAPTER); - map.register(char.class, CHARACTER_TYPE_ADAPTER); - map.register(Integer.class, INTEGER_TYPE_ADAPTER); - map.register(int.class, INTEGER_TYPE_ADAPTER); - map.register(Number.class, NUMBER_TYPE_ADAPTER); - map.register(Short.class, SHORT_TYPE_ADAPTER); - map.register(short.class, SHORT_TYPE_ADAPTER); - map.register(String.class, STRING_TYPE_ADAPTER); - - map.makeUnmodifiable(); - return map; - } - - private static ParameterizedTypeHandlerMap> createDefaultDeserializers() { - ParameterizedTypeHandlerMap> map = new ParameterizedTypeHandlerMap>(); - map.registerForTypeHierarchy(Enum.class, wrapDeserializer(ENUM_TYPE_ADAPTER)); - map.register(URL.class, wrapDeserializer(URL_TYPE_ADAPTER)); - map.register(URI.class, wrapDeserializer(URI_TYPE_ADAPTER)); - map.register(UUID.class, wrapDeserializer(UUUID_TYPE_ADAPTER)); - map.register(Locale.class, wrapDeserializer(LOCALE_TYPE_ADAPTER)); - map.registerForTypeHierarchy(Collection.class, wrapDeserializer(COLLECTION_TYPE_ADAPTER)); - map.registerForTypeHierarchy(Map.class, wrapDeserializer(MAP_TYPE_ADAPTER)); - map.register(Date.class, wrapDeserializer(DATE_TYPE_ADAPTER)); - map.register(java.sql.Date.class, wrapDeserializer(JAVA_SQL_DATE_TYPE_ADAPTER)); - map.register(Timestamp.class, wrapDeserializer(TIMESTAMP_DESERIALIZER)); - map.register(Time.class, wrapDeserializer(TIME_TYPE_ADAPTER)); - map.register(Calendar.class, GREGORIAN_CALENDAR_TYPE_ADAPTER); - map.register(GregorianCalendar.class, GREGORIAN_CALENDAR_TYPE_ADAPTER); - map.register(BigDecimal.class, wrapDeserializer(BIG_DECIMAL_TYPE_ADAPTER)); - map.register(BigInteger.class, wrapDeserializer(BIG_INTEGER_TYPE_ADAPTER)); - - // Add primitive deserializers - map.register(Boolean.class, wrapDeserializer(BOOLEAN_TYPE_ADAPTER)); - map.register(boolean.class, wrapDeserializer(BOOLEAN_TYPE_ADAPTER)); - map.register(Byte.class, wrapDeserializer(BYTE_TYPE_ADAPTER)); - map.register(byte.class, wrapDeserializer(BYTE_TYPE_ADAPTER)); - map.register(Character.class, wrapDeserializer(CHARACTER_TYPE_ADAPTER)); - map.register(char.class, wrapDeserializer(CHARACTER_TYPE_ADAPTER)); - map.register(Double.class, wrapDeserializer(DOUBLE_TYPE_ADAPTER)); - map.register(double.class, wrapDeserializer(DOUBLE_TYPE_ADAPTER)); - map.register(Float.class, wrapDeserializer(FLOAT_TYPE_ADAPTER)); - map.register(float.class, wrapDeserializer(FLOAT_TYPE_ADAPTER)); - map.register(Integer.class, wrapDeserializer(INTEGER_TYPE_ADAPTER)); - map.register(int.class, wrapDeserializer(INTEGER_TYPE_ADAPTER)); - map.register(Long.class, wrapDeserializer(LONG_DESERIALIZER)); - map.register(long.class, wrapDeserializer(LONG_DESERIALIZER)); - map.register(Number.class, wrapDeserializer(NUMBER_TYPE_ADAPTER)); - map.register(Short.class, wrapDeserializer(SHORT_TYPE_ADAPTER)); - map.register(short.class, wrapDeserializer(SHORT_TYPE_ADAPTER)); - map.register(String.class, wrapDeserializer(STRING_TYPE_ADAPTER)); - - map.makeUnmodifiable(); - return map; - } - - private static ParameterizedTypeHandlerMap> createDefaultInstanceCreators() { - ParameterizedTypeHandlerMap> map = new ParameterizedTypeHandlerMap>(); - map.registerForTypeHierarchy(Map.class, MAP_TYPE_ADAPTER); - - // Add Collection type instance creators - map.registerForTypeHierarchy(Collection.class, COLLECTION_TYPE_ADAPTER); - - map.registerForTypeHierarchy(Set.class, HASH_SET_CREATOR); - map.registerForTypeHierarchy(SortedSet.class, TREE_SET_CREATOR); - map.register(Properties.class, PROPERTIES_CREATOR); - map.makeUnmodifiable(); - return map; - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - private static JsonDeserializer wrapDeserializer(JsonDeserializer deserializer) { - return new JsonDeserializerExceptionWrapper(deserializer); - } - - static ParameterizedTypeHandlerMap> getDefaultSerializers() { - return getDefaultSerializers(false, LongSerializationPolicy.DEFAULT); - } - - static ParameterizedTypeHandlerMap> getDefaultSerializers( - boolean serializeSpecialFloatingPointValues, LongSerializationPolicy longSerializationPolicy) { - ParameterizedTypeHandlerMap> serializers = new ParameterizedTypeHandlerMap>(); - - // Double primitive - JcloudsDefaultTypeAdapters.DoubleSerializer doubleSerializer = new JcloudsDefaultTypeAdapters.DoubleSerializer( - serializeSpecialFloatingPointValues); - serializers.registerIfAbsent(Double.class, doubleSerializer); - serializers.registerIfAbsent(double.class, doubleSerializer); - - // Float primitive - JcloudsDefaultTypeAdapters.FloatSerializer floatSerializer = new JcloudsDefaultTypeAdapters.FloatSerializer( - serializeSpecialFloatingPointValues); - serializers.registerIfAbsent(Float.class, floatSerializer); - serializers.registerIfAbsent(float.class, floatSerializer); - - // Long primitive - JcloudsDefaultTypeAdapters.LongSerializer longSerializer = new JcloudsDefaultTypeAdapters.LongSerializer( - longSerializationPolicy); - serializers.registerIfAbsent(Long.class, longSerializer); - serializers.registerIfAbsent(long.class, longSerializer); - - serializers.registerIfAbsent(DEFAULT_SERIALIZERS); - return serializers; - } - - static ParameterizedTypeHandlerMap> getDefaultDeserializers() { - return DEFAULT_DESERIALIZERS; - } - - static ParameterizedTypeHandlerMap> getDefaultInstanceCreators() { - return DEFAULT_INSTANCE_CREATORS; - } - - static class DefaultDateTypeAdapter implements JsonSerializer, JsonDeserializer { - private final DateFormat format; - - DefaultDateTypeAdapter() { - this.format = DateFormat.getDateTimeInstance(); - } - - DefaultDateTypeAdapter(final String datePattern) { - this.format = new SimpleDateFormat(datePattern); - } - - DefaultDateTypeAdapter(final int style) { - this.format = DateFormat.getDateInstance(style); - } - - public DefaultDateTypeAdapter(final int dateStyle, final int timeStyle) { - this.format = DateFormat.getDateTimeInstance(dateStyle, timeStyle); - } - - // These methods need to be synchronized since JDK DateFormat classes are not thread-safe - // See issue 162 - public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) { - synchronized (format) { - String dateFormatAsString = format.format(src); - return new JsonPrimitive(dateFormatAsString); - } - } - - public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) - throws JsonParseException { - if (!(json instanceof JsonPrimitive)) { - throw new JsonParseException("The date should be a string value"); - } - try { - synchronized (format) { - return format.parse(json.getAsString()); - } - } catch (ParseException e) { - throw new JsonParseException(e); - } - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append(DefaultDateTypeAdapter.class.getSimpleName()); - sb.append('(').append(format.getClass().getSimpleName()).append(')'); - return sb.toString(); - } - } - - static class DefaultJavaSqlDateTypeAdapter implements JsonSerializer, JsonDeserializer { - private final DateFormat format; - - DefaultJavaSqlDateTypeAdapter() { - this.format = new SimpleDateFormat("MMM d, yyyy"); - } - - public JsonElement serialize(java.sql.Date src, Type typeOfSrc, JsonSerializationContext context) { - synchronized (format) { - String dateFormatAsString = format.format(src); - return new JsonPrimitive(dateFormatAsString); - } - } - - public java.sql.Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) - throws JsonParseException { - if (!(json instanceof JsonPrimitive)) { - throw new JsonParseException("The date should be a string value"); - } - try { - synchronized (format) { - Date date = format.parse(json.getAsString()); - return new java.sql.Date(date.getTime()); - } - } catch (ParseException e) { - throw new JsonParseException(e); - } - } - } - - static class DefaultTimestampDeserializer implements JsonDeserializer { - public Timestamp deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) - throws JsonParseException { - Date date = context.deserialize(json, Date.class); - return new Timestamp(date.getTime()); - } - } - - static class DefaultTimeTypeAdapter implements JsonSerializer