From 7086d98d688fcf52492f716a3b8f7472c9e7eb33 Mon Sep 17 00:00:00 2001 From: Andrew Phillips Date: Tue, 25 Oct 2011 10:26:37 -0400 Subject: [PATCH 01/16] maven-gae-plugin 0.8.4 -> 0.9.1 --- demos/tweetstore/gae-tweetstore-spring/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/demos/tweetstore/gae-tweetstore-spring/pom.xml b/demos/tweetstore/gae-tweetstore-spring/pom.xml index 3b4ccb382f..373c1386a2 100644 --- a/demos/tweetstore/gae-tweetstore-spring/pom.xml +++ b/demos/tweetstore/gae-tweetstore-spring/pom.xml @@ -196,7 +196,7 @@ net.kindleit maven-gae-plugin - 0.8.4 + 0.9.1 google-appengine ${appengine.sdk.root} From 1c32b110b22fb219599e5c0fea16312eb7ec42af Mon Sep 17 00:00:00 2001 From: Andrew Phillips Date: Tue, 25 Oct 2011 11:06:32 -0400 Subject: [PATCH 02/16] GAE SDK version 1.5.3 -> 1.5.5 --- demos/tweetstore/gae-tweetstore-spring/pom.xml | 2 +- demos/tweetstore/gae-tweetstore/pom.xml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/demos/tweetstore/gae-tweetstore-spring/pom.xml b/demos/tweetstore/gae-tweetstore-spring/pom.xml index 373c1386a2..a491ad74eb 100644 --- a/demos/tweetstore/gae-tweetstore-spring/pom.xml +++ b/demos/tweetstore/gae-tweetstore-spring/pom.xml @@ -37,7 +37,7 @@ extraction of appengine-java-sdk --> jclouds-tweetstore-spring - 1.5.3 + 1.5.5 localhost 8088 jclouds-tweetstore-spring diff --git a/demos/tweetstore/gae-tweetstore/pom.xml b/demos/tweetstore/gae-tweetstore/pom.xml index ade456540c..35cdf5dd0c 100644 --- a/demos/tweetstore/gae-tweetstore/pom.xml +++ b/demos/tweetstore/gae-tweetstore/pom.xml @@ -37,7 +37,7 @@ extraction of appengine-java-sdk --> jclouds-tweetstore - 1.5.3 + 1.5.5 localhost 8088 jclouds-tweetstore From 5d252e6fd5a34d517fbbcdf099f028de6bceb0ba Mon Sep 17 00:00:00 2001 From: Adrian Cole Date: Fri, 28 Oct 2011 15:00:56 +0200 Subject: [PATCH 03/16] removed throws clauses to UnsupportedEncodingException where they aren't thrown --- .../AtmosContainerIntegrationLiveTest.java | 6 +- .../jclouds/s3/options/CopyObjectOptions.java | 11 ++-- .../s3/options/CopyObjectOptionsTest.java | 41 +++++++------ .../s3/options/ListBucketOptionsTest.java | 27 +++++---- .../s3/options/PutBucketOptionsTest.java | 4 +- .../s3/options/PutObjectOptionsTest.java | 4 +- .../jclouds/s3/services/BucketsLiveTest.java | 12 ++-- .../java/org/jclouds/s3/xml/S3ParserTest.java | 5 +- .../options/ListContainerOptionsTest.java | 25 ++++---- .../jclouds/blobstore/options/GetOptions.java | 5 +- .../internal/BaseBlobIntegrationTest.java | 8 +-- .../BaseContainerIntegrationTest.java | 14 ++--- .../internal/BaseMapIntegrationTest.java | 3 +- .../blobstore/options/GetOptionsTest.java | 33 ++++++----- .../org/jclouds/http/options/GetOptions.java | 5 -- .../jclouds/http/options/GetOptionsTest.java | 35 ++++++------ .../internal/RestAnnotationProcessorTest.java | 57 +++++++++---------- .../java/org/jclouds/util/Strings2Test.java | 4 +- .../AzureBlobIntegrationLiveTest.java | 3 +- .../jclouds/scriptbuilder/util/UtilsTest.java | 4 +- 20 files changed, 133 insertions(+), 173 deletions(-) diff --git a/apis/atmos/src/test/java/org/jclouds/atmos/blobstore/integration/AtmosContainerIntegrationLiveTest.java b/apis/atmos/src/test/java/org/jclouds/atmos/blobstore/integration/AtmosContainerIntegrationLiveTest.java index 373379bbe9..a2f31c766b 100644 --- a/apis/atmos/src/test/java/org/jclouds/atmos/blobstore/integration/AtmosContainerIntegrationLiveTest.java +++ b/apis/atmos/src/test/java/org/jclouds/atmos/blobstore/integration/AtmosContainerIntegrationLiveTest.java @@ -21,7 +21,6 @@ package org.jclouds.atmos.blobstore.integration; import static org.testng.Assert.assertEquals; import java.io.IOException; -import java.io.UnsupportedEncodingException; import org.jclouds.blobstore.domain.BlobMetadata; import org.jclouds.blobstore.integration.internal.BaseContainerIntegrationTest; @@ -34,13 +33,12 @@ import org.testng.annotations.Test; public class AtmosContainerIntegrationLiveTest extends BaseContainerIntegrationTest { @Override - public void testListContainerMaxResults() throws InterruptedException, - UnsupportedEncodingException { + public void testListContainerMaxResults() throws InterruptedException { // Not currently working } @Override - public void testListContainerMarker() throws InterruptedException, UnsupportedEncodingException { + public void testListContainerMarker() throws InterruptedException { // Not currently working https://community.emc.com/thread/100545 } diff --git a/apis/s3/src/main/java/org/jclouds/s3/options/CopyObjectOptions.java b/apis/s3/src/main/java/org/jclouds/s3/options/CopyObjectOptions.java index b994458180..cc9989a948 100644 --- a/apis/s3/src/main/java/org/jclouds/s3/options/CopyObjectOptions.java +++ b/apis/s3/src/main/java/org/jclouds/s3/options/CopyObjectOptions.java @@ -30,7 +30,6 @@ import static org.jclouds.s3.reference.S3Headers.COPY_SOURCE_IF_UNMODIFIED_SINCE import static org.jclouds.s3.reference.S3Headers.DEFAULT_AMAZON_HEADERTAG; import static org.jclouds.s3.reference.S3Headers.METADATA_DIRECTIVE; -import java.io.UnsupportedEncodingException; import java.util.Date; import java.util.Map; import java.util.Map.Entry; @@ -227,7 +226,7 @@ public class CopyObjectOptions extends BaseHttpRequestOptions { * @param eTag * hash representing the payload */ - public CopyObjectOptions ifSourceETagMatches(String eTag) throws UnsupportedEncodingException { + public CopyObjectOptions ifSourceETagMatches(String eTag) { checkState(getIfNoneMatch() == null, "ifETagDoesntMatch() is not compatible with ifETagMatches()"); checkState(getIfModifiedSince() == null, "ifModifiedSince() is not compatible with ifETagMatches()"); replaceHeader(COPY_SOURCE_IF_MATCH, String.format("\"%1$s\"", checkNotNull(eTag, "eTag"))); @@ -242,10 +241,8 @@ public class CopyObjectOptions extends BaseHttpRequestOptions { * * @param eTag * hash representing the payload - * @throws UnsupportedEncodingException - * if there was a problem converting this into an S3 eTag string */ - public CopyObjectOptions ifSourceETagDoesntMatch(String eTag) throws UnsupportedEncodingException { + public CopyObjectOptions ifSourceETagDoesntMatch(String eTag) { checkState(getIfMatch() == null, "ifETagMatches() is not compatible with ifETagDoesntMatch()"); Preconditions.checkState(getIfUnmodifiedSince() == null, "ifUnmodifiedSince() is not compatible with ifETagDoesntMatch()"); @@ -307,7 +304,7 @@ public class CopyObjectOptions extends BaseHttpRequestOptions { /** * @see CopyObjectOptions#ifSourceETagMatches(String) */ - public static CopyObjectOptions ifSourceETagMatches(String eTag) throws UnsupportedEncodingException { + public static CopyObjectOptions ifSourceETagMatches(String eTag) { CopyObjectOptions options = new CopyObjectOptions(); return options.ifSourceETagMatches(eTag); } @@ -315,7 +312,7 @@ public class CopyObjectOptions extends BaseHttpRequestOptions { /** * @see CopyObjectOptions#ifSourceETagDoesntMatch(String) */ - public static CopyObjectOptions ifSourceETagDoesntMatch(String eTag) throws UnsupportedEncodingException { + public static CopyObjectOptions ifSourceETagDoesntMatch(String eTag) { CopyObjectOptions options = new CopyObjectOptions(); return options.ifSourceETagDoesntMatch(eTag); } diff --git a/apis/s3/src/test/java/org/jclouds/s3/options/CopyObjectOptionsTest.java b/apis/s3/src/test/java/org/jclouds/s3/options/CopyObjectOptionsTest.java index d650de40eb..68ab331456 100644 --- a/apis/s3/src/test/java/org/jclouds/s3/options/CopyObjectOptionsTest.java +++ b/apis/s3/src/test/java/org/jclouds/s3/options/CopyObjectOptionsTest.java @@ -35,7 +35,6 @@ import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNull; import static org.testng.Assert.assertTrue; -import java.io.UnsupportedEncodingException; import java.util.Date; import java.util.Map; @@ -155,7 +154,7 @@ public class CopyObjectOptionsTest { } @Test - public void testIfETagMatches() throws UnsupportedEncodingException { + public void testIfETagMatches() { CopyObjectOptions options = new CopyObjectOptions(); options.ifSourceETagMatches(etag); matchesHex(options.getIfMatch()); @@ -168,18 +167,18 @@ public class CopyObjectOptionsTest { } @Test - public void testIfETagMatchesStatic() throws UnsupportedEncodingException { + public void testIfETagMatchesStatic() { CopyObjectOptions options = ifSourceETagMatches(etag); matchesHex(options.getIfMatch()); } @Test(expectedExceptions = NullPointerException.class) - public void testIfETagMatchesNPE() throws UnsupportedEncodingException { + public void testIfETagMatchesNPE() { ifSourceETagMatches(null); } @Test - public void testIfETagDoesntMatch() throws UnsupportedEncodingException { + public void testIfETagDoesntMatch() { CopyObjectOptions options = new CopyObjectOptions(); options.ifSourceETagDoesntMatch(etag); matchesHex(options.getIfNoneMatch()); @@ -192,17 +191,17 @@ public class CopyObjectOptionsTest { } @Test - public void testIfETagDoesntMatchStatic() throws UnsupportedEncodingException { + public void testIfETagDoesntMatchStatic() { CopyObjectOptions options = ifSourceETagDoesntMatch(etag); matchesHex(options.getIfNoneMatch()); } @Test(expectedExceptions = NullPointerException.class) - public void testIfETagDoesntMatchNPE() throws UnsupportedEncodingException { + public void testIfETagDoesntMatchNPE() { ifSourceETagDoesntMatch(null); } - private void matchesHex(String match) throws UnsupportedEncodingException { + private void matchesHex(String match) { String expected = "\"" + etag + "\""; assertEquals(match, expected); } @@ -213,13 +212,13 @@ public class CopyObjectOptionsTest { } - public void testIfUnmodifiedAfterETagMatches() throws UnsupportedEncodingException { + public void testIfUnmodifiedAfterETagMatches() { ifSourceETagMatches(etag).ifSourceUnmodifiedSince(now); } @Test(expectedExceptions = IllegalStateException.class) - public void testIfUnmodifiedAfterETagDoesntMatch() throws UnsupportedEncodingException { + public void testIfUnmodifiedAfterETagDoesntMatch() { ifSourceETagDoesntMatch(etag).ifSourceUnmodifiedSince(now); } @@ -230,49 +229,49 @@ public class CopyObjectOptionsTest { } @Test(expectedExceptions = IllegalStateException.class) - public void testIfModifiedAfterETagMatches() throws UnsupportedEncodingException { + public void testIfModifiedAfterETagMatches() { ifSourceETagMatches(etag).ifSourceModifiedSince(now); } - public void testIfModifiedAfterETagDoesntMatch() throws UnsupportedEncodingException { + public void testIfModifiedAfterETagDoesntMatch() { ifSourceETagDoesntMatch(etag).ifSourceModifiedSince(now); } @Test(expectedExceptions = IllegalStateException.class) - public void testETagMatchesAfterIfModified() throws UnsupportedEncodingException { + public void testETagMatchesAfterIfModified() { ifSourceModifiedSince(now).ifSourceETagMatches(etag); } - public void testETagMatchesAfterIfUnmodified() throws UnsupportedEncodingException { + public void testETagMatchesAfterIfUnmodified() { ifSourceUnmodifiedSince(now).ifSourceETagMatches(etag); } @Test(expectedExceptions = IllegalStateException.class) - public void testETagMatchesAfterETagDoesntMatch() throws UnsupportedEncodingException { + public void testETagMatchesAfterETagDoesntMatch() { ifSourceETagDoesntMatch(etag).ifSourceETagMatches(etag); } - public void testETagDoesntMatchAfterIfModified() throws UnsupportedEncodingException { + public void testETagDoesntMatchAfterIfModified() { ifSourceModifiedSince(now).ifSourceETagDoesntMatch(etag); } @Test(expectedExceptions = IllegalStateException.class) - public void testETagDoesntMatchAfterIfUnmodified() throws UnsupportedEncodingException { + public void testETagDoesntMatchAfterIfUnmodified() { ifSourceUnmodifiedSince(now).ifSourceETagDoesntMatch(etag); } @Test(expectedExceptions = IllegalStateException.class) - public void testETagDoesntMatchAfterETagMatches() throws UnsupportedEncodingException { + public void testETagDoesntMatchAfterETagMatches() { ifSourceETagMatches(etag).ifSourceETagDoesntMatch(etag); } @Test - void testBuildRequestHeadersWhenMetadataNull() throws UnsupportedEncodingException { + void testBuildRequestHeadersWhenMetadataNull() { CopyObjectOptions options = new CopyObjectOptions(); options.setHeaderTag(DEFAULT_AMAZON_HEADERTAG); @@ -281,7 +280,7 @@ public class CopyObjectOptionsTest { } @Test - void testBuildRequestHeaders() throws UnsupportedEncodingException { + void testBuildRequestHeaders() { CopyObjectOptions options = ifSourceModifiedSince(now).ifSourceETagDoesntMatch(etag).overrideMetadataWith( goodMeta); options.setHeaderTag(DEFAULT_AMAZON_HEADERTAG); @@ -310,7 +309,7 @@ public class CopyObjectOptionsTest { } @Test - void testBuildRequestHeadersACL() throws UnsupportedEncodingException { + void testBuildRequestHeadersACL() { CopyObjectOptions options = overrideAcl(CannedAccessPolicy.AUTHENTICATED_READ); options.setHeaderTag(DEFAULT_AMAZON_HEADERTAG); diff --git a/apis/s3/src/test/java/org/jclouds/s3/options/ListBucketOptionsTest.java b/apis/s3/src/test/java/org/jclouds/s3/options/ListBucketOptionsTest.java index 486fe381d8..7d2839bd95 100644 --- a/apis/s3/src/test/java/org/jclouds/s3/options/ListBucketOptionsTest.java +++ b/apis/s3/src/test/java/org/jclouds/s3/options/ListBucketOptionsTest.java @@ -24,11 +24,10 @@ import static org.jclouds.s3.options.ListBucketOptions.Builder.maxResults; import static org.jclouds.s3.options.ListBucketOptions.Builder.withPrefix; import static org.testng.Assert.assertEquals; -import java.io.UnsupportedEncodingException; import java.util.Collections; -import org.jclouds.s3.reference.S3Constants; import org.jclouds.http.options.HttpRequestOptions; +import org.jclouds.s3.reference.S3Constants; import org.testng.annotations.Test; import com.google.common.collect.Multimap; @@ -47,7 +46,7 @@ public class ListBucketOptionsTest { } @Test - public void testPrefix() throws UnsupportedEncodingException { + public void testPrefix() { ListBucketOptions options = new ListBucketOptions(); options.withPrefix("test"); assertEquals(options.buildQueryParameters().get(S3Constants.PREFIX), Collections @@ -61,7 +60,7 @@ public class ListBucketOptionsTest { } @Test - public void testOneOptionQueryString() throws UnsupportedEncodingException { + public void testOneOptionQueryString() { ListBucketOptions options = new ListBucketOptions(); options.withPrefix("test"); Multimap map = options.buildQueryParameters(); @@ -70,7 +69,7 @@ public class ListBucketOptionsTest { } @Test - public void testTwoOptionQueryString() throws UnsupportedEncodingException { + public void testTwoOptionQueryString() { ListBucketOptions options = new ListBucketOptions(); options.withPrefix("test").maxResults(1); Multimap map = options.buildQueryParameters(); @@ -80,7 +79,7 @@ public class ListBucketOptionsTest { } @Test - public void testPrefixAndDelimiterUrlEncodingQueryString() throws UnsupportedEncodingException { + public void testPrefixAndDelimiterUrlEncodingQueryString() { ListBucketOptions options = new ListBucketOptions(); options.withPrefix("/test").delimiter("/"); Multimap map = options.buildQueryParameters(); @@ -97,19 +96,19 @@ public class ListBucketOptionsTest { } @Test - public void testPrefixStatic() throws UnsupportedEncodingException { + public void testPrefixStatic() { ListBucketOptions options = withPrefix("test"); assertEquals(options.buildQueryParameters().get(S3Constants.PREFIX), Collections .singletonList("test")); } @Test(expectedExceptions = NullPointerException.class) - public void testPrefixNPE() throws UnsupportedEncodingException { + public void testPrefixNPE() { withPrefix(null); } @Test - public void testMarker() throws UnsupportedEncodingException { + public void testMarker() { ListBucketOptions options = new ListBucketOptions(); options.afterMarker("test"); assertEquals(options.buildQueryParameters().get(S3Constants.MARKER), Collections @@ -123,14 +122,14 @@ public class ListBucketOptionsTest { } @Test - public void testMarkerStatic() throws UnsupportedEncodingException { + public void testMarkerStatic() { ListBucketOptions options = afterMarker("test"); assertEquals(options.buildQueryParameters().get(S3Constants.MARKER), Collections .singletonList("test")); } @Test(expectedExceptions = NullPointerException.class) - public void testMarkerNPE() throws UnsupportedEncodingException { + public void testMarkerNPE() { afterMarker(null); } @@ -161,7 +160,7 @@ public class ListBucketOptionsTest { } @Test - public void testDelimiter() throws UnsupportedEncodingException { + public void testDelimiter() { ListBucketOptions options = new ListBucketOptions(); options.delimiter("test"); assertEquals(options.buildQueryParameters().get(S3Constants.DELIMITER), Collections @@ -176,14 +175,14 @@ public class ListBucketOptionsTest { } @Test - public void testDelimiterStatic() throws UnsupportedEncodingException { + public void testDelimiterStatic() { ListBucketOptions options = delimiter("test"); assertEquals(options.buildQueryParameters().get(S3Constants.DELIMITER), Collections .singletonList("test")); } @Test(expectedExceptions = NullPointerException.class) - public void testDelimiterNPE() throws UnsupportedEncodingException { + public void testDelimiterNPE() { delimiter(null); } } diff --git a/apis/s3/src/test/java/org/jclouds/s3/options/PutBucketOptionsTest.java b/apis/s3/src/test/java/org/jclouds/s3/options/PutBucketOptionsTest.java index 435dd98961..adf15842f4 100644 --- a/apis/s3/src/test/java/org/jclouds/s3/options/PutBucketOptionsTest.java +++ b/apis/s3/src/test/java/org/jclouds/s3/options/PutBucketOptionsTest.java @@ -21,8 +21,6 @@ package org.jclouds.s3.options; import static org.jclouds.s3.options.PutBucketOptions.Builder.withBucketAcl; import static org.testng.Assert.assertEquals; -import java.io.UnsupportedEncodingException; - import org.jclouds.s3.domain.CannedAccessPolicy; import org.jclouds.s3.reference.S3Headers; import org.testng.annotations.Test; @@ -50,7 +48,7 @@ public class PutBucketOptionsTest { } @Test - void testBuildRequestHeaders() throws UnsupportedEncodingException { + void testBuildRequestHeaders() { PutBucketOptions options = withBucketAcl(CannedAccessPolicy.AUTHENTICATED_READ); diff --git a/apis/s3/src/test/java/org/jclouds/s3/options/PutObjectOptionsTest.java b/apis/s3/src/test/java/org/jclouds/s3/options/PutObjectOptionsTest.java index c5e2df1d94..556e8e669e 100644 --- a/apis/s3/src/test/java/org/jclouds/s3/options/PutObjectOptionsTest.java +++ b/apis/s3/src/test/java/org/jclouds/s3/options/PutObjectOptionsTest.java @@ -21,8 +21,6 @@ package org.jclouds.s3.options; import static org.jclouds.s3.options.PutObjectOptions.Builder.withAcl; import static org.testng.Assert.assertEquals; -import java.io.UnsupportedEncodingException; - import org.jclouds.s3.domain.CannedAccessPolicy; import org.jclouds.s3.reference.S3Headers; import org.testng.annotations.Test; @@ -50,7 +48,7 @@ public class PutObjectOptionsTest { } @Test - void testBuildRequestHeaders() throws UnsupportedEncodingException { + void testBuildRequestHeaders() { PutObjectOptions options = withAcl(CannedAccessPolicy.AUTHENTICATED_READ); options.setHeaderTag(S3Headers.DEFAULT_AMAZON_HEADERTAG); diff --git a/apis/s3/src/test/java/org/jclouds/s3/services/BucketsLiveTest.java b/apis/s3/src/test/java/org/jclouds/s3/services/BucketsLiveTest.java index 594c1d3b7c..d1b65f5969 100644 --- a/apis/s3/src/test/java/org/jclouds/s3/services/BucketsLiveTest.java +++ b/apis/s3/src/test/java/org/jclouds/s3/services/BucketsLiveTest.java @@ -28,7 +28,6 @@ import static org.testng.Assert.assertNull; import static org.testng.Assert.assertTrue; import java.io.IOException; -import java.io.UnsupportedEncodingException; import java.net.URL; import java.util.Date; import java.util.Set; @@ -36,6 +35,7 @@ import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeoutException; import org.jclouds.aws.domain.Region; +import org.jclouds.blobstore.integration.internal.BaseBlobStoreIntegrationTest; import org.jclouds.s3.S3Client; import org.jclouds.s3.domain.AccessControlList; import org.jclouds.s3.domain.AccessControlList.CanonicalUserGrantee; @@ -50,7 +50,6 @@ import org.jclouds.s3.domain.ListBucketResponse; import org.jclouds.s3.domain.Payer; import org.jclouds.s3.domain.S3Object; import org.jclouds.s3.internal.StubS3AsyncClient; -import org.jclouds.blobstore.integration.internal.BaseBlobStoreIntegrationTest; import org.jclouds.util.Strings2; import org.testng.annotations.Test; @@ -332,8 +331,7 @@ public class BucketsLiveTest extends BaseBlobStoreIntegrationTest { } } - public void testListBucketDelimiter() throws InterruptedException, ExecutionException, TimeoutException, - UnsupportedEncodingException { + public void testListBucketDelimiter() throws InterruptedException, ExecutionException, TimeoutException { String bucketName = getContainerName(); try { String prefix = "apps"; @@ -350,8 +348,7 @@ public class BucketsLiveTest extends BaseBlobStoreIntegrationTest { } - public void testListBucketPrefix() throws InterruptedException, ExecutionException, TimeoutException, - UnsupportedEncodingException { + public void testListBucketPrefix() throws InterruptedException, ExecutionException, TimeoutException { String bucketName = getContainerName(); try { String prefix = "apps"; @@ -368,8 +365,7 @@ public class BucketsLiveTest extends BaseBlobStoreIntegrationTest { } - public void testListBucketMaxResults() throws InterruptedException, ExecutionException, TimeoutException, - UnsupportedEncodingException { + public void testListBucketMaxResults() throws InterruptedException, ExecutionException, TimeoutException { String bucketName = getContainerName(); try { addAlphabetUnderRoot(bucketName); diff --git a/apis/s3/src/test/java/org/jclouds/s3/xml/S3ParserTest.java b/apis/s3/src/test/java/org/jclouds/s3/xml/S3ParserTest.java index b887c69feb..8ae37fc4aa 100644 --- a/apis/s3/src/test/java/org/jclouds/s3/xml/S3ParserTest.java +++ b/apis/s3/src/test/java/org/jclouds/s3/xml/S3ParserTest.java @@ -21,7 +21,6 @@ package org.jclouds.s3.xml; import static org.testng.Assert.assertEquals; import java.io.IOException; -import java.io.UnsupportedEncodingException; import java.net.URI; import java.util.Date; import java.util.Set; @@ -130,7 +129,7 @@ public class S3ParserTest extends PerformanceTest { public static final String listContainerResult = "adrianjbosstest1000false33662009-03-12T02:00:13.000Z"9d7bb64e8e18ee34eec06dd2cf37b766"136e1a5f66a480ca99a4fdfe8e318c3020446c9989d7004e7778029fbcc5d990fa0ferncamSTANDARD"; - public void testCanParseListContainerResult() throws HttpException, UnsupportedEncodingException { + public void testCanParseListContainerResult() throws HttpException { ListBucketResponse container = runParseListContainerResult(); assert !container.isTruncated(); assert container.getName().equals("adrianjbosstest"); @@ -161,7 +160,7 @@ public class S3ParserTest extends PerformanceTest { Strings2.toInputStream(successfulCopyObject200)); } - public void testCanParseCopyObjectResult() throws HttpException, UnsupportedEncodingException { + public void testCanParseCopyObjectResult() throws HttpException { ObjectMetadata metadata = runParseCopyObjectResult(); Date expected = new SimpleDateFormatDateService().iso8601DateParse("2009-03-19T13:23:27.000Z"); assertEquals(metadata.getLastModified(), expected); diff --git a/apis/swift/src/test/java/org/jclouds/openstack/swift/options/ListContainerOptionsTest.java b/apis/swift/src/test/java/org/jclouds/openstack/swift/options/ListContainerOptionsTest.java index d15a7ddd75..ab5d5762d1 100644 --- a/apis/swift/src/test/java/org/jclouds/openstack/swift/options/ListContainerOptionsTest.java +++ b/apis/swift/src/test/java/org/jclouds/openstack/swift/options/ListContainerOptionsTest.java @@ -24,7 +24,6 @@ import static org.jclouds.openstack.swift.options.ListContainerOptions.Builder.u import static org.jclouds.openstack.swift.options.ListContainerOptions.Builder.withPrefix; import static org.testng.Assert.assertEquals; -import java.io.UnsupportedEncodingException; import java.util.Collections; import org.jclouds.http.options.HttpRequestOptions; @@ -47,7 +46,7 @@ public class ListContainerOptionsTest { } @Test - public void testPrefix() throws UnsupportedEncodingException { + public void testPrefix() { ListContainerOptions options = new ListContainerOptions(); options.withPrefix("test"); assertEquals(options.buildQueryParameters().get(SwiftConstants.PREFIX), Collections.singletonList("test")); @@ -60,7 +59,7 @@ public class ListContainerOptionsTest { } @Test - public void testOneOptionQueryString() throws UnsupportedEncodingException { + public void testOneOptionQueryString() { ListContainerOptions options = new ListContainerOptions(); options.withPrefix("test"); Multimap map = options.buildQueryParameters(); @@ -69,7 +68,7 @@ public class ListContainerOptionsTest { } @Test - public void testTwoOptionQueryString() throws UnsupportedEncodingException { + public void testTwoOptionQueryString() { ListContainerOptions options = new ListContainerOptions(); options.withPrefix("test").maxResults(1); Multimap map = options.buildQueryParameters(); @@ -79,7 +78,7 @@ public class ListContainerOptionsTest { } @Test - public void testPrefixAndPathUrlEncodingQueryString() throws UnsupportedEncodingException { + public void testPrefixAndPathUrlEncodingQueryString() { ListContainerOptions options = new ListContainerOptions(); options.withPrefix("/cloudfiles/test").underPath("/"); Multimap map = options.buildQueryParameters(); @@ -96,18 +95,18 @@ public class ListContainerOptionsTest { } @Test - public void testPrefixStatic() throws UnsupportedEncodingException { + public void testPrefixStatic() { ListContainerOptions options = withPrefix("test"); assertEquals(options.buildQueryParameters().get(SwiftConstants.PREFIX), Collections.singletonList("test")); } @Test(expectedExceptions = NullPointerException.class) - public void testPrefixNPE() throws UnsupportedEncodingException { + public void testPrefixNPE() { withPrefix(null); } @Test - public void testMarker() throws UnsupportedEncodingException { + public void testMarker() { ListContainerOptions options = new ListContainerOptions(); options.afterMarker("test"); assertEquals(options.buildQueryParameters().get(SwiftConstants.MARKER), Collections.singletonList("test")); @@ -120,13 +119,13 @@ public class ListContainerOptionsTest { } @Test - public void testMarkerStatic() throws UnsupportedEncodingException { + public void testMarkerStatic() { ListContainerOptions options = afterMarker("test"); assertEquals(options.buildQueryParameters().get(SwiftConstants.MARKER), Collections.singletonList("test")); } @Test(expectedExceptions = NullPointerException.class) - public void testMarkerNPE() throws UnsupportedEncodingException { + public void testMarkerNPE() { afterMarker(null); } @@ -155,7 +154,7 @@ public class ListContainerOptionsTest { } @Test - public void testPath() throws UnsupportedEncodingException { + public void testPath() { ListContainerOptions options = new ListContainerOptions(); options.underPath("test"); assertEquals(options.buildQueryParameters().get(SwiftConstants.PATH), Collections.singletonList("test")); @@ -168,13 +167,13 @@ public class ListContainerOptionsTest { } @Test - public void testPathStatic() throws UnsupportedEncodingException { + public void testPathStatic() { ListContainerOptions options = underPath("test"); assertEquals(options.buildQueryParameters().get(SwiftConstants.PATH), Collections.singletonList("test")); } @Test(expectedExceptions = NullPointerException.class) - public void testPathNPE() throws UnsupportedEncodingException { + public void testPathNPE() { underPath(null); } } diff --git a/blobstore/src/main/java/org/jclouds/blobstore/options/GetOptions.java b/blobstore/src/main/java/org/jclouds/blobstore/options/GetOptions.java index fa172ca061..eb953d28b6 100644 --- a/blobstore/src/main/java/org/jclouds/blobstore/options/GetOptions.java +++ b/blobstore/src/main/java/org/jclouds/blobstore/options/GetOptions.java @@ -21,7 +21,6 @@ package org.jclouds.blobstore.options; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; -import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.Date; import java.util.List; @@ -221,7 +220,7 @@ public class GetOptions { /** * @see GetOptions#ifETagMatches(String) */ - public static GetOptions ifETagMatches(String eTag) throws UnsupportedEncodingException { + public static GetOptions ifETagMatches(String eTag) { GetOptions options = new GetOptions(); return options.ifETagMatches(eTag); } @@ -229,7 +228,7 @@ public class GetOptions { /** * @see GetOptions#ifETagDoesntMatch(String) */ - public static GetOptions ifETagDoesntMatch(String eTag) throws UnsupportedEncodingException { + public static GetOptions ifETagDoesntMatch(String eTag) { GetOptions options = new GetOptions(); return options.ifETagDoesntMatch(eTag); } 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 b36c8c30d7..56323f28a5 100644 --- a/blobstore/src/test/java/org/jclouds/blobstore/integration/internal/BaseBlobIntegrationTest.java +++ b/blobstore/src/test/java/org/jclouds/blobstore/integration/internal/BaseBlobIntegrationTest.java @@ -35,7 +35,6 @@ import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; -import java.io.UnsupportedEncodingException; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateException; import java.util.Arrays; @@ -51,11 +50,11 @@ import javax.ws.rs.core.MediaType; import org.jclouds.blobstore.ContainerNotFoundException; import org.jclouds.blobstore.domain.Blob; +import org.jclouds.blobstore.domain.BlobBuilder.PayloadBlobBuilder; import org.jclouds.blobstore.domain.BlobMetadata; import org.jclouds.blobstore.domain.PageSet; import org.jclouds.blobstore.domain.StorageMetadata; import org.jclouds.blobstore.domain.StorageType; -import org.jclouds.blobstore.domain.BlobBuilder.PayloadBlobBuilder; import org.jclouds.concurrent.Futures; import org.jclouds.crypto.Crypto; import org.jclouds.crypto.CryptoStreams; @@ -268,7 +267,7 @@ public class BaseBlobIntegrationTest extends BaseBlobStoreIntegrationTest { } @Test(groups = { "integration", "live" }) - public void testGetIfMatch() throws InterruptedException, UnsupportedEncodingException { + public void testGetIfMatch() throws InterruptedException { String container = getContainerName(); try { @@ -291,7 +290,7 @@ public class BaseBlobIntegrationTest extends BaseBlobStoreIntegrationTest { } @Test(groups = { "integration", "live" }) - public void testGetIfNoneMatch() throws InterruptedException, UnsupportedEncodingException { + public void testGetIfNoneMatch() throws InterruptedException { String container = getContainerName(); try { @@ -304,7 +303,6 @@ public class BaseBlobIntegrationTest extends BaseBlobStoreIntegrationTest { try { context.getBlobStore().getBlob(container, name, ifETagDoesntMatch(goodETag)); - validateContent(container, name); } catch (HttpResponseException ex) { assertEquals(ex.getResponse().getStatusCode(), 304); } diff --git a/blobstore/src/test/java/org/jclouds/blobstore/integration/internal/BaseContainerIntegrationTest.java b/blobstore/src/test/java/org/jclouds/blobstore/integration/internal/BaseContainerIntegrationTest.java index b313ce34a2..ed2bcc34d5 100644 --- a/blobstore/src/test/java/org/jclouds/blobstore/integration/internal/BaseContainerIntegrationTest.java +++ b/blobstore/src/test/java/org/jclouds/blobstore/integration/internal/BaseContainerIntegrationTest.java @@ -26,7 +26,6 @@ import static org.jclouds.blobstore.options.ListContainerOptions.Builder.maxResu import static org.testng.Assert.assertEquals; import java.io.IOException; -import java.io.UnsupportedEncodingException; import java.util.Set; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeoutException; @@ -114,7 +113,7 @@ public class BaseContainerIntegrationTest extends BaseBlobStoreIntegrationTest { } @Test(groups = { "integration", "live" }) - public void testListContainerMarker() throws InterruptedException, UnsupportedEncodingException { + public void testListContainerMarker() throws InterruptedException { String containerName = getContainerName(); try { addAlphabetUnderRoot(containerName); @@ -137,7 +136,7 @@ public class BaseContainerIntegrationTest extends BaseBlobStoreIntegrationTest { } @Test(groups = { "integration", "live" }) - public void testListRootUsesDelimiter() throws InterruptedException, UnsupportedEncodingException { + public void testListRootUsesDelimiter() throws InterruptedException { String containerName = getContainerName(); try { String prefix = "rootdelimeter"; @@ -153,7 +152,7 @@ public class BaseContainerIntegrationTest extends BaseBlobStoreIntegrationTest { } @Test(groups = { "integration", "live" }) - public void testDirectory() throws InterruptedException, UnsupportedEncodingException { + public void testDirectory() throws InterruptedException { String containerName = getContainerName(); try { String directory = "directory"; @@ -230,7 +229,7 @@ public class BaseContainerIntegrationTest extends BaseBlobStoreIntegrationTest { } @Test(groups = { "integration", "live" }) - public void testListContainerPrefix() throws InterruptedException, UnsupportedEncodingException { + public void testListContainerPrefix() throws InterruptedException { String containerName = getContainerName(); try { String prefix = "containerprefix"; @@ -247,7 +246,7 @@ public class BaseContainerIntegrationTest extends BaseBlobStoreIntegrationTest { } @Test(groups = { "integration", "live" }) - public void testListContainerMaxResults() throws InterruptedException, UnsupportedEncodingException { + public void testListContainerMaxResults() throws InterruptedException { String containerName = getContainerName(); try { addAlphabetUnderRoot(containerName); @@ -295,8 +294,7 @@ public class BaseContainerIntegrationTest extends BaseBlobStoreIntegrationTest { } @Test(groups = { "integration", "live" }) - public void testListContainer() throws InterruptedException, ExecutionException, TimeoutException, - UnsupportedEncodingException { + public void testListContainer() throws InterruptedException, ExecutionException, TimeoutException { String containerName = getContainerName(); try { add15UnderRoot(containerName); diff --git a/blobstore/src/test/java/org/jclouds/blobstore/integration/internal/BaseMapIntegrationTest.java b/blobstore/src/test/java/org/jclouds/blobstore/integration/internal/BaseMapIntegrationTest.java index 11079a0464..6e59bd2a58 100644 --- a/blobstore/src/test/java/org/jclouds/blobstore/integration/internal/BaseMapIntegrationTest.java +++ b/blobstore/src/test/java/org/jclouds/blobstore/integration/internal/BaseMapIntegrationTest.java @@ -27,7 +27,6 @@ import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; -import java.io.UnsupportedEncodingException; import java.util.Map; import java.util.Map.Entry; import java.util.Set; @@ -150,7 +149,7 @@ public abstract class BaseMapIntegrationTest extends BaseBlobStoreIntegration } @Test(groups = { "integration", "live" }) - public void testDirectory() throws InterruptedException, UnsupportedEncodingException { + public void testDirectory() throws InterruptedException { String containerName = getContainerName(); String directory = "apps"; Map rootMap = createMap(context, containerName); diff --git a/blobstore/src/test/java/org/jclouds/blobstore/options/GetOptionsTest.java b/blobstore/src/test/java/org/jclouds/blobstore/options/GetOptionsTest.java index 8870938a7e..299d8608a2 100644 --- a/blobstore/src/test/java/org/jclouds/blobstore/options/GetOptionsTest.java +++ b/blobstore/src/test/java/org/jclouds/blobstore/options/GetOptionsTest.java @@ -26,7 +26,6 @@ import static org.jclouds.blobstore.options.GetOptions.Builder.range; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNull; -import java.io.UnsupportedEncodingException; import java.util.Date; import org.testng.annotations.BeforeTest; @@ -179,7 +178,7 @@ public class GetOptionsTest { } @Test - public void testIfETagMatches() throws UnsupportedEncodingException { + public void testIfETagMatches() { GetOptions options = new GetOptions(); options.ifETagMatches(etag); assertEquals(etag, options.getIfMatch()); @@ -192,18 +191,18 @@ public class GetOptionsTest { } @Test - public void testIfETagMatchesStatic() throws UnsupportedEncodingException { + public void testIfETagMatchesStatic() { GetOptions options = ifETagMatches(etag); assertEquals(etag, options.getIfMatch()); } @Test(expectedExceptions = NullPointerException.class) - public void testIfETagMatchesNPE() throws UnsupportedEncodingException { + public void testIfETagMatchesNPE() { ifETagMatches(null); } @Test - public void testIfETagDoesntMatch() throws UnsupportedEncodingException { + public void testIfETagDoesntMatch() { GetOptions options = new GetOptions(); options.ifETagDoesntMatch(etag); assertEquals(etag, options.getIfNoneMatch()); @@ -216,13 +215,13 @@ public class GetOptionsTest { } @Test - public void testIfETagDoesntMatchStatic() throws UnsupportedEncodingException { + public void testIfETagDoesntMatchStatic() { GetOptions options = ifETagDoesntMatch(etag); assertEquals(etag, options.getIfNoneMatch()); } @Test(expectedExceptions = NullPointerException.class) - public void testIfETagDoesntMatchNPE() throws UnsupportedEncodingException { + public void testIfETagDoesntMatchNPE() { ifETagDoesntMatch(null); } @@ -232,13 +231,13 @@ public class GetOptionsTest { } - public void testIfUnmodifiedAfterETagMatches() throws UnsupportedEncodingException { + public void testIfUnmodifiedAfterETagMatches() { ifETagMatches(etag).ifUnmodifiedSince(now); } @Test(expectedExceptions = IllegalArgumentException.class) - public void testIfUnmodifiedAfterETagDoesntMatch() throws UnsupportedEncodingException { + public void testIfUnmodifiedAfterETagDoesntMatch() { ifETagDoesntMatch(etag).ifUnmodifiedSince(now); } @@ -249,44 +248,44 @@ public class GetOptionsTest { } @Test(expectedExceptions = IllegalArgumentException.class) - public void testIfModifiedAfterETagMatches() throws UnsupportedEncodingException { + public void testIfModifiedAfterETagMatches() { ifETagMatches(etag).ifModifiedSince(now); } - public void testIfModifiedAfterETagDoesntMatch() throws UnsupportedEncodingException { + public void testIfModifiedAfterETagDoesntMatch() { ifETagDoesntMatch(etag).ifModifiedSince(now); } @Test(expectedExceptions = IllegalArgumentException.class) - public void testETagMatchesAfterIfModified() throws UnsupportedEncodingException { + public void testETagMatchesAfterIfModified() { ifModifiedSince(now).ifETagMatches(etag); } - public void testETagMatchesAfterIfUnmodified() throws UnsupportedEncodingException { + public void testETagMatchesAfterIfUnmodified() { ifUnmodifiedSince(now).ifETagMatches(etag); } @Test(expectedExceptions = IllegalArgumentException.class) - public void testETagMatchesAfterETagDoesntMatch() throws UnsupportedEncodingException { + public void testETagMatchesAfterETagDoesntMatch() { ifETagDoesntMatch(etag).ifETagMatches(etag); } - public void testETagDoesntMatchAfterIfModified() throws UnsupportedEncodingException { + public void testETagDoesntMatchAfterIfModified() { ifModifiedSince(now).ifETagDoesntMatch(etag); } @Test(expectedExceptions = IllegalArgumentException.class) - public void testETagDoesntMatchAfterIfUnmodified() throws UnsupportedEncodingException { + public void testETagDoesntMatchAfterIfUnmodified() { ifUnmodifiedSince(now).ifETagDoesntMatch(etag); } @Test(expectedExceptions = IllegalArgumentException.class) - public void testETagDoesntMatchAfterETagMatches() throws UnsupportedEncodingException { + public void testETagDoesntMatchAfterETagMatches() { ifETagMatches(etag).ifETagDoesntMatch(etag); } diff --git a/core/src/main/java/org/jclouds/http/options/GetOptions.java b/core/src/main/java/org/jclouds/http/options/GetOptions.java index 77054c4001..ee4d8a635b 100644 --- a/core/src/main/java/org/jclouds/http/options/GetOptions.java +++ b/core/src/main/java/org/jclouds/http/options/GetOptions.java @@ -21,7 +21,6 @@ package org.jclouds.http.options; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; -import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.Date; import java.util.List; @@ -161,8 +160,6 @@ public class GetOptions extends BaseHttpRequestOptions { * * @param eTag * hash representing the payload - * @throws UnsupportedEncodingException - * if there was a problem converting this into an S3 eTag string */ public GetOptions ifETagMatches(String eTag) { checkArgument(getIfNoneMatch() == null, "ifETagDoesntMatch() is not compatible with ifETagMatches()"); @@ -190,8 +187,6 @@ public class GetOptions extends BaseHttpRequestOptions { * * @param eTag * hash representing the payload - * @throws UnsupportedEncodingException - * if there was a problem converting this into an S3 eTag string */ public GetOptions ifETagDoesntMatch(String eTag) { checkArgument(getIfMatch() == null, "ifETagMatches() is not compatible with ifETagDoesntMatch()"); diff --git a/core/src/test/java/org/jclouds/http/options/GetOptionsTest.java b/core/src/test/java/org/jclouds/http/options/GetOptionsTest.java index 07d5723e80..e9b75f86d6 100644 --- a/core/src/test/java/org/jclouds/http/options/GetOptionsTest.java +++ b/core/src/test/java/org/jclouds/http/options/GetOptionsTest.java @@ -28,7 +28,6 @@ import static org.jclouds.http.options.GetOptions.Builder.tail; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNull; -import java.io.UnsupportedEncodingException; import java.util.Date; import org.jclouds.date.internal.SimpleDateFormatDateService; @@ -205,7 +204,7 @@ public class GetOptionsTest { } @Test - public void testIfETagMatches() throws UnsupportedEncodingException { + public void testIfETagMatches() { GetOptions options = new GetOptions(); options.ifETagMatches(etag); matchesHex(options.getIfMatch()); @@ -218,18 +217,18 @@ public class GetOptionsTest { } @Test - public void testIfETagMatchesStatic() throws UnsupportedEncodingException { + public void testIfETagMatchesStatic() { GetOptions options = ifETagMatches(etag); matchesHex(options.getIfMatch()); } @Test(expectedExceptions = NullPointerException.class) - public void testIfETagMatchesNPE() throws UnsupportedEncodingException { + public void testIfETagMatchesNPE() { ifETagMatches(null); } @Test - public void testIfETagDoesntMatch() throws UnsupportedEncodingException { + public void testIfETagDoesntMatch() { GetOptions options = new GetOptions(); options.ifETagDoesntMatch(etag); matchesHex(options.getIfNoneMatch()); @@ -242,17 +241,17 @@ public class GetOptionsTest { } @Test - public void testIfETagDoesntMatchStatic() throws UnsupportedEncodingException { + public void testIfETagDoesntMatchStatic() { GetOptions options = ifETagDoesntMatch(etag); matchesHex(options.getIfNoneMatch()); } @Test(expectedExceptions = NullPointerException.class) - public void testIfETagDoesntMatchNPE() throws UnsupportedEncodingException { + public void testIfETagDoesntMatchNPE() { ifETagDoesntMatch(null); } - private void matchesHex(String match) throws UnsupportedEncodingException { + private void matchesHex(String match) { String expected = "\"" + etag + "\""; assertEquals(match, expected); } @@ -263,13 +262,13 @@ public class GetOptionsTest { } - public void testIfUnmodifiedAfterETagMatches() throws UnsupportedEncodingException { + public void testIfUnmodifiedAfterETagMatches() { ifETagMatches(etag).ifUnmodifiedSince(now); } @Test(expectedExceptions = IllegalArgumentException.class) - public void testIfUnmodifiedAfterETagDoesntMatch() throws UnsupportedEncodingException { + public void testIfUnmodifiedAfterETagDoesntMatch() { ifETagDoesntMatch(etag).ifUnmodifiedSince(now); } @@ -280,44 +279,44 @@ public class GetOptionsTest { } @Test(expectedExceptions = IllegalArgumentException.class) - public void testIfModifiedAfterETagMatches() throws UnsupportedEncodingException { + public void testIfModifiedAfterETagMatches() { ifETagMatches(etag).ifModifiedSince(now); } - public void testIfModifiedAfterETagDoesntMatch() throws UnsupportedEncodingException { + public void testIfModifiedAfterETagDoesntMatch() { ifETagDoesntMatch(etag).ifModifiedSince(now); } @Test(expectedExceptions = IllegalArgumentException.class) - public void testETagMatchesAfterIfModified() throws UnsupportedEncodingException { + public void testETagMatchesAfterIfModified() { ifModifiedSince(now).ifETagMatches(etag); } - public void testETagMatchesAfterIfUnmodified() throws UnsupportedEncodingException { + public void testETagMatchesAfterIfUnmodified() { ifUnmodifiedSince(now).ifETagMatches(etag); } @Test(expectedExceptions = IllegalArgumentException.class) - public void testETagMatchesAfterETagDoesntMatch() throws UnsupportedEncodingException { + public void testETagMatchesAfterETagDoesntMatch() { ifETagDoesntMatch(etag).ifETagMatches(etag); } - public void testETagDoesntMatchAfterIfModified() throws UnsupportedEncodingException { + public void testETagDoesntMatchAfterIfModified() { ifModifiedSince(now).ifETagDoesntMatch(etag); } @Test(expectedExceptions = IllegalArgumentException.class) - public void testETagDoesntMatchAfterIfUnmodified() throws UnsupportedEncodingException { + public void testETagDoesntMatchAfterIfUnmodified() { ifUnmodifiedSince(now).ifETagDoesntMatch(etag); } @Test(expectedExceptions = IllegalArgumentException.class) - public void testETagDoesntMatchAfterETagMatches() throws UnsupportedEncodingException { + public void testETagDoesntMatchAfterETagMatches() { ifETagMatches(etag).ifETagDoesntMatch(etag); } 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 c1a19b59e9..9ea6c43e66 100644 --- a/core/src/test/java/org/jclouds/rest/internal/RestAnnotationProcessorTest.java +++ b/core/src/test/java/org/jclouds/rest/internal/RestAnnotationProcessorTest.java @@ -1485,7 +1485,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { } @Test - public void testBuildTwoHeader() throws SecurityException, NoSuchMethodException, UnsupportedEncodingException { + public void testBuildTwoHeader() throws SecurityException, NoSuchMethodException { Method oneHeader = TestHeader.class.getMethod("twoHeader", String.class); Multimap headers = factory(TestHeader.class).createRequest(oneHeader, new Object[] { "robot" }) .getHeaders(); @@ -1503,7 +1503,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { } @Test - public void testBuildOneClassHeader() throws SecurityException, NoSuchMethodException, UnsupportedEncodingException { + public void testBuildOneClassHeader() throws SecurityException, NoSuchMethodException { Method oneHeader = TestClassHeader.class.getMethod("oneHeader", String.class); Multimap headers = factory(TestClassHeader.class).createRequest(oneHeader, new Object[] { "robot" }).getHeaders(); @@ -1512,7 +1512,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { } @Test - public void testBuildOneHeader() throws SecurityException, NoSuchMethodException, UnsupportedEncodingException { + public void testBuildOneHeader() throws SecurityException, NoSuchMethodException { Method oneHeader = TestHeader.class.getMethod("oneHeader", String.class); Multimap headers = factory(TestHeader.class).createRequest(oneHeader, new Object[] { "robot" }) .getHeaders(); @@ -1521,7 +1521,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { } @Test - public void testBuildTwoHeaders() throws SecurityException, NoSuchMethodException, UnsupportedEncodingException { + public void testBuildTwoHeaders() throws SecurityException, NoSuchMethodException { Method twoHeaders = TestHeader.class.getMethod("twoHeaders", String.class, String.class); Multimap headers = factory(TestHeader.class).createRequest(twoHeaders, new Object[] { "robot", "eggs" }).getHeaders(); @@ -1530,8 +1530,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { } @Test - public void testBuildTwoHeadersOutOfOrder() throws SecurityException, NoSuchMethodException, - UnsupportedEncodingException { + public void testBuildTwoHeadersOutOfOrder() throws SecurityException, NoSuchMethodException { Method twoHeadersOutOfOrder = TestHeader.class.getMethod("twoHeadersOutOfOrder", String.class, String.class); Multimap headers = factory(TestHeader.class).createRequest(twoHeadersOutOfOrder, new Object[] { "robot", "eggs" }).getHeaders(); @@ -1546,7 +1545,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { } @Test - public void testQueryInOptions() throws SecurityException, NoSuchMethodException, UnsupportedEncodingException { + public void testQueryInOptions() throws SecurityException, NoSuchMethodException { Method oneQuery = TestQueryReplace.class.getMethod("queryInOptions", String.class, TestReplaceQueryOptions.class); String query = factory(TestQueryReplace.class).createRequest(oneQuery, new Object[] { "robot", new TestReplaceQueryOptions() }).getEndpoint().getQuery(); @@ -1560,7 +1559,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { @BinderParam(BindMapToMatrixParams.class) Map options); } - public void testTestMapMatrixParams() throws SecurityException, NoSuchMethodException, UnsupportedEncodingException { + public void testTestMapMatrixParams() throws SecurityException, NoSuchMethodException { 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") }); @@ -1602,7 +1601,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { } @Test - public void testBuildTwoQuery() throws SecurityException, NoSuchMethodException, UnsupportedEncodingException { + public void testBuildTwoQuery() throws SecurityException, NoSuchMethodException { Method oneQuery = TestQueryReplace.class.getMethod("twoQuery", String.class); String query = factory(TestQueryReplace.class).createRequest(oneQuery, new Object[] { "robot" }).getEndpoint() .getQuery(); @@ -1618,7 +1617,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { } @Test - public void testBuildOneClassQuery() throws SecurityException, NoSuchMethodException, UnsupportedEncodingException { + public void testBuildOneClassQuery() throws SecurityException, NoSuchMethodException { Method oneQuery = TestClassQuery.class.getMethod("oneQuery", String.class); String query = factory(TestClassQuery.class).createRequest(oneQuery, new Object[] { "robot" }).getEndpoint() .getQuery(); @@ -1626,7 +1625,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { } @Test - public void testBuildOneQuery() throws SecurityException, NoSuchMethodException, UnsupportedEncodingException { + public void testBuildOneQuery() throws SecurityException, NoSuchMethodException { Method oneQuery = TestQueryReplace.class.getMethod("oneQuery", String.class); String query = factory(TestQueryReplace.class).createRequest(oneQuery, new Object[] { "robot" }).getEndpoint() .getQuery(); @@ -1634,7 +1633,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { } @Test - public void testBuildTwoQuerys() throws SecurityException, NoSuchMethodException, UnsupportedEncodingException { + public void testBuildTwoQuerys() throws SecurityException, NoSuchMethodException { Method twoQuerys = TestQueryReplace.class.getMethod("twoQuerys", String.class, String.class); String query = factory(TestQueryReplace.class).createRequest(twoQuerys, new Object[] { "robot", "eggs" }) .getEndpoint().getQuery(); @@ -1642,8 +1641,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { } @Test - public void testBuildTwoQuerysOutOfOrder() throws SecurityException, NoSuchMethodException, - UnsupportedEncodingException { + public void testBuildTwoQuerysOutOfOrder() throws SecurityException, NoSuchMethodException { Method twoQuerysOutOfOrder = TestQueryReplace.class.getMethod("twoQuerysOutOfOrder", String.class, String.class); String query = factory(TestQueryReplace.class).createRequest(twoQuerysOutOfOrder, new Object[] { "robot", "eggs" }).getEndpoint().getQuery(); @@ -1657,7 +1655,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { } @Test - public void testMatrixInOptions() throws SecurityException, NoSuchMethodException, UnsupportedEncodingException { + public void testMatrixInOptions() throws SecurityException, NoSuchMethodException { Method oneMatrix = TestMatrixReplace.class.getMethod("matrixInOptions", String.class, TestReplaceMatrixOptions.class); String path = factory(TestMatrixReplace.class).createRequest(oneMatrix, @@ -1699,7 +1697,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { } @Test - public void testBuildTwoMatrix() throws SecurityException, NoSuchMethodException, UnsupportedEncodingException { + public void testBuildTwoMatrix() throws SecurityException, NoSuchMethodException { Method oneMatrix = TestMatrixReplace.class.getMethod("twoMatrix", String.class); String path = factory(TestMatrixReplace.class).createRequest(oneMatrix, new Object[] { "robot" }).getEndpoint() .getPath(); @@ -1716,7 +1714,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { } @Test - public void testBuildOneClassMatrix() throws SecurityException, NoSuchMethodException, UnsupportedEncodingException { + public void testBuildOneClassMatrix() throws SecurityException, NoSuchMethodException { Method oneMatrix = TestClassMatrix.class.getMethod("oneMatrix", String.class); String path = factory(TestClassMatrix.class).createRequest(oneMatrix, new Object[] { "robot" }).getEndpoint() .getPath(); @@ -1724,7 +1722,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { } @Test - public void testBuildOneMatrix() throws SecurityException, NoSuchMethodException, UnsupportedEncodingException { + public void testBuildOneMatrix() throws SecurityException, NoSuchMethodException { Method oneMatrix = TestMatrixReplace.class.getMethod("oneMatrix", String.class); String path = factory(TestMatrixReplace.class).createRequest(oneMatrix, new Object[] { "robot" }).getEndpoint() .getPath(); @@ -1732,7 +1730,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { } @Test - public void testBuildTwoMatrixs() throws SecurityException, NoSuchMethodException, UnsupportedEncodingException { + public void testBuildTwoMatrixs() throws SecurityException, NoSuchMethodException { Method twoMatrixs = TestMatrixReplace.class.getMethod("twoMatrixs", String.class, String.class); String path = factory(TestMatrixReplace.class).createRequest(twoMatrixs, new Object[] { "robot", "eggs" }) .getEndpoint().getPath(); @@ -1740,8 +1738,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { } @Test - public void testBuildTwoMatrixsOutOfOrder() throws SecurityException, NoSuchMethodException, - UnsupportedEncodingException { + public void testBuildTwoMatrixsOutOfOrder() throws SecurityException, NoSuchMethodException { Method twoMatrixsOutOfOrder = TestMatrixReplace.class.getMethod("twoMatrixsOutOfOrder", String.class, String.class); String path = factory(TestMatrixReplace.class).createRequest(twoMatrixsOutOfOrder, @@ -2380,7 +2377,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { } @Test - public void testBuildTwoForm() throws SecurityException, NoSuchMethodException, UnsupportedEncodingException { + public void testBuildTwoForm() throws SecurityException, NoSuchMethodException { Method oneForm = TestFormReplace.class.getMethod("twoForm", String.class); Object form = factory(TestFormReplace.class).createRequest(oneForm, "robot").getPayload().getRawContent(); assertEquals(form, "slash=/robot&hyphen=-robot"); @@ -2406,40 +2403,39 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { } @Test - public void testProvidesWithGeneric() throws SecurityException, NoSuchMethodException, UnsupportedEncodingException { + public void testProvidesWithGeneric() throws SecurityException, NoSuchMethodException { Set set = injector.getInstance(AsyncClientFactory.class).create(TestClassForm.class).set(); assertEquals(set, ImmutableSet.of("foo")); } @Test - public void testProvidesWithGenericQualified() throws SecurityException, NoSuchMethodException, - UnsupportedEncodingException { + public void testProvidesWithGenericQualified() throws SecurityException, NoSuchMethodException { Set set = injector.getInstance(AsyncClientFactory.class).create(TestClassForm.class).foo(); assertEquals(set, ImmutableSet.of("bar")); } @Test(expectedExceptions = AuthorizationException.class) public void testProvidesWithGenericQualifiedAuthorizationException() throws SecurityException, - NoSuchMethodException, UnsupportedEncodingException { + NoSuchMethodException { injector.getInstance(AsyncClientFactory.class).create(TestClassForm.class).exception(); } @Test - public void testBuildOneClassForm() throws SecurityException, NoSuchMethodException, UnsupportedEncodingException { + public void testBuildOneClassForm() throws SecurityException, NoSuchMethodException { Method oneForm = TestClassForm.class.getMethod("oneForm", String.class); Object form = factory(TestClassForm.class).createRequest(oneForm, "robot").getPayload().getRawContent(); assertEquals(form, "x-amz-copy-source=/robot"); } @Test - public void testBuildOneForm() throws SecurityException, NoSuchMethodException, UnsupportedEncodingException { + public void testBuildOneForm() throws SecurityException, NoSuchMethodException { Method oneForm = TestFormReplace.class.getMethod("oneForm", String.class); Object form = factory(TestFormReplace.class).createRequest(oneForm, "robot").getPayload().getRawContent(); assertEquals(form, "x-amz-copy-source=/robot"); } @Test - public void testBuildTwoForms() throws SecurityException, NoSuchMethodException, UnsupportedEncodingException { + public void testBuildTwoForms() throws SecurityException, NoSuchMethodException { Method twoForms = TestFormReplace.class.getMethod("twoForms", String.class, String.class); Object form = factory(TestFormReplace.class).createRequest(twoForms, "robot", "eggs").getPayload() .getRawContent(); @@ -2447,8 +2443,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { } @Test - public void testBuildTwoFormsOutOfOrder() throws SecurityException, NoSuchMethodException, - UnsupportedEncodingException { + public void testBuildTwoFormsOutOfOrder() throws SecurityException, NoSuchMethodException { Method twoFormsOutOfOrder = TestFormReplace.class.getMethod("twoFormsOutOfOrder", String.class, String.class); Object form = factory(TestFormReplace.class).createRequest(twoFormsOutOfOrder, "robot", "eggs").getPayload() .getRawContent(); diff --git a/core/src/test/java/org/jclouds/util/Strings2Test.java b/core/src/test/java/org/jclouds/util/Strings2Test.java index a213eca89f..c94a4c17aa 100644 --- a/core/src/test/java/org/jclouds/util/Strings2Test.java +++ b/core/src/test/java/org/jclouds/util/Strings2Test.java @@ -20,8 +20,6 @@ package org.jclouds.util; import static org.testng.Assert.assertEquals; -import java.io.UnsupportedEncodingException; - import org.testng.annotations.Test; import com.google.common.collect.ImmutableMap; @@ -43,7 +41,7 @@ public class Strings2Test { assertEquals(Strings2.urlEncode("/read-tests/ tep", '/'), "/read-tests/%20tep"); } - public void testReplaceTokens() throws UnsupportedEncodingException { + public void testReplaceTokens() { assertEquals(Strings2.replaceTokens("hello {where}", ImmutableMap.of("where", "world")), "hello world"); } diff --git a/providers/azureblob/src/test/java/org/jclouds/azureblob/blobstore/integration/AzureBlobIntegrationLiveTest.java b/providers/azureblob/src/test/java/org/jclouds/azureblob/blobstore/integration/AzureBlobIntegrationLiveTest.java index 49bfa6c950..ce345013da 100644 --- a/providers/azureblob/src/test/java/org/jclouds/azureblob/blobstore/integration/AzureBlobIntegrationLiveTest.java +++ b/providers/azureblob/src/test/java/org/jclouds/azureblob/blobstore/integration/AzureBlobIntegrationLiveTest.java @@ -19,7 +19,6 @@ package org.jclouds.azureblob.blobstore.integration; import java.io.IOException; -import java.io.UnsupportedEncodingException; import java.util.concurrent.ExecutionException; import org.jclouds.blobstore.domain.Blob; @@ -34,7 +33,7 @@ import org.testng.annotations.Test; public class AzureBlobIntegrationLiveTest extends BaseBlobIntegrationTest { @Override - public void testGetIfMatch() throws InterruptedException, UnsupportedEncodingException { + public void testGetIfMatch() throws InterruptedException { // this currently fails } diff --git a/scriptbuilder/src/test/java/org/jclouds/scriptbuilder/util/UtilsTest.java b/scriptbuilder/src/test/java/org/jclouds/scriptbuilder/util/UtilsTest.java index dbcfc99ce7..a1a53ac728 100644 --- a/scriptbuilder/src/test/java/org/jclouds/scriptbuilder/util/UtilsTest.java +++ b/scriptbuilder/src/test/java/org/jclouds/scriptbuilder/util/UtilsTest.java @@ -20,8 +20,6 @@ package org.jclouds.scriptbuilder.util; import static org.testng.Assert.assertEquals; -import java.io.UnsupportedEncodingException; - import org.jclouds.scriptbuilder.domain.OsFamily; import org.jclouds.scriptbuilder.domain.ShellToken; import org.testng.annotations.Test; @@ -35,7 +33,7 @@ import com.google.common.collect.ImmutableMap; @Test(groups = "unit") public class UtilsTest { - public void testReplaceTokens() throws UnsupportedEncodingException { + public void testReplaceTokens() { assertEquals(Utils.replaceTokens("hello {where}", ImmutableMap.of("where", "world")), "hello world"); } From c3eb23399bd6538915576ade8d65d97d0397ae67 Mon Sep 17 00:00:00 2001 From: Mattias Holmqvist Date: Fri, 28 Oct 2011 07:09:28 +0200 Subject: [PATCH 04/16] Added ErrorCode type and ExecutionType. Now for for LaunchMachine function, but can be re-used. --- .../jclouds/virtualbox/domain/ErrorCode.java | 109 ++++++++++++++++++ .../virtualbox/domain/ExecutionType.java | 38 ++++++ 2 files changed, 147 insertions(+) create mode 100644 sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/domain/ErrorCode.java create mode 100644 sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/domain/ExecutionType.java diff --git a/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/domain/ErrorCode.java b/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/domain/ErrorCode.java new file mode 100644 index 0000000000..395cc53451 --- /dev/null +++ b/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/domain/ErrorCode.java @@ -0,0 +1,109 @@ +/* + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.virtualbox.domain; + +import org.virtualbox_4_1.VBoxException; +import org.virtualbox_4_1.jaxws.RuntimeFaultMsg; + +import java.util.HashMap; +import java.util.Map; + +/** + * Maps the error codes in the Virtual Box Java API into enum values. + *

+ *

+ * To get the error code from a VBoxException, use: + *

+ * try {
+ *    ...
+ *    ...
+ * }
+ * catch (VBoxException vboxException) {
+ *    RuntimeFaultMsg fault = (RuntimeFaultMsg) vboxException.getWrapped();
+ *    int faultCode = fault.getFaultInfo().getResultCode();
+ *    ErrorCode errorCode = ErrorCode.valueOf(faultCode);
+ * }
+ * 
+ * + * @author Mattias Holmqvist + */ +public enum ErrorCode { + + E_OBJECT_NOT_FOUND(2159738881L), + E_INVALID_VM_STATE(2159738882L), + E_VM_ERROR(2159738883L), + E_FILE_ERROR(2159738884L), + E_IPRT_ERROR(2159738885L), + E_PDM_ERROR(2159738886L), + E_INVALID_OBJECT_STATE(2159738887L), + E_HOST_ERROR(2159738888L), + E_NOT_SUPPORTED(2159738889L), + E_XML_ERROR(2159738890L), + E_INVALID_SESSION_STATE(2159738891L), + E_OBJECT_IN_USE(2159738892L), + E_ACCESSDENIED(2147942405L), + E_POINTER(2147500035L), + E_FAIL(2147500037L), + E_NOTIMPL(2147500033L), + E_OUTOFMEMORY(2147942414L), + E_INVALIDARG(2147942487L), + E_UNEXPECTED(2147549183L), + E_UNKNOWN_ERROR_CODE(-1L), + E_ERROR_CODE_UNAVAILABLE(-2L); + + private long code; + + ErrorCode(long code) { + this.code = code; + } + + private static Map table = new HashMap(); + + static { + for (ErrorCode errorCode : ErrorCode.values()) { + table.put(errorCode.code, errorCode); + } + } + + /** + * Returns an ErrorCode from the fault code given by the VirtualBox API. + * + * @param vboxException the exception to get the error code from. + * @return an ErrorCode representing the given fault code. + */ + public static ErrorCode valueOf(VBoxException vboxException) { + final Throwable wrapped = vboxException.getWrapped(); + if (wrapped instanceof RuntimeFaultMsg) { + final RuntimeFaultMsg faultCode = (RuntimeFaultMsg) wrapped; + final int resultCode = faultCode.getFaultInfo().getResultCode(); + final ErrorCode errorCode = table.get(unsignedIntToLong(resultCode)); + if (errorCode != null) { + return errorCode; + } + return E_UNKNOWN_ERROR_CODE; + } + return E_ERROR_CODE_UNAVAILABLE; + } + + private static long unsignedIntToLong(int faultCode) { + return faultCode & 0xffffffffL; + } + +} diff --git a/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/domain/ExecutionType.java b/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/domain/ExecutionType.java new file mode 100644 index 0000000000..fa986351ab --- /dev/null +++ b/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/domain/ExecutionType.java @@ -0,0 +1,38 @@ +/* + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.virtualbox.domain; + +public enum ExecutionType { + + GUI("gui"), + HEADLESS("headless"), + SDL("sdl"), + EMERGENCYSTOP("emergencystop"); + + private final String type; + + ExecutionType(String type) { + this.type = type; + } + + public String stringValue() { + return type; + } +} From f4a53fa0da0b6865de5ab6c5ca78c9f06f832633 Mon Sep 17 00:00:00 2001 From: Mattias Holmqvist Date: Fri, 28 Oct 2011 07:43:34 +0200 Subject: [PATCH 05/16] Added LaunchMachineIfNotAlreadyRunning to IsoToIMachine. --- .../jclouds/virtualbox/domain/ErrorCode.java | 46 +++++----- .../virtualbox/functions/IsoToIMachine.java | 64 +++++++------ .../LaunchMachineIfNotAlreadyRunning.java | 91 +++++++++++++++++++ .../LaunchMachineIfNotAlreadyRunningTest.java | 67 ++++++++++++++ 4 files changed, 219 insertions(+), 49 deletions(-) create mode 100644 sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/LaunchMachineIfNotAlreadyRunning.java create mode 100644 sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/LaunchMachineIfNotAlreadyRunningTest.java diff --git a/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/domain/ErrorCode.java b/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/domain/ErrorCode.java index 395cc53451..74801270d5 100644 --- a/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/domain/ErrorCode.java +++ b/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/domain/ErrorCode.java @@ -46,27 +46,27 @@ import java.util.Map; */ public enum ErrorCode { - E_OBJECT_NOT_FOUND(2159738881L), - E_INVALID_VM_STATE(2159738882L), - E_VM_ERROR(2159738883L), - E_FILE_ERROR(2159738884L), - E_IPRT_ERROR(2159738885L), - E_PDM_ERROR(2159738886L), - E_INVALID_OBJECT_STATE(2159738887L), - E_HOST_ERROR(2159738888L), - E_NOT_SUPPORTED(2159738889L), - E_XML_ERROR(2159738890L), - E_INVALID_SESSION_STATE(2159738891L), - E_OBJECT_IN_USE(2159738892L), - E_ACCESSDENIED(2147942405L), - E_POINTER(2147500035L), - E_FAIL(2147500037L), - E_NOTIMPL(2147500033L), - E_OUTOFMEMORY(2147942414L), - E_INVALIDARG(2147942487L), - E_UNEXPECTED(2147549183L), - E_UNKNOWN_ERROR_CODE(-1L), - E_ERROR_CODE_UNAVAILABLE(-2L); + VBOX_E_OBJECT_NOT_FOUND(2159738881L), + VBOX_E_INVALID_VM_STATE(2159738882L), + VBOX_E_VM_ERROR(2159738883L), + VBOX_E_FILE_ERROR(2159738884L), + VBOX_E_IPRT_ERROR(2159738885L), + VBOX_E_PDM_ERROR(2159738886L), + VBOX_E_INVALID_OBJECT_STATE(2159738887L), + VBOX_E_HOST_ERROR(2159738888L), + VBOX_E_NOT_SUPPORTED(2159738889L), + VBOX_E_XML_ERROR(2159738890L), + VBOX_E_INVALID_SESSION_STATE(2159738891L), + VBOX_E_OBJECT_IN_USE(2159738892L), + VBOX_E_ACCESSDENIED(2147942405L), + VBOX_E_POINTER(2147500035L), + VBOX_E_FAIL(2147500037L), + VBOX_E_NOTIMPL(2147500033L), + VBOX_E_OUTOFMEMORY(2147942414L), + VBOX_E_INVALIDARG(2147942487L), + VBOX_E_UNEXPECTED(2147549183L), + VBOX_E_UNKNOWN_ERROR_CODE(-1L), + VBOX_E_ERROR_CODE_UNAVAILABLE(-2L); private long code; @@ -97,9 +97,9 @@ public enum ErrorCode { if (errorCode != null) { return errorCode; } - return E_UNKNOWN_ERROR_CODE; + return VBOX_E_UNKNOWN_ERROR_CODE; } - return E_ERROR_CODE_UNAVAILABLE; + return VBOX_E_ERROR_CODE_UNAVAILABLE; } private static long unsignedIntToLong(int faultCode) { diff --git a/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/IsoToIMachine.java b/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/IsoToIMachine.java index caddb16998..9761738a15 100644 --- a/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/IsoToIMachine.java +++ b/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/IsoToIMachine.java @@ -19,23 +19,8 @@ package org.jclouds.virtualbox.functions; -import static com.google.common.base.Preconditions.checkNotNull; -import static com.google.common.base.Throwables.propagate; -import static org.jclouds.compute.options.RunScriptOptions.Builder.runAsRoot; -import static org.jclouds.compute.options.RunScriptOptions.Builder.wrapInInitScript; -import static org.jclouds.virtualbox.config.VirtualBoxConstants.VIRTUALBOX_INSTALLATION_KEY_SEQUENCE; -import static org.jclouds.virtualbox.config.VirtualBoxConstants.VIRTUALBOX_WORKINGDIR; -import static org.virtualbox_4_1.AccessMode.ReadOnly; -import static org.virtualbox_4_1.DeviceType.DVD; -import static org.virtualbox_4_1.DeviceType.HardDisk; -import static org.virtualbox_4_1.LockType.Shared; -import static org.virtualbox_4_1.LockType.Write; - -import java.io.File; - -import javax.annotation.Resource; -import javax.inject.Named; - +import com.google.common.base.Function; +import com.google.inject.Inject; import org.eclipse.jetty.server.Server; import org.jclouds.compute.ComputeServiceContext; import org.jclouds.compute.domain.ExecResponse; @@ -46,12 +31,25 @@ import org.jclouds.javax.annotation.Nullable; import org.jclouds.logging.Logger; import org.jclouds.ssh.SshException; import org.jclouds.virtualbox.config.VirtualBoxConstants; +import org.jclouds.virtualbox.domain.ExecutionType; import org.jclouds.virtualbox.functions.admin.StartJettyIfNotAlreadyRunning; import org.jclouds.virtualbox.settings.KeyboardScancodes; import org.virtualbox_4_1.*; -import com.google.common.base.Function; -import com.google.inject.Inject; +import javax.annotation.Resource; +import javax.inject.Named; +import java.io.File; + +import static com.google.common.base.Preconditions.checkNotNull; +import static org.jclouds.compute.options.RunScriptOptions.Builder.runAsRoot; +import static org.jclouds.compute.options.RunScriptOptions.Builder.wrapInInitScript; +import static org.jclouds.virtualbox.config.VirtualBoxConstants.VIRTUALBOX_INSTALLATION_KEY_SEQUENCE; +import static org.jclouds.virtualbox.config.VirtualBoxConstants.VIRTUALBOX_WORKINGDIR; +import static org.virtualbox_4_1.AccessMode.ReadOnly; +import static org.virtualbox_4_1.DeviceType.DVD; +import static org.virtualbox_4_1.DeviceType.HardDisk; +import static org.virtualbox_4_1.LockType.Shared; +import static org.virtualbox_4_1.LockType.Write; public class IsoToIMachine implements Function { @@ -136,13 +134,8 @@ public class IsoToIMachine implements Function { // Guest additions ensureGuestAdditionsMediumIsAttached(vmName, guestAdditionsDvdMedium); - IProgress prog = vm.launchVMProcess(manager.getSessionObject(), "gui", ""); - prog.waitForCompletion(-1); - try { - Thread.sleep(5000); - } catch (InterruptedException e) { - propagate(e); - } + // Launch machine and wait for it to come online + ensureMachineIsLaunched(vmName); String installKeySequence = System.getProperty(VIRTUALBOX_INSTALLATION_KEY_SEQUENCE, defaultInstallSequence()); sendKeyboardSequence(installKeySequence); @@ -180,6 +173,10 @@ public class IsoToIMachine implements Function { return vm; } + private void ensureMachineIsLaunched(String vmName) { + applyForMachine(manager, vmName, new LaunchMachineIfNotAlreadyRunning(manager, ExecutionType.GUI, "")); + } + private void ensureGuestAdditionsMediumIsAttached(String vmName, final IMedium guestAdditionsDvdMedium) { lockMachineAndApply(manager, Write, vmName, new AttachMediumToMachineIfNotAlreadyAttached(controllerIDE, guestAdditionsDvdMedium, 1, 1, DeviceType.DVD)); @@ -219,6 +216,21 @@ public class IsoToIMachine implements Function { new AddIDEControllerIfNotExists(checkNotNull(controllerIDE, "controllerIDE"))); } + private T applyForMachine(VirtualBoxManager manager, final String machineId, final Function function) { + final IMachine immutableMachine = manager.getVBox().findMachine(machineId); + return new Function() { + @Override + public T apply(IMachine machine) { + return function.apply(machine); + } + + @Override + public String toString() { + return function.toString(); + } + }.apply(immutableMachine); + } + public static T lockMachineAndApply(VirtualBoxManager manager, final LockType type, final String machineId, final Function function) { return lockSessionOnMachineAndApply(manager, type, machineId, new Function() { diff --git a/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/LaunchMachineIfNotAlreadyRunning.java b/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/LaunchMachineIfNotAlreadyRunning.java new file mode 100644 index 0000000000..a118c77658 --- /dev/null +++ b/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/LaunchMachineIfNotAlreadyRunning.java @@ -0,0 +1,91 @@ +/* + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.virtualbox.functions; + +import com.google.common.base.Function; +import org.jclouds.compute.reference.ComputeServiceConstants; +import org.jclouds.logging.Logger; +import org.jclouds.virtualbox.domain.ErrorCode; +import org.jclouds.virtualbox.domain.ExecutionType; +import org.virtualbox_4_1.*; +import org.virtualbox_4_1.jaxws.RuntimeFaultMsg; + +import javax.annotation.Nullable; +import javax.annotation.Resource; +import javax.inject.Named; +import javax.lang.model.type.ExecutableType; + +import static com.google.common.base.Throwables.propagate; +import static javax.xml.bind.DatatypeConverter.parseUnsignedInt; + +/** + * Starts a machine using launchMachine() with the provided type and environment. + *

+ * Note that launchMachine() may throw VBoxException with the following error codes: + *

+ * VBOX_E_UNEXPECTED: Virtual machine not registered. + * VBOX_E_INVALIDARG: Invalid session type type. + * VBOX_E_OBJECT_NOT_FOUND: No machine matching machineId found. + * VBOX_E_INVALID_OBJECT_STATE: Session already open or being opened. + * VBOX_E_IPRT_ERROR: Launching process for machine failed. + * VBOX_E_VM_ERROR: Failed to assign machine to session. + * + * @author Mattias Holmqvist + * + * @see ErrorCode + */ +public class LaunchMachineIfNotAlreadyRunning implements Function { + + @Resource + @Named(ComputeServiceConstants.COMPUTE_LOGGER) + protected Logger logger = Logger.NULL; + + private final VirtualBoxManager manager; + private final ExecutionType type; + private final String environment; + + public LaunchMachineIfNotAlreadyRunning(VirtualBoxManager manager, ExecutionType type, String environment) { + this.manager = manager; + this.type = type; + this.environment = environment; + } + + @Override + public Void apply(@Nullable IMachine machine) { + try { + final IProgress progress = machine.launchVMProcess(manager.getSessionObject(), type.stringValue(), environment); + progress.waitForCompletion(-1); + Thread.sleep(5000); + } catch (InterruptedException e) { + propagate(e); + } catch (VBoxException e) { + ErrorCode errorCode = ErrorCode.valueOf(e); + switch (errorCode) { + case VBOX_E_INVALID_OBJECT_STATE: + logger.warn(e, "Could not start machine. Got error code %s from launchMachine(). " + + "The machine might already be running.", errorCode); + break; + default: + propagate(e); + } + } + return null; + } +} diff --git a/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/LaunchMachineIfNotAlreadyRunningTest.java b/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/LaunchMachineIfNotAlreadyRunningTest.java new file mode 100644 index 0000000000..c512905735 --- /dev/null +++ b/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/LaunchMachineIfNotAlreadyRunningTest.java @@ -0,0 +1,67 @@ +/* + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.virtualbox.functions; + +import org.jclouds.virtualbox.domain.ExecutionType; +import org.testng.annotations.Test; +import org.virtualbox_4_1.IMachine; +import org.virtualbox_4_1.IProgress; +import org.virtualbox_4_1.ISession; +import org.virtualbox_4_1.VirtualBoxManager; + +import static org.easymock.classextension.EasyMock.verify; +import static org.easymock.classextension.EasyMock.replay; +import static org.easymock.classextension.EasyMock.createMock; +import static org.easymock.classextension.EasyMock.expect; + +@Test(groups = "unit", testName = "LaunchMachineIfNotAlreadyRunningTest") +public class LaunchMachineIfNotAlreadyRunningTest { + + @Test + public void testDoNotLaunchIfAlreadyRunning() throws Exception { + + } + +// VirtualBox error: The given session is busy (0x80BB0007) +// VirtualBox error: The machine 'jclouds-image-virtualbox-iso-to-machine-test' is not registered (0x8000FFFF) + + + @Test + public void testLaunchIfNotStarted() throws Exception { + + final String type = "gui"; + final String environment = ""; + ISession session = createMock(ISession.class); + VirtualBoxManager manager = createMock(VirtualBoxManager.class); + IMachine machine = createMock(IMachine.class); + IProgress progress = createMock(IProgress.class); + + expect(manager.getSessionObject()).andReturn(session); + expect(machine.launchVMProcess(session, type, environment)).andReturn(progress); + progress.waitForCompletion(-1); + + replay(manager, machine, session, progress); + + new LaunchMachineIfNotAlreadyRunning(manager, ExecutionType.GUI, "").apply(machine); + + verify(manager, machine, session, progress); + + } +} From 45a1bcac85422a3de3ed477039ede736bb1ca096 Mon Sep 17 00:00:00 2001 From: Ignasi Barrera Date: Tue, 25 Oct 2011 11:06:47 +0200 Subject: [PATCH 06/16] Added parser to RestAnnotationProcessor to parse XML using JAXB --- .../http/functions/ParseXMLWithJAXB.java | 105 ++++++++++++++++++ .../rest/annotations/JAXBResponseParser.java | 40 +++++++ .../internal/RestAnnotationProcessor.java | 13 ++- .../main/java/org/jclouds/xml/XMLParser.java | 54 +++++++++ .../org/jclouds/xml/internal/JAXBParser.java | 81 ++++++++++++++ .../internal/RestAnnotationProcessorTest.java | 52 +++++++++ 6 files changed, 344 insertions(+), 1 deletion(-) create mode 100644 core/src/main/java/org/jclouds/http/functions/ParseXMLWithJAXB.java create mode 100644 core/src/main/java/org/jclouds/rest/annotations/JAXBResponseParser.java create mode 100644 core/src/main/java/org/jclouds/xml/XMLParser.java create mode 100644 core/src/main/java/org/jclouds/xml/internal/JAXBParser.java diff --git a/core/src/main/java/org/jclouds/http/functions/ParseXMLWithJAXB.java b/core/src/main/java/org/jclouds/http/functions/ParseXMLWithJAXB.java new file mode 100644 index 0000000000..8320931f8c --- /dev/null +++ b/core/src/main/java/org/jclouds/http/functions/ParseXMLWithJAXB.java @@ -0,0 +1,105 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.http.functions; + +import static org.jclouds.http.HttpUtils.releasePayload; + +import java.io.IOException; +import java.io.InputStream; + +import javax.annotation.Resource; +import javax.inject.Inject; +import javax.inject.Singleton; + +import org.jclouds.http.HttpResponse; +import org.jclouds.http.HttpResponseException; +import org.jclouds.logging.Logger; +import org.jclouds.util.Strings2; +import org.jclouds.xml.XMLParser; + +import com.google.common.base.Function; +import com.google.inject.TypeLiteral; + +/** + * This object will parse the body of an HttpResponse and return the result of type back to the + * caller. + * + * @author Ignasi Barrera + */ +@Singleton +public class ParseXMLWithJAXB implements Function +{ + @Resource + protected Logger logger = Logger.NULL; + + protected XMLParser xml; + + protected final TypeLiteral type; + + @Inject + public ParseXMLWithJAXB(final XMLParser xml, final TypeLiteral type) + { + this.xml = xml; + this.type = type; + } + + @Override + public T apply(final HttpResponse from) + { + InputStream xml = from.getPayload().getInput(); + try + { + return apply(xml); + } + catch (Exception e) + { + StringBuffer message = new StringBuffer(); + message.append("Error parsing input"); + logger.error(e, message.toString()); + throw new HttpResponseException(message.toString() + "\n" + from, null, from, e); + } + finally + { + releasePayload(from); + } + } + + @SuppressWarnings("unchecked") + public T apply(final InputStream stream) throws IOException + { + return (T) apply(stream, type.getRawType()); + } + + public V apply(final InputStream stream, final Class type) throws IOException + { + try + { + return xml.fromXML(Strings2.toStringAndClose(stream), type); + } + finally + { + if (stream != null) + { + stream.close(); + } + } + } + +} diff --git a/core/src/main/java/org/jclouds/rest/annotations/JAXBResponseParser.java b/core/src/main/java/org/jclouds/rest/annotations/JAXBResponseParser.java new file mode 100644 index 0000000000..6129c0c9f3 --- /dev/null +++ b/core/src/main/java/org/jclouds/rest/annotations/JAXBResponseParser.java @@ -0,0 +1,40 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.rest.annotations; + +import static java.lang.annotation.ElementType.METHOD; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +import org.jclouds.http.functions.ParseXMLWithJAXB; + +/** + * Shows the transformer type used to parse XML with the {@link ParseXMLWithJAXB} parser in a + * HttpResponse. + * + * @author Ignasi Barrera + */ +@Target(METHOD) +@Retention(RUNTIME) +public @interface JAXBResponseParser +{ + +} 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 6ea7e2a4a7..df2b0ed22f 100644 --- a/core/src/main/java/org/jclouds/rest/internal/RestAnnotationProcessor.java +++ b/core/src/main/java/org/jclouds/rest/internal/RestAnnotationProcessor.java @@ -78,6 +78,7 @@ import org.jclouds.http.functions.ParseFirstJsonValueNamed; import org.jclouds.http.functions.ParseJson; import org.jclouds.http.functions.ParseSax; import org.jclouds.http.functions.ParseURIFromListOrLocationHeaderIf20x; +import org.jclouds.http.functions.ParseXMLWithJAXB; import org.jclouds.http.functions.ReleasePayloadAndReturn; import org.jclouds.http.functions.ReturnInputStream; import org.jclouds.http.functions.ReturnStringIf2xx; @@ -109,6 +110,7 @@ import org.jclouds.rest.annotations.EndpointParam; import org.jclouds.rest.annotations.ExceptionParser; import org.jclouds.rest.annotations.FormParams; import org.jclouds.rest.annotations.Headers; +import org.jclouds.rest.annotations.JAXBResponseParser; import org.jclouds.rest.annotations.MapBinder; import org.jclouds.rest.annotations.MatrixParams; import org.jclouds.rest.annotations.OnlyElement; @@ -775,7 +777,9 @@ public class RestAnnotationProcessor { public static Key> getParserOrThrowException(Method method) { ResponseParser annotation = method.getAnnotation(ResponseParser.class); if (annotation == null) { - if (method.getReturnType().equals(void.class) + if (method.isAnnotationPresent(JAXBResponseParser.class)) { + return getJAXBParserKeyForMethod(method); + } else if (method.getReturnType().equals(void.class) || TypeLiteral.get(method.getGenericReturnType()).equals(futureVoidLiteral)) { return Key.get(ReleasePayloadAndReturn.class); } else if (method.getReturnType().equals(boolean.class) || method.getReturnType().equals(Boolean.class) @@ -806,6 +810,13 @@ public class RestAnnotationProcessor { Type returnVal = getReturnTypeForMethod(method); return getJsonParserKeyForMethodAnType(method, returnVal); } + + @SuppressWarnings("unchecked") + public static Key> getJAXBParserKeyForMethod(Method method) { + Type returnVal = getReturnTypeForMethod(method); + Type parserType = Types.newParameterizedType(ParseXMLWithJAXB.class, returnVal); + return (Key>) Key.get(parserType); + } public static Type getReturnTypeForMethod(Method method) { Type returnVal; diff --git a/core/src/main/java/org/jclouds/xml/XMLParser.java b/core/src/main/java/org/jclouds/xml/XMLParser.java new file mode 100644 index 0000000000..82b308b6a7 --- /dev/null +++ b/core/src/main/java/org/jclouds/xml/XMLParser.java @@ -0,0 +1,54 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.xml; + +import java.io.IOException; + +import org.jclouds.xml.internal.JAXBParser; + +import com.google.inject.ImplementedBy; + +/** + * Parses XML documents. + * + * @author Ignasi Barrera + */ +@ImplementedBy(JAXBParser.class) +public interface XMLParser +{ + /** + * Serialize the object into xml. If the object is a generic type, use + * {@link #toXML(Object, Type)} + */ + public String toXML(Object src) throws IOException; + + /** + * Serialize the generic object into xml. If the object is not a generic, use + * {@link #toXML(Object, Type)} + */ + public String toXML(Object src, Class type) throws IOException; + + /** + * Deserialize the generic object from xml. If the object is not a generic type, use + * {@link #fromXML(Object, Class)} + */ + public T fromXML(String xml, Class type) throws IOException; + +} diff --git a/core/src/main/java/org/jclouds/xml/internal/JAXBParser.java b/core/src/main/java/org/jclouds/xml/internal/JAXBParser.java new file mode 100644 index 0000000000..f3851acbb4 --- /dev/null +++ b/core/src/main/java/org/jclouds/xml/internal/JAXBParser.java @@ -0,0 +1,81 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.xml.internal; + +import java.io.IOException; +import java.io.StringReader; +import java.io.StringWriter; + +import javax.inject.Singleton; +import javax.xml.bind.JAXBContext; +import javax.xml.bind.JAXBException; +import javax.xml.bind.Marshaller; +import javax.xml.bind.Unmarshaller; + +import org.jclouds.xml.XMLParser; + +/** + * Parses XML documents using JAXB. + * + * @author Ignasi Barrera + */ +@Singleton +public class JAXBParser implements XMLParser +{ + @Override + public String toXML(final Object src) throws IOException + { + return toXML(src, src.getClass()); + } + + @Override + public String toXML(final Object src, final Class type) throws IOException + { + try + { + JAXBContext context = JAXBContext.newInstance(type); + Marshaller marshaller = context.createMarshaller(); + StringWriter writer = new StringWriter(); + marshaller.marshal(src, writer); + return writer.toString(); + } + catch (JAXBException ex) + { + throw new IOException("Could not marshall object", ex); + } + } + + @SuppressWarnings("unchecked") + @Override + public T fromXML(final String xml, final Class type) throws IOException + { + try + { + StringReader reader = new StringReader(xml); + JAXBContext context = JAXBContext.newInstance(type); + Unmarshaller unmarshaller = context.createUnmarshaller(); + return (T) unmarshaller.unmarshal(reader); + } + catch (Exception ex) + { + throw new IOException("Could not unmarshall document", ex); + } + } +} 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 9ea6c43e66..1b33ea6db3 100644 --- a/core/src/test/java/org/jclouds/rest/internal/RestAnnotationProcessorTest.java +++ b/core/src/test/java/org/jclouds/rest/internal/RestAnnotationProcessorTest.java @@ -32,6 +32,7 @@ import static org.jclouds.io.Payloads.newStringPayload; import static org.jclouds.rest.RestContextFactory.contextSpec; import static org.jclouds.rest.RestContextFactory.createContextBuilder; import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotNull; import java.io.File; import java.io.IOException; @@ -72,6 +73,7 @@ import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.UriBuilder; +import javax.xml.bind.annotation.XmlRootElement; import org.easymock.IArgumentMatcher; import org.eclipse.jetty.http.HttpHeaders; @@ -91,6 +93,7 @@ import org.jclouds.http.functions.ParseFirstJsonValueNamed; import org.jclouds.http.functions.ParseJson; import org.jclouds.http.functions.ParseSax; import org.jclouds.http.functions.ParseURIFromListOrLocationHeaderIf20x; +import org.jclouds.http.functions.ParseXMLWithJAXB; import org.jclouds.http.functions.ReleasePayloadAndReturn; import org.jclouds.http.functions.ReturnInputStream; import org.jclouds.http.functions.ReturnStringIf2xx; @@ -120,6 +123,7 @@ import org.jclouds.rest.annotations.Endpoint; import org.jclouds.rest.annotations.EndpointParam; import org.jclouds.rest.annotations.FormParams; import org.jclouds.rest.annotations.Headers; +import org.jclouds.rest.annotations.JAXBResponseParser; import org.jclouds.rest.annotations.MapBinder; import org.jclouds.rest.annotations.MatrixParams; import org.jclouds.rest.annotations.OnlyElement; @@ -2449,6 +2453,54 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { .getRawContent(); assertEquals(form, "x-amz-copy-source=/eggs/robot"); } + + public interface TestJAXBResponseParser { + @GET + @Path("/jaxb") + @JAXBResponseParser + public ListenableFuture jaxbGet(); + } + + @XmlRootElement(name = "test") + public static class TestJAXBDomain { + private String elem; + + public String getElem() { + return elem; + } + public void setElem(String elem) { + this.elem = elem; + } + } + + @Test + public void testCreateJAXBResponseParser() throws SecurityException, NoSuchMethodException { + RestAnnotationProcessor processor = factory(TestJAXBResponseParser.class); + Method method = TestJAXBResponseParser.class.getMethod("jaxbGet"); + GeneratedHttpRequest request = GeneratedHttpRequest. builder().method("GET") + .endpoint(URI.create("http://localhost")).declaring(TestJAXBResponseParser.class).javaMethod(method).args( + new Object[] {}).build(); + Function transformer = processor.createResponseParser(method, request); + assertEquals(transformer.getClass(), ParseXMLWithJAXB.class); + } + + @SuppressWarnings("unchecked") + @Test + public void testJAXBResponseParser() throws SecurityException, NoSuchMethodException, IOException { + Method method = TestJAXBResponseParser.class.getMethod("jaxbGet"); + HttpRequest request = factory(TestJAXBResponseParser.class).createRequest(method); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + // now test that it works! + + Function parser = (Function) RestAnnotationProcessor + .createResponseParser(parserFactory, injector, method, request); + + StringBuffer payload = new StringBuffer(""); + payload.append("Hello World"); + TestJAXBDomain domain = parser.apply(new HttpResponse(200, "ok", newStringPayload(payload.toString()))); + assertEquals(domain.getElem(), "Hello World"); + } DateService dateService = new SimpleDateFormatDateService(); From 69163eb4477045660a016d7262db2f2b0c1d4e6e Mon Sep 17 00:00:00 2001 From: Ignasi Barrera Date: Tue, 25 Oct 2011 11:11:15 +0200 Subject: [PATCH 07/16] Added methods to ModifyRequest to add multiple query parameters --- .../org/jclouds/http/utils/ModifyRequest.java | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/core/src/main/java/org/jclouds/http/utils/ModifyRequest.java b/core/src/main/java/org/jclouds/http/utils/ModifyRequest.java index 03b015bebb..522e16ef29 100644 --- a/core/src/main/java/org/jclouds/http/utils/ModifyRequest.java +++ b/core/src/main/java/org/jclouds/http/utils/ModifyRequest.java @@ -101,6 +101,21 @@ public class ModifyRequest { builder.replaceQuery(makeQueryLine(map, null, skips)); return (R) request.toBuilder().endpoint(builder.build()).build(); } + + public static R addQueryParams(R request, Multimap parameters, UriBuilder builder) { + return addQueryParams(request, parameters, builder, request.getSkips()); + } + + @SuppressWarnings("unchecked") + public static R addQueryParams(R request, + Multimap parameters, UriBuilder builder, char... skips) { + builder.uri(request.getEndpoint()); + Multimap map = + org.jclouds.http.utils.ModifyRequest.parseQueryToMap(request.getEndpoint().getQuery()); + map.putAll(parameters); + builder.replaceQuery(org.jclouds.http.utils.ModifyRequest.makeQueryLine(map, null, skips)); + return (R) request.toBuilder().endpoint(builder.build()).build(); + } public static R replaceMatrixParam(R request, String name, Object value, UriBuilder builder) { return replaceMatrixParam(request, name, new Object[] { value }, builder); From b90f74352f3c0c54075d43a0cb473d62e855f4d4 Mon Sep 17 00:00:00 2001 From: Ignasi Barrera Date: Tue, 25 Oct 2011 11:18:29 +0200 Subject: [PATCH 08/16] Added javadoc to JAXB parser --- .../java/org/jclouds/http/functions/ParseXMLWithJAXB.java | 8 ++++++++ .../main/java/org/jclouds/xml/internal/JAXBParser.java | 2 ++ 2 files changed, 10 insertions(+) diff --git a/core/src/main/java/org/jclouds/http/functions/ParseXMLWithJAXB.java b/core/src/main/java/org/jclouds/http/functions/ParseXMLWithJAXB.java index 8320931f8c..6e9dbf9478 100644 --- a/core/src/main/java/org/jclouds/http/functions/ParseXMLWithJAXB.java +++ b/core/src/main/java/org/jclouds/http/functions/ParseXMLWithJAXB.java @@ -23,10 +23,12 @@ import static org.jclouds.http.HttpUtils.releasePayload; import java.io.IOException; import java.io.InputStream; +import java.lang.reflect.Type; import javax.annotation.Resource; import javax.inject.Inject; import javax.inject.Singleton; +import javax.xml.bind.JAXBContext; import org.jclouds.http.HttpResponse; import org.jclouds.http.HttpResponseException; @@ -40,6 +42,12 @@ import com.google.inject.TypeLiteral; /** * This object will parse the body of an HttpResponse and return the result of type back to the * caller. + *

+ * {@link JAXBContext} works with {@link Class} objects instead of {@link Type}. This could be a + * limitation if we are trying to parse typed collections of objects. However, when using JAXB we + * expect to have well formed XML documents with one single root element, so the objects to parse + * should not be collections but objects that wrap collections of elements, and that should work + * fine. * * @author Ignasi Barrera */ diff --git a/core/src/main/java/org/jclouds/xml/internal/JAXBParser.java b/core/src/main/java/org/jclouds/xml/internal/JAXBParser.java index f3851acbb4..d7facb8269 100644 --- a/core/src/main/java/org/jclouds/xml/internal/JAXBParser.java +++ b/core/src/main/java/org/jclouds/xml/internal/JAXBParser.java @@ -29,12 +29,14 @@ import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; +import org.jclouds.http.functions.ParseXMLWithJAXB; import org.jclouds.xml.XMLParser; /** * Parses XML documents using JAXB. * * @author Ignasi Barrera + * @see ParseXMLWithJAXB */ @Singleton public class JAXBParser implements XMLParser From 0387b1bb926703c8ec9d38a93e9b6abaa48e45a5 Mon Sep 17 00:00:00 2001 From: Ignasi Barrera Date: Wed, 26 Oct 2011 10:12:45 +0200 Subject: [PATCH 09/16] Updated JAXB parser configuration Now JAXB response parser is activated by default if the Accept header is set to application/xml or the method is annotated with the @JAXBResponseParser annotation (this way we can still use it to parse documents with vendor-specific mime-types). This will not break current XML parsers, since they must be explicitly defined with the @XMLResponseParser annotation, and will provide a default XML parsing mechanism. The only requirement will be to have domain objects annotated with standard Java JAXB annotations. It would be great to refactor the @XMLResponseParser annotation to be more flexible and to allow using other parsers than SAX, this way the @JAXBResponseParser annotation could be removed. However, this change may affect existing providers and must be studied with care. --- .../internal/RestAnnotationProcessor.java | 7 +-- .../internal/RestAnnotationProcessorTest.java | 47 ++++++++++++++++--- 2 files changed, 44 insertions(+), 10 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 df2b0ed22f..1de7fa947e 100644 --- a/core/src/main/java/org/jclouds/rest/internal/RestAnnotationProcessor.java +++ b/core/src/main/java/org/jclouds/rest/internal/RestAnnotationProcessor.java @@ -777,9 +777,7 @@ public class RestAnnotationProcessor { public static Key> getParserOrThrowException(Method method) { ResponseParser annotation = method.getAnnotation(ResponseParser.class); if (annotation == null) { - if (method.isAnnotationPresent(JAXBResponseParser.class)) { - return getJAXBParserKeyForMethod(method); - } else if (method.getReturnType().equals(void.class) + if (method.getReturnType().equals(void.class) || TypeLiteral.get(method.getGenericReturnType()).equals(futureVoidLiteral)) { return Key.get(ReleasePayloadAndReturn.class); } else if (method.getReturnType().equals(boolean.class) || method.getReturnType().equals(Boolean.class) @@ -793,6 +791,9 @@ public class RestAnnotationProcessor { return Key.get((Class) IdentityFunction.class); } else if (getAcceptHeadersOrNull(method).contains(MediaType.APPLICATION_JSON)) { return getJsonParserKeyForMethod(method); + } else if (getAcceptHeadersOrNull(method).contains(MediaType.APPLICATION_XML) + || method.isAnnotationPresent(JAXBResponseParser.class)) { + return getJAXBParserKeyForMethod(method); } else if (method.getReturnType().equals(String.class) || TypeLiteral.get(method.getGenericReturnType()).equals(futureStringLiteral)) { return Key.get(ReturnStringIf2xx.class); 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 1b33ea6db3..11785926f2 100644 --- a/core/src/test/java/org/jclouds/rest/internal/RestAnnotationProcessorTest.java +++ b/core/src/test/java/org/jclouds/rest/internal/RestAnnotationProcessorTest.java @@ -32,7 +32,6 @@ import static org.jclouds.io.Payloads.newStringPayload; import static org.jclouds.rest.RestContextFactory.contextSpec; import static org.jclouds.rest.RestContextFactory.createContextBuilder; import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertNotNull; import java.io.File; import java.io.IOException; @@ -2456,9 +2455,14 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { public interface TestJAXBResponseParser { @GET - @Path("/jaxb") + @Path("/jaxb/annotation") @JAXBResponseParser - public ListenableFuture jaxbGet(); + public ListenableFuture jaxbGetWithAnnotation(); + + @GET + @Path("/jaxb/header") + @Consumes(MediaType.APPLICATION_XML) + public ListenableFuture jaxbGetWithAcceptHeader(); } @XmlRootElement(name = "test") @@ -2474,9 +2478,20 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { } @Test - public void testCreateJAXBResponseParser() throws SecurityException, NoSuchMethodException { + public void testCreateJAXBResponseParserWithAnnotation() throws SecurityException, NoSuchMethodException { RestAnnotationProcessor processor = factory(TestJAXBResponseParser.class); - Method method = TestJAXBResponseParser.class.getMethod("jaxbGet"); + Method method = TestJAXBResponseParser.class.getMethod("jaxbGetWithAnnotation"); + GeneratedHttpRequest request = GeneratedHttpRequest. builder().method("GET") + .endpoint(URI.create("http://localhost")).declaring(TestJAXBResponseParser.class).javaMethod(method).args( + new Object[] {}).build(); + Function transformer = processor.createResponseParser(method, request); + assertEquals(transformer.getClass(), ParseXMLWithJAXB.class); + } + + @Test + public void testCreateJAXBResponseParserWithAcceptHeader() throws SecurityException, NoSuchMethodException { + RestAnnotationProcessor processor = factory(TestJAXBResponseParser.class); + Method method = TestJAXBResponseParser.class.getMethod("jaxbGetWithAcceptHeader"); GeneratedHttpRequest request = GeneratedHttpRequest. builder().method("GET") .endpoint(URI.create("http://localhost")).declaring(TestJAXBResponseParser.class).javaMethod(method).args( new Object[] {}).build(); @@ -2486,8 +2501,26 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { @SuppressWarnings("unchecked") @Test - public void testJAXBResponseParser() throws SecurityException, NoSuchMethodException, IOException { - Method method = TestJAXBResponseParser.class.getMethod("jaxbGet"); + public void testJAXBResponseParserWithAnnotation() throws SecurityException, NoSuchMethodException, IOException { + Method method = TestJAXBResponseParser.class.getMethod("jaxbGetWithAnnotation"); + HttpRequest request = factory(TestJAXBResponseParser.class).createRequest(method); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + // now test that it works! + + Function parser = (Function) RestAnnotationProcessor + .createResponseParser(parserFactory, injector, method, request); + + StringBuffer payload = new StringBuffer(""); + payload.append("Hello World"); + TestJAXBDomain domain = parser.apply(new HttpResponse(200, "ok", newStringPayload(payload.toString()))); + assertEquals(domain.getElem(), "Hello World"); + } + + @SuppressWarnings("unchecked") + @Test + public void testJAXBResponseParserWithAcceptHeader() throws SecurityException, NoSuchMethodException, IOException { + Method method = TestJAXBResponseParser.class.getMethod("jaxbGetWithAcceptHeader"); HttpRequest request = factory(TestJAXBResponseParser.class).createRequest(method); assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); From e5478cdd84e37df73c01d688eed6e02844a98632 Mon Sep 17 00:00:00 2001 From: Ignasi Barrera Date: Fri, 28 Oct 2011 13:25:54 +0200 Subject: [PATCH 10/16] Added BindToXMLPayload binder to allow seralization of objects to the payload using JAXB --- .../jclouds/rest/binders/BindException.java | 71 ++++++++++++++ .../rest/binders/BindToXMLPayload.java | 78 ++++++++++++++++ .../main/java/org/jclouds/xml/XMLParser.java | 3 + .../rest/binders/BindToXMLPayloadTest.java | 93 +++++++++++++++++++ .../internal/RestAnnotationProcessorTest.java | 5 +- 5 files changed, 248 insertions(+), 2 deletions(-) create mode 100644 core/src/main/java/org/jclouds/rest/binders/BindException.java create mode 100644 core/src/main/java/org/jclouds/rest/binders/BindToXMLPayload.java create mode 100644 core/src/test/java/org/jclouds/rest/binders/BindToXMLPayloadTest.java diff --git a/core/src/main/java/org/jclouds/rest/binders/BindException.java b/core/src/main/java/org/jclouds/rest/binders/BindException.java new file mode 100644 index 0000000000..78e696b53f --- /dev/null +++ b/core/src/main/java/org/jclouds/rest/binders/BindException.java @@ -0,0 +1,71 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.rest.binders; + +import org.jclouds.http.HttpRequest; + +/** + * Exception thrown during the binding process. + * + * @author Ignasi Barrera + */ +public class BindException extends RuntimeException +{ + private static final long serialVersionUID = 1L; + + private HttpRequest request; + + public BindException(final HttpRequest request) + { + super(); + this.request = request; + } + + public BindException(final HttpRequest request, final String message) + { + super(message); + this.request = request; + } + + public BindException(final HttpRequest request, final Throwable cause) + { + super(cause.getMessage(), cause); + this.request = request; + } + + public BindException(final HttpRequest request, final String message, final Throwable cause) + { + super(message, cause); + this.request = request; + } + + @Override + public String getMessage() + { + String msg = "Could not bind object to request" + request + ": "; + return msg + super.getMessage(); + } + + public HttpRequest getRequest() + { + return request; + } + +} diff --git a/core/src/main/java/org/jclouds/rest/binders/BindToXMLPayload.java b/core/src/main/java/org/jclouds/rest/binders/BindToXMLPayload.java new file mode 100644 index 0000000000..446b07c142 --- /dev/null +++ b/core/src/main/java/org/jclouds/rest/binders/BindToXMLPayload.java @@ -0,0 +1,78 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.rest.binders; + +import static com.google.common.base.Preconditions.checkNotNull; + +import java.io.IOException; + +import javax.inject.Inject; +import javax.inject.Singleton; +import javax.ws.rs.core.MediaType; + +import org.jclouds.http.HttpRequest; +import org.jclouds.io.MutableContentMetadata; +import org.jclouds.rest.Binder; +import org.jclouds.xml.XMLParser; + +import com.google.common.base.Strings; + +/** + * Binds the request parameters to an XML formatted payload. + * + * @author Ignasi Barrera + */ +@Singleton +public class BindToXMLPayload implements Binder +{ + protected final XMLParser xmlParser; + + @Inject + public BindToXMLPayload(final XMLParser xmlParser) + { + this.xmlParser = checkNotNull(xmlParser, "xmlParser"); + } + + @Override + public R bindToRequest(final R request, final Object input) + { + try + { + String xml = xmlParser.toXML(checkNotNull(input, "input")); + request.setPayload(xml); + MutableContentMetadata metadata = request.getPayload().getContentMetadata(); + if (contentTypeMustBeAdded(metadata)) + { + metadata.setContentType(MediaType.APPLICATION_XML); + } + return request; + } + catch (IOException ex) + { + throw new BindException(request, ex); + } + } + + private static boolean contentTypeMustBeAdded(final MutableContentMetadata metadata) + { + return Strings.isNullOrEmpty(metadata.getContentType()) + || metadata.getContentType().equals("application/unknown"); + } +} diff --git a/core/src/main/java/org/jclouds/xml/XMLParser.java b/core/src/main/java/org/jclouds/xml/XMLParser.java index 82b308b6a7..797978914a 100644 --- a/core/src/main/java/org/jclouds/xml/XMLParser.java +++ b/core/src/main/java/org/jclouds/xml/XMLParser.java @@ -33,6 +33,9 @@ import com.google.inject.ImplementedBy; @ImplementedBy(JAXBParser.class) public interface XMLParser { + /** The default xml header. */ + public static final String DEFAULT_XML_HEADER = ""; + /** * Serialize the object into xml. If the object is a generic type, use * {@link #toXML(Object, Type)} diff --git a/core/src/test/java/org/jclouds/rest/binders/BindToXMLPayloadTest.java b/core/src/test/java/org/jclouds/rest/binders/BindToXMLPayloadTest.java new file mode 100644 index 0000000000..8629a51d40 --- /dev/null +++ b/core/src/test/java/org/jclouds/rest/binders/BindToXMLPayloadTest.java @@ -0,0 +1,93 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.rest.binders; + +import static org.testng.Assert.assertEquals; + +import java.net.URI; + +import javax.ws.rs.core.MediaType; + +import org.jclouds.http.HttpRequest; +import org.jclouds.rest.internal.RestAnnotationProcessorTest.TestJAXBDomain; +import org.jclouds.xml.XMLParser; +import org.jclouds.xml.internal.JAXBParser; +import org.testng.annotations.Test; + +import com.google.common.collect.ImmutableMultimap; +import com.google.common.collect.Multimap; + +/** + * Tests behavior of {@code BindToXMLPayload}. + * + * @author Ignasi Barrera + */ +@Test(groups = "unit", testName = "BindToXMLPayloadTest") +public class BindToXMLPayloadTest +{ + XMLParser xml = new JAXBParser(); + + @Test + public void testBindJAXBObject() throws SecurityException, NoSuchMethodException + { + BindToXMLPayload binder = new BindToXMLPayload(xml); + + // Build the object to bind + TestJAXBDomain obj = new TestJAXBDomain(); + obj.setElem("Hello World"); + + HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://momma")).build(); + request = binder.bindToRequest(request, obj); + assertEquals(request.getPayload().getRawContent(), XMLParser.DEFAULT_XML_HEADER + "Hello World"); + assertEquals(request.getPayload().getContentMetadata().getContentType(), MediaType.APPLICATION_XML); + } + + @Test + public void testHeaderIsChangedIfNeeded() throws SecurityException, NoSuchMethodException + { + BindToXMLPayload binder = new BindToXMLPayload(xml); + + // Build the object to bind + TestJAXBDomain obj = new TestJAXBDomain(); + obj.setElem("Hello World"); + + // Add teh unknown content-type header to verify it is changed by the binder + Multimap headers = ImmutableMultimap. of("Content-type", "application/unknown"); + HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://momma")).headers(headers).build(); + + request = binder.bindToRequest(request, obj); + assertEquals(request.getPayload().getRawContent(), XMLParser.DEFAULT_XML_HEADER + "Hello World"); + assertEquals(request.getPayload().getContentMetadata().getContentType(), MediaType.APPLICATION_XML); + } + + @Test(expectedExceptions = NullPointerException.class) + public void testNullIsBad() + { + BindToXMLPayload binder = new BindToXMLPayload(xml); + binder.bindToRequest(HttpRequest.builder().method("GET").endpoint(URI.create("http://momma")).build(), null); + } + + @Test(expectedExceptions = BindException.class) + public void testInvalidObjectBinding() + { + BindToXMLPayload binder = new BindToXMLPayload(xml); + HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://momma")).build(); + request = binder.bindToRequest(request, new Object()); + } +} 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 11785926f2..ce13902449 100644 --- a/core/src/test/java/org/jclouds/rest/internal/RestAnnotationProcessorTest.java +++ b/core/src/test/java/org/jclouds/rest/internal/RestAnnotationProcessorTest.java @@ -145,6 +145,7 @@ import org.jclouds.rest.binders.BindToJsonPayload; import org.jclouds.rest.binders.BindToStringPayload; import org.jclouds.rest.config.RestClientModule; import org.jclouds.util.Strings2; +import org.jclouds.xml.XMLParser; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.DataProvider; @@ -2511,7 +2512,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { Function parser = (Function) RestAnnotationProcessor .createResponseParser(parserFactory, injector, method, request); - StringBuffer payload = new StringBuffer(""); + StringBuffer payload = new StringBuffer(XMLParser.DEFAULT_XML_HEADER); payload.append("Hello World"); TestJAXBDomain domain = parser.apply(new HttpResponse(200, "ok", newStringPayload(payload.toString()))); assertEquals(domain.getElem(), "Hello World"); @@ -2529,7 +2530,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { Function parser = (Function) RestAnnotationProcessor .createResponseParser(parserFactory, injector, method, request); - StringBuffer payload = new StringBuffer(""); + StringBuffer payload = new StringBuffer(XMLParser.DEFAULT_XML_HEADER); payload.append("Hello World"); TestJAXBDomain domain = parser.apply(new HttpResponse(200, "ok", newStringPayload(payload.toString()))); assertEquals(domain.getElem(), "Hello World"); From 71ac2b89e1797b59649c16eaeb47850ab50c5dbb Mon Sep 17 00:00:00 2001 From: Adrian Cole Date: Sat, 29 Oct 2011 00:00:49 +0200 Subject: [PATCH 11/16] formatting --- .../http/functions/ParseXMLWithJAXB.java | 103 ++-- .../rest/annotations/JAXBResponseParser.java | 7 +- .../jclouds/rest/binders/BindException.java | 61 +- .../rest/binders/BindToXMLPayload.java | 54 +- .../main/java/org/jclouds/xml/XMLParser.java | 36 +- .../org/jclouds/xml/internal/JAXBParser.java | 68 +-- .../rest/binders/BindToXMLPayloadTest.java | 93 ++-- .../internal/RestAnnotationProcessorTest.java | 522 +++++++++--------- 8 files changed, 449 insertions(+), 495 deletions(-) diff --git a/core/src/main/java/org/jclouds/http/functions/ParseXMLWithJAXB.java b/core/src/main/java/org/jclouds/http/functions/ParseXMLWithJAXB.java index 6e9dbf9478..2b7e5e83b1 100644 --- a/core/src/main/java/org/jclouds/http/functions/ParseXMLWithJAXB.java +++ b/core/src/main/java/org/jclouds/http/functions/ParseXMLWithJAXB.java @@ -40,74 +40,61 @@ import com.google.common.base.Function; import com.google.inject.TypeLiteral; /** - * This object will parse the body of an HttpResponse and return the result of type back to the - * caller. + * This object will parse the body of an HttpResponse and return the result of + * type back to the caller. *

- * {@link JAXBContext} works with {@link Class} objects instead of {@link Type}. This could be a - * limitation if we are trying to parse typed collections of objects. However, when using JAXB we - * expect to have well formed XML documents with one single root element, so the objects to parse - * should not be collections but objects that wrap collections of elements, and that should work - * fine. + * {@link JAXBContext} works with {@link Class} objects instead of {@link Type}. + * This could be a limitation if we are trying to parse typed collections of + * objects. However, when using JAXB we expect to have well formed XML documents + * with one single root element, so the objects to parse should not be + * collections but objects that wrap collections of elements, and that should + * work fine. * * @author Ignasi Barrera */ @Singleton -public class ParseXMLWithJAXB implements Function -{ - @Resource - protected Logger logger = Logger.NULL; +public class ParseXMLWithJAXB implements Function { + @Resource + protected Logger logger = Logger.NULL; - protected XMLParser xml; + protected XMLParser xml; - protected final TypeLiteral type; + protected final TypeLiteral type; - @Inject - public ParseXMLWithJAXB(final XMLParser xml, final TypeLiteral type) - { - this.xml = xml; - this.type = type; - } + @Inject + public ParseXMLWithJAXB(final XMLParser xml, final TypeLiteral type) { + this.xml = xml; + this.type = type; + } - @Override - public T apply(final HttpResponse from) - { - InputStream xml = from.getPayload().getInput(); - try - { - return apply(xml); - } - catch (Exception e) - { - StringBuffer message = new StringBuffer(); - message.append("Error parsing input"); - logger.error(e, message.toString()); - throw new HttpResponseException(message.toString() + "\n" + from, null, from, e); - } - finally - { - releasePayload(from); - } - } + @Override + public T apply(final HttpResponse from) { + InputStream xml = from.getPayload().getInput(); + try { + return apply(xml); + } catch (Exception e) { + StringBuffer message = new StringBuffer(); + message.append("Error parsing input"); + logger.error(e, message.toString()); + throw new HttpResponseException(message.toString() + "\n" + from, null, from, e); + } finally { + releasePayload(from); + } + } - @SuppressWarnings("unchecked") - public T apply(final InputStream stream) throws IOException - { - return (T) apply(stream, type.getRawType()); - } + @SuppressWarnings("unchecked") + public T apply(final InputStream stream) throws IOException { + return (T) apply(stream, type.getRawType()); + } - public V apply(final InputStream stream, final Class type) throws IOException - { - try - { - return xml.fromXML(Strings2.toStringAndClose(stream), type); - } - finally - { - if (stream != null) - { - stream.close(); - } - } - } + public V apply(final InputStream stream, final Class type) throws IOException { + try { + return xml.fromXML(Strings2.toStringAndClose(stream), type); + } finally { + if (stream != null) { + stream.close(); + } + } + } } diff --git a/core/src/main/java/org/jclouds/rest/annotations/JAXBResponseParser.java b/core/src/main/java/org/jclouds/rest/annotations/JAXBResponseParser.java index 6129c0c9f3..6eb7cf99fc 100644 --- a/core/src/main/java/org/jclouds/rest/annotations/JAXBResponseParser.java +++ b/core/src/main/java/org/jclouds/rest/annotations/JAXBResponseParser.java @@ -27,14 +27,13 @@ import java.lang.annotation.Target; import org.jclouds.http.functions.ParseXMLWithJAXB; /** - * Shows the transformer type used to parse XML with the {@link ParseXMLWithJAXB} parser in a - * HttpResponse. + * Shows the transformer type used to parse XML with the + * {@link ParseXMLWithJAXB} parser in a HttpResponse. * * @author Ignasi Barrera */ @Target(METHOD) @Retention(RUNTIME) -public @interface JAXBResponseParser -{ +public @interface JAXBResponseParser { } diff --git a/core/src/main/java/org/jclouds/rest/binders/BindException.java b/core/src/main/java/org/jclouds/rest/binders/BindException.java index 78e696b53f..fe2fcbf465 100644 --- a/core/src/main/java/org/jclouds/rest/binders/BindException.java +++ b/core/src/main/java/org/jclouds/rest/binders/BindException.java @@ -26,46 +26,39 @@ import org.jclouds.http.HttpRequest; * * @author Ignasi Barrera */ -public class BindException extends RuntimeException -{ - private static final long serialVersionUID = 1L; +public class BindException extends RuntimeException { + private static final long serialVersionUID = 1L; - private HttpRequest request; + private HttpRequest request; - public BindException(final HttpRequest request) - { - super(); - this.request = request; - } + public BindException(final HttpRequest request) { + super(); + this.request = request; + } - public BindException(final HttpRequest request, final String message) - { - super(message); - this.request = request; - } + public BindException(final HttpRequest request, final String message) { + super(message); + this.request = request; + } - public BindException(final HttpRequest request, final Throwable cause) - { - super(cause.getMessage(), cause); - this.request = request; - } + public BindException(final HttpRequest request, final Throwable cause) { + super(cause.getMessage(), cause); + this.request = request; + } - public BindException(final HttpRequest request, final String message, final Throwable cause) - { - super(message, cause); - this.request = request; - } + public BindException(final HttpRequest request, final String message, final Throwable cause) { + super(message, cause); + this.request = request; + } - @Override - public String getMessage() - { - String msg = "Could not bind object to request" + request + ": "; - return msg + super.getMessage(); - } + @Override + public String getMessage() { + String msg = "Could not bind object to request" + request + ": "; + return msg + super.getMessage(); + } - public HttpRequest getRequest() - { - return request; - } + public HttpRequest getRequest() { + return request; + } } diff --git a/core/src/main/java/org/jclouds/rest/binders/BindToXMLPayload.java b/core/src/main/java/org/jclouds/rest/binders/BindToXMLPayload.java index 446b07c142..6adfecb199 100644 --- a/core/src/main/java/org/jclouds/rest/binders/BindToXMLPayload.java +++ b/core/src/main/java/org/jclouds/rest/binders/BindToXMLPayload.java @@ -40,39 +40,31 @@ import com.google.common.base.Strings; * @author Ignasi Barrera */ @Singleton -public class BindToXMLPayload implements Binder -{ - protected final XMLParser xmlParser; +public class BindToXMLPayload implements Binder { + protected final XMLParser xmlParser; - @Inject - public BindToXMLPayload(final XMLParser xmlParser) - { - this.xmlParser = checkNotNull(xmlParser, "xmlParser"); - } + @Inject + public BindToXMLPayload(final XMLParser xmlParser) { + this.xmlParser = checkNotNull(xmlParser, "xmlParser"); + } - @Override - public R bindToRequest(final R request, final Object input) - { - try - { - String xml = xmlParser.toXML(checkNotNull(input, "input")); - request.setPayload(xml); - MutableContentMetadata metadata = request.getPayload().getContentMetadata(); - if (contentTypeMustBeAdded(metadata)) - { - metadata.setContentType(MediaType.APPLICATION_XML); - } - return request; - } - catch (IOException ex) - { - throw new BindException(request, ex); - } - } + @Override + public R bindToRequest(final R request, final Object input) { + try { + String xml = xmlParser.toXML(checkNotNull(input, "input")); + request.setPayload(xml); + MutableContentMetadata metadata = request.getPayload().getContentMetadata(); + if (contentTypeMustBeAdded(metadata)) { + metadata.setContentType(MediaType.APPLICATION_XML); + } + return request; + } catch (IOException ex) { + throw new BindException(request, ex); + } + } - private static boolean contentTypeMustBeAdded(final MutableContentMetadata metadata) - { - return Strings.isNullOrEmpty(metadata.getContentType()) + private static boolean contentTypeMustBeAdded(final MutableContentMetadata metadata) { + return Strings.isNullOrEmpty(metadata.getContentType()) || metadata.getContentType().equals("application/unknown"); - } + } } diff --git a/core/src/main/java/org/jclouds/xml/XMLParser.java b/core/src/main/java/org/jclouds/xml/XMLParser.java index 797978914a..e79c52189a 100644 --- a/core/src/main/java/org/jclouds/xml/XMLParser.java +++ b/core/src/main/java/org/jclouds/xml/XMLParser.java @@ -31,27 +31,23 @@ import com.google.inject.ImplementedBy; * @author Ignasi Barrera */ @ImplementedBy(JAXBParser.class) -public interface XMLParser -{ - /** The default xml header. */ - public static final String DEFAULT_XML_HEADER = ""; - - /** - * Serialize the object into xml. If the object is a generic type, use - * {@link #toXML(Object, Type)} - */ - public String toXML(Object src) throws IOException; +public interface XMLParser { + /** The default xml header. */ + public static final String DEFAULT_XML_HEADER = ""; - /** - * Serialize the generic object into xml. If the object is not a generic, use - * {@link #toXML(Object, Type)} - */ - public String toXML(Object src, Class type) throws IOException; + /** + * Serialize the object into xml. + */ + public String toXML(Object src) throws IOException; - /** - * Deserialize the generic object from xml. If the object is not a generic type, use - * {@link #fromXML(Object, Class)} - */ - public T fromXML(String xml, Class type) throws IOException; + /** + * Serialize the object into xml, as the declared type. + */ + public String toXML(Object src, Class type) throws IOException; + + /** + * Deserialize the object from xml. + */ + public T fromXML(String xml, Class type) throws IOException; } diff --git a/core/src/main/java/org/jclouds/xml/internal/JAXBParser.java b/core/src/main/java/org/jclouds/xml/internal/JAXBParser.java index d7facb8269..928c725ce3 100644 --- a/core/src/main/java/org/jclouds/xml/internal/JAXBParser.java +++ b/core/src/main/java/org/jclouds/xml/internal/JAXBParser.java @@ -39,45 +39,35 @@ import org.jclouds.xml.XMLParser; * @see ParseXMLWithJAXB */ @Singleton -public class JAXBParser implements XMLParser -{ - @Override - public String toXML(final Object src) throws IOException - { - return toXML(src, src.getClass()); - } +public class JAXBParser implements XMLParser { + @Override + public String toXML(final Object src) throws IOException { + return toXML(src, src.getClass()); + } - @Override - public String toXML(final Object src, final Class type) throws IOException - { - try - { - JAXBContext context = JAXBContext.newInstance(type); - Marshaller marshaller = context.createMarshaller(); - StringWriter writer = new StringWriter(); - marshaller.marshal(src, writer); - return writer.toString(); - } - catch (JAXBException ex) - { - throw new IOException("Could not marshall object", ex); - } - } + @Override + public String toXML(final Object src, final Class type) throws IOException { + try { + JAXBContext context = JAXBContext.newInstance(type); + Marshaller marshaller = context.createMarshaller(); + StringWriter writer = new StringWriter(); + marshaller.marshal(src, writer); + return writer.toString(); + } catch (JAXBException ex) { + throw new IOException("Could not marshall object", ex); + } + } - @SuppressWarnings("unchecked") - @Override - public T fromXML(final String xml, final Class type) throws IOException - { - try - { - StringReader reader = new StringReader(xml); - JAXBContext context = JAXBContext.newInstance(type); - Unmarshaller unmarshaller = context.createUnmarshaller(); - return (T) unmarshaller.unmarshal(reader); - } - catch (Exception ex) - { - throw new IOException("Could not unmarshall document", ex); - } - } + @SuppressWarnings("unchecked") + @Override + public T fromXML(final String xml, final Class type) throws IOException { + try { + StringReader reader = new StringReader(xml); + JAXBContext context = JAXBContext.newInstance(type); + Unmarshaller unmarshaller = context.createUnmarshaller(); + return (T) unmarshaller.unmarshal(reader); + } catch (Exception ex) { + throw new IOException("Could not unmarshall document", ex); + } + } } diff --git a/core/src/test/java/org/jclouds/rest/binders/BindToXMLPayloadTest.java b/core/src/test/java/org/jclouds/rest/binders/BindToXMLPayloadTest.java index 8629a51d40..f387253024 100644 --- a/core/src/test/java/org/jclouds/rest/binders/BindToXMLPayloadTest.java +++ b/core/src/test/java/org/jclouds/rest/binders/BindToXMLPayloadTest.java @@ -39,55 +39,54 @@ import com.google.common.collect.Multimap; * @author Ignasi Barrera */ @Test(groups = "unit", testName = "BindToXMLPayloadTest") -public class BindToXMLPayloadTest -{ - XMLParser xml = new JAXBParser(); +public class BindToXMLPayloadTest { + XMLParser xml = new JAXBParser(); - @Test - public void testBindJAXBObject() throws SecurityException, NoSuchMethodException - { - BindToXMLPayload binder = new BindToXMLPayload(xml); - - // Build the object to bind - TestJAXBDomain obj = new TestJAXBDomain(); - obj.setElem("Hello World"); + @Test + public void testBindJAXBObject() throws SecurityException, NoSuchMethodException { + BindToXMLPayload binder = new BindToXMLPayload(xml); - HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://momma")).build(); - request = binder.bindToRequest(request, obj); - assertEquals(request.getPayload().getRawContent(), XMLParser.DEFAULT_XML_HEADER + "Hello World"); - assertEquals(request.getPayload().getContentMetadata().getContentType(), MediaType.APPLICATION_XML); - } - - @Test - public void testHeaderIsChangedIfNeeded() throws SecurityException, NoSuchMethodException - { - BindToXMLPayload binder = new BindToXMLPayload(xml); - - // Build the object to bind - TestJAXBDomain obj = new TestJAXBDomain(); - obj.setElem("Hello World"); + // Build the object to bind + TestJAXBDomain obj = new TestJAXBDomain(); + obj.setElem("Hello World"); - // Add teh unknown content-type header to verify it is changed by the binder - Multimap headers = ImmutableMultimap. of("Content-type", "application/unknown"); - HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://momma")).headers(headers).build(); - - request = binder.bindToRequest(request, obj); - assertEquals(request.getPayload().getRawContent(), XMLParser.DEFAULT_XML_HEADER + "Hello World"); - assertEquals(request.getPayload().getContentMetadata().getContentType(), MediaType.APPLICATION_XML); - } + HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://momma")).build(); + request = binder.bindToRequest(request, obj); + assertEquals(request.getPayload().getRawContent(), XMLParser.DEFAULT_XML_HEADER + + "Hello World"); + assertEquals(request.getPayload().getContentMetadata().getContentType(), MediaType.APPLICATION_XML); + } - @Test(expectedExceptions = NullPointerException.class) - public void testNullIsBad() - { - BindToXMLPayload binder = new BindToXMLPayload(xml); - binder.bindToRequest(HttpRequest.builder().method("GET").endpoint(URI.create("http://momma")).build(), null); - } - - @Test(expectedExceptions = BindException.class) - public void testInvalidObjectBinding() - { - BindToXMLPayload binder = new BindToXMLPayload(xml); - HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://momma")).build(); - request = binder.bindToRequest(request, new Object()); - } + @Test + public void testHeaderIsChangedIfNeeded() throws SecurityException, NoSuchMethodException { + BindToXMLPayload binder = new BindToXMLPayload(xml); + + // Build the object to bind + TestJAXBDomain obj = new TestJAXBDomain(); + obj.setElem("Hello World"); + + // Add teh unknown content-type header to verify it is changed by the + // binder + Multimap headers = ImmutableMultimap. of("Content-type", "application/unknown"); + HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://momma")).headers(headers) + .build(); + + request = binder.bindToRequest(request, obj); + assertEquals(request.getPayload().getRawContent(), XMLParser.DEFAULT_XML_HEADER + + "Hello World"); + assertEquals(request.getPayload().getContentMetadata().getContentType(), MediaType.APPLICATION_XML); + } + + @Test(expectedExceptions = NullPointerException.class) + public void testNullIsBad() { + BindToXMLPayload binder = new BindToXMLPayload(xml); + binder.bindToRequest(HttpRequest.builder().method("GET").endpoint(URI.create("http://momma")).build(), null); + } + + @Test(expectedExceptions = BindException.class) + public void testInvalidObjectBinding() { + BindToXMLPayload binder = new BindToXMLPayload(xml); + HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://momma")).build(); + request = binder.bindToRequest(request, new Object()); + } } 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 ce13902449..68c346e37c 100644 --- a/core/src/test/java/org/jclouds/rest/internal/RestAnnotationProcessorTest.java +++ b/core/src/test/java/org/jclouds/rest/internal/RestAnnotationProcessorTest.java @@ -175,7 +175,8 @@ import com.sun.jersey.api.uri.UriBuilderImpl; * * @author Adrian Cole */ -// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire +// NOTE:without testName, this will not call @Before* and fail w/NPE during +// surefire @Test(groups = "unit", testName = "RestAnnotationProcessorTest") public class RestAnnotationProcessorTest extends BaseRestClientTest { @@ -230,7 +231,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { @SuppressWarnings("unchecked") public void testDelegateAsyncIncludesVersion() throws SecurityException, NoSuchMethodException, - InterruptedException, ExecutionException { + InterruptedException, ExecutionException { Injector child = injectorForClient(); TransformingHttpCommandExecutorService mock = child.getInstance(TransformingHttpCommandExecutorService.class); @@ -245,7 +246,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { AsyncCaller caller = child.getInstance(AsyncCaller.class); expect(mock.submit(requestLineEquals("GET http://localhost:9999/client/1/foo HTTP/1.1"), eq(function))) - .andReturn(createNiceMock(ListenableFuture.class)).atLeastOnce(); + .andReturn(createNiceMock(ListenableFuture.class)).atLeastOnce(); replay(mock); caller.getCallee().onePath("foo"); @@ -274,7 +275,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); @@ -289,7 +290,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { Caller caller = child.getInstance(Caller.class); expect(mock.submit(requestLineEquals("GET http://localhost:1111/client/1/foo HTTP/1.1"), eq(function))) - .andReturn(Futures. immediateFuture(null)).atLeastOnce(); + .andReturn(Futures. immediateFuture(null)).atLeastOnce(); replay(mock); caller.getCallee().onePath("foo"); @@ -299,7 +300,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { } public void testDelegateWithOverridingEndpointOnMethod() throws SecurityException, NoSuchMethodException, - InterruptedException, ExecutionException { + InterruptedException, ExecutionException { Injector child = injectorForClient(); TransformingHttpCommandExecutorService mock = child.getInstance(TransformingHttpCommandExecutorService.class); @@ -314,7 +315,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { Caller caller = child.getInstance(Caller.class); expect(mock.submit(requestLineEquals("GET http://howdyboys/client/1/foo HTTP/1.1"), eq(function))).andReturn( - Futures. immediateFuture(null)).atLeastOnce(); + Futures. immediateFuture(null)).atLeastOnce(); replay(mock); caller.getCallee(URI.create("http://howdyboys")).onePath("foo"); @@ -326,8 +327,8 @@ 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())); + "userfoo", null, Caller.class, AsyncCaller.class, + ImmutableSet. of(new MockModule(), new NullLoggingModule(), new CallerCalleeModule())); return createContextBuilder(contextSpec).buildInjector(); @@ -342,7 +343,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { }; - @Target( { ElementType.METHOD }) + @Target({ ElementType.METHOD }) @Retention(RetentionPolicy.RUNTIME) @javax.ws.rs.HttpMethod("FOO") public @interface FOO { @@ -377,10 +378,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); } @@ -451,7 +452,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); } @@ -544,7 +545,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(), ""); @@ -557,7 +558,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { @POST void postNonnull(@BinderParam(BindToStringPayload.class) String content); - + @POST public void postAsJson(@BinderParam(BindToJsonPayload.class) String content); @@ -615,12 +616,10 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { Method method = TestPost.class.getMethod("postNonnull", String.class); try { HttpRequest request = factory(TestPost.class).createRequest(method); - Assert - .fail("call should have failed with illegal null parameter, not permitted " + request - + " to be created"); + Assert.fail("call should have failed with illegal null parameter, not permitted " + request + " to be created"); } catch (NullPointerException e) { Assert.assertTrue(e.toString().indexOf("postNonnull parameter 1") >= 0, - "Error message should have referred to 'parameter 1': " + e); + "Error message should have referred to 'parameter 1': " + e); } } @@ -628,12 +627,10 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { Method method = TestPost.class.getMethod("postNonnull", String.class); try { HttpRequest request = factory(TestPost.class).createRequest(method, (String) null); - Assert - .fail("call should have failed with illegal null parameter, not permitted " + request - + " to be created"); + Assert.fail("call should have failed with illegal null parameter, not permitted " + request + " to be created"); } catch (NullPointerException e) { Assert.assertTrue(e.toString().indexOf("postNonnull parameter 1") >= 0, - "Error message should have referred to parameter 'parameter 1': " + e); + "Error message should have referred to parameter 'parameter 1': " + e); } } @@ -703,55 +700,57 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { @POST 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 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 testMultipartWithStringPartNullNotOkay() throws SecurityException, NoSuchMethodException, IOException { Method method = TestMultipartForm.class.getMethod("withStringPart", String.class); try { GeneratedHttpRequest httpRequest = factory(TestMultipartForm.class).createRequest(method, - (String)null); - Assert.fail("call should have failed with illegal null parameter, not permitted "+httpRequest+" to be created"); + (String) null); + Assert.fail("call should have failed with illegal null parameter, not permitted " + httpRequest + + " to be created"); } catch (NullPointerException e) { - Assert.assertTrue(e.toString().indexOf("fooble")>=0, "Error message should have referred to parameter 'fooble': "+e); + Assert.assertTrue(e.toString().indexOf("fooble") >= 0, + "Error message should have referred to parameter 'fooble': " + e); } } 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 testMultipartWithParamStringPartNullNotOk() throws SecurityException, NoSuchMethodException, IOException { @@ -759,9 +758,11 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { try { GeneratedHttpRequest httpRequest = factory(TestMultipartForm.class).createRequest(method, null, "foobledata"); - Assert.fail("call should have failed with illegal null parameter, not permitted "+httpRequest+" to be created"); + Assert.fail("call should have failed with illegal null parameter, not permitted " + httpRequest + + " to be created"); } catch (NullPointerException e) { - Assert.assertTrue(e.toString().indexOf("name")>=0, "Error message should have referred to parameter 'name': "+e); + Assert.assertTrue(e.toString().indexOf("name") >= 0, + "Error message should have referred to parameter 'name': " + e); } } @@ -772,38 +773,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 { @@ -813,20 +814,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 { @@ -872,7 +873,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { @SelectJson("foo") @Consumes(MediaType.APPLICATION_JSON) String testUnwrapValueNamed(); - + @POST @Path("/") String testWrapWith(@WrapWith("foo") String param); @@ -906,32 +907,32 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { @Unwrap(depth = 2) @Consumes(MediaType.APPLICATION_JSON) ListenableFuture testUnwrapDepth2Long(); - + @GET @Path("/") @SelectJson("jobid") ListenableFuture selectLong(); - + @GET @Path("/") @Unwrap(depth = 2, edgeCollection = Set.class) @Consumes(MediaType.APPLICATION_JSON) ListenableFuture testUnwrapDepth2Set(); - + @GET @Path("/") @SelectJson("runit") @OnlyElement @Consumes(MediaType.APPLICATION_JSON) ListenableFuture selectOnlyElement(); - + @GET @Path("/") @Unwrap(depth = 3, edgeCollection = Set.class) @Consumes(MediaType.APPLICATION_JSON) ListenableFuture testUnwrapDepth3(); - @Target( { ElementType.METHOD }) + @Target({ ElementType.METHOD }) @Retention(RetentionPolicy.RUNTIME) @HttpMethod("ROWDY") public @interface ROWDY { @@ -999,7 +1000,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"); @@ -1014,10 +1015,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")); } @@ -1030,10 +1031,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")); } @@ -1046,10 +1047,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")); } @@ -1062,13 +1063,12 @@ 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"); } - @SuppressWarnings("unchecked") public void testUnwrapValueNamed() throws SecurityException, NoSuchMethodException, IOException { Method method = TestPut.class.getMethod("testUnwrapValueNamed"); @@ -1078,11 +1078,12 @@ 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"); } + public void testWrapWith() throws SecurityException, NoSuchMethodException, IOException { Method method = TestPut.class.getMethod("testWrapWith", String.class); HttpRequest request = factory(TestPut.class).createRequest(method, "bar"); @@ -1098,7 +1099,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"); @@ -1113,10 +1114,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") @@ -1128,10 +1129,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") @@ -1143,13 +1144,13 @@ 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\":{\"runit\":[\"0.7.0\",\"0.7.1\"]}}"))), ImmutableSet.of("0.7.0", "0.7.1")); + newStringPayload("{\"runit\":{\"runit\":[\"0.7.0\",\"0.7.1\"]}}"))), ImmutableSet.of("0.7.0", "0.7.1")); - assertEquals(parser.apply(new HttpResponse(200, "ok", newStringPayload("{\"runit\":{}}"))), ImmutableSet - . of()); + assertEquals(parser.apply(new HttpResponse(200, "ok", newStringPayload("{\"runit\":{}}"))), + ImmutableSet. of()); } @SuppressWarnings("unchecked") @@ -1161,21 +1162,20 @@ 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.0"); assertEquals(parser.apply(new HttpResponse(200, "ok", newStringPayload("{\"runit\":[]}"))), null); } - @SuppressWarnings("unchecked") public void testSelectOnlyElement() throws SecurityException, NoSuchMethodException, IOException { Method method = TestPut.class.getMethod("selectOnlyElement"); HttpRequest request = factory(TestPut.class).createRequest(method); 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.0"); @@ -1191,10 +1191,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("{ \"destroyvirtualmachineresponse\" : {\"jobid\":4} }"))), new Long(4)); + newStringPayload("{ \"destroyvirtualmachineresponse\" : {\"jobid\":4} }"))), new Long(4)); } @SuppressWarnings("unchecked") @@ -1206,12 +1206,12 @@ 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("{ \"destroyvirtualmachineresponse\" : {\"jobid\":4} }"))), new Long(4)); + newStringPayload("{ \"destroyvirtualmachineresponse\" : {\"jobid\":4} }"))), new Long(4)); } - + @SuppressWarnings("unchecked") public void testUnwrapDepth3() throws SecurityException, NoSuchMethodException, IOException { Method method = TestPut.class.getMethod("testUnwrapDepth3"); @@ -1221,10 +1221,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\":{\"runit\":[\"0.7.0\"]}}"))), - "0.7.0"); + "0.7.0"); } @SuppressWarnings("unchecked") @@ -1236,7 +1236,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("{\"runit\":{\"runit\":[]}}"))), null); assertEquals(parser.apply(new HttpResponse(200, "ok", newStringPayload("{\"runit\":{}}"))), null); @@ -1253,7 +1253,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); parser.apply(new HttpResponse(200, "ok", newStringPayload("{\"runit\":{\"runit\":[\"0.7.0\",\"0.7.1\"]}}"))); } @@ -1305,9 +1305,9 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { public void testRequestFilterOverrideOnRequest() throws SecurityException, NoSuchMethodException { Method method = TestRequestFilter.class.getMethod("getOverride", HttpRequest.class); HttpRequest request = factory(TestRequestFilter.class).createRequest( - method, - HttpRequest.builder().method("GET").endpoint(URI.create("http://localhost")).headers( - ImmutableMultimap.of("foo", "bar")).build()); + method, + HttpRequest.builder().method("GET").endpoint(URI.create("http://localhost")) + .headers(ImmutableMultimap.of("foo", "bar")).build()); assertEquals(request.getFilters().size(), 1); assertEquals(request.getHeaders().size(), 1); assertEquals(request.getFilters().get(0).getClass(), TestRequestFilter2.class); @@ -1355,7 +1355,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); @@ -1492,7 +1492,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { public void testBuildTwoHeader() throws SecurityException, NoSuchMethodException { 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")); @@ -1510,7 +1510,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { public void testBuildOneClassHeader() throws SecurityException, NoSuchMethodException { 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")); } @@ -1519,7 +1519,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { public void testBuildOneHeader() throws SecurityException, NoSuchMethodException { 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")); } @@ -1528,7 +1528,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { public void testBuildTwoHeaders() throws SecurityException, NoSuchMethodException { 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")); } @@ -1537,7 +1537,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { public void testBuildTwoHeadersOutOfOrder() throws SecurityException, NoSuchMethodException { 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")); } @@ -1551,8 +1551,8 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { @Test public void testQueryInOptions() throws SecurityException, NoSuchMethodException { 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"); } @@ -1560,13 +1560,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 { 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); } @@ -1608,7 +1608,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { public void testBuildTwoQuery() throws SecurityException, NoSuchMethodException { 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"); } @@ -1624,7 +1624,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { public void testBuildOneClassQuery() throws SecurityException, NoSuchMethodException { 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"); } @@ -1632,7 +1632,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { public void testBuildOneQuery() throws SecurityException, NoSuchMethodException { 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"); } @@ -1640,15 +1640,15 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { public void testBuildTwoQuerys() throws SecurityException, NoSuchMethodException { 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 { 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"); } @@ -1661,9 +1661,9 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { @Test public void testMatrixInOptions() throws SecurityException, NoSuchMethodException { 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"); } @@ -1704,7 +1704,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { public void testBuildTwoMatrix() throws SecurityException, NoSuchMethodException { 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"); } @@ -1721,7 +1721,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { public void testBuildOneClassMatrix() throws SecurityException, NoSuchMethodException { 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"); } @@ -1729,7 +1729,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { public void testBuildOneMatrix() throws SecurityException, NoSuchMethodException { 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"); } @@ -1737,16 +1737,16 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { public void testBuildTwoMatrixs() throws SecurityException, NoSuchMethodException { 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 { 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"); } @@ -1788,7 +1788,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); @@ -1806,10 +1806,10 @@ 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(Strings2 - .toInputStream("whoops"))); + PayloadEnclosing payloadEnclosing = new PayloadEnclosingImpl( + newInputStreamPayload(Strings2.toInputStream("whoops"))); calculateMD5(payloadEnclosing, crypto.md5()); HttpRequest request = factory(TestQuery.class).createRequest(method, payloadEnclosing); @@ -1866,7 +1866,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); @@ -1887,7 +1887,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); @@ -1911,9 +1911,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 { @@ -1929,7 +1929,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { } public static class ReturnStringIf200Context extends ReturnStringIf2xx implements - InvocationContext { + InvocationContext { public HttpRequest request; @@ -1951,8 +1951,8 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { RestAnnotationProcessor processor = factory(TestTransformers.class); Method method = TestTransformers.class.getMethod("oneTransformerWithContext"); GeneratedHttpRequest request = GeneratedHttpRequest. builder().method("GET") - .endpoint(URI.create("http://localhost")).declaring(TestTransformers.class).javaMethod(method).args( - new Object[] {}).build(); + .endpoint(URI.create("http://localhost")).declaring(TestTransformers.class).javaMethod(method) + .args(new Object[] {}).build(); Function transformer = processor.createResponseParser(method, request); assertEquals(transformer.getClass(), ReturnStringIf200Context.class); assertEquals(((ReturnStringIf200Context) transformer).request, request); @@ -1992,13 +1992,13 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { @GET @Path("/{id}") - @QueryParams(keys = "acl", values="") + @QueryParams(keys = "acl", values = "") ListenableFuture getQueryEmpty(@PathParam("id") String id); @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}") @@ -2010,7 +2010,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 { @@ -2024,8 +2024,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:9999")); - 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 { @@ -2038,8 +2038,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:9999")); - 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 { @@ -2077,7 +2077,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { assertEquals(request.getMethod(), HttpMethod.GET); assertEquals(request.getHeaders().size(), 0); } - + public void testCreateGetQueryEmpty() throws SecurityException, NoSuchMethodException { Method method = TestRequest.class.getMethod("getQueryEmpty", String.class); HttpRequest request = factory(TestRequest.class).createRequest(method, new Object[] { "1" }); @@ -2112,7 +2112,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"); @@ -2155,7 +2155,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); @@ -2220,7 +2220,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { public void testOneHeader() throws SecurityException, NoSuchMethodException, ExecutionException { 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")); } @@ -2229,7 +2229,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { public void testOneIntHeader() throws SecurityException, NoSuchMethodException, ExecutionException { 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")); } @@ -2238,7 +2238,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { public void testTwoDifferentHeaders() throws SecurityException, NoSuchMethodException, ExecutionException { 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")); @@ -2248,7 +2248,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { public void testTwoSameHeaders() throws SecurityException, NoSuchMethodException, ExecutionException { 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"); @@ -2271,7 +2271,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 { @@ -2291,7 +2291,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { public void testOneEndpointParam() throws SecurityException, NoSuchMethodException, ExecutionException { 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")); } @@ -2301,7 +2301,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { public void testTwoDifferentEndpointParams() throws SecurityException, NoSuchMethodException, ExecutionException { 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")); } @@ -2312,11 +2312,11 @@ 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 public void twoEntities(@BinderParam(BindToStringPayload.class) String payload1, - @BinderParam(BindToStringPayload.class) String payload2); + @BinderParam(BindToStringPayload.class) String payload2); } @Test @@ -2419,8 +2419,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { } @Test(expectedExceptions = AuthorizationException.class) - public void testProvidesWithGenericQualifiedAuthorizationException() throws SecurityException, - NoSuchMethodException { + public void testProvidesWithGenericQualifiedAuthorizationException() throws SecurityException, NoSuchMethodException { injector.getInstance(AsyncClientFactory.class).create(TestClassForm.class).exception(); } @@ -2442,7 +2441,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { public void testBuildTwoForms() throws SecurityException, NoSuchMethodException { 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"); } @@ -2450,119 +2449,118 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest { public void testBuildTwoFormsOutOfOrder() throws SecurityException, NoSuchMethodException { 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"); } - + public interface TestJAXBResponseParser { - @GET - @Path("/jaxb/annotation") - @JAXBResponseParser - public ListenableFuture jaxbGetWithAnnotation(); - - @GET - @Path("/jaxb/header") - @Consumes(MediaType.APPLICATION_XML) - public ListenableFuture jaxbGetWithAcceptHeader(); + @GET + @Path("/jaxb/annotation") + @JAXBResponseParser + public ListenableFuture jaxbGetWithAnnotation(); + + @GET + @Path("/jaxb/header") + @Consumes(MediaType.APPLICATION_XML) + public ListenableFuture jaxbGetWithAcceptHeader(); } - + @XmlRootElement(name = "test") public static class TestJAXBDomain { - private String elem; + private String elem; - public String getElem() { - return elem; - } - public void setElem(String elem) { - this.elem = elem; - } + public String getElem() { + return elem; + } + + public void setElem(String elem) { + this.elem = elem; + } } - + @Test public void testCreateJAXBResponseParserWithAnnotation() throws SecurityException, NoSuchMethodException { - RestAnnotationProcessor processor = factory(TestJAXBResponseParser.class); - Method method = TestJAXBResponseParser.class.getMethod("jaxbGetWithAnnotation"); - GeneratedHttpRequest request = GeneratedHttpRequest. builder().method("GET") - .endpoint(URI.create("http://localhost")).declaring(TestJAXBResponseParser.class).javaMethod(method).args( - new Object[] {}).build(); - Function transformer = processor.createResponseParser(method, request); - assertEquals(transformer.getClass(), ParseXMLWithJAXB.class); - } - + RestAnnotationProcessor processor = factory(TestJAXBResponseParser.class); + Method method = TestJAXBResponseParser.class.getMethod("jaxbGetWithAnnotation"); + GeneratedHttpRequest request = GeneratedHttpRequest. builder() + .method("GET").endpoint(URI.create("http://localhost")).declaring(TestJAXBResponseParser.class) + .javaMethod(method).args(new Object[] {}).build(); + Function transformer = processor.createResponseParser(method, request); + assertEquals(transformer.getClass(), ParseXMLWithJAXB.class); + } + @Test public void testCreateJAXBResponseParserWithAcceptHeader() throws SecurityException, NoSuchMethodException { - RestAnnotationProcessor processor = factory(TestJAXBResponseParser.class); - Method method = TestJAXBResponseParser.class.getMethod("jaxbGetWithAcceptHeader"); - GeneratedHttpRequest request = GeneratedHttpRequest. builder().method("GET") - .endpoint(URI.create("http://localhost")).declaring(TestJAXBResponseParser.class).javaMethod(method).args( - new Object[] {}).build(); - Function transformer = processor.createResponseParser(method, request); - assertEquals(transformer.getClass(), ParseXMLWithJAXB.class); - } - + RestAnnotationProcessor processor = factory(TestJAXBResponseParser.class); + Method method = TestJAXBResponseParser.class.getMethod("jaxbGetWithAcceptHeader"); + GeneratedHttpRequest request = GeneratedHttpRequest. builder() + .method("GET").endpoint(URI.create("http://localhost")).declaring(TestJAXBResponseParser.class) + .javaMethod(method).args(new Object[] {}).build(); + Function transformer = processor.createResponseParser(method, request); + assertEquals(transformer.getClass(), ParseXMLWithJAXB.class); + } + @SuppressWarnings("unchecked") @Test public void testJAXBResponseParserWithAnnotation() throws SecurityException, NoSuchMethodException, IOException { - Method method = TestJAXBResponseParser.class.getMethod("jaxbGetWithAnnotation"); - HttpRequest request = factory(TestJAXBResponseParser.class).createRequest(method); + Method method = TestJAXBResponseParser.class.getMethod("jaxbGetWithAnnotation"); + HttpRequest request = factory(TestJAXBResponseParser.class).createRequest(method); - assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); - // now test that it works! + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + // now test that it works! + + Function parser = (Function) RestAnnotationProcessor + .createResponseParser(parserFactory, injector, method, request); + + StringBuffer payload = new StringBuffer(XMLParser.DEFAULT_XML_HEADER); + payload.append("Hello World"); + TestJAXBDomain domain = parser.apply(new HttpResponse(200, "ok", newStringPayload(payload.toString()))); + assertEquals(domain.getElem(), "Hello World"); + } - Function parser = (Function) RestAnnotationProcessor - .createResponseParser(parserFactory, injector, method, request); - - StringBuffer payload = new StringBuffer(XMLParser.DEFAULT_XML_HEADER); - payload.append("Hello World"); - TestJAXBDomain domain = parser.apply(new HttpResponse(200, "ok", newStringPayload(payload.toString()))); - assertEquals(domain.getElem(), "Hello World"); - } - @SuppressWarnings("unchecked") @Test public void testJAXBResponseParserWithAcceptHeader() throws SecurityException, NoSuchMethodException, IOException { - Method method = TestJAXBResponseParser.class.getMethod("jaxbGetWithAcceptHeader"); - HttpRequest request = factory(TestJAXBResponseParser.class).createRequest(method); + Method method = TestJAXBResponseParser.class.getMethod("jaxbGetWithAcceptHeader"); + HttpRequest request = factory(TestJAXBResponseParser.class).createRequest(method); - assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); - // now test that it works! + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + // now test that it works! - Function parser = (Function) RestAnnotationProcessor - .createResponseParser(parserFactory, injector, method, request); - - StringBuffer payload = new StringBuffer(XMLParser.DEFAULT_XML_HEADER); - payload.append("Hello World"); - TestJAXBDomain domain = parser.apply(new HttpResponse(200, "ok", newStringPayload(payload.toString()))); - assertEquals(domain.getElem(), "Hello World"); - } + Function parser = (Function) RestAnnotationProcessor + .createResponseParser(parserFactory, injector, method, request); + StringBuffer payload = new StringBuffer(XMLParser.DEFAULT_XML_HEADER); + payload.append("Hello World"); + TestJAXBDomain domain = parser.apply(new HttpResponse(200, "ok", newStringPayload(payload.toString()))); + assertEquals(domain.getElem(), "Hello World"); + } DateService dateService = new SimpleDateFormatDateService(); @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() { + null, String.class, Integer.class, + ImmutableSet. of(new MockModule(), new NullLoggingModule(), new AbstractModule() { - @Override - protected void configure() { - bind(new TypeLiteral>() { - }).toInstance(ImmutableSet.of("foo")); - bind(new TypeLiteral>() { - }).annotatedWith(Names.named("bar")).toInstance(ImmutableSet.of("bar")); - bind(URI.class).annotatedWith(Localhost2.class).toInstance( - URI.create("http://localhost:1111")); - } + @Override + protected void configure() { + bind(new TypeLiteral>() { + }).toInstance(ImmutableSet.of("foo")); + bind(new TypeLiteral>() { + }).annotatedWith(Names.named("bar")).toInstance(ImmutableSet.of("bar")); + bind(URI.class).annotatedWith(Localhost2.class).toInstance(URI.create("http://localhost:1111")); + } - @SuppressWarnings("unused") - @Provides - @Named("exception") - Set exception() { - throw new AuthorizationException(); - } + @SuppressWarnings("unused") + @Provides + @Named("exception") + Set exception() { + throw new AuthorizationException(); + } - })); + })); injector = createContextBuilder(contextSpec).buildInjector(); parserFactory = injector.getInstance(ParseSax.Factory.class); From d300681bcc42fe86e0827260ef1e49507d5abdd5 Mon Sep 17 00:00:00 2001 From: Adrian Cole Date: Sat, 29 Oct 2011 11:00:02 +0200 Subject: [PATCH 12/16] formatting in virtualbox --- .../virtualbox/VirtualBoxContextBuilder.java | 6 +- .../VirtualBoxPropertiesBuilder.java | 40 +-- .../compute/LoadMachineFromVirtualBox.java | 60 ++-- .../VirtualBoxComputeServiceAdapter.java | 41 +-- ...VirtualBoxComputeServiceContextModule.java | 58 ++-- .../config/VirtualBoxConstants.java | 8 +- .../jclouds/virtualbox/domain/ErrorCode.java | 43 +-- .../virtualbox/domain/ExecutionType.java | 7 +- .../jclouds/virtualbox/domain/YamlImage.java | 145 +++++----- .../AddIDEControllerIfNotExists.java | 1 + .../functions/ApplyMemoryToMachine.java | 7 +- .../AttachDistroMediumToMachine.java | 5 +- ...chMediumToMachineIfNotAlreadyAttached.java | 13 +- .../AttachNATRedirectRuleToMachine.java | 13 +- ...isterMachineFromIsoIfNotAlreadyExists.java | 6 +- .../CreateMediumIfNotAlreadyExists.java | 25 +- .../functions/IMachineToHardware.java | 1 - .../virtualbox/functions/IMachineToImage.java | 3 +- .../functions/IMachineToIpAddress.java | 28 +- .../functions/IMachineToNodeMetadata.java | 31 ++- .../virtualbox/functions/IsoToIMachine.java | 89 +++--- .../LaunchMachineIfNotAlreadyRunning.java | 55 ++-- .../functions/admin/FileDownloadFromURI.java | 4 +- .../functions/admin/ImageFromYamlStream.java | 81 +++--- .../admin/StartJettyIfNotAlreadyRunning.java | 100 +++---- .../admin/StartVBoxIfNotAlreadyRunning.java | 19 +- .../settings/KeyboardScancodes.java | 256 +++++++++--------- ...rtualBoxComputeServiceAdapterLiveTest.java | 40 +-- .../VirtualBoxComputeServiceAdapterTest.java | 34 +-- .../compute/VirtualBoxExperimentLiveTest.java | 2 +- .../VirtualBoxTemplateBuilderLiveTest.java | 61 ++--- .../SetupVirtualBoxForLiveTest.java | 38 ++- .../virtualbox/experiment/TestUtils.java | 103 +++---- .../functions/ApplyMemoryToMachineTest.java | 14 +- .../AttachDistroMediumToMachineTest.java | 16 +- ...diumToMachineIfNotAlreadyAttachedTest.java | 34 ++- .../AttachNATRedirectRuleToMachineTest.java | 22 +- ...rMachineFromIsoIfNotAlreadyExistsTest.java | 23 +- .../CreateMediumIfNotAlreadyExistsTest.java | 18 +- .../functions/IMachineToNodeMetadataTest.java | 1 - .../functions/IsoToIMachineLiveTest.java | 35 +-- .../LaunchMachineIfNotAlreadyRunningTest.java | 17 +- .../admin/ImageFromYamlStreamTest.java | 36 +-- ...StartJettyIfNotAlreadyRunningLiveTest.java | 10 +- .../StartVBoxIfNotAlreadyRunningLiveTest.java | 24 +- 45 files changed, 853 insertions(+), 820 deletions(-) diff --git a/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/VirtualBoxContextBuilder.java b/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/VirtualBoxContextBuilder.java index f9d48ddfbf..5a1ce5638d 100644 --- a/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/VirtualBoxContextBuilder.java +++ b/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/VirtualBoxContextBuilder.java @@ -30,11 +30,11 @@ import com.google.inject.Module; /** * Creates compute service context for VirtualBox - * + * * @author Mattias Holmqvist, Andrea Turli */ public class VirtualBoxContextBuilder extends StandaloneComputeServiceContextBuilder { - + public VirtualBoxContextBuilder(Properties properties) { super(VirtualBoxManager.class, properties); } @@ -43,5 +43,5 @@ public class VirtualBoxContextBuilder extends StandaloneComputeServiceContextBui protected void addContextModule(List modules) { modules.add(new VirtualBoxComputeServiceContextModule()); } - + } diff --git a/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/VirtualBoxPropertiesBuilder.java b/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/VirtualBoxPropertiesBuilder.java index 0f8f03111f..91877c3d5c 100644 --- a/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/VirtualBoxPropertiesBuilder.java +++ b/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/VirtualBoxPropertiesBuilder.java @@ -19,17 +19,19 @@ package org.jclouds.virtualbox; -import org.jclouds.PropertiesBuilder; -import org.jclouds.virtualbox.config.VirtualBoxConstants; +import static org.jclouds.Constants.PROPERTY_CREDENTIAL; +import static org.jclouds.Constants.PROPERTY_ENDPOINT; +import static org.jclouds.Constants.PROPERTY_IDENTITY; import java.io.File; import java.util.Properties; -import static org.jclouds.Constants.*; +import org.jclouds.PropertiesBuilder; +import org.jclouds.virtualbox.config.VirtualBoxConstants; /** * Builds properties for VirtualBox integration. - * + * * @author Mattias Holmqvist */ public class VirtualBoxPropertiesBuilder extends PropertiesBuilder { @@ -51,24 +53,24 @@ public class VirtualBoxPropertiesBuilder extends PropertiesBuilder { properties.put(VirtualBoxConstants.VIRTUALBOX_PRESEED_URL, "http://dl.dropbox.com/u/693111/preseed.cfg"); properties.put(VirtualBoxConstants.VIRTUALBOX_SNAPSHOT_DESCRIPTION, "jclouds-virtualbox-snaphot"); properties.put(VirtualBoxConstants.VIRTUALBOX_HOSTNAME, "jclouds-virtualbox-kickstart-admin"); - properties.put(VirtualBoxConstants.VIRTUALBOX_INSTALLATION_KEY_SEQUENCE, " " - + "/install/vmlinuz noapic preseed/url=http://10.0.2.2:8080/src/test/resources/preseed.cfg " - + "debian-installer=en_US auto locale=en_US kbd-chooser/method=us " - + "hostname=" - + properties.get(VirtualBoxConstants.VIRTUALBOX_HOSTNAME) - + " " - + "fb=false debconf/frontend=noninteractive " - + "keyboard-configuration/layout=USA keyboard-configuration/variant=USA console-setup/ask_detect=false " - + "initrd=/install/initrd.gz -- "); + properties + .put(VirtualBoxConstants.VIRTUALBOX_INSTALLATION_KEY_SEQUENCE, + " " + + "/install/vmlinuz noapic preseed/url=http://10.0.2.2:8080/src/test/resources/preseed.cfg " + + "debian-installer=en_US auto locale=en_US kbd-chooser/method=us " + + "hostname=" + + properties.get(VirtualBoxConstants.VIRTUALBOX_HOSTNAME) + + " " + + "fb=false debconf/frontend=noninteractive " + + "keyboard-configuration/layout=USA keyboard-configuration/variant=USA console-setup/ask_detect=false " + + "initrd=/install/initrd.gz -- "); + + properties.put(VirtualBoxConstants.VIRTUALBOX_WORKINGDIR, System.getProperty("user.home") + File.separator + + System.getProperty("test.virtualbox.workingDir", "jclouds-virtualbox-test")); - properties.put(VirtualBoxConstants.VIRTUALBOX_WORKINGDIR, System.getProperty("user.home") - + File.separator - + System.getProperty("test.virtualbox.workingDir", - "jclouds-virtualbox-test")); - // TODO: Add more properties and use the wired properties from test code. properties.put(VirtualBoxConstants.VIRTUALBOX_DISTRO_ISO_NAME, "ubuntu-11.04-server-i386.iso"); - + properties.put(VirtualBoxConstants.VIRTUALBOX_JETTY_PORT, "8080"); return properties; diff --git a/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/compute/LoadMachineFromVirtualBox.java b/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/compute/LoadMachineFromVirtualBox.java index 2300050b95..b84b3550ea 100644 --- a/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/compute/LoadMachineFromVirtualBox.java +++ b/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/compute/LoadMachineFromVirtualBox.java @@ -19,23 +19,28 @@ package org.jclouds.virtualbox.compute; -import com.google.common.base.Function; -import com.google.common.cache.CacheLoader; +import static org.jclouds.virtualbox.config.VirtualBoxConstants.VIRTUALBOX_MACHINE_CREDENTIAL; +import static org.jclouds.virtualbox.config.VirtualBoxConstants.VIRTUALBOX_MACHINE_GROUP; +import static org.jclouds.virtualbox.config.VirtualBoxConstants.VIRTUALBOX_MACHINE_LOCATION; +import static org.jclouds.virtualbox.config.VirtualBoxConstants.VIRTUALBOX_MACHINE_USERNAME; + +import java.net.URI; +import java.net.URISyntaxException; + +import javax.inject.Inject; + import org.jclouds.byon.Node; import org.jclouds.compute.domain.OsFamily; import org.virtualbox_4_1.IGuestOSType; import org.virtualbox_4_1.IMachine; import org.virtualbox_4_1.VirtualBoxManager; -import javax.inject.Inject; -import java.net.URI; -import java.net.URISyntaxException; - -import static org.jclouds.virtualbox.config.VirtualBoxConstants.*; +import com.google.common.base.Function; +import com.google.common.cache.CacheLoader; /** * Loads a node from a VirtualBox IMachine - * + * * @author Mattias Holmqvist */ public class LoadMachineFromVirtualBox extends CacheLoader { @@ -53,16 +58,10 @@ public class LoadMachineFromVirtualBox extends CacheLoader { public Node load(final String id) throws Exception { if (id.equals("host")) { - final Node hostNode = Node.builder().id("host") - .name("host installing virtualbox") - .hostname("localhost") - .osFamily(OsFamily.LINUX.toString()) - .osDescription(System.getProperty("os.name")) - .osVersion(System.getProperty("os.version")) - .group("ssh") - .username(System.getProperty("user.name")) - .credentialUrl(privateKeyFile()) - .build(); + final Node hostNode = Node.builder().id("host").name("host installing virtualbox").hostname("localhost") + .osFamily(OsFamily.LINUX.toString()).osDescription(System.getProperty("os.name")) + .osVersion(System.getProperty("os.version")).group("ssh").username(System.getProperty("user.name")) + .credentialUrl(privateKeyFile()).build(); return hostNode; } @@ -71,23 +70,14 @@ public class LoadMachineFromVirtualBox extends CacheLoader { final String osTypeId = machine.getOSTypeId(); final IGuestOSType guestOSType = manager.getVBox().getGuestOSType(osTypeId); - final Node node = Node.builder() - .id(machine.getId()) - .name(machine.getName()) - .description(machine.getDescription()) - .loginPort(22) - .group(System.getProperty(VIRTUALBOX_MACHINE_GROUP)) - .username(System.getProperty(VIRTUALBOX_MACHINE_USERNAME)) - .credential(System.getProperty(VIRTUALBOX_MACHINE_CREDENTIAL)) - .sudoPassword(System.getProperty(VIRTUALBOX_MACHINE_CREDENTIAL)) - .locationId(System.getProperty(VIRTUALBOX_MACHINE_LOCATION)) - .os64Bit(guestOSType.getIs64Bit()) - .osArch(guestOSType.getDescription()) - .osFamily(guestOSType.getFamilyDescription()) - .osVersion(guestOSType.getId()) - .osDescription(guestOSType.getDescription()) - .hostname(ipAddress) - .build(); + final Node node = Node.builder().id(machine.getId()).name(machine.getName()) + .description(machine.getDescription()).loginPort(22).group(System.getProperty(VIRTUALBOX_MACHINE_GROUP)) + .username(System.getProperty(VIRTUALBOX_MACHINE_USERNAME)) + .credential(System.getProperty(VIRTUALBOX_MACHINE_CREDENTIAL)) + .sudoPassword(System.getProperty(VIRTUALBOX_MACHINE_CREDENTIAL)) + .locationId(System.getProperty(VIRTUALBOX_MACHINE_LOCATION)).os64Bit(guestOSType.getIs64Bit()) + .osArch(guestOSType.getDescription()).osFamily(guestOSType.getFamilyDescription()) + .osVersion(guestOSType.getId()).osDescription(guestOSType.getDescription()).hostname(ipAddress).build(); return node; diff --git a/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/compute/VirtualBoxComputeServiceAdapter.java b/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/compute/VirtualBoxComputeServiceAdapter.java index e43d65ada7..7ba6c7ae95 100644 --- a/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/compute/VirtualBoxComputeServiceAdapter.java +++ b/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/compute/VirtualBoxComputeServiceAdapter.java @@ -19,10 +19,16 @@ package org.jclouds.virtualbox.compute; -import com.google.common.base.Function; -import com.google.common.base.Predicate; -import com.google.common.base.Throwables; -import com.google.inject.Singleton; +import static com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.collect.Iterables.filter; +import static com.google.common.collect.Iterables.transform; +import static org.jclouds.virtualbox.config.VirtualBoxConstants.VIRTUALBOX_IMAGE_PREFIX; + +import java.util.Collections; +import java.util.Map; + +import javax.inject.Inject; + import org.jclouds.compute.ComputeServiceAdapter; import org.jclouds.compute.domain.Image; import org.jclouds.compute.domain.Template; @@ -30,15 +36,17 @@ import org.jclouds.domain.Credentials; import org.jclouds.domain.Location; import org.jclouds.javax.annotation.Nullable; import org.jclouds.location.suppliers.JustProvider; -import org.virtualbox_4_1.*; +import org.virtualbox_4_1.CleanupMode; +import org.virtualbox_4_1.IMachine; +import org.virtualbox_4_1.IProgress; +import org.virtualbox_4_1.ISession; +import org.virtualbox_4_1.SessionState; +import org.virtualbox_4_1.VirtualBoxManager; -import javax.inject.Inject; -import java.util.*; - -import static com.google.common.base.Preconditions.checkNotNull; -import static com.google.common.collect.Iterables.filter; -import static com.google.common.collect.Iterables.transform; -import static org.jclouds.virtualbox.config.VirtualBoxConstants.VIRTUALBOX_IMAGE_PREFIX; +import com.google.common.base.Function; +import com.google.common.base.Predicate; +import com.google.common.base.Throwables; +import com.google.inject.Singleton; /** * Defines the connection between the @@ -55,7 +63,8 @@ public class VirtualBoxComputeServiceAdapter implements ComputeServiceAdapter iMachineToImage; @Inject - public VirtualBoxComputeServiceAdapter(VirtualBoxManager manager, JustProvider justProvider, Function iMachineToImage) { + public VirtualBoxComputeServiceAdapter(VirtualBoxManager manager, JustProvider justProvider, + Function iMachineToImage) { this.iMachineToImage = iMachineToImage; this.manager = checkNotNull(manager, "manager"); this.justProvider = checkNotNull(justProvider, "justProvider"); @@ -77,8 +86,8 @@ public class VirtualBoxComputeServiceAdapter implements ComputeServiceAdapter listImages() { + @Override + public Iterable listImages() { final Predicate imagePredicate = new Predicate() { @Override public boolean apply(@Nullable IMachine iMachine) { @@ -87,7 +96,7 @@ public class VirtualBoxComputeServiceAdapter implements ComputeServiceAdapter imageMachines = filter(manager.getVBox().getMachines(), imagePredicate); return transform(imageMachines, iMachineToImage); - } + } @SuppressWarnings("unchecked") @Override diff --git a/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/config/VirtualBoxComputeServiceContextModule.java b/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/config/VirtualBoxComputeServiceContextModule.java index 8cdc72a22a..6f3274f22e 100644 --- a/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/config/VirtualBoxComputeServiceContextModule.java +++ b/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/config/VirtualBoxComputeServiceContextModule.java @@ -57,20 +57,21 @@ import com.google.inject.TypeLiteral; /** * @author Mattias Holmqvist, Andrea Turli */ -public class VirtualBoxComputeServiceContextModule extends ComputeServiceAdapterContextModule { +public class VirtualBoxComputeServiceContextModule extends + ComputeServiceAdapterContextModule { public VirtualBoxComputeServiceContextModule() { super(VirtualBoxManager.class, VirtualBoxManager.class); } - + @Provides @Singleton - protected VirtualBoxManager createInstance(@Provider URI endpoint, @Named(Constants.PROPERTY_IDENTITY) String identity, - @Named(Constants.PROPERTY_CREDENTIAL) String credential) { - - VirtualBoxManager manager = VirtualBoxManager.createInstance(""); - manager.connect(endpoint.toASCIIString(), identity, credential); - return manager; + protected VirtualBoxManager createInstance(@Provider URI endpoint, + @Named(Constants.PROPERTY_IDENTITY) String identity, @Named(Constants.PROPERTY_CREDENTIAL) String credential) { + + VirtualBoxManager manager = VirtualBoxManager.createInstance(""); + manager.connect(endpoint.toASCIIString(), identity, credential); + return manager; } @SuppressWarnings({ "unchecked", "rawtypes" }) @@ -100,31 +101,24 @@ public class VirtualBoxComputeServiceContextModule extends ComputeServiceAdapter @VisibleForTesting public static final Map machineToNodeState = ImmutableMap - .builder() - .put(MachineState.Running, NodeState.RUNNING) - .put(MachineState.PoweredOff, NodeState.SUSPENDED) - .put(MachineState.DeletingSnapshot, NodeState.PENDING) - .put(MachineState.DeletingSnapshotOnline, NodeState.PENDING) - .put(MachineState.DeletingSnapshotPaused, NodeState.PENDING) - .put(MachineState.FaultTolerantSyncing, NodeState.PENDING) - .put(MachineState.LiveSnapshotting, NodeState.PENDING) - .put(MachineState.SettingUp, NodeState.PENDING) - .put(MachineState.Starting, NodeState.PENDING) - .put(MachineState.Stopping, NodeState.PENDING) - .put(MachineState.Restoring, NodeState.PENDING) - // TODO What to map these states to? - .put(MachineState.FirstOnline, NodeState.PENDING) - .put(MachineState.FirstTransient, NodeState.PENDING) - .put(MachineState.LastOnline, NodeState.PENDING) - .put(MachineState.LastTransient, NodeState.PENDING) - .put(MachineState.Teleported, NodeState.PENDING) - .put(MachineState.TeleportingIn, NodeState.PENDING) - .put(MachineState.TeleportingPausedVM, NodeState.PENDING) + . builder().put(MachineState.Running, NodeState.RUNNING) + .put(MachineState.PoweredOff, NodeState.SUSPENDED).put(MachineState.DeletingSnapshot, NodeState.PENDING) + .put(MachineState.DeletingSnapshotOnline, NodeState.PENDING) + .put(MachineState.DeletingSnapshotPaused, NodeState.PENDING) + .put(MachineState.FaultTolerantSyncing, NodeState.PENDING) + .put(MachineState.LiveSnapshotting, NodeState.PENDING) + .put(MachineState.SettingUp, NodeState.PENDING) + .put(MachineState.Starting, NodeState.PENDING) + .put(MachineState.Stopping, NodeState.PENDING) + .put(MachineState.Restoring, NodeState.PENDING) + // TODO What to map these states to? + .put(MachineState.FirstOnline, NodeState.PENDING).put(MachineState.FirstTransient, NodeState.PENDING) + .put(MachineState.LastOnline, NodeState.PENDING).put(MachineState.LastTransient, NodeState.PENDING) + .put(MachineState.Teleported, NodeState.PENDING).put(MachineState.TeleportingIn, NodeState.PENDING) + .put(MachineState.TeleportingPausedVM, NodeState.PENDING) + .put(MachineState.Aborted, NodeState.ERROR).put(MachineState.Stuck, NodeState.ERROR) - .put(MachineState.Aborted, NodeState.ERROR) - .put(MachineState.Stuck, NodeState.ERROR) - - .put(MachineState.Null, NodeState.UNRECOGNIZED).build(); + .put(MachineState.Null, NodeState.UNRECOGNIZED).build(); } diff --git a/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/config/VirtualBoxConstants.java b/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/config/VirtualBoxConstants.java index f83bf795fb..804718e6ab 100644 --- a/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/config/VirtualBoxConstants.java +++ b/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/config/VirtualBoxConstants.java @@ -21,7 +21,7 @@ package org.jclouds.virtualbox.config; /** * Configuration properties used for interacting with VirtualBox instances. - * + * * @author Mattias Holmqvist, Andrea Turli * */ @@ -34,11 +34,11 @@ public interface VirtualBoxConstants { public static final String VIRTUALBOX_SNAPSHOT_DESCRIPTION = "jclouds.virtualbox.snapshotDescription"; public static final String VIRTUALBOX_INSTALLATION_KEY_SEQUENCE = "jclouds.virtualbox.installationkeysequence"; - + public static final String VIRTUALBOX_HOSTNAME = "jclouds.virtualbox.hostname"; - + public static final String VIRTUALBOX_WORKINGDIR = "jclouds.virtualbox.workingdir"; - + public static final String VIRTUALBOX_ISOFILE = "jclouds.virtualbox.isofile"; public static final String VIRTUALBOX_MACHINE_GROUP = "jclouds.virtualbox.machinegroup"; diff --git a/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/domain/ErrorCode.java b/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/domain/ErrorCode.java index 74801270d5..96255ac145 100644 --- a/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/domain/ErrorCode.java +++ b/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/domain/ErrorCode.java @@ -1,4 +1,4 @@ -/* +/** * Licensed to jclouds, Inc. (jclouds) under one or more * contributor license agreements. See the NOTICE file * distributed with this work for additional information @@ -19,17 +19,18 @@ package org.jclouds.virtualbox.domain; -import org.virtualbox_4_1.VBoxException; -import org.virtualbox_4_1.jaxws.RuntimeFaultMsg; - import java.util.HashMap; import java.util.Map; +import org.virtualbox_4_1.VBoxException; +import org.virtualbox_4_1.jaxws.RuntimeFaultMsg; + /** * Maps the error codes in the Virtual Box Java API into enum values. *

*

* To get the error code from a VBoxException, use: + * *

  * try {
  *    ...
@@ -41,32 +42,17 @@ import java.util.Map;
  *    ErrorCode errorCode = ErrorCode.valueOf(faultCode);
  * }
  * 
- * + * * @author Mattias Holmqvist */ public enum ErrorCode { - VBOX_E_OBJECT_NOT_FOUND(2159738881L), - VBOX_E_INVALID_VM_STATE(2159738882L), - VBOX_E_VM_ERROR(2159738883L), - VBOX_E_FILE_ERROR(2159738884L), - VBOX_E_IPRT_ERROR(2159738885L), - VBOX_E_PDM_ERROR(2159738886L), - VBOX_E_INVALID_OBJECT_STATE(2159738887L), - VBOX_E_HOST_ERROR(2159738888L), - VBOX_E_NOT_SUPPORTED(2159738889L), - VBOX_E_XML_ERROR(2159738890L), - VBOX_E_INVALID_SESSION_STATE(2159738891L), - VBOX_E_OBJECT_IN_USE(2159738892L), - VBOX_E_ACCESSDENIED(2147942405L), - VBOX_E_POINTER(2147500035L), - VBOX_E_FAIL(2147500037L), - VBOX_E_NOTIMPL(2147500033L), - VBOX_E_OUTOFMEMORY(2147942414L), - VBOX_E_INVALIDARG(2147942487L), - VBOX_E_UNEXPECTED(2147549183L), - VBOX_E_UNKNOWN_ERROR_CODE(-1L), - VBOX_E_ERROR_CODE_UNAVAILABLE(-2L); + VBOX_E_OBJECT_NOT_FOUND(2159738881L), VBOX_E_INVALID_VM_STATE(2159738882L), VBOX_E_VM_ERROR(2159738883L), VBOX_E_FILE_ERROR( + 2159738884L), VBOX_E_IPRT_ERROR(2159738885L), VBOX_E_PDM_ERROR(2159738886L), VBOX_E_INVALID_OBJECT_STATE( + 2159738887L), VBOX_E_HOST_ERROR(2159738888L), VBOX_E_NOT_SUPPORTED(2159738889L), VBOX_E_XML_ERROR(2159738890L), VBOX_E_INVALID_SESSION_STATE( + 2159738891L), VBOX_E_OBJECT_IN_USE(2159738892L), VBOX_E_ACCESSDENIED(2147942405L), VBOX_E_POINTER(2147500035L), VBOX_E_FAIL( + 2147500037L), VBOX_E_NOTIMPL(2147500033L), VBOX_E_OUTOFMEMORY(2147942414L), VBOX_E_INVALIDARG(2147942487L), VBOX_E_UNEXPECTED( + 2147549183L), VBOX_E_UNKNOWN_ERROR_CODE(-1L), VBOX_E_ERROR_CODE_UNAVAILABLE(-2L); private long code; @@ -84,8 +70,9 @@ public enum ErrorCode { /** * Returns an ErrorCode from the fault code given by the VirtualBox API. - * - * @param vboxException the exception to get the error code from. + * + * @param vboxException + * the exception to get the error code from. * @return an ErrorCode representing the given fault code. */ public static ErrorCode valueOf(VBoxException vboxException) { diff --git a/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/domain/ExecutionType.java b/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/domain/ExecutionType.java index fa986351ab..9d97f15fa1 100644 --- a/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/domain/ExecutionType.java +++ b/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/domain/ExecutionType.java @@ -1,4 +1,4 @@ -/* +/** * Licensed to jclouds, Inc. (jclouds) under one or more * contributor license agreements. See the NOTICE file * distributed with this work for additional information @@ -21,10 +21,7 @@ package org.jclouds.virtualbox.domain; public enum ExecutionType { - GUI("gui"), - HEADLESS("headless"), - SDL("sdl"), - EMERGENCYSTOP("emergencystop"); + GUI("gui"), HEADLESS("headless"), SDL("sdl"), EMERGENCYSTOP("emergencystop"); private final String type; diff --git a/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/domain/YamlImage.java b/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/domain/YamlImage.java index fb4c472c76..61a40d828c 100644 --- a/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/domain/YamlImage.java +++ b/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/domain/YamlImage.java @@ -41,73 +41,73 @@ import com.google.common.collect.Maps; * Serializes to the following * *
-id: myTestId
-      name: ubuntu-11.04-server-i386
-      description: ubuntu 11.04 server (i386)
-      os_arch: x86
-      os_family: linux
-      os_description: ubuntu
-      os_version: 11.04
-      iso: http://releases.ubuntu.com/11.04/ubuntu-11.04-server-i386.iso
-      keystroke_sequence: |
-                 
-                /install/vmlinuz noapic preseed/url=http://10.0.2.2:8080/src/test/resources/preseed.cfg 
-                debian-installer=en_US auto locale=en_US kbd-chooser/method=us 
-                hostname=vmName 
-                fb=false debconf/frontend=noninteractive 
-                keyboard-configuration/layout=USA keyboard-configuration/variant=USA console-setup/ask_detect=false 
-                initrd=/install/initrd.gz -- 
-      preseed_cfg: |                
-                      ## Options to set on the command line
-                      d-i debian-installer/locale string en_US.utf8
-                      d-i console-setup/ask_detect boolean false
-                      d-i console-setup/layout string USA
-                      d-i netcfg/get_hostname string unassigned-hostname
-                      d-i netcfg/get_domain string unassigned-domain
-                      # Continue without a default route
-                      # Not working , specify a dummy in the DHCP
-                      d-i time/zone string UTC
-                      d-i clock-setup/utc-auto boolean true
-                      d-i clock-setup/utc boolean true
-                      d-i kbd-chooser/method	select	American English
-                      d-i netcfg/wireless_wep string
-                      d-i base-installer/kernel/override-image string linux-server
-                      # Choices: Dialog, Readline, Gnome, Kde, Editor, Noninteractive
-                      d-i debconf debconf/frontend select Noninteractive
-                      d-i pkgsel/install-language-support boolean false
-                      tasksel tasksel/first multiselect standard, ubuntu-server
-                      d-i partman-auto/method string lvm
-                      d-i partman-lvm/confirm boolean true
-                      d-i partman-lvm/device_remove_lvm boolean true
-                      d-i partman-auto/choose_recipe select atomic
-                      d-i partman/confirm_write_new_label boolean true
-                      d-i partman/confirm_nooverwrite boolean true
-                      d-i partman/choose_partition select finish
-                      d-i partman/confirm boolean true
-                      # Write the changes to disks and configure LVM?
-                      d-i partman-lvm/confirm boolean true
-                      d-i partman-lvm/confirm_nooverwrite boolean true
-                      d-i partman-auto-lvm/guided_size string max
-                      ## Default user, we can get away with a recipe to change this
-                      d-i passwd/user-fullname string toor
-                      d-i passwd/username string toor
-                      d-i passwd/user-password password password
-                      d-i passwd/user-password-again password password
-                      d-i user-setup/encrypt-home boolean false
-                      d-i user-setup/allow-password-weak boolean true
-                      # Individual additional packages to install
-                      d-i pkgsel/include string openssh-server ntp
-                      # Whether to upgrade packages after debootstrap.
-                      # Allowed values: none, safe-upgrade, full-upgrade
-                      d-i pkgsel/upgrade select full-upgrade
-                      d-i grub-installer/only_debian boolean true
-                      d-i grub-installer/with_other_os boolean true
-                      d-i finish-install/reboot_in_progress note
-                      #For the update
-                      d-i pkgsel/update-policy select none
-                      # debconf-get-selections --install
-                      #Use mirror
-                      choose-mirror-bin mirror/http/proxy string
+ * id: myTestId
+ *       name: ubuntu-11.04-server-i386
+ *       description: ubuntu 11.04 server (i386)
+ *       os_arch: x86
+ *       os_family: linux
+ *       os_description: ubuntu
+ *       os_version: 11.04
+ *       iso: http://releases.ubuntu.com/11.04/ubuntu-11.04-server-i386.iso
+ *       keystroke_sequence: |
+ *                  
+ *                 /install/vmlinuz noapic preseed/url=http://10.0.2.2:8080/src/test/resources/preseed.cfg 
+ *                 debian-installer=en_US auto locale=en_US kbd-chooser/method=us 
+ *                 hostname=vmName 
+ *                 fb=false debconf/frontend=noninteractive 
+ *                 keyboard-configuration/layout=USA keyboard-configuration/variant=USA console-setup/ask_detect=false 
+ *                 initrd=/install/initrd.gz -- 
+ *       preseed_cfg: |                
+ *                       ## Options to set on the command line
+ *                       d-i debian-installer/locale string en_US.utf8
+ *                       d-i console-setup/ask_detect boolean false
+ *                       d-i console-setup/layout string USA
+ *                       d-i netcfg/get_hostname string unassigned-hostname
+ *                       d-i netcfg/get_domain string unassigned-domain
+ *                       # Continue without a default route
+ *                       # Not working , specify a dummy in the DHCP
+ *                       d-i time/zone string UTC
+ *                       d-i clock-setup/utc-auto boolean true
+ *                       d-i clock-setup/utc boolean true
+ *                       d-i kbd-chooser/method	select	American English
+ *                       d-i netcfg/wireless_wep string
+ *                       d-i base-installer/kernel/override-image string linux-server
+ *                       # Choices: Dialog, Readline, Gnome, Kde, Editor, Noninteractive
+ *                       d-i debconf debconf/frontend select Noninteractive
+ *                       d-i pkgsel/install-language-support boolean false
+ *                       tasksel tasksel/first multiselect standard, ubuntu-server
+ *                       d-i partman-auto/method string lvm
+ *                       d-i partman-lvm/confirm boolean true
+ *                       d-i partman-lvm/device_remove_lvm boolean true
+ *                       d-i partman-auto/choose_recipe select atomic
+ *                       d-i partman/confirm_write_new_label boolean true
+ *                       d-i partman/confirm_nooverwrite boolean true
+ *                       d-i partman/choose_partition select finish
+ *                       d-i partman/confirm boolean true
+ *                       # Write the changes to disks and configure LVM?
+ *                       d-i partman-lvm/confirm boolean true
+ *                       d-i partman-lvm/confirm_nooverwrite boolean true
+ *                       d-i partman-auto-lvm/guided_size string max
+ *                       ## Default user, we can get away with a recipe to change this
+ *                       d-i passwd/user-fullname string toor
+ *                       d-i passwd/username string toor
+ *                       d-i passwd/user-password password password
+ *                       d-i passwd/user-password-again password password
+ *                       d-i user-setup/encrypt-home boolean false
+ *                       d-i user-setup/allow-password-weak boolean true
+ *                       # Individual additional packages to install
+ *                       d-i pkgsel/include string openssh-server ntp
+ *                       # Whether to upgrade packages after debootstrap.
+ *                       # Allowed values: none, safe-upgrade, full-upgrade
+ *                       d-i pkgsel/upgrade select full-upgrade
+ *                       d-i grub-installer/only_debian boolean true
+ *                       d-i grub-installer/with_other_os boolean true
+ *                       d-i finish-install/reboot_in_progress note
+ *                       #For the update
+ *                       d-i pkgsel/update-policy select none
+ *                       # debconf-get-selections --install
+ *                       #Use mirror
+ *                       choose-mirror-bin mirror/http/proxy string
  * 
* * @author Kelvin Kakugawa @@ -143,14 +143,11 @@ public class YamlImage { return null; OsFamily family = parseOsFamilyOrUnrecognized(arg0.os_family); - OperatingSystem operatingSystem = OperatingSystem.builder() - .description(arg0.os_description) - .family(family) - .version(arg0.os_version) - .is64Bit(arg0.os_64bit) - .build(); + OperatingSystem operatingSystem = OperatingSystem.builder().description(arg0.os_description).family(family) + .version(arg0.os_version).is64Bit(arg0.os_64bit).build(); - return new ImageBuilder().id(arg0.id).name(arg0.name).description(arg0.description).operatingSystem(operatingSystem).build(); + return new ImageBuilder().id(arg0.id).name(arg0.name).description(arg0.description) + .operatingSystem(operatingSystem).build(); } }; diff --git a/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/AddIDEControllerIfNotExists.java b/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/AddIDEControllerIfNotExists.java index 69628e8d05..b3c52b1cc4 100644 --- a/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/AddIDEControllerIfNotExists.java +++ b/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/AddIDEControllerIfNotExists.java @@ -16,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ + package org.jclouds.virtualbox.functions; import static com.google.common.base.Preconditions.checkNotNull; diff --git a/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/ApplyMemoryToMachine.java b/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/ApplyMemoryToMachine.java index dc60249a94..c40fedc811 100644 --- a/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/ApplyMemoryToMachine.java +++ b/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/ApplyMemoryToMachine.java @@ -1,4 +1,4 @@ -/* +/** * Licensed to jclouds, Inc. (jclouds) under one or more * contributor license agreements. See the NOTICE file * distributed with this work for additional information @@ -19,10 +19,11 @@ package org.jclouds.virtualbox.functions; -import com.google.common.base.Function; +import javax.annotation.Nullable; + import org.virtualbox_4_1.IMachine; -import javax.annotation.Nullable; +import com.google.common.base.Function; /** * @author Mattias Holmqvist diff --git a/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/AttachDistroMediumToMachine.java b/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/AttachDistroMediumToMachine.java index 253b2c5fbf..e4325e70c2 100644 --- a/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/AttachDistroMediumToMachine.java +++ b/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/AttachDistroMediumToMachine.java @@ -19,13 +19,14 @@ package org.jclouds.virtualbox.functions; -import com.google.common.base.Function; +import javax.annotation.Nullable; + import org.virtualbox_4_1.DeviceType; import org.virtualbox_4_1.IMachine; import org.virtualbox_4_1.IMedium; import org.virtualbox_4_1.VBoxException; -import javax.annotation.Nullable; +import com.google.common.base.Function; /** * @author Mattias Holmqvist diff --git a/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/AttachMediumToMachineIfNotAlreadyAttached.java b/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/AttachMediumToMachineIfNotAlreadyAttached.java index 4d88b5e2e0..81bff200c8 100644 --- a/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/AttachMediumToMachineIfNotAlreadyAttached.java +++ b/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/AttachMediumToMachineIfNotAlreadyAttached.java @@ -19,12 +19,14 @@ package org.jclouds.virtualbox.functions; -import com.google.common.base.Function; -import org.virtualbox_4_1.*; - import javax.annotation.Nullable; -import static org.virtualbox_4_1.DeviceType.HardDisk; +import org.virtualbox_4_1.DeviceType; +import org.virtualbox_4_1.IMachine; +import org.virtualbox_4_1.IMedium; +import org.virtualbox_4_1.VBoxException; + +import com.google.common.base.Function; /** * @author Mattias Holmqvist @@ -37,7 +39,8 @@ public class AttachMediumToMachineIfNotAlreadyAttached implements Function private void createBaseStorage(IMedium hardDisk) { try { long size = 4L * 1024L * 1024L * 1024L - 4L; - IProgress storageCreation = hardDisk.createBaseStorage(size, (long) org.virtualbox_4_1.jaxws.MediumVariant.STANDARD.ordinal()); + IProgress storageCreation = hardDisk.createBaseStorage(size, + (long) org.virtualbox_4_1.jaxws.MediumVariant.STANDARD.ordinal()); storageCreation.waitForCompletion(-1); } catch (VBoxException e) { if (fileNotFoundException(e)) { - // File for medium could not be found. Something wrong with creation. + // File for medium could not be found. Something wrong with + // creation. hardDisk.deleteStorage(); } if (!storageAlreadyExists(e)) { - // Hard disk file was created but the storage had been created before that. + // Hard disk file was created but the storage had been created + // before that. throw e; } } @@ -90,8 +99,8 @@ public class CreateMediumIfNotAlreadyExists implements Function } private boolean storageAlreadyExists(VBoxException e) { - return e.getMessage().indexOf("VirtualBox error: Storage for the medium ") != -1 && - e.getMessage().indexOf("is already created") != -1; + return e.getMessage().indexOf("VirtualBox error: Storage for the medium ") != -1 + && e.getMessage().indexOf("is already created") != -1; } } diff --git a/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/IMachineToHardware.java b/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/IMachineToHardware.java index 1c30996721..3bebaa7c40 100644 --- a/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/IMachineToHardware.java +++ b/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/IMachineToHardware.java @@ -44,7 +44,6 @@ public class IMachineToHardware implements Function { public Hardware apply(@Nullable IMachine vm) { String osTypeId = vm.getOSTypeId(); - IGuestOSType guestOSType = virtualBoxManager.getVBox().getGuestOSType(osTypeId); Boolean is64Bit = guestOSType.getIs64Bit(); HardwareBuilder hardwareBuilder = new HardwareBuilder(); diff --git a/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/IMachineToImage.java b/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/IMachineToImage.java index 8e5454c8d0..b3b4f26a05 100644 --- a/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/IMachineToImage.java +++ b/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/IMachineToImage.java @@ -58,8 +58,7 @@ public class IMachineToImage implements Function { IGuestOSType guestOSType = virtualboxManager.getVBox().getGuestOSType(from.getOSTypeId()); OsFamily family = parseOsFamilyOrUnrecognized(guestOSType.getDescription()); - String version = parseVersionOrReturnEmptyString(family, guestOSType.getDescription(), - osVersionMap); + String version = parseVersionOrReturnEmptyString(family, guestOSType.getDescription(), osVersionMap); OperatingSystem os = OperatingSystem.builder().description(guestOSType.getDescription()).family(family) .version(version).is64Bit(guestOSType.getIs64Bit()).build(); diff --git a/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/IMachineToIpAddress.java b/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/IMachineToIpAddress.java index 0fef44fd8f..f7727e90ca 100644 --- a/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/IMachineToIpAddress.java +++ b/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/IMachineToIpAddress.java @@ -19,7 +19,10 @@ package org.jclouds.virtualbox.functions; -import com.google.common.base.Function; +import static org.jclouds.compute.options.RunScriptOptions.Builder.runAsRoot; + +import javax.annotation.Nullable; + import org.jclouds.compute.ComputeService; import org.jclouds.compute.domain.ExecResponse; import org.jclouds.compute.options.RunScriptOptions; @@ -28,13 +31,11 @@ import org.virtualbox_4_1.IGuestOSType; import org.virtualbox_4_1.IMachine; import org.virtualbox_4_1.VirtualBoxManager; -import javax.annotation.Nullable; - -import static org.jclouds.compute.options.RunScriptOptions.Builder.runAsRoot; +import com.google.common.base.Function; /** * Get an IP address from an IMachine using arp of the host machine. - * + * * @author Mattias Holmqvist, Andrea Turli */ public class IMachineToIpAddress implements Function { @@ -63,18 +64,25 @@ public class IMachineToIpAddress implements Function { IMachine hostMachine = manager.getVBox().findMachine(hostId); if (isOSX(hostMachine)) { if (simplifiedMacAddressOfClonedVM.contains("00")) - simplifiedMacAddressOfClonedVM = new StringBuffer(simplifiedMacAddressOfClonedVM).delete(simplifiedMacAddressOfClonedVM.indexOf("00"), simplifiedMacAddressOfClonedVM.indexOf("00") + 1).toString(); + simplifiedMacAddressOfClonedVM = new StringBuffer(simplifiedMacAddressOfClonedVM).delete( + simplifiedMacAddressOfClonedVM.indexOf("00"), simplifiedMacAddressOfClonedVM.indexOf("00") + 1) + .toString(); if (simplifiedMacAddressOfClonedVM.contains("0")) - if (simplifiedMacAddressOfClonedVM.indexOf("0") + 1 != ':' && simplifiedMacAddressOfClonedVM.indexOf("0") - 1 != ':') - simplifiedMacAddressOfClonedVM = new StringBuffer(simplifiedMacAddressOfClonedVM).delete(simplifiedMacAddressOfClonedVM.indexOf("0"), simplifiedMacAddressOfClonedVM.indexOf("0") + 1).toString(); + if (simplifiedMacAddressOfClonedVM.indexOf("0") + 1 != ':' + && simplifiedMacAddressOfClonedVM.indexOf("0") - 1 != ':') + simplifiedMacAddressOfClonedVM = new StringBuffer(simplifiedMacAddressOfClonedVM).delete( + simplifiedMacAddressOfClonedVM.indexOf("0"), simplifiedMacAddressOfClonedVM.indexOf("0") + 1) + .toString(); } // TODO: This is both shell-dependent and hard-coded. Needs to be fixed. - ExecResponse execResponse = runScriptOnNode(hostId, "for i in {1..254} ; do ping -c 1 -t 1 192.168.2.$i & done", runAsRoot(false).wrapInInitScript(false)); + ExecResponse execResponse = runScriptOnNode(hostId, "for i in {1..254} ; do ping -c 1 -t 1 192.168.2.$i & done", + runAsRoot(false).wrapInInitScript(false)); System.out.println(execResponse); - String arpLine = runScriptOnNode(hostId, "arp -an | grep " + simplifiedMacAddressOfClonedVM, runAsRoot(false).wrapInInitScript(false)).getOutput(); + String arpLine = runScriptOnNode(hostId, "arp -an | grep " + simplifiedMacAddressOfClonedVM, + runAsRoot(false).wrapInInitScript(false)).getOutput(); String ipAddress = arpLine.substring(arpLine.indexOf("(") + 1, arpLine.indexOf(")")); System.out.println("IP address " + ipAddress); return ipAddress; diff --git a/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/IMachineToNodeMetadata.java b/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/IMachineToNodeMetadata.java index 7dc2a07c62..808b30efa5 100644 --- a/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/IMachineToNodeMetadata.java +++ b/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/IMachineToNodeMetadata.java @@ -19,8 +19,19 @@ package org.jclouds.virtualbox.functions; -import com.google.common.base.Function; -import org.jclouds.compute.domain.*; +import static org.jclouds.virtualbox.config.VirtualBoxComputeServiceContextModule.machineToNodeState; + +import java.util.HashSet; +import java.util.Set; + +import javax.annotation.Resource; +import javax.inject.Named; + +import org.jclouds.compute.domain.HardwareBuilder; +import org.jclouds.compute.domain.NodeMetadata; +import org.jclouds.compute.domain.NodeMetadataBuilder; +import org.jclouds.compute.domain.NodeState; +import org.jclouds.compute.domain.Processor; import org.jclouds.compute.reference.ComputeServiceConstants; import org.jclouds.domain.Credentials; import org.jclouds.domain.LocationBuilder; @@ -31,12 +42,7 @@ import org.virtualbox_4_1.IMachine; import org.virtualbox_4_1.INetworkAdapter; import org.virtualbox_4_1.MachineState; -import javax.annotation.Resource; -import javax.inject.Named; -import java.util.HashSet; -import java.util.Set; - -import static org.jclouds.virtualbox.config.VirtualBoxComputeServiceContextModule.machineToNodeState; +import com.google.common.base.Function; public class IMachineToNodeMetadata implements Function { @@ -57,7 +63,7 @@ public class IMachineToNodeMetadata implements Function locationBuilder.id(""); locationBuilder.scope(LocationScope.HOST); nodeMetadataBuilder.location(locationBuilder.build()); - + HardwareBuilder hardwareBuilder = new HardwareBuilder(); hardwareBuilder.ram(vm.getMemorySize().intValue()); @@ -75,7 +81,6 @@ public class IMachineToNodeMetadata implements Function nodeMetadataBuilder.hostname(vm.getName()); nodeMetadataBuilder.loginPort(18083); - MachineState vmState = vm.getState(); NodeState nodeState = machineToNodeState.get(vmState); if (nodeState == null) @@ -90,8 +95,8 @@ public class IMachineToNodeMetadata implements Function System.out.println("Interface: " + bridgedInterface); } -// nodeMetadataBuilder.imageId(""); -// nodeMetadataBuilder.group(""); + // nodeMetadataBuilder.imageId(""); + // nodeMetadataBuilder.group(""); String provider = "virtualbox"; String identity = System.getProperty("test." + provider + ".identity", "administrator"); @@ -101,5 +106,5 @@ public class IMachineToNodeMetadata implements Function nodeMetadataBuilder.id(vm.getId()); return nodeMetadataBuilder.build(); } - + } diff --git a/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/IsoToIMachine.java b/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/IsoToIMachine.java index 9761738a15..932a9a22b6 100644 --- a/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/IsoToIMachine.java +++ b/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/IsoToIMachine.java @@ -19,8 +19,22 @@ package org.jclouds.virtualbox.functions; -import com.google.common.base.Function; -import com.google.inject.Inject; +import static com.google.common.base.Preconditions.checkNotNull; +import static org.jclouds.compute.options.RunScriptOptions.Builder.runAsRoot; +import static org.jclouds.compute.options.RunScriptOptions.Builder.wrapInInitScript; +import static org.jclouds.virtualbox.config.VirtualBoxConstants.VIRTUALBOX_INSTALLATION_KEY_SEQUENCE; +import static org.jclouds.virtualbox.config.VirtualBoxConstants.VIRTUALBOX_WORKINGDIR; +import static org.virtualbox_4_1.AccessMode.ReadOnly; +import static org.virtualbox_4_1.DeviceType.DVD; +import static org.virtualbox_4_1.DeviceType.HardDisk; +import static org.virtualbox_4_1.LockType.Shared; +import static org.virtualbox_4_1.LockType.Write; + +import java.io.File; + +import javax.annotation.Resource; +import javax.inject.Named; + import org.eclipse.jetty.server.Server; import org.jclouds.compute.ComputeServiceContext; import org.jclouds.compute.domain.ExecResponse; @@ -34,22 +48,18 @@ import org.jclouds.virtualbox.config.VirtualBoxConstants; import org.jclouds.virtualbox.domain.ExecutionType; import org.jclouds.virtualbox.functions.admin.StartJettyIfNotAlreadyRunning; import org.jclouds.virtualbox.settings.KeyboardScancodes; -import org.virtualbox_4_1.*; +import org.virtualbox_4_1.AccessMode; +import org.virtualbox_4_1.DeviceType; +import org.virtualbox_4_1.IMachine; +import org.virtualbox_4_1.IMedium; +import org.virtualbox_4_1.IProgress; +import org.virtualbox_4_1.ISession; +import org.virtualbox_4_1.LockType; +import org.virtualbox_4_1.VBoxException; +import org.virtualbox_4_1.VirtualBoxManager; -import javax.annotation.Resource; -import javax.inject.Named; -import java.io.File; - -import static com.google.common.base.Preconditions.checkNotNull; -import static org.jclouds.compute.options.RunScriptOptions.Builder.runAsRoot; -import static org.jclouds.compute.options.RunScriptOptions.Builder.wrapInInitScript; -import static org.jclouds.virtualbox.config.VirtualBoxConstants.VIRTUALBOX_INSTALLATION_KEY_SEQUENCE; -import static org.jclouds.virtualbox.config.VirtualBoxConstants.VIRTUALBOX_WORKINGDIR; -import static org.virtualbox_4_1.AccessMode.ReadOnly; -import static org.virtualbox_4_1.DeviceType.DVD; -import static org.virtualbox_4_1.DeviceType.HardDisk; -import static org.virtualbox_4_1.LockType.Shared; -import static org.virtualbox_4_1.LockType.Write; +import com.google.common.base.Function; +import com.google.inject.Inject; public class IsoToIMachine implements Function { @@ -73,8 +83,8 @@ public class IsoToIMachine implements Function { @Inject public IsoToIMachine(VirtualBoxManager manager, String adminDisk, String diskFormat, String settingsFile, - String vmName, String osTypeId, String vmId, boolean forceOverwrite, String controllerIDE, - ComputeServiceContext context, String hostId, String guestId, Credentials credentials) { + String vmName, String osTypeId, String vmId, boolean forceOverwrite, String controllerIDE, + ComputeServiceContext context, String hostId, String guestId, Credentials credentials) { super(); this.manager = manager; this.adminDisk = adminDisk; @@ -98,7 +108,8 @@ public class IsoToIMachine implements Function { String baseResource = "."; Server server = new StartJettyIfNotAlreadyRunning(port).apply(baseResource); - IMachine vm = new CreateAndRegisterMachineFromIsoIfNotAlreadyExists(settingsFile, osTypeId, vmId, forceOverwrite, manager).apply(vmName); + IMachine vm = new CreateAndRegisterMachineFromIsoIfNotAlreadyExists(settingsFile, osTypeId, vmId, forceOverwrite, + manager).apply(vmName); String defaultWorkingDir = System.getProperty("user.home") + "/jclouds-virtualbox-test"; String workingDir = System.getProperty(VIRTUALBOX_WORKINGDIR, defaultWorkingDir); @@ -129,7 +140,7 @@ public class IsoToIMachine implements Function { String guestAdditionsDvd = workingDir + "/VBoxGuestAdditions_4.1.2.iso"; final IMedium guestAdditionsDvdMedium = manager.getVBox().openMedium(guestAdditionsDvd, DeviceType.DVD, - AccessMode.ReadOnly, forceOverwrite); + AccessMode.ReadOnly, forceOverwrite); // Guest additions ensureGuestAdditionsMediumIsAttached(vmName, guestAdditionsDvdMedium); @@ -178,13 +189,13 @@ public class IsoToIMachine implements Function { } private void ensureGuestAdditionsMediumIsAttached(String vmName, final IMedium guestAdditionsDvdMedium) { - lockMachineAndApply(manager, Write, vmName, - new AttachMediumToMachineIfNotAlreadyAttached(controllerIDE, guestAdditionsDvdMedium, 1, 1, DeviceType.DVD)); + lockMachineAndApply(manager, Write, vmName, new AttachMediumToMachineIfNotAlreadyAttached(controllerIDE, + guestAdditionsDvdMedium, 1, 1, DeviceType.DVD)); } private void ensureMachineHasHardDiskAttached(String vmName, IMedium hardDisk) { - lockMachineAndApply(manager, Write, vmName, - new AttachMediumToMachineIfNotAlreadyAttached(controllerIDE, hardDisk, 0, 1, HardDisk)); + lockMachineAndApply(manager, Write, vmName, new AttachMediumToMachineIfNotAlreadyAttached(controllerIDE, + hardDisk, 0, 1, HardDisk)); } private void ensureMachineHasMemory(String vmName, final long memorySize) { @@ -198,10 +209,12 @@ public class IsoToIMachine implements Function { private void ensureMachineHasAttachedDistroMedium(String isoName, String workingDir, String controllerIDE) { final String pathToIsoFile = checkFileExists(workingDir + "/" + isoName); final IMedium distroMedium = manager.getVBox().openMedium(pathToIsoFile, DVD, ReadOnly, forceOverwrite); - lockMachineAndApply(manager, Write, vmName, - new AttachDistroMediumToMachine( - checkNotNull(controllerIDE, "controllerIDE"), - checkNotNull(distroMedium, "distroMedium"))); + lockMachineAndApply( + manager, + Write, + vmName, + new AttachDistroMediumToMachine(checkNotNull(controllerIDE, "controllerIDE"), checkNotNull(distroMedium, + "distroMedium"))); } public static String checkFileExists(String filePath) { @@ -213,7 +226,7 @@ public class IsoToIMachine implements Function { public void ensureMachineHasIDEControllerNamed(String vmName, String controllerIDE) { lockMachineAndApply(manager, Write, checkNotNull(vmName, "vmName"), - new AddIDEControllerIfNotExists(checkNotNull(controllerIDE, "controllerIDE"))); + new AddIDEControllerIfNotExists(checkNotNull(controllerIDE, "controllerIDE"))); } private T applyForMachine(VirtualBoxManager manager, final String machineId, final Function function) { @@ -232,7 +245,7 @@ public class IsoToIMachine implements Function { } public static T lockMachineAndApply(VirtualBoxManager manager, final LockType type, final String machineId, - final Function function) { + final Function function) { return lockSessionOnMachineAndApply(manager, type, machineId, new Function() { @Override @@ -250,7 +263,7 @@ public class IsoToIMachine implements Function { } public static T lockSessionOnMachineAndApply(VirtualBoxManager manager, LockType type, String machineId, - Function function) { + Function function) { try { ISession session = manager.getSessionObject(); IMachine immutableMachine = manager.getVBox().findMachine(machineId); @@ -262,17 +275,17 @@ public class IsoToIMachine implements Function { } } catch (VBoxException e) { throw new RuntimeException(String.format("error applying %s to %s with %s lock: %s", function, machineId, - type, e.getMessage()), e); + type, e.getMessage()), e); } } private String defaultInstallSequence() { return " " - + "/install/vmlinuz noapic preseed/url=http://10.0.2.2:8080/src/test/resources/preseed.cfg " - + "debian-installer=en_US auto locale=en_US kbd-chooser/method=us " + "hostname=" + vmName + " " - + "fb=false debconf/frontend=noninteractive " - + "keyboard-configuration/layout=USA keyboard-configuration/variant=USA console-setup/ask_detect=false " - + "initrd=/install/initrd.gz -- "; + + "/install/vmlinuz noapic preseed/url=http://10.0.2.2:8080/src/test/resources/preseed.cfg " + + "debian-installer=en_US auto locale=en_US kbd-chooser/method=us " + "hostname=" + vmName + " " + + "fb=false debconf/frontend=noninteractive " + + "keyboard-configuration/layout=USA keyboard-configuration/variant=USA console-setup/ask_detect=false " + + "initrd=/install/initrd.gz -- "; } private void sendKeyboardSequence(String keyboardSequence) { diff --git a/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/LaunchMachineIfNotAlreadyRunning.java b/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/LaunchMachineIfNotAlreadyRunning.java index a118c77658..8c7059f9c4 100644 --- a/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/LaunchMachineIfNotAlreadyRunning.java +++ b/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/LaunchMachineIfNotAlreadyRunning.java @@ -19,34 +19,36 @@ package org.jclouds.virtualbox.functions; -import com.google.common.base.Function; -import org.jclouds.compute.reference.ComputeServiceConstants; -import org.jclouds.logging.Logger; -import org.jclouds.virtualbox.domain.ErrorCode; -import org.jclouds.virtualbox.domain.ExecutionType; -import org.virtualbox_4_1.*; -import org.virtualbox_4_1.jaxws.RuntimeFaultMsg; +import static com.google.common.base.Throwables.propagate; import javax.annotation.Nullable; import javax.annotation.Resource; import javax.inject.Named; -import javax.lang.model.type.ExecutableType; -import static com.google.common.base.Throwables.propagate; -import static javax.xml.bind.DatatypeConverter.parseUnsignedInt; +import org.jclouds.compute.reference.ComputeServiceConstants; +import org.jclouds.logging.Logger; +import org.jclouds.virtualbox.domain.ErrorCode; +import org.jclouds.virtualbox.domain.ExecutionType; +import org.virtualbox_4_1.IMachine; +import org.virtualbox_4_1.IProgress; +import org.virtualbox_4_1.VBoxException; +import org.virtualbox_4_1.VirtualBoxManager; + +import com.google.common.base.Function; /** - * Starts a machine using launchMachine() with the provided type and environment. + * Starts a machine using launchMachine() with the provided type and + * environment. *

- * Note that launchMachine() may throw VBoxException with the following error codes: + * Note that launchMachine() may throw VBoxException with the following error + * codes: *

- * VBOX_E_UNEXPECTED: Virtual machine not registered. - * VBOX_E_INVALIDARG: Invalid session type type. - * VBOX_E_OBJECT_NOT_FOUND: No machine matching machineId found. - * VBOX_E_INVALID_OBJECT_STATE: Session already open or being opened. - * VBOX_E_IPRT_ERROR: Launching process for machine failed. - * VBOX_E_VM_ERROR: Failed to assign machine to session. - * + * VBOX_E_UNEXPECTED: Virtual machine not registered. VBOX_E_INVALIDARG: Invalid + * session type type. VBOX_E_OBJECT_NOT_FOUND: No machine matching machineId + * found. VBOX_E_INVALID_OBJECT_STATE: Session already open or being opened. + * VBOX_E_IPRT_ERROR: Launching process for machine failed. VBOX_E_VM_ERROR: + * Failed to assign machine to session. + * * @author Mattias Holmqvist * * @see ErrorCode @@ -70,7 +72,8 @@ public class LaunchMachineIfNotAlreadyRunning implements Function { @Inject public FileDownloadFromURI(final ComputeServiceContext context, - @Named(VIRTUALBOX_WORKINGDIR) final String workingDir, - @Named(VirtualBoxConstants.VIRTUALBOX_ISOFILE) final String isoFile) { + @Named(VIRTUALBOX_WORKINGDIR) final String workingDir, + @Named(VirtualBoxConstants.VIRTUALBOX_ISOFILE) final String isoFile) { this.context = context; this.workingDir = workingDir; this.isoFile = isoFile; diff --git a/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/admin/ImageFromYamlStream.java b/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/admin/ImageFromYamlStream.java index fc68e70fd5..c6ec3a02da 100644 --- a/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/admin/ImageFromYamlStream.java +++ b/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/admin/ImageFromYamlStream.java @@ -1,28 +1,4 @@ -package org.jclouds.virtualbox.functions.admin; - -import com.google.common.base.Function; -import com.google.common.base.Functions; -import com.google.common.cache.Cache; -import com.google.common.cache.CacheBuilder; -import com.google.common.cache.CacheLoader; -import com.google.common.collect.Iterables; -import com.google.common.collect.Maps; -import org.jclouds.compute.domain.Image; -import org.jclouds.virtualbox.domain.YamlImage; -import org.yaml.snakeyaml.Loader; -import org.yaml.snakeyaml.TypeDescription; -import org.yaml.snakeyaml.Yaml; -import org.yaml.snakeyaml.constructor.Constructor; - -import javax.inject.Singleton; -import java.io.InputStream; -import java.util.List; -import java.util.Map; - -import static com.google.common.base.Preconditions.checkState; - /** - * * Licensed to jclouds, Inc. (jclouds) under one or more * contributor license agreements. See the NOTICE file * distributed with this work for additional information @@ -39,7 +15,34 @@ import static com.google.common.base.Preconditions.checkState; * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. - * + */ + +package org.jclouds.virtualbox.functions.admin; + +import static com.google.common.base.Preconditions.checkState; + +import java.io.InputStream; +import java.util.List; +import java.util.Map; + +import javax.inject.Singleton; + +import org.jclouds.compute.domain.Image; +import org.jclouds.virtualbox.domain.YamlImage; +import org.yaml.snakeyaml.Loader; +import org.yaml.snakeyaml.TypeDescription; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.constructor.Constructor; + +import com.google.common.base.Function; +import com.google.common.base.Functions; +import com.google.common.cache.Cache; +import com.google.common.cache.CacheBuilder; +import com.google.common.cache.CacheLoader; +import com.google.common.collect.Iterables; +import com.google.common.collect.Maps; + +/** * * @author Andrea Turli */ @@ -53,12 +56,12 @@ public class ImageFromYamlStream implements Function images; } - + private Object construct(String data) { - Yaml yaml = new Yaml(); - return yaml.load(data); + Yaml yaml = new Yaml(); + return yaml.load(data); } - + @Override public Cache apply(InputStream source) { @@ -74,15 +77,15 @@ public class ImageFromYamlStream implements Function backingMap = Maps.uniqueIndex(Iterables.transform(config.images, YamlImage.toImage), - new Function() { - public String apply(Image image) { - return image.getId(); - } - }); - Cache cache = CacheBuilder.newBuilder().build(CacheLoader.from(Functions.forMap(backingMap))); - for (String node : backingMap.keySet()) - cache.getUnchecked(node); - return cache; + new Function() { + public String apply(Image image) { + return image.getId(); + } + }); + Cache cache = CacheBuilder.newBuilder().build(CacheLoader.from(Functions.forMap(backingMap))); + for (String node : backingMap.keySet()) + cache.getUnchecked(node); + return cache; } - + } \ No newline at end of file diff --git a/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/admin/StartJettyIfNotAlreadyRunning.java b/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/admin/StartJettyIfNotAlreadyRunning.java index 9d9538a55d..96d5e4c21f 100644 --- a/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/admin/StartJettyIfNotAlreadyRunning.java +++ b/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/admin/StartJettyIfNotAlreadyRunning.java @@ -43,65 +43,65 @@ import com.google.inject.Singleton; */ public class StartJettyIfNotAlreadyRunning implements Function { - @Resource - @Named(ComputeServiceConstants.COMPUTE_LOGGER) - protected Logger logger = Logger.NULL; + @Resource + @Named(ComputeServiceConstants.COMPUTE_LOGGER) + protected Logger logger = Logger.NULL; - private final int port; + private final int port; - @Inject - public StartJettyIfNotAlreadyRunning( - @Named(VirtualBoxConstants.VIRTUALBOX_JETTY_PORT) final String port) { - this.port = Integer.parseInt(port); - } + @Inject + public StartJettyIfNotAlreadyRunning(@Named(VirtualBoxConstants.VIRTUALBOX_JETTY_PORT) final String port) { + this.port = Integer.parseInt(port); + } - @Override - public Server apply(@Nullable String baseResource) { - final Server server = ServerJetty.getInstance().getServer(); + @Override + public Server apply(@Nullable String baseResource) { + final Server server = ServerJetty.getInstance().getServer(); - if (!server.getState().equals(Server.STARTED) && !new InetSocketAddressConnect().apply(new IPSocket("localhost", port))) { - ResourceHandler resource_handler = new ResourceHandler(); - resource_handler.setDirectoriesListed(true); - resource_handler.setWelcomeFiles(new String[] { "index.html" }); + if (!server.getState().equals(Server.STARTED) + && !new InetSocketAddressConnect().apply(new IPSocket("localhost", port))) { + ResourceHandler resource_handler = new ResourceHandler(); + resource_handler.setDirectoriesListed(true); + resource_handler.setWelcomeFiles(new String[] { "index.html" }); - resource_handler.setResourceBase(baseResource); - logger.info("serving " + resource_handler.getBaseResource()); + resource_handler.setResourceBase(baseResource); + logger.info("serving " + resource_handler.getBaseResource()); - HandlerList handlers = new HandlerList(); - handlers.setHandlers(new Handler[] { resource_handler, new DefaultHandler() }); - server.setHandler(handlers); + HandlerList handlers = new HandlerList(); + handlers.setHandlers(new Handler[] { resource_handler, new DefaultHandler() }); + server.setHandler(handlers); - try { - server.start(); - } catch (Exception e) { - logger.error(e, "Server jetty could not be started at this %s", baseResource); - } - return server; - } else { - logger.debug("Server jetty serving %s already running. Skipping start", baseResource); - return server; - } + try { + server.start(); + } catch (Exception e) { + logger.error(e, "Server jetty could not be started at this %s", baseResource); + } + return server; + } else { + logger.debug("Server jetty serving %s already running. Skipping start", baseResource); + return server; + } - } - - @Singleton - private static class ServerJetty { - private static ServerJetty instance; - private Server server; - private String port = System.getProperty(VirtualBoxConstants.VIRTUALBOX_JETTY_PORT, "8080"); + } - private ServerJetty() { - this.server = new Server(Integer.parseInt(port)); - } + @Singleton + private static class ServerJetty { + private static ServerJetty instance; + private Server server; + private String port = System.getProperty(VirtualBoxConstants.VIRTUALBOX_JETTY_PORT, "8080"); - public static ServerJetty getInstance() { - if (instance == null) - instance = new ServerJetty(); - return instance; - } + private ServerJetty() { + this.server = new Server(Integer.parseInt(port)); + } - public Server getServer() { - return server; - } - } + public static ServerJetty getInstance() { + if (instance == null) + instance = new ServerJetty(); + return instance; + } + + public Server getServer() { + return server; + } + } } diff --git a/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/admin/StartVBoxIfNotAlreadyRunning.java b/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/admin/StartVBoxIfNotAlreadyRunning.java index 4add602999..9da826f9f1 100644 --- a/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/admin/StartVBoxIfNotAlreadyRunning.java +++ b/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/admin/StartVBoxIfNotAlreadyRunning.java @@ -20,8 +20,14 @@ package org.jclouds.virtualbox.functions.admin; -import com.google.common.base.Function; -import com.google.common.cache.Cache; +import static org.jclouds.compute.options.RunScriptOptions.Builder.runAsRoot; + +import java.net.URI; + +import javax.annotation.Nullable; +import javax.annotation.Resource; +import javax.inject.Named; + import org.jclouds.compute.ComputeServiceContext; import org.jclouds.compute.reference.ComputeServiceConstants; import org.jclouds.domain.Credentials; @@ -30,14 +36,7 @@ import org.jclouds.net.IPSocket; import org.jclouds.predicates.InetSocketAddressConnect; import org.virtualbox_4_1.VirtualBoxManager; -import javax.annotation.Nullable; -import javax.annotation.Resource; -import javax.inject.Named; - -import java.net.URI; -import java.util.concurrent.ExecutionException; - -import static org.jclouds.compute.options.RunScriptOptions.Builder.runAsRoot; +import com.google.common.base.Function; public class StartVBoxIfNotAlreadyRunning implements Function { diff --git a/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/settings/KeyboardScancodes.java b/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/settings/KeyboardScancodes.java index bbd00825d9..5491364a11 100644 --- a/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/settings/KeyboardScancodes.java +++ b/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/settings/KeyboardScancodes.java @@ -16,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ + package org.jclouds.virtualbox.settings; import java.util.Collections; @@ -24,138 +25,139 @@ import java.util.Map; public class KeyboardScancodes { - // http://www.win.tue.nl/~aeb/linux/kbd/scancodes-1.html - - public static final Map NORMAL_KEYBOARD_BUTTON_MAP = createMap(); - public static final Map SPECIAL_KEYBOARD_BUTTON_MAP = createSpecialMap(); + // http://www.win.tue.nl/~aeb/linux/kbd/scancodes-1.html - private static Map createMap() { - Map alphaToHex = new HashMap(); - alphaToHex.put("1", "02 82"); - alphaToHex.put("2", "03 83"); - alphaToHex.put("3", "04 84"); - alphaToHex.put("4", "05 85"); - alphaToHex.put("5", "06 86"); - alphaToHex.put("6", "07 87"); - alphaToHex.put("7", "08 88"); - alphaToHex.put("8", "09 89"); - alphaToHex.put("9", "0a 8a"); - alphaToHex.put("0", "0b 8b"); - alphaToHex.put("-", "0c 8c"); - alphaToHex.put("=", "0d 8d"); - alphaToHex.put("Tab", "0f 8f"); - alphaToHex.put("q", "10 90"); - alphaToHex.put("w", "11 91"); - alphaToHex.put("e", "12 92"); - alphaToHex.put("r", "13 93"); - alphaToHex.put("t", "14 94"); - alphaToHex.put("y", "15 95"); - alphaToHex.put("u", "16 96"); - alphaToHex.put("i", "17 97"); - alphaToHex.put("o", "18 98"); - alphaToHex.put("p", "19 99"); + public static final Map NORMAL_KEYBOARD_BUTTON_MAP = createMap(); + public static final Map SPECIAL_KEYBOARD_BUTTON_MAP = createSpecialMap(); - alphaToHex.put("Q", "2a 10 aa"); - alphaToHex.put("W", "2a 11 aa"); - alphaToHex.put("E", "2a 12 aa"); - alphaToHex.put("R", "2a 13 aa"); - alphaToHex.put("T", "2a 14 aa"); - alphaToHex.put("Y", "2a 15 aa"); - alphaToHex.put("U", "2a 16 aa"); - alphaToHex.put("I", "2a 17 aa"); - alphaToHex.put("O", "2a 18 aa"); - alphaToHex.put("P", "2a 19 aa"); + private static Map createMap() { + Map alphaToHex = new HashMap(); + alphaToHex.put("1", "02 82"); + alphaToHex.put("2", "03 83"); + alphaToHex.put("3", "04 84"); + alphaToHex.put("4", "05 85"); + alphaToHex.put("5", "06 86"); + alphaToHex.put("6", "07 87"); + alphaToHex.put("7", "08 88"); + alphaToHex.put("8", "09 89"); + alphaToHex.put("9", "0a 8a"); + alphaToHex.put("0", "0b 8b"); + alphaToHex.put("-", "0c 8c"); + alphaToHex.put("=", "0d 8d"); + alphaToHex.put("Tab", "0f 8f"); + alphaToHex.put("q", "10 90"); + alphaToHex.put("w", "11 91"); + alphaToHex.put("e", "12 92"); + alphaToHex.put("r", "13 93"); + alphaToHex.put("t", "14 94"); + alphaToHex.put("y", "15 95"); + alphaToHex.put("u", "16 96"); + alphaToHex.put("i", "17 97"); + alphaToHex.put("o", "18 98"); + alphaToHex.put("p", "19 99"); - alphaToHex.put("a", "1e 9e"); - alphaToHex.put("s", "1f 9f"); - alphaToHex.put("d", "20 a0"); - alphaToHex.put("f", "21 a1"); - alphaToHex.put("g", "22 a2"); - alphaToHex.put("h", "23 a3"); - alphaToHex.put("j", "24 a4"); - alphaToHex.put("k", "25 a5"); - alphaToHex.put("l", "26 a6"); + alphaToHex.put("Q", "2a 10 aa"); + alphaToHex.put("W", "2a 11 aa"); + alphaToHex.put("E", "2a 12 aa"); + alphaToHex.put("R", "2a 13 aa"); + alphaToHex.put("T", "2a 14 aa"); + alphaToHex.put("Y", "2a 15 aa"); + alphaToHex.put("U", "2a 16 aa"); + alphaToHex.put("I", "2a 17 aa"); + alphaToHex.put("O", "2a 18 aa"); + alphaToHex.put("P", "2a 19 aa"); - alphaToHex.put("A", "2a 1e aa 9e"); - alphaToHex.put("S", "2a 1f aa 9f"); - alphaToHex.put("D", "2a 20 aa a0"); - alphaToHex.put("F", "2a 21 aa a1"); - alphaToHex.put("G", "2a 22 aa a2"); - alphaToHex.put("H", "2a 23 aa a3"); - alphaToHex.put("J", "2a 24 aa a4"); - alphaToHex.put("K", "2a 25 aa a5"); - alphaToHex.put("L", "2a 26 aa a6"); + alphaToHex.put("a", "1e 9e"); + alphaToHex.put("s", "1f 9f"); + alphaToHex.put("d", "20 a0"); + alphaToHex.put("f", "21 a1"); + alphaToHex.put("g", "22 a2"); + alphaToHex.put("h", "23 a3"); + alphaToHex.put("j", "24 a4"); + alphaToHex.put("k", "25 a5"); + alphaToHex.put("l", "26 a6"); - alphaToHex.put(");", "27 a7"); - alphaToHex.put("\"", "2a 28 aa a8"); - alphaToHex.put("\"", "28 a8"); - alphaToHex.put("\\", "2b ab"); - alphaToHex.put("|", "2a 2b aa 8b"); - alphaToHex.put("[", "1a 9a"); - alphaToHex.put("", "1b 9b"); - alphaToHex.put("<", "2a 33 aa b3"); - alphaToHex.put(">", "2a 34 aa b4"); - alphaToHex.put("$", "2a 05 aa 85"); - alphaToHex.put("+", "2a 0d aa 8d"); + alphaToHex.put("A", "2a 1e aa 9e"); + alphaToHex.put("S", "2a 1f aa 9f"); + alphaToHex.put("D", "2a 20 aa a0"); + alphaToHex.put("F", "2a 21 aa a1"); + alphaToHex.put("G", "2a 22 aa a2"); + alphaToHex.put("H", "2a 23 aa a3"); + alphaToHex.put("J", "2a 24 aa a4"); + alphaToHex.put("K", "2a 25 aa a5"); + alphaToHex.put("L", "2a 26 aa a6"); - alphaToHex.put("z", "2c ac"); - alphaToHex.put("x", "2d ad"); - alphaToHex.put("c", "2e ae"); - alphaToHex.put("v", "2f af"); - alphaToHex.put("b", "30 b0"); - alphaToHex.put("n", "31 b1"); - alphaToHex.put("m", "32 b2"); - alphaToHex.put("Z", "2a 2c aa ac"); - alphaToHex.put("X", "2a 2d aa ad"); - alphaToHex.put("C", "2a 2e aa ae"); - alphaToHex.put("V", "2a 2f aa af"); - alphaToHex.put("B", "2a 30 aa b0"); - alphaToHex.put("N", "2a 31 aa b1"); - alphaToHex.put("M", "2a 32 aa b2"); + alphaToHex.put(");", "27 a7"); + alphaToHex.put("\"", "2a 28 aa a8"); + alphaToHex.put("\"", "28 a8"); + alphaToHex.put("\\", "2b ab"); + alphaToHex.put("|", "2a 2b aa 8b"); + alphaToHex.put("[", "1a 9a"); + alphaToHex.put("", "1b 9b"); + alphaToHex.put("<", "2a 33 aa b3"); + alphaToHex.put(">", "2a 34 aa b4"); + alphaToHex.put("$", "2a 05 aa 85"); + alphaToHex.put("+", "2a 0d aa 8d"); - alphaToHex.put(",", "33 b3"); - alphaToHex.put(".", "34 b4"); - alphaToHex.put("/", "35 b5"); - alphaToHex.put(":", "2a 27 aa a7"); - alphaToHex.put("%", "2a 06 aa 86"); - alphaToHex.put("_", "2a 0c aa 8c"); - alphaToHex.put("&", "2a 08 aa 88"); - alphaToHex.put("(", "2a 0a aa 8a"); - alphaToHex.put(")", "2a 0b aa 8b"); - return Collections.unmodifiableMap(alphaToHex); - } - private static Map createSpecialMap() { - Map special = new HashMap(); - special.put("", "1c 9c"); - special.put("", "0e 8e"); - special.put("", "39 b9"); - special.put("", "1c 9c"); - special.put("", "01 81"); - special.put("", "0f 8f"); - special.put("", "1d 38 0e"); - special.put("", "wait"); - - special.put("", "48 c8"); - special.put("", "50 d0"); - special.put("", "49 c9"); - special.put("", "51 d1"); - special.put("", "4f cf"); - special.put("", "52 d2"); - special.put("", "53 d3"); - special.put("", "4b cb"); - special.put("", "4d cd"); - special.put("", "47 c7"); - - special.put("", "3b"); - special.put("", "3c"); - special.put("", "3d"); - special.put("", "3e"); - special.put("", "3f"); - special.put("", "40"); - special.put("", "41"); - special.put("", "42"); - special.put("", "43"); - special.put("", "44"); - return Collections.unmodifiableMap(special); - } + alphaToHex.put("z", "2c ac"); + alphaToHex.put("x", "2d ad"); + alphaToHex.put("c", "2e ae"); + alphaToHex.put("v", "2f af"); + alphaToHex.put("b", "30 b0"); + alphaToHex.put("n", "31 b1"); + alphaToHex.put("m", "32 b2"); + alphaToHex.put("Z", "2a 2c aa ac"); + alphaToHex.put("X", "2a 2d aa ad"); + alphaToHex.put("C", "2a 2e aa ae"); + alphaToHex.put("V", "2a 2f aa af"); + alphaToHex.put("B", "2a 30 aa b0"); + alphaToHex.put("N", "2a 31 aa b1"); + alphaToHex.put("M", "2a 32 aa b2"); + + alphaToHex.put(",", "33 b3"); + alphaToHex.put(".", "34 b4"); + alphaToHex.put("/", "35 b5"); + alphaToHex.put(":", "2a 27 aa a7"); + alphaToHex.put("%", "2a 06 aa 86"); + alphaToHex.put("_", "2a 0c aa 8c"); + alphaToHex.put("&", "2a 08 aa 88"); + alphaToHex.put("(", "2a 0a aa 8a"); + alphaToHex.put(")", "2a 0b aa 8b"); + return Collections.unmodifiableMap(alphaToHex); + } + + private static Map createSpecialMap() { + Map special = new HashMap(); + special.put("", "1c 9c"); + special.put("", "0e 8e"); + special.put("", "39 b9"); + special.put("", "1c 9c"); + special.put("", "01 81"); + special.put("", "0f 8f"); + special.put("", "1d 38 0e"); + special.put("", "wait"); + + special.put("", "48 c8"); + special.put("", "50 d0"); + special.put("", "49 c9"); + special.put("", "51 d1"); + special.put("", "4f cf"); + special.put("", "52 d2"); + special.put("", "53 d3"); + special.put("", "4b cb"); + special.put("", "4d cd"); + special.put("", "47 c7"); + + special.put("", "3b"); + special.put("", "3c"); + special.put("", "3d"); + special.put("", "3e"); + special.put("", "3f"); + special.put("", "40"); + special.put("", "41"); + special.put("", "42"); + special.put("", "43"); + special.put("", "44"); + return Collections.unmodifiableMap(special); + } } diff --git a/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/compute/VirtualBoxComputeServiceAdapterLiveTest.java b/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/compute/VirtualBoxComputeServiceAdapterLiveTest.java index f4f35dea00..893eb6a392 100644 --- a/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/compute/VirtualBoxComputeServiceAdapterLiveTest.java +++ b/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/compute/VirtualBoxComputeServiceAdapterLiveTest.java @@ -19,11 +19,12 @@ package org.jclouds.virtualbox.compute; -import com.google.common.base.Function; -import com.google.common.collect.ImmutableSet; -import com.google.common.collect.Iterables; -import com.google.common.collect.Maps; -import com.google.inject.Guice; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertFalse; + +import java.net.URI; +import java.util.Map; + import org.jclouds.compute.config.BaseComputeServiceContextModule; import org.jclouds.compute.domain.ExecResponse; import org.jclouds.compute.domain.Image; @@ -44,11 +45,11 @@ import org.testng.annotations.Test; import org.virtualbox_4_1.IMachine; import org.virtualbox_4_1.VirtualBoxManager; -import java.net.URI; -import java.util.Map; - -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; +import com.google.common.base.Function; +import com.google.common.collect.ImmutableSet; +import com.google.common.collect.Iterables; +import com.google.common.collect.Maps; +import com.google.inject.Guice; @Test(groups = "live", singleThreaded = true, testName = "VirtualBoxComputeServiceAdapterLiveTest") public class VirtualBoxComputeServiceAdapterLiveTest extends BaseVirtualBoxClientLiveTest { @@ -57,15 +58,15 @@ public class VirtualBoxComputeServiceAdapterLiveTest extends BaseVirtualBoxClien private IMachine machine; private final Map> osVersionMap = new BaseComputeServiceContextModule() { }.provideOsVersionMap(new ComputeServiceConstants.ReferenceData(), Guice.createInjector(new GsonModule()) - .getInstance(Json.class)); + .getInstance(Json.class)); - @BeforeGroups(groups = {"live"}) + @BeforeGroups(groups = { "live" }) public void setupClient() { super.setupClient(); final VirtualBoxManager manager = getManager(); Function iMachineToImage = new IMachineToImage(manager, osVersionMap); - adapter = new VirtualBoxComputeServiceAdapter(manager, - new JustProvider(provider, URI.create(endpoint), ImmutableSet.of()), iMachineToImage); + adapter = new VirtualBoxComputeServiceAdapter(manager, new JustProvider(provider, URI.create(endpoint), + ImmutableSet. of()), iMachineToImage); } protected VirtualBoxManager getManager() { @@ -89,15 +90,16 @@ public class VirtualBoxComputeServiceAdapterLiveTest extends BaseVirtualBoxClien // check other things, like cpu correct, mem correct, image/os is correct // (as possible) assert credentialStore.containsKey("node#" + machine.getId()) : "credentials to log into machine not found " - + machine; -// TODO: what's the IP address? -// assert InetAddresses.isInetAddress(machine.getPrimaryBackendIpAddress()) : machine; + + machine; + // TODO: what's the IP address? + // assert + // InetAddresses.isInetAddress(machine.getPrimaryBackendIpAddress()) : + // machine; doConnectViaSsh(machine, credentialStore.get("node#" + machine.getId())); } protected void doConnectViaSsh(IMachine machine, Credentials creds) { - SshClient ssh = context.utils().sshFactory() - .create(new IPSocket("//TODO", 22), creds); + SshClient ssh = context.utils().sshFactory().create(new IPSocket("//TODO", 22), creds); try { ssh.connect(); ExecResponse hello = ssh.exec("echo hello"); diff --git a/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/compute/VirtualBoxComputeServiceAdapterTest.java b/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/compute/VirtualBoxComputeServiceAdapterTest.java index 96d40a535a..71d6a4f302 100644 --- a/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/compute/VirtualBoxComputeServiceAdapterTest.java +++ b/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/compute/VirtualBoxComputeServiceAdapterTest.java @@ -19,9 +19,17 @@ package org.jclouds.virtualbox.compute; -import com.google.common.base.Function; -import com.google.common.collect.Iterators; -import com.google.inject.Guice; +import static org.easymock.EasyMock.expect; +import static org.easymock.classextension.EasyMock.createNiceMock; +import static org.easymock.classextension.EasyMock.replay; +import static org.jclouds.virtualbox.config.VirtualBoxConstants.VIRTUALBOX_IMAGE_PREFIX; +import static org.testng.Assert.assertEquals; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + import org.easymock.EasyMock; import org.jclouds.compute.config.BaseComputeServiceContextModule; import org.jclouds.compute.domain.Image; @@ -37,23 +45,16 @@ import org.virtualbox_4_1.IMachine; import org.virtualbox_4_1.IVirtualBox; import org.virtualbox_4_1.VirtualBoxManager; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import static org.easymock.classextension.EasyMock.expect; -import static org.easymock.classextension.EasyMock.createNiceMock; -import static org.easymock.classextension.EasyMock.replay; -import static org.jclouds.virtualbox.config.VirtualBoxConstants.VIRTUALBOX_IMAGE_PREFIX; -import static org.testng.Assert.assertEquals; +import com.google.common.base.Function; +import com.google.common.collect.Iterators; +import com.google.inject.Guice; @Test(groups = "unit") public class VirtualBoxComputeServiceAdapterTest { Map> osMap = new BaseComputeServiceContextModule() { }.provideOsVersionMap(new ComputeServiceConstants.ReferenceData(), Guice.createInjector(new GsonModule()) - .getInstance(Json.class)); + .getInstance(Json.class)); @Test public void testListImages() throws Exception { @@ -76,14 +77,15 @@ public class VirtualBoxComputeServiceAdapterTest { expect(manager.getVBox()).andReturn(vBox).anyTimes(); expect(vBox.getMachines()).andReturn(machines).anyTimes(); - expect(vBox.getGuestOSType(EasyMock.anyObject())).andReturn(osType).anyTimes(); + expect(vBox.getGuestOSType(EasyMock. anyObject())).andReturn(osType).anyTimes(); expect(osType.getDescription()).andReturn("Ubuntu 10.04").anyTimes(); expect(osType.getIs64Bit()).andReturn(true).anyTimes(); replay(manager, justProvider, vBox, clonedMachine, imageMachine, osType); Function iMachineToImage = new IMachineToImage(manager, osMap); - VirtualBoxComputeServiceAdapter adapter = new VirtualBoxComputeServiceAdapter(manager, justProvider, iMachineToImage); + VirtualBoxComputeServiceAdapter adapter = new VirtualBoxComputeServiceAdapter(manager, justProvider, + iMachineToImage); Iterator iterator = adapter.listImages().iterator(); Image image = Iterators.getOnlyElement(iterator); diff --git a/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/compute/VirtualBoxExperimentLiveTest.java b/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/compute/VirtualBoxExperimentLiveTest.java index afe953a031..996dd31c3d 100644 --- a/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/compute/VirtualBoxExperimentLiveTest.java +++ b/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/compute/VirtualBoxExperimentLiveTest.java @@ -27,7 +27,7 @@ import org.testng.annotations.Test; * @author Adrian Cole */ @Test(groups = "live", testName = "VirtualBoxExperimentLiveTest") -public class VirtualBoxExperimentLiveTest extends BaseVirtualBoxClientLiveTest{ +public class VirtualBoxExperimentLiveTest extends BaseVirtualBoxClientLiveTest { @Test public void testAndExperiment() { diff --git a/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/compute/VirtualBoxTemplateBuilderLiveTest.java b/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/compute/VirtualBoxTemplateBuilderLiveTest.java index 7936318c65..4dad539af0 100644 --- a/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/compute/VirtualBoxTemplateBuilderLiveTest.java +++ b/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/compute/VirtualBoxTemplateBuilderLiveTest.java @@ -34,7 +34,6 @@ import com.google.common.base.Predicate; import com.google.common.base.Predicates; import com.google.common.collect.ImmutableSet; - /** * * @author Andrea Turli @@ -43,40 +42,40 @@ import com.google.common.collect.ImmutableSet; @Test(groups = "live", testName = "VirtualBoxTemplateBuilderLiveTest") public class VirtualBoxTemplateBuilderLiveTest extends BaseTemplateBuilderLiveTest { - public VirtualBoxTemplateBuilderLiveTest() { - provider = "virtualbox"; - } + public VirtualBoxTemplateBuilderLiveTest() { + provider = "virtualbox"; + } - @Override - protected Predicate defineUnsupportedOperatingSystems() { - return Predicates.not(new Predicate() { + @Override + protected Predicate defineUnsupportedOperatingSystems() { + return Predicates.not(new Predicate() { - @Override - public boolean apply(OsFamilyVersion64Bit input) { - switch (input.family) { - case UBUNTU: - return input.version.equals("11.04") && !input.is64Bit; - default: - return false; - } - } + @Override + public boolean apply(OsFamilyVersion64Bit input) { + switch (input.family) { + case UBUNTU: + return input.version.equals("11.04") && !input.is64Bit; + default: + return false; + } + } - }); - } + }); + } - @Test - public void testTemplateBuilder() { - System.out.println(this.context.getComputeService().listImages()); - Template defaultTemplate = this.context.getComputeService().templateBuilder().build(); - assertEquals(defaultTemplate.getImage().getOperatingSystem().is64Bit(), false); - assertEquals(defaultTemplate.getImage().getOperatingSystem().getVersion(), "10.04"); - assertEquals(defaultTemplate.getImage().getOperatingSystem().getFamily(), OsFamily.UBUNTU); - assertEquals(getCores(defaultTemplate.getHardware()), 1.0d); - } + @Test + public void testTemplateBuilder() { + System.out.println(this.context.getComputeService().listImages()); + Template defaultTemplate = this.context.getComputeService().templateBuilder().build(); + assertEquals(defaultTemplate.getImage().getOperatingSystem().is64Bit(), false); + assertEquals(defaultTemplate.getImage().getOperatingSystem().getVersion(), "10.04"); + assertEquals(defaultTemplate.getImage().getOperatingSystem().getFamily(), OsFamily.UBUNTU); + assertEquals(getCores(defaultTemplate.getHardware()), 1.0d); + } - @Override - protected Set getIso3166Codes() { - return ImmutableSet. of(); - } + @Override + protected Set getIso3166Codes() { + return ImmutableSet. of(); + } } diff --git a/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/experiment/SetupVirtualBoxForLiveTest.java b/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/experiment/SetupVirtualBoxForLiveTest.java index 9ed33c02e3..be23f0aa5b 100644 --- a/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/experiment/SetupVirtualBoxForLiveTest.java +++ b/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/experiment/SetupVirtualBoxForLiveTest.java @@ -1,12 +1,8 @@ /** - * - * Copyright (C) 2009 Global Cloud Specialists, Inc. - * - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file + * regarding copyright ownership. jclouds licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at @@ -19,8 +15,8 @@ * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. - * ==================================================================== */ + package org.jclouds.virtualbox.experiment; import static com.google.common.base.Preconditions.checkNotNull; @@ -40,8 +36,8 @@ import org.jclouds.compute.options.RunScriptOptions; import org.jclouds.domain.Credentials; import org.jclouds.logging.Logger; import org.jclouds.virtualbox.config.VirtualBoxConstants; -import org.jclouds.virtualbox.functions.admin.StartVBoxIfNotAlreadyRunning; import org.jclouds.virtualbox.functions.admin.StartJettyIfNotAlreadyRunning; +import org.jclouds.virtualbox.functions.admin.StartVBoxIfNotAlreadyRunning; import org.testng.annotations.AfterSuite; import org.testng.annotations.BeforeSuite; @@ -72,7 +68,7 @@ public class SetupVirtualBoxForLiveTest { private String vboxVersionName; private String basebaseResource; private String port; - + private String vboxWebServerCredential; private String vboxWebServerIdentity; @@ -88,18 +84,18 @@ public class SetupVirtualBoxForLiveTest { public void setupConfigurationProperties() { workingDir = System.getProperty("user.home") + File.separator - + System.getProperty("test." + provider + ".workingDir", "jclouds-virtualbox-test"); + + System.getProperty("test." + provider + ".workingDir", "jclouds-virtualbox-test"); if (new File(workingDir).mkdir()) ; gaIsoName = System.getProperty("test." + provider + ".gaIsoName", "VBoxGuestAdditions_" + majorVersion + ".iso"); gaIsoUrl = URI.create(System.getProperty("test." + provider + ".gaIsoUrl", - "http://download.virtualbox.org/virtualbox/" + majorVersion + "/" + gaIsoName)); + "http://download.virtualbox.org/virtualbox/" + majorVersion + "/" + gaIsoName)); distroIsoName = System.getProperty("test." + provider + ".distroIsoName", "ubuntu-11.04-server-i386.iso"); distroIsoUrl = URI.create(System.getProperty("test." + provider + ".distroIsoUrl", - "http://releases.ubuntu.com/11.04/ubuntu-11.04-server-i386.iso")); + "http://releases.ubuntu.com/11.04/ubuntu-11.04-server-i386.iso")); vboxDmg = URI.create(System.getProperty("test." + provider + ".vboxDmg", - "http://download.virtualbox.org/virtualbox/4.1.2/VirtualBox-4.1.2-73507-OSX.dmg")); + "http://download.virtualbox.org/virtualbox/4.1.2/VirtualBox-4.1.2-73507-OSX.dmg")); vboxVersionName = System.getProperty("test" + provider + ".vboxVersionName", "VirtualBox-4.1.2-73507-OSX.dmg"); basebaseResource = System.getProperty(VirtualBoxConstants.VIRTUALBOX_JETTY_BASE_RESOURCE, "."); port = System.getProperty(VirtualBoxConstants.VIRTUALBOX_JETTY_PORT, "8080"); @@ -120,7 +116,7 @@ public class SetupVirtualBoxForLiveTest { new StartVBoxIfNotAlreadyRunning(context, hostId, new Credentials(vboxWebServerIdentity, vboxWebServerCredential)); new StartJettyIfNotAlreadyRunning(port).apply(basebaseResource); } - + @AfterSuite public void stopVboxWebServer() throws IOException { runScriptOnNode(hostId, "pidof vboxwebsrv | xargs kill"); @@ -133,29 +129,29 @@ public class SetupVirtualBoxForLiveTest { downloadFileUnlessPresent(vboxDmg, workingDir, vboxVersionName); runScriptOnNode(hostId, "hdiutil attach " + workingDir + "/" + vboxVersionName); runScriptOnNode(hostId, - "installer -pkg /Volumes/VirtualBox/VirtualBox.mpkg -target /Volumes/Macintosh\\ HD"); + "installer -pkg /Volumes/VirtualBox/VirtualBox.mpkg -target /Volumes/Macintosh\\ HD"); } else { // TODO other platforms runScriptOnNode(hostId, "cat > /etc/apt/sources.list.d/TODO"); runScriptOnNode(hostId, - "wget -q http://download.virtualbox.org/virtualbox/debian/oracle_vbox.asc -O- | apt-key add -"); + "wget -q http://download.virtualbox.org/virtualbox/debian/oracle_vbox.asc -O- | apt-key add -"); runScriptOnNode(hostId, "apt-get update"); runScriptOnNode(hostId, "apt-get --yes install virtualbox-4.1"); } } } - public void checkVboxVersionExpected() throws IOException, InterruptedException { + public void checkVboxVersionExpected() throws IOException, InterruptedException { logger().debug("checking virtualbox version"); assertEquals(runScriptOnNode(hostId, "VBoxManage -version").getOutput().trim(), apiVersion); } public boolean isOSX(String id) { - return context.getComputeService().getNodeMetadata(hostId).getOperatingSystem().getDescription().equals( - "Mac OS X"); + return context.getComputeService().getNodeMetadata(hostId).getOperatingSystem().getDescription() + .equals("Mac OS X"); } - public File downloadFileUnlessPresent(URI sourceURL, String destinationDir, String filename) throws Exception { + public File downloadFileUnlessPresent(URI sourceURL, String destinationDir, String filename) throws Exception { File iso = new File(destinationDir, filename); diff --git a/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/experiment/TestUtils.java b/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/experiment/TestUtils.java index 2c27a5a80c..38def58dac 100644 --- a/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/experiment/TestUtils.java +++ b/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/experiment/TestUtils.java @@ -18,10 +18,11 @@ */ package org.jclouds.virtualbox.experiment; -import com.google.common.cache.Cache; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.ImmutableSet; -import com.google.inject.Module; +import java.io.IOException; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.Map; + import org.jclouds.byon.Node; import org.jclouds.byon.config.CacheNodeStoreModule; import org.jclouds.compute.ComputeServiceContext; @@ -31,75 +32,48 @@ import org.jclouds.domain.Credentials; import org.jclouds.encryption.bouncycastle.config.BouncyCastleCryptoModule; import org.jclouds.logging.slf4j.config.SLF4JLoggingModule; import org.jclouds.sshj.config.SshjSshClientModule; -import org.jclouds.virtualbox.config.VirtualBoxConstants; -import java.io.IOException; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.Map; +import com.google.common.cache.Cache; +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.ImmutableSet; +import com.google.inject.Module; public class TestUtils { public static ComputeServiceContext computeServiceForLocalhostAndGuest() throws IOException { - Node host = Node.builder().id("host") - .name("host installing virtualbox") - .hostname("localhost") - .osFamily(OsFamily.LINUX.toString()) - .osDescription(System.getProperty("os.name")) - .osVersion(System.getProperty("os.version")) - .group("ssh") - .username(System.getProperty("user.name")) - .credentialUrl(privateKeyFile()) - .build(); - Node guest = Node.builder().id("guest") - .name("new guest") - .hostname("localhost") - .loginPort(2222) - .osFamily(OsFamily.UBUNTU.toString()) - .osDescription("ubuntu/11.04") - .osVersion(System.getProperty("11.04")) - .group("guest") - .username("toor") - .sudoPassword("password") - .credential("password") - .build(); + Node host = Node.builder().id("host").name("host installing virtualbox").hostname("localhost") + .osFamily(OsFamily.LINUX.toString()).osDescription(System.getProperty("os.name")) + .osVersion(System.getProperty("os.version")).group("ssh").username(System.getProperty("user.name")) + .credentialUrl(privateKeyFile()).build(); + Node guest = Node.builder().id("guest").name("new guest").hostname("localhost").loginPort(2222) + .osFamily(OsFamily.UBUNTU.toString()).osDescription("ubuntu/11.04").osVersion(System.getProperty("11.04")) + .group("guest").username("toor").sudoPassword("password").credential("password").build(); - final Map nodeMap = ImmutableMap.builder().put("host", host).put("guest", guest).build(); - return new ComputeServiceContextFactory().createContext("byon", "foo", "bar", ImmutableSet.of( - new SshjSshClientModule(), new SLF4JLoggingModule(), new BouncyCastleCryptoModule(), new CacheNodeStoreModule(nodeMap))); + final Map nodeMap = ImmutableMap. builder().put("host", host).put("guest", guest) + .build(); + return new ComputeServiceContextFactory().createContext("byon", "foo", "bar", ImmutableSet. of( + new SshjSshClientModule(), new SLF4JLoggingModule(), new BouncyCastleCryptoModule(), + new CacheNodeStoreModule(nodeMap))); } - public static ComputeServiceContext computeServiceForLocalhostAndGuest(String hostId, String hostname, String guestId, String guestHostname, - Credentials guestLogin) throws IOException { + public static ComputeServiceContext computeServiceForLocalhostAndGuest(String hostId, String hostname, + String guestId, String guestHostname, Credentials guestLogin) throws IOException { - Node host = Node.builder().id(hostId) - .name("host installing virtualbox") - .hostname(hostname) - .osFamily(OsFamily.LINUX.toString()) - .osDescription(System.getProperty("os.name")) - .osVersion(System.getProperty("os.version")) - .group("ssh") - .username(System.getProperty("user.name")) - .credentialUrl(privateKeyFile()) - .build(); - Node guest = Node.builder().id(guestId) - .name("new guest") - .hostname(guestHostname) - .loginPort(2222) - .osFamily(OsFamily.UBUNTU.toString()) - .osDescription("ubuntu/11.04") - .osVersion(System.getProperty("11.04")) - .group("jclouds-linux-image") - .username(guestLogin.identity) - .sudoPassword(guestLogin.credential) - .credential(guestLogin.credential) - .build(); + Node host = Node.builder().id(hostId).name("host installing virtualbox").hostname(hostname) + .osFamily(OsFamily.LINUX.toString()).osDescription(System.getProperty("os.name")) + .osVersion(System.getProperty("os.version")).group("ssh").username(System.getProperty("user.name")) + .credentialUrl(privateKeyFile()).build(); + Node guest = Node.builder().id(guestId).name("new guest").hostname(guestHostname).loginPort(2222) + .osFamily(OsFamily.UBUNTU.toString()).osDescription("ubuntu/11.04").osVersion(System.getProperty("11.04")) + .group("jclouds-linux-image").username(guestLogin.identity).sudoPassword(guestLogin.credential) + .credential(guestLogin.credential).build(); - - final Map nodeMap = ImmutableMap.builder().put(hostId, host).put(guestId, guest).build(); - return new ComputeServiceContextFactory().createContext("byon", "foo", "bar", ImmutableSet.of( - new SshjSshClientModule(), new SLF4JLoggingModule(), new BouncyCastleCryptoModule(), new CacheNodeStoreModule(nodeMap))); + final Map nodeMap = ImmutableMap. builder().put(hostId, host).put(guestId, guest) + .build(); + return new ComputeServiceContextFactory().createContext("byon", "foo", "bar", ImmutableSet. of( + new SshjSshClientModule(), new SLF4JLoggingModule(), new BouncyCastleCryptoModule(), + new CacheNodeStoreModule(nodeMap))); } private static URI privateKeyFile() { @@ -112,7 +86,8 @@ public class TestUtils { } public static ComputeServiceContext computeServiceForVirtualBox(Cache cache) { - return new ComputeServiceContextFactory().createContext("byon", "foo", "bar", ImmutableSet.of( - new SshjSshClientModule(), new SLF4JLoggingModule(), new BouncyCastleCryptoModule(), new CacheNodeStoreModule(cache))); + return new ComputeServiceContextFactory().createContext("byon", "foo", "bar", ImmutableSet. of( + new SshjSshClientModule(), new SLF4JLoggingModule(), new BouncyCastleCryptoModule(), + new CacheNodeStoreModule(cache))); } } diff --git a/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/ApplyMemoryToMachineTest.java b/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/ApplyMemoryToMachineTest.java index fee8274493..1e0894736e 100644 --- a/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/ApplyMemoryToMachineTest.java +++ b/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/ApplyMemoryToMachineTest.java @@ -1,4 +1,4 @@ -/* +/** * Licensed to jclouds, Inc. (jclouds) under one or more * contributor license agreements. See the NOTICE file * distributed with this work for additional information @@ -19,12 +19,16 @@ package org.jclouds.virtualbox.functions; +import static org.easymock.EasyMock.expectLastCall; +import static org.easymock.classextension.EasyMock.createMock; +import static org.easymock.classextension.EasyMock.createNiceMock; +import static org.easymock.classextension.EasyMock.replay; +import static org.easymock.classextension.EasyMock.verify; + import org.testng.annotations.Test; import org.virtualbox_4_1.IMachine; import org.virtualbox_4_1.VBoxException; -import static org.easymock.classextension.EasyMock.*; - /** * @author Mattias Holmqvist */ @@ -49,8 +53,8 @@ public class ApplyMemoryToMachineTest { @Test(expectedExceptions = VBoxException.class) public void testRethrowInvalidRamSizeError() throws Exception { // Mainly here for documentation purposes - final String error = "VirtualBox error: Invalid RAM size: " + - "3567587327 MB (must be in range [4, 2097152] MB) (0x80070057)"; + final String error = "VirtualBox error: Invalid RAM size: " + + "3567587327 MB (must be in range [4, 2097152] MB) (0x80070057)"; long memorySize = 1024l; IMachine machine = createMock(IMachine.class); diff --git a/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/AttachDistroMediumToMachineTest.java b/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/AttachDistroMediumToMachineTest.java index 6e7544f0b0..e4cd4af4e4 100644 --- a/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/AttachDistroMediumToMachineTest.java +++ b/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/AttachDistroMediumToMachineTest.java @@ -18,15 +18,18 @@ */ package org.jclouds.virtualbox.functions; +import static org.easymock.EasyMock.expectLastCall; +import static org.easymock.classextension.EasyMock.createMock; +import static org.easymock.classextension.EasyMock.createNiceMock; +import static org.easymock.classextension.EasyMock.replay; +import static org.easymock.classextension.EasyMock.verify; + import org.testng.annotations.Test; import org.virtualbox_4_1.DeviceType; import org.virtualbox_4_1.IMachine; import org.virtualbox_4_1.IMedium; import org.virtualbox_4_1.VBoxException; -import static org.easymock.classextension.EasyMock.*; - - /** * @author Mattias Holmqvist */ @@ -67,7 +70,8 @@ public class AttachDistroMediumToMachineTest { errorBuilder.append("of this virtual machine (0x80BB000C)"); String isoAlreadyAttachedException = errorBuilder.toString(); - VBoxException isoAttachedException = new VBoxException(createNiceMock(Throwable.class), isoAlreadyAttachedException); + VBoxException isoAttachedException = new VBoxException(createNiceMock(Throwable.class), + isoAlreadyAttachedException); machine.attachDevice(controllerIDE, 0, 0, DeviceType.DVD, distroMedium); expectLastCall().andThrow(isoAttachedException); @@ -92,7 +96,8 @@ public class AttachDistroMediumToMachineTest { errorBuilder.append("Some other VBox error"); String isoAlreadyAttachedException = errorBuilder.toString(); - VBoxException isoAttachedException = new VBoxException(createNiceMock(Throwable.class), isoAlreadyAttachedException); + VBoxException isoAttachedException = new VBoxException(createNiceMock(Throwable.class), + isoAlreadyAttachedException); machine.attachDevice(controllerIDE, 0, 0, DeviceType.DVD, distroMedium); expectLastCall().andThrow(isoAttachedException); @@ -102,5 +107,4 @@ public class AttachDistroMediumToMachineTest { } - } diff --git a/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/AttachMediumToMachineIfNotAlreadyAttachedTest.java b/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/AttachMediumToMachineIfNotAlreadyAttachedTest.java index c684c44028..b4889b01b3 100644 --- a/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/AttachMediumToMachineIfNotAlreadyAttachedTest.java +++ b/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/AttachMediumToMachineIfNotAlreadyAttachedTest.java @@ -19,12 +19,23 @@ package org.jclouds.virtualbox.functions; -import org.testng.annotations.Test; -import org.virtualbox_4_1.*; - -import static org.easymock.classextension.EasyMock.*; +import static org.easymock.EasyMock.anyLong; +import static org.easymock.EasyMock.expect; +import static org.easymock.EasyMock.expectLastCall; +import static org.easymock.classextension.EasyMock.createMock; +import static org.easymock.classextension.EasyMock.createNiceMock; +import static org.easymock.classextension.EasyMock.replay; +import static org.easymock.classextension.EasyMock.verify; import static org.virtualbox_4_1.DeviceType.HardDisk; +import org.testng.annotations.Test; +import org.virtualbox_4_1.IMachine; +import org.virtualbox_4_1.IMedium; +import org.virtualbox_4_1.IProgress; +import org.virtualbox_4_1.IVirtualBox; +import org.virtualbox_4_1.VBoxException; +import org.virtualbox_4_1.VirtualBoxManager; + /** * @author Mattias Holmqvist */ @@ -54,7 +65,8 @@ public class AttachMediumToMachineIfNotAlreadyAttachedTest { machine.saveSettings(); replay(manager, machine, vBox, hardDisk); - new AttachMediumToMachineIfNotAlreadyAttached(controllerIDE, hardDisk, controllerPort, device, HardDisk).apply(machine); + new AttachMediumToMachineIfNotAlreadyAttached(controllerIDE, hardDisk, controllerPort, device, HardDisk) + .apply(machine); verify(machine); @@ -79,13 +91,15 @@ public class AttachMediumToMachineIfNotAlreadyAttachedTest { errorBuilder.append("of this virtual machine (0x80BB000C)"); String isoAlreadyAttachedException = errorBuilder.toString(); - VBoxException isoAttachedException = new VBoxException(createNiceMock(Throwable.class), isoAlreadyAttachedException); + VBoxException isoAttachedException = new VBoxException(createNiceMock(Throwable.class), + isoAlreadyAttachedException); machine.attachDevice(controllerIDE, controllerPort, device, HardDisk, hardDisk); expectLastCall().andThrow(isoAttachedException); replay(manager, machine, vBox, hardDisk); - new AttachMediumToMachineIfNotAlreadyAttached(controllerIDE, hardDisk, controllerPort, device, HardDisk).apply(machine); + new AttachMediumToMachineIfNotAlreadyAttached(controllerIDE, hardDisk, controllerPort, device, HardDisk) + .apply(machine); verify(machine); @@ -108,13 +122,15 @@ public class AttachMediumToMachineIfNotAlreadyAttachedTest { errorBuilder.append("Some other VBox error"); String isoAlreadyAttachedException = errorBuilder.toString(); - VBoxException isoAttachedException = new VBoxException(createNiceMock(Throwable.class), isoAlreadyAttachedException); + VBoxException isoAttachedException = new VBoxException(createNiceMock(Throwable.class), + isoAlreadyAttachedException); machine.attachDevice(controllerIDE, controllerPort, device, HardDisk, hardDisk); expectLastCall().andThrow(isoAttachedException); replay(manager, machine, vBox, hardDisk); - new AttachMediumToMachineIfNotAlreadyAttached(controllerIDE, hardDisk, controllerPort, device, HardDisk).apply(machine); + new AttachMediumToMachineIfNotAlreadyAttached(controllerIDE, hardDisk, controllerPort, device, HardDisk) + .apply(machine); } diff --git a/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/AttachNATRedirectRuleToMachineTest.java b/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/AttachNATRedirectRuleToMachineTest.java index be7cdd1fda..22321e9aad 100644 --- a/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/AttachNATRedirectRuleToMachineTest.java +++ b/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/AttachNATRedirectRuleToMachineTest.java @@ -1,4 +1,4 @@ -/* +/** * Licensed to jclouds, Inc. (jclouds) under one or more * contributor license agreements. See the NOTICE file * distributed with this work for additional information @@ -19,13 +19,20 @@ package org.jclouds.virtualbox.functions; -import org.testng.annotations.Test; -import org.virtualbox_4_1.*; - -import static org.easymock.classextension.EasyMock.*; +import static org.easymock.EasyMock.expect; +import static org.easymock.classextension.EasyMock.createMock; +import static org.easymock.classextension.EasyMock.createNiceMock; +import static org.easymock.classextension.EasyMock.replay; +import static org.easymock.classextension.EasyMock.verify; import static org.virtualbox_4_1.NATProtocol.TCP; import static org.virtualbox_4_1.NetworkAttachmentType.NAT; +import org.testng.annotations.Test; +import org.virtualbox_4_1.IMachine; +import org.virtualbox_4_1.INATEngine; +import org.virtualbox_4_1.INetworkAdapter; +import org.virtualbox_4_1.VBoxException; + /** * @author Mattias Holmqvist */ @@ -60,8 +67,8 @@ public class AttachNATRedirectRuleToMachineTest { INetworkAdapter networkAdapter = createMock(INetworkAdapter.class); INATEngine natEngine = createMock(INATEngine.class); - String error = "VirtualBox error: Argument slot is invalid " + - "(must be slot < RT_ELEMENTS(mNetworkAdapters)) (0x80070057)"; + String error = "VirtualBox error: Argument slot is invalid " + + "(must be slot < RT_ELEMENTS(mNetworkAdapters)) (0x80070057)"; VBoxException invalidSlotException = new VBoxException(createNiceMock(Throwable.class), error); expect(machine.getNetworkAdapter(adapterId)).andThrow(invalidSlotException); @@ -73,5 +80,4 @@ public class AttachNATRedirectRuleToMachineTest { verify(machine, networkAdapter, natEngine); } - } diff --git a/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/CreateAndRegisterMachineFromIsoIfNotAlreadyExistsTest.java b/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/CreateAndRegisterMachineFromIsoIfNotAlreadyExistsTest.java index 890430de89..0cbd5d9126 100644 --- a/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/CreateAndRegisterMachineFromIsoIfNotAlreadyExistsTest.java +++ b/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/CreateAndRegisterMachineFromIsoIfNotAlreadyExistsTest.java @@ -19,6 +19,15 @@ package org.jclouds.virtualbox.functions; +import static org.easymock.EasyMock.anyBoolean; +import static org.easymock.EasyMock.eq; +import static org.easymock.EasyMock.expect; +import static org.easymock.EasyMock.expectLastCall; +import static org.easymock.classextension.EasyMock.createMock; +import static org.easymock.classextension.EasyMock.createNiceMock; +import static org.easymock.classextension.EasyMock.replay; +import static org.easymock.classextension.EasyMock.verify; + import org.easymock.EasyMock; import org.testng.annotations.Test; import org.virtualbox_4_1.IMachine; @@ -26,10 +35,6 @@ import org.virtualbox_4_1.IVirtualBox; import org.virtualbox_4_1.VBoxException; import org.virtualbox_4_1.VirtualBoxManager; -import static org.easymock.EasyMock.anyBoolean; -import static org.easymock.EasyMock.expect; -import static org.easymock.classextension.EasyMock.*; - /** * @author Mattias Holmqvist */ @@ -55,9 +60,10 @@ public class CreateAndRegisterMachineFromIsoIfNotAlreadyExistsTest { vBox.findMachine(vmName); expectLastCall().andThrow(vBoxException); - - expect(vBox.createMachine(anyString(), eq(vmName), anyString(), anyString(), anyBoolean())).andReturn(createdMachine).anyTimes(); - + + expect(vBox.createMachine(anyString(), eq(vmName), anyString(), anyString(), anyBoolean())).andReturn( + createdMachine).anyTimes(); + vBox.registerMachine(createdMachine); replay(manager, vBox); @@ -103,10 +109,9 @@ public class CreateAndRegisterMachineFromIsoIfNotAlreadyExistsTest { new CreateAndRegisterMachineFromIsoIfNotAlreadyExists("", "", "", false, manager).apply(vmName); - } private String anyString() { - return EasyMock.anyObject(); + return EasyMock. anyObject(); } } diff --git a/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/CreateMediumIfNotAlreadyExistsTest.java b/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/CreateMediumIfNotAlreadyExistsTest.java index 240bb60fd7..5d6ff30f33 100644 --- a/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/CreateMediumIfNotAlreadyExistsTest.java +++ b/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/CreateMediumIfNotAlreadyExistsTest.java @@ -19,14 +19,23 @@ package org.jclouds.virtualbox.functions; -import org.testng.annotations.Test; -import org.virtualbox_4_1.*; - import static org.easymock.EasyMock.anyLong; import static org.easymock.EasyMock.expect; -import static org.easymock.classextension.EasyMock.*; +import static org.easymock.classextension.EasyMock.createMock; +import static org.easymock.classextension.EasyMock.createNiceMock; +import static org.easymock.classextension.EasyMock.replay; +import static org.easymock.classextension.EasyMock.verify; import static org.testng.Assert.assertNotSame; +import org.testng.annotations.Test; +import org.virtualbox_4_1.DeviceType; +import org.virtualbox_4_1.IMachine; +import org.virtualbox_4_1.IMedium; +import org.virtualbox_4_1.IProgress; +import org.virtualbox_4_1.IVirtualBox; +import org.virtualbox_4_1.VBoxException; +import org.virtualbox_4_1.VirtualBoxManager; + /** * @author Mattias Holmqvist */ @@ -137,5 +146,4 @@ public class CreateMediumIfNotAlreadyExistsTest { new CreateMediumIfNotAlreadyExists(manager, diskFormat, true).apply(adminDiskPath); } - } diff --git a/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/IMachineToNodeMetadataTest.java b/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/IMachineToNodeMetadataTest.java index 6c706156fa..62c454f19d 100644 --- a/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/IMachineToNodeMetadataTest.java +++ b/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/IMachineToNodeMetadataTest.java @@ -33,7 +33,6 @@ import org.virtualbox_4_1.VirtualBoxManager; import com.google.common.collect.ImmutableSet; -//@Test(groups = "live") public class IMachineToNodeMetadataTest { @Test diff --git a/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/IsoToIMachineLiveTest.java b/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/IsoToIMachineLiveTest.java index 98cce45b41..eb7286d382 100644 --- a/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/IsoToIMachineLiveTest.java +++ b/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/IsoToIMachineLiveTest.java @@ -19,10 +19,6 @@ package org.jclouds.virtualbox.functions; -/** - * @author Andrea Turli, Mattias Holmqvist - */ - import static com.google.common.base.Predicates.equalTo; import static com.google.common.collect.Iterables.any; import static org.jclouds.virtualbox.experiment.TestUtils.computeServiceForLocalhostAndGuest; @@ -47,13 +43,16 @@ import org.virtualbox_4_1.VirtualBoxManager; import com.google.inject.Guice; +/** + * @author Andrea Turli, Mattias Holmqvist + */ @Test(groups = "live", singleThreaded = true, testName = "IsoToIMachineLiveTest") public class IsoToIMachineLiveTest extends BaseVirtualBoxClientLiveTest { - + Map> map = new BaseComputeServiceContextModule() { }.provideOsVersionMap(new ComputeServiceConstants.ReferenceData(), Guice.createInjector(new GsonModule()) - .getInstance(Json.class)); - + .getInstance(Json.class)); + private String settingsFile = null; private boolean forceOverwrite = true; private String vmId = "jclouds-image-iso-1"; @@ -76,24 +75,16 @@ public class IsoToIMachineLiveTest extends BaseVirtualBoxClientLiveTest { public void testCreateImageMachineFromIso() throws Exception { VirtualBoxManager manager = (VirtualBoxManager) context.getProviderSpecificContext().getApi(); - ComputeServiceContext localHostContext = computeServiceForLocalhostAndGuest(hostId, "localhost", guestId, "localhost", new Credentials("toor", "password")); - IMachine imageMachine = new IsoToIMachine(manager, - adminDisk, - diskFormat, - settingsFile, - vmName, - osTypeId, - vmId, - forceOverwrite, - controllerIDE, - localHostContext, - hostId, - guestId, - new Credentials("toor", "password")).apply("ubuntu-11.04-server-i386.iso"); + ComputeServiceContext localHostContext = computeServiceForLocalhostAndGuest(hostId, "localhost", guestId, + "localhost", new Credentials("toor", "password")); + IMachine imageMachine = new IsoToIMachine(manager, adminDisk, diskFormat, settingsFile, vmName, osTypeId, vmId, + forceOverwrite, controllerIDE, localHostContext, hostId, guestId, new Credentials("toor", "password")) + .apply("ubuntu-11.04-server-i386.iso"); IMachineToImage iMachineToImage = new IMachineToImage(manager, map); Image newImage = iMachineToImage.apply(imageMachine); - //TODO add the description to the cache of the images or serialize to YAML the image desc + // TODO add the description to the cache of the images or serialize to + // YAML the image desc Set images = context.getComputeService().listImages(); assertTrue(any(images, equalTo(newImage))); diff --git a/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/LaunchMachineIfNotAlreadyRunningTest.java b/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/LaunchMachineIfNotAlreadyRunningTest.java index c512905735..e18781d585 100644 --- a/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/LaunchMachineIfNotAlreadyRunningTest.java +++ b/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/LaunchMachineIfNotAlreadyRunningTest.java @@ -19,6 +19,11 @@ package org.jclouds.virtualbox.functions; +import static org.easymock.EasyMock.expect; +import static org.easymock.classextension.EasyMock.createMock; +import static org.easymock.classextension.EasyMock.replay; +import static org.easymock.classextension.EasyMock.verify; + import org.jclouds.virtualbox.domain.ExecutionType; import org.testng.annotations.Test; import org.virtualbox_4_1.IMachine; @@ -26,11 +31,6 @@ import org.virtualbox_4_1.IProgress; import org.virtualbox_4_1.ISession; import org.virtualbox_4_1.VirtualBoxManager; -import static org.easymock.classextension.EasyMock.verify; -import static org.easymock.classextension.EasyMock.replay; -import static org.easymock.classextension.EasyMock.createMock; -import static org.easymock.classextension.EasyMock.expect; - @Test(groups = "unit", testName = "LaunchMachineIfNotAlreadyRunningTest") public class LaunchMachineIfNotAlreadyRunningTest { @@ -39,9 +39,10 @@ public class LaunchMachineIfNotAlreadyRunningTest { } -// VirtualBox error: The given session is busy (0x80BB0007) -// VirtualBox error: The machine 'jclouds-image-virtualbox-iso-to-machine-test' is not registered (0x8000FFFF) - + // VirtualBox error: The given session is busy (0x80BB0007) + // VirtualBox error: The machine + // 'jclouds-image-virtualbox-iso-to-machine-test' is not registered + // (0x8000FFFF) @Test public void testLaunchIfNotStarted() throws Exception { diff --git a/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/admin/ImageFromYamlStreamTest.java b/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/admin/ImageFromYamlStreamTest.java index 6ada15cb17..3061979225 100644 --- a/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/admin/ImageFromYamlStreamTest.java +++ b/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/admin/ImageFromYamlStreamTest.java @@ -1,3 +1,22 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + package org.jclouds.virtualbox.functions.admin; import static org.testng.Assert.assertEquals; @@ -13,23 +32,6 @@ import org.testng.annotations.Test; import com.google.common.collect.ImmutableMap; /** - * - * Licensed to jclouds, Inc. (jclouds) under one or more contributor license - * agreements. See the NOTICE file distributed with this work for additional - * information regarding copyright ownership. jclouds licenses this file to you - * under the Apache License, Version 2.0 (the "License"); you may not use this - * file except in compliance with the License. You may obtain a copy of the - * License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. - * - * * @author Andrea Turli */ @Test(groups = "unit") diff --git a/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/admin/StartJettyIfNotAlreadyRunningLiveTest.java b/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/admin/StartJettyIfNotAlreadyRunningLiveTest.java index 502348fcea..d9b3f8d08f 100644 --- a/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/admin/StartJettyIfNotAlreadyRunningLiveTest.java +++ b/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/admin/StartJettyIfNotAlreadyRunningLiveTest.java @@ -19,17 +19,15 @@ package org.jclouds.virtualbox.functions.admin; -/** - * @author Andrea Turli - */ - import static org.testng.Assert.assertEquals; import org.eclipse.jetty.server.Server; import org.jclouds.virtualbox.BaseVirtualBoxClientLiveTest; import org.testng.annotations.Test; - +/** + * @author Andrea Turli + */ @Test(groups = "live", singleThreaded = true, testName = "StartJettyIfNotAlreadyRunningLiveTest") public class StartJettyIfNotAlreadyRunningLiveTest extends BaseVirtualBoxClientLiveTest { @@ -42,7 +40,7 @@ public class StartJettyIfNotAlreadyRunningLiveTest extends BaseVirtualBoxClientL server.stop(); assertEquals(server.getState(), server.STOPPED); } - + @Test public void testLaunchingSameJettyServer() throws Exception { Server server = new StartJettyIfNotAlreadyRunning(port).apply(basebaseResource); diff --git a/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/admin/StartVBoxIfNotAlreadyRunningLiveTest.java b/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/admin/StartVBoxIfNotAlreadyRunningLiveTest.java index d73f59bb18..d87dad2aec 100644 --- a/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/admin/StartVBoxIfNotAlreadyRunningLiveTest.java +++ b/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/admin/StartVBoxIfNotAlreadyRunningLiveTest.java @@ -16,31 +16,33 @@ * specific language governing permissions and limitations * under the License. */ + package org.jclouds.virtualbox.functions.admin; -import org.jclouds.compute.ComputeServiceContext; -import org.jclouds.domain.Credentials; -import org.jclouds.virtualbox.functions.admin.StartVBoxIfNotAlreadyRunning; -import org.testng.annotations.Test; -import org.virtualbox_4_1.SessionState; -import org.virtualbox_4_1.VirtualBoxManager; - -import java.net.URI; - import static org.jclouds.virtualbox.experiment.TestUtils.computeServiceForLocalhostAndGuest; import static org.testng.Assert.assertEquals; +import java.net.URI; + +import org.jclouds.compute.ComputeServiceContext; +import org.jclouds.domain.Credentials; +import org.testng.annotations.Test; +import org.virtualbox_4_1.SessionState; +import org.virtualbox_4_1.VirtualBoxManager; + @Test(groups = "live", singleThreaded = true, testName = "startVBoxIfNotAlreadyRunningLiveTest") public class StartVBoxIfNotAlreadyRunningLiveTest { @Test public void testStartVbox() throws Exception { Credentials localhostCredentials = new Credentials("toor", "password"); - ComputeServiceContext localHostContext = computeServiceForLocalhostAndGuest("hostId", "localhost", "guestId", "localhost", localhostCredentials); + ComputeServiceContext localHostContext = computeServiceForLocalhostAndGuest("hostId", "localhost", "guestId", + "localhost", localhostCredentials); URI endpointUri = URI.create("http://localhost:18083/"); - VirtualBoxManager manager = new StartVBoxIfNotAlreadyRunning(localHostContext, "hostId", localhostCredentials).apply(endpointUri); + VirtualBoxManager manager = new StartVBoxIfNotAlreadyRunning(localHostContext, "hostId", localhostCredentials) + .apply(endpointUri); assertEquals(manager.getSessionObject().getState(), SessionState.Unlocked); } From 00c47eeab20a90e8b8146c6ea347a85ba2c6f44f Mon Sep 17 00:00:00 2001 From: Adrian Cole Date: Sat, 29 Oct 2011 12:28:02 +0200 Subject: [PATCH 13/16] removed tests that are too confusing to troubleshoot at this stage of development --- .../VirtualBoxTemplateBuilderLiveTest.java | 81 -------- .../SetupVirtualBoxForLiveTest.java | 180 ------------------ 2 files changed, 261 deletions(-) delete mode 100644 sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/compute/VirtualBoxTemplateBuilderLiveTest.java delete mode 100644 sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/experiment/SetupVirtualBoxForLiveTest.java diff --git a/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/compute/VirtualBoxTemplateBuilderLiveTest.java b/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/compute/VirtualBoxTemplateBuilderLiveTest.java deleted file mode 100644 index 4dad539af0..0000000000 --- a/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/compute/VirtualBoxTemplateBuilderLiveTest.java +++ /dev/null @@ -1,81 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.jclouds.virtualbox.compute; - -import static org.jclouds.compute.util.ComputeServiceUtils.getCores; -import static org.testng.Assert.assertEquals; - -import java.util.Set; - -import org.jclouds.compute.BaseTemplateBuilderLiveTest; -import org.jclouds.compute.domain.OsFamily; -import org.jclouds.compute.domain.OsFamilyVersion64Bit; -import org.jclouds.compute.domain.Template; -import org.testng.annotations.Test; - -import com.google.common.base.Predicate; -import com.google.common.base.Predicates; -import com.google.common.collect.ImmutableSet; - -/** - * - * @author Andrea Turli - */ - -@Test(groups = "live", testName = "VirtualBoxTemplateBuilderLiveTest") -public class VirtualBoxTemplateBuilderLiveTest extends BaseTemplateBuilderLiveTest { - - public VirtualBoxTemplateBuilderLiveTest() { - provider = "virtualbox"; - } - - @Override - protected Predicate defineUnsupportedOperatingSystems() { - return Predicates.not(new Predicate() { - - @Override - public boolean apply(OsFamilyVersion64Bit input) { - switch (input.family) { - case UBUNTU: - return input.version.equals("11.04") && !input.is64Bit; - default: - return false; - } - } - - }); - } - - @Test - public void testTemplateBuilder() { - System.out.println(this.context.getComputeService().listImages()); - Template defaultTemplate = this.context.getComputeService().templateBuilder().build(); - assertEquals(defaultTemplate.getImage().getOperatingSystem().is64Bit(), false); - assertEquals(defaultTemplate.getImage().getOperatingSystem().getVersion(), "10.04"); - assertEquals(defaultTemplate.getImage().getOperatingSystem().getFamily(), OsFamily.UBUNTU); - assertEquals(getCores(defaultTemplate.getHardware()), 1.0d); - } - - @Override - protected Set getIso3166Codes() { - return ImmutableSet. of(); - } - -} diff --git a/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/experiment/SetupVirtualBoxForLiveTest.java b/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/experiment/SetupVirtualBoxForLiveTest.java deleted file mode 100644 index be23f0aa5b..0000000000 --- a/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/experiment/SetupVirtualBoxForLiveTest.java +++ /dev/null @@ -1,180 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.jclouds.virtualbox.experiment; - -import static com.google.common.base.Preconditions.checkNotNull; -import static org.jclouds.compute.options.RunScriptOptions.Builder.runAsRoot; -import static org.jclouds.compute.options.RunScriptOptions.Builder.wrapInInitScript; -import static org.testng.Assert.assertEquals; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.net.URI; - -import org.jclouds.compute.ComputeServiceContext; -import org.jclouds.compute.domain.ExecResponse; -import org.jclouds.compute.options.RunScriptOptions; -import org.jclouds.domain.Credentials; -import org.jclouds.logging.Logger; -import org.jclouds.virtualbox.config.VirtualBoxConstants; -import org.jclouds.virtualbox.functions.admin.StartJettyIfNotAlreadyRunning; -import org.jclouds.virtualbox.functions.admin.StartVBoxIfNotAlreadyRunning; -import org.testng.annotations.AfterSuite; -import org.testng.annotations.BeforeSuite; - -import com.google.common.base.Splitter; -import com.google.common.collect.Iterables; -import com.google.common.io.ByteStreams; -import com.google.common.io.Closeables; - -public class SetupVirtualBoxForLiveTest { - - private String provider = "virtualbox"; - private URI endpoint; - private String apiVersion; - - private String workingDir; - - private URI gaIsoUrl; - - private String gaIsoName; - private URI distroIsoUrl; - private String distroIsoName; - - private ComputeServiceContext context; - private String hostId = "host"; - private String guestId = "guest"; - private String majorVersion; - private URI vboxDmg; - private String vboxVersionName; - private String basebaseResource; - private String port; - - private String vboxWebServerCredential; - private String vboxWebServerIdentity; - - public void setupCredentials() { - endpoint = URI.create(System.getProperty("test." + provider + ".endpoint", "http://localhost:18083/")); - apiVersion = System.getProperty("test." + provider + ".apiversion", "4.1.2r73507"); - majorVersion = Iterables.get(Splitter.on('r').split(apiVersion), 0); - } - - public Logger logger() { - return context.utils().loggerFactory().getLogger("jclouds.compute"); - } - - public void setupConfigurationProperties() { - workingDir = System.getProperty("user.home") + File.separator - + System.getProperty("test." + provider + ".workingDir", "jclouds-virtualbox-test"); - if (new File(workingDir).mkdir()) - ; - gaIsoName = System.getProperty("test." + provider + ".gaIsoName", "VBoxGuestAdditions_" + majorVersion + ".iso"); - gaIsoUrl = URI.create(System.getProperty("test." + provider + ".gaIsoUrl", - "http://download.virtualbox.org/virtualbox/" + majorVersion + "/" + gaIsoName)); - - distroIsoName = System.getProperty("test." + provider + ".distroIsoName", "ubuntu-11.04-server-i386.iso"); - distroIsoUrl = URI.create(System.getProperty("test." + provider + ".distroIsoUrl", - "http://releases.ubuntu.com/11.04/ubuntu-11.04-server-i386.iso")); - vboxDmg = URI.create(System.getProperty("test." + provider + ".vboxDmg", - "http://download.virtualbox.org/virtualbox/4.1.2/VirtualBox-4.1.2-73507-OSX.dmg")); - vboxVersionName = System.getProperty("test" + provider + ".vboxVersionName", "VirtualBox-4.1.2-73507-OSX.dmg"); - basebaseResource = System.getProperty(VirtualBoxConstants.VIRTUALBOX_JETTY_BASE_RESOURCE, "."); - port = System.getProperty(VirtualBoxConstants.VIRTUALBOX_JETTY_PORT, "8080"); - vboxWebServerIdentity = System.getProperty(VirtualBoxConstants.VIRTUALBOX_WEBSERVER_IDENTITY, "toor"); - vboxWebServerCredential = System.getProperty(VirtualBoxConstants.VIRTUALBOX_WEBSERVER_CREDENTIAL, "12345"); - } - - @BeforeSuite - public void setupClient() throws Exception { - context = TestUtils.computeServiceForLocalhostAndGuest(); - setupCredentials(); - setupConfigurationProperties(); - downloadFileUnlessPresent(distroIsoUrl, workingDir, distroIsoName); - downloadFileUnlessPresent(gaIsoUrl, workingDir, gaIsoName); - - installVbox(); - checkVboxVersionExpected(); - new StartVBoxIfNotAlreadyRunning(context, hostId, new Credentials(vboxWebServerIdentity, vboxWebServerCredential)); - new StartJettyIfNotAlreadyRunning(port).apply(basebaseResource); - } - - @AfterSuite - public void stopVboxWebServer() throws IOException { - runScriptOnNode(hostId, "pidof vboxwebsrv | xargs kill"); - } - - public void installVbox() throws Exception { - if (runScriptOnNode(hostId, "VBoxManage --version", runAsRoot(false).wrapInInitScript(false)).getExitCode() != 0) { - logger().debug("installing virtualbox"); - if (isOSX(hostId)) { - downloadFileUnlessPresent(vboxDmg, workingDir, vboxVersionName); - runScriptOnNode(hostId, "hdiutil attach " + workingDir + "/" + vboxVersionName); - runScriptOnNode(hostId, - "installer -pkg /Volumes/VirtualBox/VirtualBox.mpkg -target /Volumes/Macintosh\\ HD"); - } else { - // TODO other platforms - runScriptOnNode(hostId, "cat > /etc/apt/sources.list.d/TODO"); - runScriptOnNode(hostId, - "wget -q http://download.virtualbox.org/virtualbox/debian/oracle_vbox.asc -O- | apt-key add -"); - runScriptOnNode(hostId, "apt-get update"); - runScriptOnNode(hostId, "apt-get --yes install virtualbox-4.1"); - } - } - } - - public void checkVboxVersionExpected() throws IOException, InterruptedException { - logger().debug("checking virtualbox version"); - assertEquals(runScriptOnNode(hostId, "VBoxManage -version").getOutput().trim(), apiVersion); - } - - public boolean isOSX(String id) { - return context.getComputeService().getNodeMetadata(hostId).getOperatingSystem().getDescription() - .equals("Mac OS X"); - } - - public File downloadFileUnlessPresent(URI sourceURL, String destinationDir, String filename) throws Exception { - - File iso = new File(destinationDir, filename); - - if (!iso.exists()) { - InputStream is = context.utils().http().get(sourceURL); - checkNotNull(is, "%s not found", sourceURL); - try { - ByteStreams.copy(is, new FileOutputStream(iso)); - } finally { - Closeables.closeQuietly(is); - } - } - return iso; - } - - public ExecResponse runScriptOnNode(String nodeId, String command, RunScriptOptions options) { - ExecResponse toReturn = context.getComputeService().runScriptOnNode(nodeId, command, options); - assert toReturn.getExitCode() == 0 : toReturn; - return toReturn; - } - - public ExecResponse runScriptOnNode(String nodeId, String command) { - return runScriptOnNode(nodeId, command, wrapInInitScript(false)); - } - -} \ No newline at end of file From fe4a971d55bc742cdc35813ab243a897413dc287 Mon Sep 17 00:00:00 2001 From: Adrian Cole Date: Sat, 29 Oct 2011 12:29:16 +0200 Subject: [PATCH 14/16] changed setup function tests to be mocks so they don't conflict with test fixture setup --- .../BaseVirtualBoxClientLiveTest.java | 36 +++- ...=> StartJettyIfNotAlreadyRunningTest.java} | 31 ++-- .../StartVBoxIfNotAlreadyRunningLiveTest.java | 50 ------ .../StartVBoxIfNotAlreadyRunningTest.java | 167 ++++++++++++++++++ 4 files changed, 219 insertions(+), 65 deletions(-) rename sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/admin/{StartJettyIfNotAlreadyRunningLiveTest.java => StartJettyIfNotAlreadyRunningTest.java} (56%) delete mode 100644 sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/admin/StartVBoxIfNotAlreadyRunningLiveTest.java create mode 100644 sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/admin/StartVBoxIfNotAlreadyRunningTest.java diff --git a/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/BaseVirtualBoxClientLiveTest.java b/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/BaseVirtualBoxClientLiveTest.java index a8e1d57995..9bb431f149 100644 --- a/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/BaseVirtualBoxClientLiveTest.java +++ b/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/BaseVirtualBoxClientLiveTest.java @@ -20,17 +20,27 @@ package org.jclouds.virtualbox; import static com.google.common.base.Preconditions.checkNotNull; +import static org.jclouds.virtualbox.experiment.TestUtils.computeServiceForLocalhostAndGuest; +import java.net.URI; import java.util.Properties; +import org.eclipse.jetty.server.Server; import org.jclouds.compute.ComputeServiceContext; import org.jclouds.compute.ComputeServiceContextFactory; +import org.jclouds.domain.Credentials; import org.jclouds.logging.log4j.config.Log4JLoggingModule; +import org.jclouds.predicates.InetSocketAddressConnect; import org.jclouds.sshj.config.SshjSshClientModule; +import org.jclouds.virtualbox.config.VirtualBoxConstants; +import org.jclouds.virtualbox.functions.admin.StartJettyIfNotAlreadyRunning; +import org.jclouds.virtualbox.functions.admin.StartVBoxIfNotAlreadyRunning; import org.testng.annotations.AfterGroups; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeGroups; import org.testng.annotations.Test; +import org.virtualbox_4_1.SessionState; +import org.virtualbox_4_1.VirtualBoxManager; import com.google.common.collect.ImmutableSet; import com.google.inject.Module; @@ -58,6 +68,8 @@ public class BaseVirtualBoxClientLiveTest { } protected ComputeServiceContext context; + protected VirtualBoxManager manager; + protected Server jetty; @BeforeGroups(groups = { "live" }) public void setupClient() { @@ -66,12 +78,34 @@ public class BaseVirtualBoxClientLiveTest { properties.setProperty(provider + ".apiversion", apiversion); context = new ComputeServiceContextFactory().createContext(provider, identity, credential, ImmutableSet. of(new Log4JLoggingModule(), new SshjSshClientModule())); + jetty = new StartJettyIfNotAlreadyRunning(port).apply(basebaseResource); + startVboxIfNotAlreadyRunning(); } @AfterGroups(groups = "live") - protected void tearDown() { + protected void tearDown() throws Exception { if (context != null) context.close(); + if (jetty != null) + jetty.stop(); + // TODO: should we stop the vbox manager? } + private String basebaseResource = "."; + // TODO: I'd not use 8080, maybe something like 28080 + // also update pom.xml so that this passes through + private int port = Integer.parseInt(System.getProperty(VirtualBoxConstants.VIRTUALBOX_JETTY_PORT, "8080")); + + protected void startVboxIfNotAlreadyRunning() { + Credentials localhostCredentials = new Credentials("toor", "password"); + ComputeServiceContext localHostContext = computeServiceForLocalhostAndGuest("hostId", "localhost", "guestId", + "localhost", localhostCredentials); + + manager = new StartVBoxIfNotAlreadyRunning(localHostContext.getComputeService(), + VirtualBoxManager.createInstance("hostId"), new InetSocketAddressConnect(), "hostId", localhostCredentials) + .apply(URI.create(endpoint)); + + assert manager.getSessionObject().getState() == SessionState.Unlocked : "manager needs to be in unlocked state or all tests will fail!!: " + + manager; + } } diff --git a/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/admin/StartJettyIfNotAlreadyRunningLiveTest.java b/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/admin/StartJettyIfNotAlreadyRunningTest.java similarity index 56% rename from sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/admin/StartJettyIfNotAlreadyRunningLiveTest.java rename to sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/admin/StartJettyIfNotAlreadyRunningTest.java index d9b3f8d08f..bcca15eaab 100644 --- a/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/admin/StartJettyIfNotAlreadyRunningLiveTest.java +++ b/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/admin/StartJettyIfNotAlreadyRunningTest.java @@ -19,34 +19,37 @@ package org.jclouds.virtualbox.functions.admin; +import static org.easymock.EasyMock.expect; +import static org.easymock.classextension.EasyMock.createMock; +import static org.easymock.classextension.EasyMock.replay; +import static org.easymock.classextension.EasyMock.verify; import static org.testng.Assert.assertEquals; import org.eclipse.jetty.server.Server; -import org.jclouds.virtualbox.BaseVirtualBoxClientLiveTest; import org.testng.annotations.Test; /** * @author Andrea Turli */ -@Test(groups = "live", singleThreaded = true, testName = "StartJettyIfNotAlreadyRunningLiveTest") -public class StartJettyIfNotAlreadyRunningLiveTest extends BaseVirtualBoxClientLiveTest { +@Test(groups = "unit", singleThreaded = true, testName = "StartJettyIfNotAlreadyRunningTest") +public class StartJettyIfNotAlreadyRunningTest { private String basebaseResource = "."; - private String port = "8080"; + private int port = 8080; @Test - public void testLaunchJettyServer() throws Exception { - Server server = new StartJettyIfNotAlreadyRunning(port).apply(basebaseResource); - server.stop(); - assertEquals(server.getState(), server.STOPPED); + public void testLaunchJettyServerWhenAlreadyRunningDoesntLaunchAgain() { + Server jetty = createMock(Server.class); + expect(jetty.getState()).andReturn(Server.STARTED); + replay(jetty); + + assertEquals(new StartJettyIfNotAlreadyRunning(jetty, port).apply(basebaseResource), jetty); + verify(jetty); + } @Test - public void testLaunchingSameJettyServer() throws Exception { - Server server = new StartJettyIfNotAlreadyRunning(port).apply(basebaseResource); - assertEquals(server.getState(), server.STARTED); - Server sameServer = new StartJettyIfNotAlreadyRunning(port).apply(basebaseResource); - sameServer.stop(); + public void testLaunchJettyServerWhenNotRunningStartsJettyOnCorrectHostPortAndBasedir() { + // TODO: all yours! } - } diff --git a/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/admin/StartVBoxIfNotAlreadyRunningLiveTest.java b/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/admin/StartVBoxIfNotAlreadyRunningLiveTest.java deleted file mode 100644 index d87dad2aec..0000000000 --- a/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/admin/StartVBoxIfNotAlreadyRunningLiveTest.java +++ /dev/null @@ -1,50 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.jclouds.virtualbox.functions.admin; - -import static org.jclouds.virtualbox.experiment.TestUtils.computeServiceForLocalhostAndGuest; -import static org.testng.Assert.assertEquals; - -import java.net.URI; - -import org.jclouds.compute.ComputeServiceContext; -import org.jclouds.domain.Credentials; -import org.testng.annotations.Test; -import org.virtualbox_4_1.SessionState; -import org.virtualbox_4_1.VirtualBoxManager; - -@Test(groups = "live", singleThreaded = true, testName = "startVBoxIfNotAlreadyRunningLiveTest") -public class StartVBoxIfNotAlreadyRunningLiveTest { - - @Test - public void testStartVbox() throws Exception { - Credentials localhostCredentials = new Credentials("toor", "password"); - ComputeServiceContext localHostContext = computeServiceForLocalhostAndGuest("hostId", "localhost", "guestId", - "localhost", localhostCredentials); - - URI endpointUri = URI.create("http://localhost:18083/"); - - VirtualBoxManager manager = new StartVBoxIfNotAlreadyRunning(localHostContext, "hostId", localhostCredentials) - .apply(endpointUri); - - assertEquals(manager.getSessionObject().getState(), SessionState.Unlocked); - } - -} diff --git a/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/admin/StartVBoxIfNotAlreadyRunningTest.java b/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/admin/StartVBoxIfNotAlreadyRunningTest.java new file mode 100644 index 0000000000..00506d22b1 --- /dev/null +++ b/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/functions/admin/StartVBoxIfNotAlreadyRunningTest.java @@ -0,0 +1,167 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.virtualbox.functions.admin; + +import static org.easymock.EasyMock.expect; +import static org.easymock.classextension.EasyMock.createMock; +import static org.easymock.classextension.EasyMock.replay; +import static org.easymock.classextension.EasyMock.verify; +import static org.testng.Assert.assertEquals; + +import java.net.URI; + +import org.jclouds.compute.ComputeService; +import org.jclouds.compute.ComputeServiceContextFactory; +import org.jclouds.compute.domain.ExecResponse; +import org.jclouds.compute.domain.NodeMetadata; +import org.jclouds.domain.Credentials; +import org.jclouds.net.IPSocket; +import org.jclouds.ssh.ConfiguresSshClient; +import org.jclouds.ssh.SshClient; +import org.testng.annotations.Test; +import org.virtualbox_4_1.VirtualBoxManager; + +import com.google.common.base.Predicate; +import com.google.common.collect.ImmutableSet; +import com.google.common.collect.Iterables; +import com.google.inject.AbstractModule; +import com.google.inject.Module; + +@Test(groups = "unit", singleThreaded = true, testName = "StartVBoxIfNotAlreadyRunningTest") +public class StartVBoxIfNotAlreadyRunningTest { + + @Test(expectedExceptions = IllegalStateException.class) + public void testStartVboxThrowsIllegalStateExceptionIfTheNodeIdConfiguredIsntAround() throws Exception { + + ComputeService compute = new ComputeServiceContextFactory().createContext("stub", "foo", "bar") + .getComputeService(); + + VirtualBoxManager manager = createMock(VirtualBoxManager.class); + @SuppressWarnings("unchecked") + Predicate socketTester = createMock(Predicate.class); + String hostId = "hostId"; + URI endpointUri = URI.create("http://localhost:18083/"); + Credentials localhostCredentials = new Credentials("toor", "password"); + + manager.connect(endpointUri.toASCIIString(), localhostCredentials.identity, localhostCredentials.credential); + + replay(socketTester); + replay(manager); + + new StartVBoxIfNotAlreadyRunning(compute, manager, socketTester, hostId, localhostCredentials).apply(endpointUri); + + } + + @Test + public void testStartVboxConnectsToManagerWhenPortAlreadyListening() throws Exception { + + ComputeService compute = new ComputeServiceContextFactory().createContext("stub", "foo", "bar") + .getComputeService(); + + // TODO: possibly better to use a defined name as opposed to an id, since + // most compute services the id is not predictable. + NodeMetadata node = Iterables.getOnlyElement(compute.createNodesInGroup("foo", 1)); + String hostId = node.getId(); + + VirtualBoxManager manager = createMock(VirtualBoxManager.class); + @SuppressWarnings("unchecked") + Predicate socketTester = createMock(Predicate.class); + URI endpointUri = URI.create("http://localhost:18083/"); + Credentials localhostCredentials = new Credentials("toor", "password"); + + expect(socketTester.apply(new IPSocket(endpointUri.getHost(), endpointUri.getPort()))).andReturn(true); + manager.connect(endpointUri.toASCIIString(), localhostCredentials.identity, localhostCredentials.credential); + + replay(socketTester); + replay(manager); + + assertEquals( + new StartVBoxIfNotAlreadyRunning(compute, manager, socketTester, hostId, localhostCredentials) + .apply(endpointUri), + manager); + + verify(socketTester); + verify(manager); + } + + @ConfiguresSshClient + static class StartingVBoxWhenNotRunningModule extends AbstractModule { + + @Override + protected void configure() { + SshClient.Factory factory = createMock(SshClient.Factory.class); + SshClient client = createMock(SshClient.class); + // NOTE we may want to switch to a node supplier so that we can predict + // these values. Right now, it is node 2 since the above test made node + // 1. + IPSocket expectedSshSockectFor2ndCreatedNode = new IPSocket("144.175.1.2", 22); + Credentials expectedCredentialsFor2ndCreatedNode = new Credentials("root", "password2"); + expect(factory.create(expectedSshSockectFor2ndCreatedNode, expectedCredentialsFor2ndCreatedNode)).andReturn( + client).times(2); + + expect(client.getUsername()).andReturn(expectedCredentialsFor2ndCreatedNode.identity).times(2); + expect(client.getHostAddress()).andReturn(expectedSshSockectFor2ndCreatedNode.getAddress()).times(2); + + client.disconnect(); + client.connect(); + expect(client.exec("VBoxManage setproperty websrvauthlibrary null\n")).andReturn(new ExecResponse("", "", 0)); + + client.disconnect(); + client.connect(); + expect(client.exec("vboxwebsrv -t 10000 -v -b\n")).andReturn(new ExecResponse("", "", 0)); + + replay(factory); + replay(client); + bind(SshClient.Factory.class).toInstance(factory); + + } + + } + + @Test + public void testStartVboxDisablesPasswordAccessOnWebsrvauthlibraryStartsVboxwebsrvInBackgroundAndConnectsManagerWhenPortIsNotListening() + throws Exception { + ComputeService compute = new ComputeServiceContextFactory().createContext("stub", "foo", "bar", + ImmutableSet. of(new StartingVBoxWhenNotRunningModule())).getComputeService(); + NodeMetadata node = Iterables.getOnlyElement(compute.createNodesInGroup("foo", 1)); + String hostId = node.getId(); + + VirtualBoxManager manager = createMock(VirtualBoxManager.class); + @SuppressWarnings("unchecked") + Predicate socketTester = createMock(Predicate.class); + Credentials localhostCredentials = new Credentials("toor", "password"); + URI endpointUri = URI.create("http://localhost:18083/"); + + expect(socketTester.apply(new IPSocket(endpointUri.getHost(), endpointUri.getPort()))).andReturn(false); + + manager.connect(endpointUri.toASCIIString(), localhostCredentials.identity, localhostCredentials.credential); + + replay(socketTester); + replay(manager); + + assertEquals( + new StartVBoxIfNotAlreadyRunning(compute, manager, socketTester, hostId, localhostCredentials) + .apply(endpointUri), + manager); + + verify(socketTester); + verify(manager); + } +} From ca723ed909bd6202d803012f3e4f0b2a4e3f3790 Mon Sep 17 00:00:00 2001 From: Adrian Cole Date: Sat, 29 Oct 2011 12:30:03 +0200 Subject: [PATCH 15/16] ensure integration tests only run one at a time, so that troubleshooting is easier --- sandbox-apis/virtualbox/pom.xml | 1 + 1 file changed, 1 insertion(+) diff --git a/sandbox-apis/virtualbox/pom.xml b/sandbox-apis/virtualbox/pom.xml index a08b6d36e0..9315ba2cae 100644 --- a/sandbox-apis/virtualbox/pom.xml +++ b/sandbox-apis/virtualbox/pom.xml @@ -160,6 +160,7 @@ test + 1 test.virtualbox.endpoint From c889077f50aa2d36f0aa5eed2162047e3790d8e4 Mon Sep 17 00:00:00 2001 From: Adrian Cole Date: Sat, 29 Oct 2011 12:30:24 +0200 Subject: [PATCH 16/16] cleaning up virtualbox constructors, etc --- .../virtualbox/functions/IsoToIMachine.java | 31 +++++++----- .../admin/StartJettyIfNotAlreadyRunning.java | 27 +++++++---- .../admin/StartVBoxIfNotAlreadyRunning.java | 47 +++++++++++-------- ...rtualBoxComputeServiceAdapterLiveTest.java | 2 +- .../virtualbox/experiment/TestUtils.java | 2 +- 5 files changed, 65 insertions(+), 44 deletions(-) diff --git a/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/IsoToIMachine.java b/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/IsoToIMachine.java index 932a9a22b6..9cd2458158 100644 --- a/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/IsoToIMachine.java +++ b/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/IsoToIMachine.java @@ -35,7 +35,6 @@ import java.io.File; import javax.annotation.Resource; import javax.inject.Named; -import org.eclipse.jetty.server.Server; import org.jclouds.compute.ComputeServiceContext; import org.jclouds.compute.domain.ExecResponse; import org.jclouds.compute.options.RunScriptOptions; @@ -44,9 +43,7 @@ import org.jclouds.domain.Credentials; import org.jclouds.javax.annotation.Nullable; import org.jclouds.logging.Logger; import org.jclouds.ssh.SshException; -import org.jclouds.virtualbox.config.VirtualBoxConstants; import org.jclouds.virtualbox.domain.ExecutionType; -import org.jclouds.virtualbox.functions.admin.StartJettyIfNotAlreadyRunning; import org.jclouds.virtualbox.settings.KeyboardScancodes; import org.virtualbox_4_1.AccessMode; import org.virtualbox_4_1.DeviceType; @@ -104,9 +101,12 @@ public class IsoToIMachine implements Function { @Override public IMachine apply(@Nullable String isoName) { - String port = System.getProperty(VirtualBoxConstants.VIRTUALBOX_JETTY_PORT, "8080"); - String baseResource = "."; - Server server = new StartJettyIfNotAlreadyRunning(port).apply(baseResource); + // TODO: WTF :) this is a prerequisite, so check state as opposed to + // starting. + // ex checkState(endpoint accessible, "please start jetty on %s", + // endpoint) + // Server server = new + // StartJettyIfNotAlreadyRunning(port).apply(baseResource); IMachine vm = new CreateAndRegisterMachineFromIsoIfNotAlreadyExists(settingsFile, osTypeId, vmId, forceOverwrite, manager).apply(vmName); @@ -174,13 +174,18 @@ public class IsoToIMachine implements Function { } }); - try { - logger.debug("Stopping Jetty server..."); - server.stop(); - logger.debug("Jetty server stopped."); - } catch (Exception e) { - logger.error(e, "Could not stop Jetty server."); - } + // TODO: See above. + // if you want to manage jetty, do it outside this class as it + // has too many responsibilities otherwise. Allow this class to focus + // solely on making an IMachine + // + // try { + // logger.debug("Stopping Jetty server..."); + // server.stop(); + // logger.debug("Jetty server stopped."); + // } catch (Exception e) { + // logger.error(e, "Could not stop Jetty server."); + // } return vm; } diff --git a/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/admin/StartJettyIfNotAlreadyRunning.java b/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/admin/StartJettyIfNotAlreadyRunning.java index 96d5e4c21f..9ca1b1799d 100644 --- a/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/admin/StartJettyIfNotAlreadyRunning.java +++ b/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/admin/StartJettyIfNotAlreadyRunning.java @@ -19,6 +19,8 @@ package org.jclouds.virtualbox.functions.admin; +import static com.google.common.base.Preconditions.checkNotNull; + import javax.annotation.Resource; import javax.inject.Inject; import javax.inject.Named; @@ -47,18 +49,25 @@ public class StartJettyIfNotAlreadyRunning implements Function { @Named(ComputeServiceConstants.COMPUTE_LOGGER) protected Logger logger = Logger.NULL; + private final Server jetty; private final int port; + public StartJettyIfNotAlreadyRunning(Server jetty, @Named(VirtualBoxConstants.VIRTUALBOX_JETTY_PORT) int port) { + this.jetty = checkNotNull(jetty, "jetty"); + this.port = port; + } + + // TODO: getting an instance of the Server object should really be done in + // Guice, so inside a *Module class, perhaps as a @Provides method @Inject - public StartJettyIfNotAlreadyRunning(@Named(VirtualBoxConstants.VIRTUALBOX_JETTY_PORT) final String port) { - this.port = Integer.parseInt(port); + public StartJettyIfNotAlreadyRunning(@Named(VirtualBoxConstants.VIRTUALBOX_JETTY_PORT) int port) { + this(ServerJetty.getInstance().getServer(), port); } @Override public Server apply(@Nullable String baseResource) { - final Server server = ServerJetty.getInstance().getServer(); - - if (!server.getState().equals(Server.STARTED) + if (!jetty.getState().equals(Server.STARTED) + // TODO code smell = hard coding addresses or ports!! && !new InetSocketAddressConnect().apply(new IPSocket("localhost", port))) { ResourceHandler resource_handler = new ResourceHandler(); resource_handler.setDirectoriesListed(true); @@ -69,17 +78,17 @@ public class StartJettyIfNotAlreadyRunning implements Function { HandlerList handlers = new HandlerList(); handlers.setHandlers(new Handler[] { resource_handler, new DefaultHandler() }); - server.setHandler(handlers); + jetty.setHandler(handlers); try { - server.start(); + jetty.start(); } catch (Exception e) { logger.error(e, "Server jetty could not be started at this %s", baseResource); } - return server; + return jetty; } else { logger.debug("Server jetty serving %s already running. Skipping start", baseResource); - return server; + return jetty; } } diff --git a/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/admin/StartVBoxIfNotAlreadyRunning.java b/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/admin/StartVBoxIfNotAlreadyRunning.java index 9da826f9f1..59c4898800 100644 --- a/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/admin/StartVBoxIfNotAlreadyRunning.java +++ b/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/admin/StartVBoxIfNotAlreadyRunning.java @@ -19,67 +19,74 @@ package org.jclouds.virtualbox.functions.admin; - +import static com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.base.Preconditions.checkState; import static org.jclouds.compute.options.RunScriptOptions.Builder.runAsRoot; import java.net.URI; -import javax.annotation.Nullable; import javax.annotation.Resource; import javax.inject.Named; -import org.jclouds.compute.ComputeServiceContext; +import org.jclouds.compute.ComputeService; import org.jclouds.compute.reference.ComputeServiceConstants; import org.jclouds.domain.Credentials; import org.jclouds.logging.Logger; import org.jclouds.net.IPSocket; -import org.jclouds.predicates.InetSocketAddressConnect; import org.virtualbox_4_1.VirtualBoxManager; import com.google.common.base.Function; +import com.google.common.base.Predicate; public class StartVBoxIfNotAlreadyRunning implements Function { @Resource @Named(ComputeServiceConstants.COMPUTE_LOGGER) protected Logger logger = Logger.NULL; - private ComputeServiceContext context; - private String hostId; - private Credentials credentials; - public StartVBoxIfNotAlreadyRunning(ComputeServiceContext context, String hostId, Credentials credentials) { - this.context = context; - this.hostId = hostId; - this.credentials = credentials; + private final ComputeService compute; + private final VirtualBoxManager manager; + private final Predicate socketTester; + private final String hostId; + private final Credentials credentials; + + public StartVBoxIfNotAlreadyRunning(ComputeService compute, VirtualBoxManager manager, + Predicate socketTester, String hostId, Credentials credentials) { + this.compute = checkNotNull(compute, "compute"); + this.manager = checkNotNull(manager, "manager"); + this.socketTester = checkNotNull(socketTester, "socketTester"); + this.hostId = checkNotNull(hostId, "hostId"); + this.credentials = checkNotNull(credentials, "credentials"); } @Override - public VirtualBoxManager apply(@Nullable URI endpoint) { + public VirtualBoxManager apply(URI endpoint) { + checkState(compute.getNodeMetadata(hostId) != null, "compute service %s cannot locate node with id %s", compute, + hostId); + checkNotNull(endpoint, "endpoint to virtualbox websrvd is needed"); - // TODO Really create new object here? Should we cache these instead? - VirtualBoxManager manager = VirtualBoxManager.createInstance(hostId); - - if (new InetSocketAddressConnect().apply(new IPSocket(endpoint.getHost(), endpoint.getPort()))) { + if (socketTester.apply(new IPSocket(endpoint.getHost(), endpoint.getPort()))) { manager.connect(endpoint.toASCIIString(), credentials.identity, credentials.credential); return manager; } logger.debug("disabling password access"); - context.getComputeService().runScriptOnNode(hostId, "VBoxManage setproperty websrvauthlibrary null", runAsRoot(false).wrapInInitScript(false)); + compute.runScriptOnNode(hostId, "VBoxManage setproperty websrvauthlibrary null", runAsRoot(false) + .wrapInInitScript(false)); logger.debug("starting vboxwebsrv"); String vboxwebsrv = "vboxwebsrv -t 10000 -v -b"; if (isOSX(hostId)) vboxwebsrv = "cd /Applications/VirtualBox.app/Contents/MacOS/ && " + vboxwebsrv; - context.getComputeService().runScriptOnNode(hostId, vboxwebsrv, runAsRoot(false).wrapInInitScript(false).blockOnComplete(false).nameTask("vboxwebsrv")); + compute.runScriptOnNode(hostId, vboxwebsrv, runAsRoot(false).wrapInInitScript(false).blockOnComplete(false) + .nameTask("vboxwebsrv")); manager.connect(endpoint.toASCIIString(), credentials.identity, credentials.credential); return manager; } private boolean isOSX(String hostId) { - return context.getComputeService().getNodeMetadata(hostId).getOperatingSystem().getDescription().equals( - "Mac OS X"); + return compute.getNodeMetadata(hostId).getOperatingSystem().getDescription().equals("Mac OS X"); } } diff --git a/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/compute/VirtualBoxComputeServiceAdapterLiveTest.java b/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/compute/VirtualBoxComputeServiceAdapterLiveTest.java index 893eb6a392..cb600efbd1 100644 --- a/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/compute/VirtualBoxComputeServiceAdapterLiveTest.java +++ b/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/compute/VirtualBoxComputeServiceAdapterLiveTest.java @@ -130,7 +130,7 @@ public class VirtualBoxComputeServiceAdapterLiveTest extends BaseVirtualBoxClien } @AfterGroups(groups = "live") - protected void tearDown() { + protected void tearDown() throws Exception { if (machine != null) adapter.destroyNode(machine.getId() + ""); super.tearDown(); diff --git a/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/experiment/TestUtils.java b/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/experiment/TestUtils.java index 38def58dac..05b133a19d 100644 --- a/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/experiment/TestUtils.java +++ b/sandbox-apis/virtualbox/src/test/java/org/jclouds/virtualbox/experiment/TestUtils.java @@ -58,7 +58,7 @@ public class TestUtils { } public static ComputeServiceContext computeServiceForLocalhostAndGuest(String hostId, String hostname, - String guestId, String guestHostname, Credentials guestLogin) throws IOException { + String guestId, String guestHostname, Credentials guestLogin) { Node host = Node.builder().id(hostId).name("host installing virtualbox").hostname(hostname) .osFamily(OsFamily.LINUX.toString()).osDescription(System.getProperty("os.name"))