Issue 76: Reverted decision to rename binders to decorators. binders are not decorators, as they do not enclose objects and add behavior

git-svn-id: http://jclouds.googlecode.com/svn/trunk@1970 3d8758e0-26b5-11de-8745-db77d3ebf521
This commit is contained in:
adrian.f.cole 2009-10-11 23:22:49 +00:00
parent 06c63e6284
commit 9c3dcdf495
96 changed files with 1149 additions and 1023 deletions

View File

@ -34,7 +34,7 @@ import javax.ws.rs.PUT;
import javax.ws.rs.Path; import javax.ws.rs.Path;
import javax.ws.rs.PathParam; import javax.ws.rs.PathParam;
import org.jclouds.aws.s3.decorators.AddS3ObjectEntity; import org.jclouds.aws.s3.binders.BindS3ObjectToEntity;
import org.jclouds.aws.s3.domain.BucketMetadata; import org.jclouds.aws.s3.domain.BucketMetadata;
import org.jclouds.aws.s3.domain.ListBucketResponse; import org.jclouds.aws.s3.domain.ListBucketResponse;
import org.jclouds.aws.s3.domain.ObjectMetadata; import org.jclouds.aws.s3.domain.ObjectMetadata;
@ -55,7 +55,7 @@ import org.jclouds.blobstore.functions.ThrowKeyNotFoundOn404;
import org.jclouds.http.functions.ParseETagHeader; import org.jclouds.http.functions.ParseETagHeader;
import org.jclouds.http.functions.ReturnFalseOn404; import org.jclouds.http.functions.ReturnFalseOn404;
import org.jclouds.http.options.GetOptions; import org.jclouds.http.options.GetOptions;
import org.jclouds.rest.annotations.DecoratorParam; import org.jclouds.rest.annotations.BinderParam;
import org.jclouds.rest.annotations.Endpoint; import org.jclouds.rest.annotations.Endpoint;
import org.jclouds.rest.annotations.ExceptionParser; import org.jclouds.rest.annotations.ExceptionParser;
import org.jclouds.rest.annotations.HostPrefixParam; import org.jclouds.rest.annotations.HostPrefixParam;
@ -181,7 +181,7 @@ public interface S3BlobStore extends BlobStore<BucketMetadata, ObjectMetadata, S
@ResponseParser(ParseETagHeader.class) @ResponseParser(ParseETagHeader.class)
Future<byte[]> putBlob( Future<byte[]> putBlob(
@HostPrefixParam String bucketName, @HostPrefixParam String bucketName,
@PathParam("key") @ParamParser(BlobKey.class) @DecoratorParam(AddS3ObjectEntity.class) S3Object object); @PathParam("key") @ParamParser(BlobKey.class) @BinderParam(BindS3ObjectToEntity.class) S3Object object);
@PUT @PUT
@Path("/") @Path("/")

View File

@ -34,8 +34,8 @@ import javax.ws.rs.PUT;
import javax.ws.rs.Path; import javax.ws.rs.Path;
import javax.ws.rs.PathParam; import javax.ws.rs.PathParam;
import org.jclouds.aws.s3.decorators.AddACLAsXMLEntity; import org.jclouds.aws.s3.binders.BindACLToXMLEntity;
import org.jclouds.aws.s3.decorators.AddS3ObjectEntity; import org.jclouds.aws.s3.binders.BindS3ObjectToEntity;
import org.jclouds.aws.s3.domain.AccessControlList; import org.jclouds.aws.s3.domain.AccessControlList;
import org.jclouds.aws.s3.domain.BucketMetadata; import org.jclouds.aws.s3.domain.BucketMetadata;
import org.jclouds.aws.s3.domain.ListBucketResponse; import org.jclouds.aws.s3.domain.ListBucketResponse;
@ -62,7 +62,7 @@ import org.jclouds.blobstore.functions.ThrowKeyNotFoundOn404;
import org.jclouds.http.functions.ParseETagHeader; import org.jclouds.http.functions.ParseETagHeader;
import org.jclouds.http.functions.ReturnFalseOn404; import org.jclouds.http.functions.ReturnFalseOn404;
import org.jclouds.http.options.GetOptions; import org.jclouds.http.options.GetOptions;
import org.jclouds.rest.annotations.DecoratorParam; import org.jclouds.rest.annotations.BinderParam;
import org.jclouds.rest.annotations.Endpoint; import org.jclouds.rest.annotations.Endpoint;
import org.jclouds.rest.annotations.ExceptionParser; import org.jclouds.rest.annotations.ExceptionParser;
import org.jclouds.rest.annotations.Headers; import org.jclouds.rest.annotations.Headers;
@ -206,7 +206,7 @@ public interface S3Connection {
@ResponseParser(ParseETagHeader.class) @ResponseParser(ParseETagHeader.class)
Future<byte[]> putObject( Future<byte[]> putObject(
@HostPrefixParam String bucketName, @HostPrefixParam String bucketName,
@PathParam("key") @ParamParser(BlobKey.class) @DecoratorParam(AddS3ObjectEntity.class) S3Object object, @PathParam("key") @ParamParser(BlobKey.class) @BinderParam(BindS3ObjectToEntity.class) S3Object object,
PutObjectOptions... options); PutObjectOptions... options);
/** /**
@ -375,7 +375,7 @@ public interface S3Connection {
@Path("/") @Path("/")
@QueryParams(keys = "acl") @QueryParams(keys = "acl")
Future<Boolean> putBucketACL(@HostPrefixParam String bucketName, Future<Boolean> putBucketACL(@HostPrefixParam String bucketName,
@DecoratorParam(AddACLAsXMLEntity.class) AccessControlList acl); @BinderParam(BindACLToXMLEntity.class) AccessControlList acl);
/** /**
* A GET request operation directed at an object or bucket URI with the "acl" parameter retrieves * A GET request operation directed at an object or bucket URI with the "acl" parameter retrieves
@ -418,6 +418,6 @@ public interface S3Connection {
@QueryParams(keys = "acl") @QueryParams(keys = "acl")
@Path("{key}") @Path("{key}")
Future<Boolean> putObjectACL(@HostPrefixParam String bucketName, @PathParam("key") String key, Future<Boolean> putObjectACL(@HostPrefixParam String bucketName, @PathParam("key") String key,
@DecoratorParam(AddACLAsXMLEntity.class) AccessControlList acl); @BinderParam(BindACLToXMLEntity.class) AccessControlList acl);
} }

View File

@ -21,7 +21,7 @@
* under the License. * under the License.
* ==================================================================== * ====================================================================
*/ */
package org.jclouds.aws.s3.decorators; package org.jclouds.aws.s3.binders;
import java.util.Properties; import java.util.Properties;
@ -37,14 +37,14 @@ import org.jclouds.aws.s3.domain.AccessControlList.Grant;
import org.jclouds.aws.s3.domain.AccessControlList.GroupGrantee; import org.jclouds.aws.s3.domain.AccessControlList.GroupGrantee;
import org.jclouds.aws.s3.reference.S3Constants; import org.jclouds.aws.s3.reference.S3Constants;
import org.jclouds.http.HttpRequest; import org.jclouds.http.HttpRequest;
import org.jclouds.rest.decorators.RequestDecorator; import org.jclouds.rest.Binder;
import org.jclouds.util.Utils; import org.jclouds.util.Utils;
import com.jamesmurty.utils.XMLBuilder; import com.jamesmurty.utils.XMLBuilder;
public class AddACLAsXMLEntity implements RequestDecorator { public class BindACLToXMLEntity implements Binder {
public HttpRequest decorateRequest(HttpRequest request, Object entity) { public void bindToRequest(HttpRequest request, Object entity) {
AccessControlList from = (AccessControlList) entity; AccessControlList from = (AccessControlList) entity;
Properties outputProperties = new Properties(); Properties outputProperties = new Properties();
outputProperties.put(javax.xml.transform.OutputKeys.OMIT_XML_DECLARATION, "yes"); outputProperties.put(javax.xml.transform.OutputKeys.OMIT_XML_DECLARATION, "yes");
@ -57,7 +57,6 @@ public class AddACLAsXMLEntity implements RequestDecorator {
Utils.rethrowIfRuntime(e); Utils.rethrowIfRuntime(e);
throw new RuntimeException("error transforming acl: " + from, e); throw new RuntimeException("error transforming acl: " + from, e);
} }
return request;
} }
protected XMLBuilder generateBuilder(AccessControlList acl) throws ParserConfigurationException, protected XMLBuilder generateBuilder(AccessControlList acl) throws ParserConfigurationException,

View File

@ -21,7 +21,7 @@
* under the License. * under the License.
* ==================================================================== * ====================================================================
*/ */
package org.jclouds.aws.s3.decorators; package org.jclouds.aws.s3.binders;
import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkArgument;
import static org.jclouds.blobstore.reference.BlobStoreConstants.PROPERTY_USER_METADATA_PREFIX; import static org.jclouds.blobstore.reference.BlobStoreConstants.PROPERTY_USER_METADATA_PREFIX;
@ -31,17 +31,17 @@ import javax.inject.Named;
import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.HttpHeaders;
import org.jclouds.aws.s3.domain.S3Object; import org.jclouds.aws.s3.domain.S3Object;
import org.jclouds.blobstore.decorators.AddBlobEntity; import org.jclouds.blobstore.binders.BindBlobToEntity;
import org.jclouds.blobstore.domain.Blob; import org.jclouds.blobstore.domain.Blob;
import org.jclouds.http.HttpRequest; import org.jclouds.http.HttpRequest;
public class AddS3ObjectEntity extends AddBlobEntity { public class BindS3ObjectToEntity extends BindBlobToEntity {
@Inject @Inject
public AddS3ObjectEntity(@Named(PROPERTY_USER_METADATA_PREFIX) String metadataPrefix) { public BindS3ObjectToEntity(@Named(PROPERTY_USER_METADATA_PREFIX) String metadataPrefix) {
super(metadataPrefix); super(metadataPrefix);
} }
public HttpRequest decorateRequest(HttpRequest request, Object entity) { public void bindToRequest(HttpRequest request, Object entity) {
Blob<?> object = (Blob<?>) entity; Blob<?> object = (Blob<?>) entity;
checkArgument(object.getMetadata().getSize() >= 0, "size must be set"); checkArgument(object.getMetadata().getSize() >= 0, "size must be set");
checkArgument(object.getContentLength() <= 5 * 1024 * 1024 * 1024, checkArgument(object.getContentLength() <= 5 * 1024 * 1024 * 1024,
@ -63,6 +63,6 @@ public class AddS3ObjectEntity extends AddBlobEntity {
s3Object.getMetadata().getContentEncoding()); s3Object.getMetadata().getContentEncoding());
} }
} }
return super.decorateRequest(request, entity); super.bindToRequest(request, entity);
} }
} }

View File

@ -32,6 +32,9 @@ import java.util.TreeSet;
import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.atomic.AtomicReference;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.HttpHeaders;
import org.jclouds.aws.s3.reference.S3Constants; import org.jclouds.aws.s3.reference.S3Constants;
@ -42,9 +45,6 @@ import org.jclouds.http.HttpUtils;
import org.jclouds.util.DateService; import org.jclouds.util.DateService;
import com.google.common.annotations.VisibleForTesting; import com.google.common.annotations.VisibleForTesting;
import javax.inject.Inject;
import javax.inject.Singleton;
import javax.inject.Named;
/** /**
* Signs the S3 request. This will update timestamps at most once per second. * Signs the S3 request. This will update timestamps at most once per second.
@ -102,11 +102,10 @@ public class RequestAuthorizeSignature implements HttpRequestFilter {
timeStamp = new AtomicReference<String>(createNewStamp()); timeStamp = new AtomicReference<String>(createNewStamp());
} }
public HttpRequest filter(HttpRequest request) throws HttpException { public void filter(HttpRequest request) throws HttpException {
replaceDateHeader(request); replaceDateHeader(request);
String toSign = createStringToSign(request); String toSign = createStringToSign(request);
calculateAndReplaceAuthHeader(request, toSign); calculateAndReplaceAuthHeader(request, toSign);
return request;
} }
public String createStringToSign(HttpRequest request) { public String createStringToSign(HttpRequest request) {

View File

@ -33,6 +33,7 @@ import javax.ws.rs.core.HttpHeaders;
import org.jclouds.aws.s3.reference.S3Constants; import org.jclouds.aws.s3.reference.S3Constants;
import org.jclouds.http.HttpRequest; import org.jclouds.http.HttpRequest;
import org.jclouds.util.DateService; import org.jclouds.util.DateService;
import org.jclouds.util.Jsr330;
import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider; import org.testng.annotations.DataProvider;
import org.testng.annotations.Test; import org.testng.annotations.Test;
@ -40,7 +41,6 @@ import org.testng.annotations.Test;
import com.google.inject.AbstractModule; import com.google.inject.AbstractModule;
import com.google.inject.Guice; import com.google.inject.Guice;
import com.google.inject.Injector; import com.google.inject.Injector;
import org.jclouds.util.Jsr330;
@Test(groups = "unit", testName = "s3.RequestAuthorizeSignatureTest") @Test(groups = "unit", testName = "s3.RequestAuthorizeSignatureTest")
public class RequestAuthorizeSignatureTest { public class RequestAuthorizeSignatureTest {
@ -72,7 +72,9 @@ public class RequestAuthorizeSignatureTest {
String signature = request.getFirstHeaderOrNull(HttpHeaders.AUTHORIZATION); String signature = request.getFirstHeaderOrNull(HttpHeaders.AUTHORIZATION);
String date = request.getFirstHeaderOrNull(HttpHeaders.DATE); String date = request.getFirstHeaderOrNull(HttpHeaders.DATE);
int iterations = 1; int iterations = 1;
while (filter.filter(request).getFirstHeaderOrNull(HttpHeaders.DATE).equals(date)) { while (request.getFirstHeaderOrNull(HttpHeaders.DATE).equals(date)) {
date = request.getFirstHeaderOrNull(HttpHeaders.DATE);
filter.filter(request);
iterations++; iterations++;
assertEquals(signature, request.getFirstHeaderOrNull(HttpHeaders.AUTHORIZATION)); assertEquals(signature, request.getFirstHeaderOrNull(HttpHeaders.AUTHORIZATION));
} }
@ -111,7 +113,6 @@ public class RequestAuthorizeSignatureTest {
assertEquals(builder.toString(), ""); assertEquals(builder.toString(), "");
} }
@Test @Test
void testHeadersGoLowercase() { void testHeadersGoLowercase() {
URI host = URI.create("http://s3.amazonaws.com:80"); URI host = URI.create("http://s3.amazonaws.com:80");
@ -121,6 +122,7 @@ public class RequestAuthorizeSignatureTest {
filter.appendBucketName(request, builder); filter.appendBucketName(request, builder);
assertEquals(builder.toString(), ""); assertEquals(builder.toString(), "");
} }
@Test @Test
void testAppendBucketNameURIHost() { void testAppendBucketNameURIHost() {
URI host = URI.create("http://adriancole.s3int5.s3-external-3.amazonaws.com:80"); URI host = URI.create("http://adriancole.s3int5.s3-external-3.amazonaws.com:80");
@ -154,8 +156,8 @@ public class RequestAuthorizeSignatureTest {
protected void configure() { protected void configure() {
bindConstant().annotatedWith(Jsr330.named(S3Constants.PROPERTY_AWS_ACCESSKEYID)).to( bindConstant().annotatedWith(Jsr330.named(S3Constants.PROPERTY_AWS_ACCESSKEYID)).to(
"foo"); "foo");
bindConstant().annotatedWith(Jsr330.named(S3Constants.PROPERTY_AWS_SECRETACCESSKEY)).to( bindConstant().annotatedWith(Jsr330.named(S3Constants.PROPERTY_AWS_SECRETACCESSKEY))
"bar"); .to("bar");
bind(DateService.class); bind(DateService.class);
} }

View File

@ -50,15 +50,15 @@ import org.jclouds.azure.storage.domain.BoundedSortedSet;
import org.jclouds.azure.storage.filters.SharedKeyAuthentication; import org.jclouds.azure.storage.filters.SharedKeyAuthentication;
import org.jclouds.azure.storage.options.ListOptions; import org.jclouds.azure.storage.options.ListOptions;
import org.jclouds.azure.storage.reference.AzureStorageHeaders; import org.jclouds.azure.storage.reference.AzureStorageHeaders;
import org.jclouds.blobstore.decorators.AddBlobEntity; import org.jclouds.blobstore.binders.BindBlobToEntity;
import org.jclouds.blobstore.decorators.AddHeadersWithPrefix; import org.jclouds.blobstore.binders.BindMultimapToHeadersWithPrefix;
import org.jclouds.blobstore.functions.BlobKey; import org.jclouds.blobstore.functions.BlobKey;
import org.jclouds.blobstore.functions.ReturnVoidOnNotFoundOr404; import org.jclouds.blobstore.functions.ReturnVoidOnNotFoundOr404;
import org.jclouds.blobstore.functions.ThrowKeyNotFoundOn404; import org.jclouds.blobstore.functions.ThrowKeyNotFoundOn404;
import org.jclouds.http.functions.ParseETagHeader; import org.jclouds.http.functions.ParseETagHeader;
import org.jclouds.http.functions.ReturnTrueOn404; import org.jclouds.http.functions.ReturnTrueOn404;
import org.jclouds.http.options.GetOptions; import org.jclouds.http.options.GetOptions;
import org.jclouds.rest.annotations.DecoratorParam; import org.jclouds.rest.annotations.BinderParam;
import org.jclouds.rest.annotations.Endpoint; import org.jclouds.rest.annotations.Endpoint;
import org.jclouds.rest.annotations.ExceptionParser; import org.jclouds.rest.annotations.ExceptionParser;
import org.jclouds.rest.annotations.Headers; import org.jclouds.rest.annotations.Headers;
@ -144,7 +144,7 @@ public interface AzureBlobConnection {
@Path("{container}") @Path("{container}")
@QueryParams(keys = { "restype", "comp" }, values = { "container", "metadata" }) @QueryParams(keys = { "restype", "comp" }, values = { "container", "metadata" })
void setContainerMetadata(@PathParam("container") String container, void setContainerMetadata(@PathParam("container") String container,
@DecoratorParam(AddHeadersWithPrefix.class) Multimap<String, String> metadata); @BinderParam(BindMultimapToHeadersWithPrefix.class) Multimap<String, String> metadata);
/** /**
* The Delete Container operation marks the specified container for deletion. The container and * The Delete Container operation marks the specified container for deletion. The container and
@ -272,7 +272,7 @@ public interface AzureBlobConnection {
@Path("{container}/{key}") @Path("{container}/{key}")
@ResponseParser(ParseETagHeader.class) @ResponseParser(ParseETagHeader.class)
Future<byte[]> putBlob(@PathParam("container") String container, Future<byte[]> putBlob(@PathParam("container") String container,
@PathParam("key") @ParamParser(BlobKey.class) @DecoratorParam(AddBlobEntity.class) Blob object); @PathParam("key") @ParamParser(BlobKey.class) @BinderParam(BindBlobToEntity.class) Blob object);
/** /**
* The Get Blob operation reads or downloads a blob from the system, including its metadata and * The Get Blob operation reads or downloads a blob from the system, including its metadata and
@ -302,7 +302,7 @@ public interface AzureBlobConnection {
@Path("{container}/{key}") @Path("{container}/{key}")
@QueryParams(keys = { "comp" }, values = { "metadata" }) @QueryParams(keys = { "comp" }, values = { "metadata" })
void setBlobMetadata(@PathParam("container") String container, @PathParam("key") String key, void setBlobMetadata(@PathParam("container") String container, @PathParam("key") String key,
@DecoratorParam(AddHeadersWithPrefix.class) Multimap<String, String> metadata); @BinderParam(BindMultimapToHeadersWithPrefix.class) Multimap<String, String> metadata);
/** /**
* The Delete Blob operation marks the specified blob for deletion. The blob is later deleted * The Delete Blob operation marks the specified blob for deletion. The blob is later deleted

View File

@ -35,7 +35,7 @@ import javax.ws.rs.Path;
import javax.ws.rs.PathParam; import javax.ws.rs.PathParam;
import org.jclouds.azure.storage.AzureBlob; import org.jclouds.azure.storage.AzureBlob;
import org.jclouds.azure.storage.blob.decorators.GenerateMD5AndAddBlobEntity; import org.jclouds.azure.storage.blob.binders.GenerateMD5AndBindBlobToEntity;
import org.jclouds.azure.storage.blob.domain.Blob; import org.jclouds.azure.storage.blob.domain.Blob;
import org.jclouds.azure.storage.blob.domain.BlobMetadata; import org.jclouds.azure.storage.blob.domain.BlobMetadata;
import org.jclouds.azure.storage.blob.domain.ContainerMetadata; import org.jclouds.azure.storage.blob.domain.ContainerMetadata;
@ -56,7 +56,7 @@ import org.jclouds.blobstore.functions.ThrowKeyNotFoundOn404;
import org.jclouds.http.functions.ParseETagHeader; import org.jclouds.http.functions.ParseETagHeader;
import org.jclouds.http.functions.ReturnFalseOn404; import org.jclouds.http.functions.ReturnFalseOn404;
import org.jclouds.http.options.GetOptions; import org.jclouds.http.options.GetOptions;
import org.jclouds.rest.annotations.DecoratorParam; import org.jclouds.rest.annotations.BinderParam;
import org.jclouds.rest.annotations.Endpoint; import org.jclouds.rest.annotations.Endpoint;
import org.jclouds.rest.annotations.ExceptionParser; import org.jclouds.rest.annotations.ExceptionParser;
import org.jclouds.rest.annotations.Headers; import org.jclouds.rest.annotations.Headers;
@ -149,7 +149,7 @@ public interface AzureBlobStore extends BlobStore<ContainerMetadata, BlobMetadat
@ResponseParser(ParseETagHeader.class) @ResponseParser(ParseETagHeader.class)
Future<byte[]> putBlob( Future<byte[]> putBlob(
@PathParam("container") String container, @PathParam("container") String container,
@PathParam("key") @ParamParser(BlobKey.class) @DecoratorParam(GenerateMD5AndAddBlobEntity.class) Blob object); @PathParam("key") @ParamParser(BlobKey.class) @BinderParam(GenerateMD5AndBindBlobToEntity.class) Blob object);
@GET @GET
@ResponseParser(ParseBlobFromHeadersAndHttpContent.class) @ResponseParser(ParseBlobFromHeadersAndHttpContent.class)

View File

@ -21,7 +21,7 @@
* under the License. * under the License.
* ==================================================================== * ====================================================================
*/ */
package org.jclouds.azure.storage.blob.decorators; package org.jclouds.azure.storage.blob.binders;
import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkArgument;
import static org.jclouds.blobstore.reference.BlobStoreConstants.PROPERTY_USER_METADATA_PREFIX; import static org.jclouds.blobstore.reference.BlobStoreConstants.PROPERTY_USER_METADATA_PREFIX;
@ -34,14 +34,14 @@ import org.jclouds.azure.storage.blob.domain.BlobMetadata;
import org.jclouds.blobstore.domain.Blob; import org.jclouds.blobstore.domain.Blob;
import org.jclouds.http.HttpRequest; import org.jclouds.http.HttpRequest;
public class AddBlobEntity extends org.jclouds.blobstore.decorators.AddBlobEntity { public class BindBlobToEntity extends org.jclouds.blobstore.binders.BindBlobToEntity {
@Inject @Inject
public AddBlobEntity(@Named(PROPERTY_USER_METADATA_PREFIX) String metadataPrefix) { public BindBlobToEntity(@Named(PROPERTY_USER_METADATA_PREFIX) String metadataPrefix) {
super(metadataPrefix); super(metadataPrefix);
} }
@Override @Override
public HttpRequest decorateRequest(HttpRequest request, Object entity) { public void bindToRequest(HttpRequest request, Object entity) {
Blob<?> object = (Blob<?>) entity; Blob<?> object = (Blob<?>) entity;
checkArgument(object.getMetadata().getSize() >= 0, "size must be set"); checkArgument(object.getMetadata().getSize() >= 0, "size must be set");
checkArgument(object.getContentLength() <= 64 * 1024 * 1024, checkArgument(object.getContentLength() <= 64 * 1024 * 1024,
@ -57,6 +57,6 @@ public class AddBlobEntity extends org.jclouds.blobstore.decorators.AddBlobEntit
request.getHeaders().put(HttpHeaders.CONTENT_ENCODING, md.getContentEncoding()); request.getHeaders().put(HttpHeaders.CONTENT_ENCODING, md.getContentEncoding());
} }
} }
return super.decorateRequest(request, entity); super.bindToRequest(request, entity);
} }
} }

View File

@ -21,7 +21,7 @@
* under the License. * under the License.
* ==================================================================== * ====================================================================
*/ */
package org.jclouds.azure.storage.blob.decorators; package org.jclouds.azure.storage.blob.binders;
import static org.jclouds.blobstore.reference.BlobStoreConstants.PROPERTY_USER_METADATA_PREFIX; import static org.jclouds.blobstore.reference.BlobStoreConstants.PROPERTY_USER_METADATA_PREFIX;
@ -33,15 +33,15 @@ import javax.inject.Named;
import org.jclouds.blobstore.domain.Blob; import org.jclouds.blobstore.domain.Blob;
import org.jclouds.http.HttpRequest; import org.jclouds.http.HttpRequest;
public class GenerateMD5AndAddBlobEntity extends AddBlobEntity { public class GenerateMD5AndBindBlobToEntity extends BindBlobToEntity {
@Inject @Inject
public GenerateMD5AndAddBlobEntity(@Named(PROPERTY_USER_METADATA_PREFIX) String metadataPrefix) { public GenerateMD5AndBindBlobToEntity(@Named(PROPERTY_USER_METADATA_PREFIX) String metadataPrefix) {
super(metadataPrefix); super(metadataPrefix);
} }
@Override @Override
public HttpRequest decorateRequest(HttpRequest request, Object entity) { public void bindToRequest(HttpRequest request, Object entity) {
Blob<?> object = (Blob<?>) entity; Blob<?> object = (Blob<?>) entity;
if (object.getMetadata().getContentMD5() == null) { if (object.getMetadata().getContentMD5() == null) {
try { try {
@ -50,6 +50,6 @@ public class GenerateMD5AndAddBlobEntity extends AddBlobEntity {
throw new RuntimeException("Could not generate MD5 for " + object.getKey(), e); throw new RuntimeException("Could not generate MD5 for " + object.getKey(), e);
} }
} }
return super.decorateRequest(request, entity); super.bindToRequest(request, entity);
} }
} }

View File

@ -33,10 +33,10 @@ import javax.ws.rs.core.HttpHeaders;
import org.jclouds.azure.storage.blob.domain.ContainerMetadata; import org.jclouds.azure.storage.blob.domain.ContainerMetadata;
import org.jclouds.http.HttpException; import org.jclouds.http.HttpException;
import org.jclouds.http.HttpRequest;
import org.jclouds.http.HttpResponse; import org.jclouds.http.HttpResponse;
import org.jclouds.http.HttpUtils; import org.jclouds.http.HttpUtils;
import org.jclouds.rest.InvocationContext; import org.jclouds.rest.InvocationContext;
import org.jclouds.rest.internal.GeneratedHttpRequest;
import org.jclouds.util.DateService; import org.jclouds.util.DateService;
import com.google.common.annotations.VisibleForTesting; import com.google.common.annotations.VisibleForTesting;
@ -54,8 +54,7 @@ public class ParseContainerMetadataFromHeaders implements
private final DateService dateParser; private final DateService dateParser;
private final String metadataPrefix; private final String metadataPrefix;
private HttpRequest request; private GeneratedHttpRequest<?> request;
private Object[] args;
@Inject @Inject
public ParseContainerMetadataFromHeaders(DateService dateParser, public ParseContainerMetadataFromHeaders(DateService dateParser,
@ -65,11 +64,11 @@ public class ParseContainerMetadataFromHeaders implements
} }
public ContainerMetadata apply(HttpResponse from) { public ContainerMetadata apply(HttpResponse from) {
ContainerMetadata to = new ContainerMetadata(getArgs()[0].toString()); ContainerMetadata to = new ContainerMetadata(request.getArgs()[0].toString());
addUserMetadataTo(from, to); addUserMetadataTo(from, to);
parseLastModifiedOrThrowException(from, to); parseLastModifiedOrThrowException(from, to);
addETagTo(from, to); addETagTo(from, to);
to.setUrl(getRequest().getEndpoint()); to.setUrl(request.getEndpoint());
return to; return to;
} }
@ -104,17 +103,8 @@ public class ParseContainerMetadataFromHeaders implements
} }
} }
public Object[] getArgs() { public void setContext(GeneratedHttpRequest<?> request) {
return args;
}
public HttpRequest getRequest() {
return request;
}
public void setContext(HttpRequest request, Object[] args) {
this.request = request; this.request = request;
this.args = args;
} }
} }

View File

@ -46,7 +46,6 @@ import org.jclouds.blobstore.functions.ReturnVoidOnNotFoundOr404;
import org.jclouds.blobstore.reference.BlobStoreConstants; import org.jclouds.blobstore.reference.BlobStoreConstants;
import org.jclouds.concurrent.WithinThreadExecutorService; import org.jclouds.concurrent.WithinThreadExecutorService;
import org.jclouds.concurrent.config.ExecutorServiceModule; import org.jclouds.concurrent.config.ExecutorServiceModule;
import org.jclouds.http.HttpRequest;
import org.jclouds.http.HttpUtils; import org.jclouds.http.HttpUtils;
import org.jclouds.http.config.JavaUrlHttpCommandExecutorServiceModule; import org.jclouds.http.config.JavaUrlHttpCommandExecutorServiceModule;
import org.jclouds.http.functions.ParseSax; import org.jclouds.http.functions.ParseSax;
@ -56,6 +55,7 @@ import org.jclouds.http.functions.ReturnVoidIf2xx;
import org.jclouds.logging.Logger; import org.jclouds.logging.Logger;
import org.jclouds.logging.Logger.LoggerFactory; import org.jclouds.logging.Logger.LoggerFactory;
import org.jclouds.rest.config.RestModule; import org.jclouds.rest.config.RestModule;
import org.jclouds.rest.internal.GeneratedHttpRequest;
import org.jclouds.rest.internal.RestAnnotationProcessor; import org.jclouds.rest.internal.RestAnnotationProcessor;
import org.jclouds.util.Jsr330; import org.jclouds.util.Jsr330;
import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeClass;
@ -81,7 +81,7 @@ public class AzureBlobConnectionTest {
Method method = AzureBlobConnection.class.getMethod("listContainers", Array.newInstance( Method method = AzureBlobConnection.class.getMethod("listContainers", Array.newInstance(
ListOptions.class, 0).getClass()); ListOptions.class, 0).getClass());
HttpRequest httpMethod = processor.createRequest(method, new Object[] {}); GeneratedHttpRequest<AzureBlobConnection> httpMethod = processor.createRequest(method, new Object[] {});
assertEquals(httpMethod.getEndpoint().getHost(), "myaccount.blob.core.windows.net"); assertEquals(httpMethod.getEndpoint().getHost(), "myaccount.blob.core.windows.net");
assertEquals(httpMethod.getEndpoint().getPath(), "/"); assertEquals(httpMethod.getEndpoint().getPath(), "/");
assertEquals(httpMethod.getEndpoint().getQuery(), "comp=list"); assertEquals(httpMethod.getEndpoint().getQuery(), "comp=list");
@ -89,7 +89,7 @@ public class AzureBlobConnectionTest {
assertEquals(httpMethod.getHeaders().size(), 1); assertEquals(httpMethod.getHeaders().size(), 1);
assertEquals(httpMethod.getHeaders().get("x-ms-version"), Collections assertEquals(httpMethod.getHeaders().get("x-ms-version"), Collections
.singletonList("2009-07-17")); .singletonList("2009-07-17"));
assertEquals(processor.createResponseParser(method, httpMethod, null).getClass(), assertEquals(processor.createResponseParser(method, httpMethod).getClass(),
ParseSax.class); ParseSax.class);
// TODO check generic type of response parser // TODO check generic type of response parser
assertEquals(processor.createExceptionParserOrNullIfNotFound(method), null); assertEquals(processor.createExceptionParserOrNullIfNotFound(method), null);
@ -99,7 +99,7 @@ public class AzureBlobConnectionTest {
Method method = AzureBlobConnection.class.getMethod("listContainers", Array.newInstance( Method method = AzureBlobConnection.class.getMethod("listContainers", Array.newInstance(
ListOptions.class, 0).getClass()); ListOptions.class, 0).getClass());
HttpRequest httpMethod = processor.createRequest(method, new Object[] { maxResults(1).marker( GeneratedHttpRequest<AzureBlobConnection> httpMethod = processor.createRequest(method, new Object[] { maxResults(1).marker(
"marker").prefix("prefix") }); "marker").prefix("prefix") });
assertEquals(httpMethod.getEndpoint().getHost(), "myaccount.blob.core.windows.net"); assertEquals(httpMethod.getEndpoint().getHost(), "myaccount.blob.core.windows.net");
assertEquals(httpMethod.getEndpoint().getPath(), "/"); assertEquals(httpMethod.getEndpoint().getPath(), "/");
@ -111,7 +111,7 @@ public class AzureBlobConnectionTest {
assertEquals(httpMethod.getHeaders().size(), 1); assertEquals(httpMethod.getHeaders().size(), 1);
assertEquals(httpMethod.getHeaders().get("x-ms-version"), Collections assertEquals(httpMethod.getHeaders().get("x-ms-version"), Collections
.singletonList("2009-07-17")); .singletonList("2009-07-17"));
assertEquals(processor.createResponseParser(method, httpMethod, null).getClass(), assertEquals(processor.createResponseParser(method, httpMethod).getClass(),
ParseSax.class); ParseSax.class);
// TODO check generic type of response parser // TODO check generic type of response parser
assertEquals(processor.createExceptionParserOrNullIfNotFound(method), null); assertEquals(processor.createExceptionParserOrNullIfNotFound(method), null);
@ -121,7 +121,7 @@ public class AzureBlobConnectionTest {
Method method = AzureBlobConnection.class.getMethod("createContainer", String.class, Array Method method = AzureBlobConnection.class.getMethod("createContainer", String.class, Array
.newInstance(CreateContainerOptions.class, 0).getClass()); .newInstance(CreateContainerOptions.class, 0).getClass());
HttpRequest httpMethod = processor.createRequest(method, new Object[] { "container" }); GeneratedHttpRequest<AzureBlobConnection> httpMethod = processor.createRequest(method, new Object[] { "container" });
assertEquals(httpMethod.getEndpoint().getHost(), "myaccount.blob.core.windows.net"); assertEquals(httpMethod.getEndpoint().getHost(), "myaccount.blob.core.windows.net");
assertEquals(httpMethod.getEndpoint().getPath(), "/container"); assertEquals(httpMethod.getEndpoint().getPath(), "/container");
assertEquals(httpMethod.getEndpoint().getQuery(), "restype=container"); assertEquals(httpMethod.getEndpoint().getQuery(), "restype=container");
@ -130,7 +130,7 @@ public class AzureBlobConnectionTest {
assertEquals(httpMethod.getHeaders().get("x-ms-version"), Collections assertEquals(httpMethod.getHeaders().get("x-ms-version"), Collections
.singletonList("2009-07-17")); .singletonList("2009-07-17"));
assertEquals(httpMethod.getHeaders().get("Content-Length"), Collections.singletonList("0")); assertEquals(httpMethod.getHeaders().get("Content-Length"), Collections.singletonList("0"));
assertEquals(processor.createResponseParser(method, httpMethod, null).getClass(), assertEquals(processor.createResponseParser(method, httpMethod).getClass(),
ReturnTrueIf2xx.class); ReturnTrueIf2xx.class);
// TODO check generic type of response parser // TODO check generic type of response parser
assertEquals(processor.createExceptionParserOrNullIfNotFound(method).getClass(), assertEquals(processor.createExceptionParserOrNullIfNotFound(method).getClass(),
@ -140,7 +140,7 @@ public class AzureBlobConnectionTest {
public void testDeleteContainer() throws SecurityException, NoSuchMethodException { public void testDeleteContainer() throws SecurityException, NoSuchMethodException {
Method method = AzureBlobConnection.class.getMethod("deleteContainer", String.class); Method method = AzureBlobConnection.class.getMethod("deleteContainer", String.class);
HttpRequest httpMethod = processor.createRequest(method, new Object[] { "container" }); GeneratedHttpRequest<AzureBlobConnection> httpMethod = processor.createRequest(method, new Object[] { "container" });
assertEquals(httpMethod.getEndpoint().getHost(), "myaccount.blob.core.windows.net"); assertEquals(httpMethod.getEndpoint().getHost(), "myaccount.blob.core.windows.net");
assertEquals(httpMethod.getEndpoint().getPath(), "/container"); assertEquals(httpMethod.getEndpoint().getPath(), "/container");
assertEquals(httpMethod.getEndpoint().getQuery(), "restype=container"); assertEquals(httpMethod.getEndpoint().getQuery(), "restype=container");
@ -148,7 +148,7 @@ public class AzureBlobConnectionTest {
assertEquals(httpMethod.getHeaders().size(), 1); assertEquals(httpMethod.getHeaders().size(), 1);
assertEquals(httpMethod.getHeaders().get("x-ms-version"), Collections assertEquals(httpMethod.getHeaders().get("x-ms-version"), Collections
.singletonList("2009-07-17")); .singletonList("2009-07-17"));
assertEquals(processor.createResponseParser(method, httpMethod, null).getClass(), assertEquals(processor.createResponseParser(method, httpMethod).getClass(),
ReturnVoidIf2xx.class); ReturnVoidIf2xx.class);
// TODO check generic type of response parser // TODO check generic type of response parser
assertEquals(processor.createExceptionParserOrNullIfNotFound(method).getClass(), assertEquals(processor.createExceptionParserOrNullIfNotFound(method).getClass(),
@ -159,7 +159,7 @@ public class AzureBlobConnectionTest {
Method method = AzureBlobConnection.class.getMethod("createContainer", String.class, Array Method method = AzureBlobConnection.class.getMethod("createContainer", String.class, Array
.newInstance(CreateContainerOptions.class, 0).getClass()); .newInstance(CreateContainerOptions.class, 0).getClass());
HttpRequest httpMethod = processor.createRequest(method, new Object[] { "container", GeneratedHttpRequest<AzureBlobConnection> httpMethod = processor.createRequest(method, new Object[] { "container",
withPublicAcl().withMetadata(ImmutableMultimap.of("foo", "bar")) }); withPublicAcl().withMetadata(ImmutableMultimap.of("foo", "bar")) });
assertEquals(httpMethod.getEndpoint().getHost(), "myaccount.blob.core.windows.net"); assertEquals(httpMethod.getEndpoint().getHost(), "myaccount.blob.core.windows.net");
assertEquals(httpMethod.getEndpoint().getPath(), "/container"); assertEquals(httpMethod.getEndpoint().getPath(), "/container");
@ -172,7 +172,7 @@ public class AzureBlobConnectionTest {
assertEquals(httpMethod.getHeaders().get("x-ms-prop-publicaccess"), Collections assertEquals(httpMethod.getHeaders().get("x-ms-prop-publicaccess"), Collections
.singletonList("true")); .singletonList("true"));
assertEquals(httpMethod.getHeaders().get("Content-Length"), Collections.singletonList("0")); assertEquals(httpMethod.getHeaders().get("Content-Length"), Collections.singletonList("0"));
assertEquals(processor.createResponseParser(method, httpMethod, null).getClass(), assertEquals(processor.createResponseParser(method, httpMethod).getClass(),
ReturnTrueIf2xx.class); ReturnTrueIf2xx.class);
// TODO check generic type of response parser // TODO check generic type of response parser
assertEquals(processor.createExceptionParserOrNullIfNotFound(method).getClass(), assertEquals(processor.createExceptionParserOrNullIfNotFound(method).getClass(),
@ -183,7 +183,7 @@ public class AzureBlobConnectionTest {
Method method = AzureBlobConnection.class.getMethod("createRootContainer", Array.newInstance( Method method = AzureBlobConnection.class.getMethod("createRootContainer", Array.newInstance(
CreateContainerOptions.class, 0).getClass()); CreateContainerOptions.class, 0).getClass());
HttpRequest httpMethod = processor.createRequest(method, new Object[] {}); GeneratedHttpRequest<AzureBlobConnection> httpMethod = processor.createRequest(method, new Object[] {});
assertEquals(httpMethod.getEndpoint().getHost(), "myaccount.blob.core.windows.net"); assertEquals(httpMethod.getEndpoint().getHost(), "myaccount.blob.core.windows.net");
assertEquals(httpMethod.getEndpoint().getPath(), "/$root"); assertEquals(httpMethod.getEndpoint().getPath(), "/$root");
assertEquals(httpMethod.getEndpoint().getQuery(), "restype=container"); assertEquals(httpMethod.getEndpoint().getQuery(), "restype=container");
@ -192,7 +192,7 @@ public class AzureBlobConnectionTest {
assertEquals(httpMethod.getHeaders().get("x-ms-version"), Collections assertEquals(httpMethod.getHeaders().get("x-ms-version"), Collections
.singletonList("2009-07-17")); .singletonList("2009-07-17"));
assertEquals(httpMethod.getHeaders().get("Content-Length"), Collections.singletonList("0")); assertEquals(httpMethod.getHeaders().get("Content-Length"), Collections.singletonList("0"));
assertEquals(processor.createResponseParser(method, httpMethod, null).getClass(), assertEquals(processor.createResponseParser(method, httpMethod).getClass(),
ReturnTrueIf2xx.class); ReturnTrueIf2xx.class);
// TODO check generic type of response parser // TODO check generic type of response parser
assertEquals(processor.createExceptionParserOrNullIfNotFound(method).getClass(), assertEquals(processor.createExceptionParserOrNullIfNotFound(method).getClass(),
@ -202,7 +202,7 @@ public class AzureBlobConnectionTest {
public void testDeleteRootContainer() throws SecurityException, NoSuchMethodException { public void testDeleteRootContainer() throws SecurityException, NoSuchMethodException {
Method method = AzureBlobConnection.class.getMethod("deleteRootContainer"); Method method = AzureBlobConnection.class.getMethod("deleteRootContainer");
HttpRequest httpMethod = processor.createRequest(method, new Object[] {}); GeneratedHttpRequest<AzureBlobConnection> httpMethod = processor.createRequest(method, new Object[] {});
assertEquals(httpMethod.getEndpoint().getHost(), "myaccount.blob.core.windows.net"); assertEquals(httpMethod.getEndpoint().getHost(), "myaccount.blob.core.windows.net");
assertEquals(httpMethod.getEndpoint().getPath(), "/$root"); assertEquals(httpMethod.getEndpoint().getPath(), "/$root");
assertEquals(httpMethod.getEndpoint().getQuery(), "restype=container"); assertEquals(httpMethod.getEndpoint().getQuery(), "restype=container");
@ -210,7 +210,7 @@ public class AzureBlobConnectionTest {
assertEquals(httpMethod.getHeaders().size(), 1); assertEquals(httpMethod.getHeaders().size(), 1);
assertEquals(httpMethod.getHeaders().get("x-ms-version"), Collections assertEquals(httpMethod.getHeaders().get("x-ms-version"), Collections
.singletonList("2009-07-17")); .singletonList("2009-07-17"));
assertEquals(processor.createResponseParser(method, httpMethod, null).getClass(), assertEquals(processor.createResponseParser(method, httpMethod).getClass(),
ReturnTrueIf2xx.class); ReturnTrueIf2xx.class);
// TODO check generic type of response parser // TODO check generic type of response parser
assertEquals(processor.createExceptionParserOrNullIfNotFound(method).getClass(), assertEquals(processor.createExceptionParserOrNullIfNotFound(method).getClass(),
@ -221,7 +221,7 @@ public class AzureBlobConnectionTest {
Method method = AzureBlobConnection.class.getMethod("createRootContainer", Array.newInstance( Method method = AzureBlobConnection.class.getMethod("createRootContainer", Array.newInstance(
CreateContainerOptions.class, 0).getClass()); CreateContainerOptions.class, 0).getClass());
HttpRequest httpMethod = processor.createRequest(method, new Object[] { withPublicAcl() GeneratedHttpRequest<AzureBlobConnection> httpMethod = processor.createRequest(method, new Object[] { withPublicAcl()
.withMetadata(ImmutableMultimap.of("foo", "bar")) }); .withMetadata(ImmutableMultimap.of("foo", "bar")) });
assertEquals(httpMethod.getEndpoint().getHost(), "myaccount.blob.core.windows.net"); assertEquals(httpMethod.getEndpoint().getHost(), "myaccount.blob.core.windows.net");
assertEquals(httpMethod.getEndpoint().getPath(), "/$root"); assertEquals(httpMethod.getEndpoint().getPath(), "/$root");
@ -234,7 +234,7 @@ public class AzureBlobConnectionTest {
assertEquals(httpMethod.getHeaders().get("x-ms-prop-publicaccess"), Collections assertEquals(httpMethod.getHeaders().get("x-ms-prop-publicaccess"), Collections
.singletonList("true")); .singletonList("true"));
assertEquals(httpMethod.getHeaders().get("Content-Length"), Collections.singletonList("0")); assertEquals(httpMethod.getHeaders().get("Content-Length"), Collections.singletonList("0"));
assertEquals(processor.createResponseParser(method, httpMethod, null).getClass(), assertEquals(processor.createResponseParser(method, httpMethod).getClass(),
ReturnTrueIf2xx.class); ReturnTrueIf2xx.class);
// TODO check generic type of response parser // TODO check generic type of response parser
assertEquals(processor.createExceptionParserOrNullIfNotFound(method).getClass(), assertEquals(processor.createExceptionParserOrNullIfNotFound(method).getClass(),
@ -245,7 +245,7 @@ public class AzureBlobConnectionTest {
Method method = AzureBlobConnection.class.getMethod("listBlobs", String.class, Array Method method = AzureBlobConnection.class.getMethod("listBlobs", String.class, Array
.newInstance(ListBlobsOptions.class, 0).getClass()); .newInstance(ListBlobsOptions.class, 0).getClass());
HttpRequest httpMethod = processor.createRequest(method, new Object[] { "container" }); GeneratedHttpRequest<AzureBlobConnection> httpMethod = processor.createRequest(method, new Object[] { "container" });
assertEquals(httpMethod.getEndpoint().getHost(), "myaccount.blob.core.windows.net"); assertEquals(httpMethod.getEndpoint().getHost(), "myaccount.blob.core.windows.net");
assertEquals(httpMethod.getEndpoint().getPath(), "/container"); assertEquals(httpMethod.getEndpoint().getPath(), "/container");
assertEquals(httpMethod.getEndpoint().getQuery(), "restype=container&comp=list"); assertEquals(httpMethod.getEndpoint().getQuery(), "restype=container&comp=list");
@ -253,7 +253,7 @@ public class AzureBlobConnectionTest {
assertEquals(httpMethod.getHeaders().size(), 1); assertEquals(httpMethod.getHeaders().size(), 1);
assertEquals(httpMethod.getHeaders().get("x-ms-version"), Collections assertEquals(httpMethod.getHeaders().get("x-ms-version"), Collections
.singletonList("2009-07-17")); .singletonList("2009-07-17"));
assertEquals(processor.createResponseParser(method, httpMethod, null).getClass(), assertEquals(processor.createResponseParser(method, httpMethod).getClass(),
ParseSax.class); ParseSax.class);
// TODO check generic type of response parser // TODO check generic type of response parser
assertEquals(processor.createExceptionParserOrNullIfNotFound(method), null); assertEquals(processor.createExceptionParserOrNullIfNotFound(method), null);
@ -263,7 +263,7 @@ public class AzureBlobConnectionTest {
Method method = AzureBlobConnection.class.getMethod("listBlobs", Array.newInstance( Method method = AzureBlobConnection.class.getMethod("listBlobs", Array.newInstance(
ListBlobsOptions.class, 0).getClass()); ListBlobsOptions.class, 0).getClass());
HttpRequest httpMethod = processor.createRequest(method, new Object[] {}); GeneratedHttpRequest<AzureBlobConnection> httpMethod = processor.createRequest(method, new Object[] {});
assertEquals(httpMethod.getEndpoint().getHost(), "myaccount.blob.core.windows.net"); assertEquals(httpMethod.getEndpoint().getHost(), "myaccount.blob.core.windows.net");
assertEquals(httpMethod.getEndpoint().getPath(), "/$root"); assertEquals(httpMethod.getEndpoint().getPath(), "/$root");
assertEquals(httpMethod.getEndpoint().getQuery(), "restype=container&comp=list"); assertEquals(httpMethod.getEndpoint().getQuery(), "restype=container&comp=list");
@ -271,7 +271,7 @@ public class AzureBlobConnectionTest {
assertEquals(httpMethod.getHeaders().size(), 1); assertEquals(httpMethod.getHeaders().size(), 1);
assertEquals(httpMethod.getHeaders().get("x-ms-version"), Collections assertEquals(httpMethod.getHeaders().get("x-ms-version"), Collections
.singletonList("2009-07-17")); .singletonList("2009-07-17"));
assertEquals(processor.createResponseParser(method, httpMethod, null).getClass(), assertEquals(processor.createResponseParser(method, httpMethod).getClass(),
ParseSax.class); ParseSax.class);
// TODO check generic type of response parser // TODO check generic type of response parser
assertEquals(processor.createExceptionParserOrNullIfNotFound(method), null); assertEquals(processor.createExceptionParserOrNullIfNotFound(method), null);
@ -280,7 +280,7 @@ public class AzureBlobConnectionTest {
public void testContainerProperties() throws SecurityException, NoSuchMethodException { public void testContainerProperties() throws SecurityException, NoSuchMethodException {
Method method = AzureBlobConnection.class.getMethod("getContainerProperties", String.class); Method method = AzureBlobConnection.class.getMethod("getContainerProperties", String.class);
HttpRequest httpMethod = processor.createRequest(method, new Object[] { "container" }); GeneratedHttpRequest<AzureBlobConnection> httpMethod = processor.createRequest(method, new Object[] { "container" });
assertEquals(httpMethod.getEndpoint().getHost(), "myaccount.blob.core.windows.net"); assertEquals(httpMethod.getEndpoint().getHost(), "myaccount.blob.core.windows.net");
assertEquals(httpMethod.getEndpoint().getPath(), "/container"); assertEquals(httpMethod.getEndpoint().getPath(), "/container");
assertEquals(httpMethod.getEndpoint().getQuery(), "restype=container"); assertEquals(httpMethod.getEndpoint().getQuery(), "restype=container");
@ -288,7 +288,7 @@ public class AzureBlobConnectionTest {
assertEquals(httpMethod.getHeaders().size(), 1); assertEquals(httpMethod.getHeaders().size(), 1);
assertEquals(httpMethod.getHeaders().get("x-ms-version"), Collections assertEquals(httpMethod.getHeaders().get("x-ms-version"), Collections
.singletonList("2009-07-17")); .singletonList("2009-07-17"));
assertEquals(processor.createResponseParser(method, httpMethod, null).getClass(), assertEquals(processor.createResponseParser(method, httpMethod).getClass(),
ParseContainerMetadataFromHeaders.class); ParseContainerMetadataFromHeaders.class);
assertEquals(processor.createExceptionParserOrNullIfNotFound(method), null); assertEquals(processor.createExceptionParserOrNullIfNotFound(method), null);
} }
@ -297,7 +297,7 @@ public class AzureBlobConnectionTest {
Method method = AzureBlobConnection.class.getMethod("setContainerMetadata", String.class, Method method = AzureBlobConnection.class.getMethod("setContainerMetadata", String.class,
Multimap.class); Multimap.class);
HttpRequest httpMethod = processor.createRequest(method, new Object[] { "container", GeneratedHttpRequest<AzureBlobConnection> httpMethod = processor.createRequest(method, new Object[] { "container",
ImmutableMultimap.of("key", "value") }); ImmutableMultimap.of("key", "value") });
assertEquals(httpMethod.getEndpoint().getHost(), "myaccount.blob.core.windows.net"); assertEquals(httpMethod.getEndpoint().getHost(), "myaccount.blob.core.windows.net");
assertEquals(httpMethod.getEndpoint().getPath(), "/container"); assertEquals(httpMethod.getEndpoint().getPath(), "/container");
@ -310,7 +310,7 @@ public class AzureBlobConnectionTest {
.singletonList("2009-07-17")); .singletonList("2009-07-17"));
assertEquals(httpMethod.getHeaders().get("x-ms-meta-key"), Collections.singletonList("value")); assertEquals(httpMethod.getHeaders().get("x-ms-meta-key"), Collections.singletonList("value"));
assertEquals(processor.createResponseParser(method, httpMethod, null).getClass(), assertEquals(processor.createResponseParser(method, httpMethod).getClass(),
ReturnVoidIf2xx.class); ReturnVoidIf2xx.class);
assertEquals(processor.createExceptionParserOrNullIfNotFound(method), null); assertEquals(processor.createExceptionParserOrNullIfNotFound(method), null);
} }
@ -318,7 +318,7 @@ public class AzureBlobConnectionTest {
public void testSetBlobMetadata() throws SecurityException, NoSuchMethodException { public void testSetBlobMetadata() throws SecurityException, NoSuchMethodException {
Method method = AzureBlobConnection.class.getMethod("setBlobMetadata", String.class, Method method = AzureBlobConnection.class.getMethod("setBlobMetadata", String.class,
String.class, Multimap.class); String.class, Multimap.class);
HttpRequest httpMethod = processor.createRequest(method, new Object[] { "container", "blob", GeneratedHttpRequest<AzureBlobConnection> httpMethod = processor.createRequest(method, new Object[] { "container", "blob",
ImmutableMultimap.of("key", "value") }); ImmutableMultimap.of("key", "value") });
assertEquals(httpMethod.getEndpoint().getHost(), "myaccount.blob.core.windows.net"); assertEquals(httpMethod.getEndpoint().getHost(), "myaccount.blob.core.windows.net");
assertEquals(httpMethod.getEndpoint().getPath(), "/container/blob"); assertEquals(httpMethod.getEndpoint().getPath(), "/container/blob");
@ -331,7 +331,7 @@ public class AzureBlobConnectionTest {
.singletonList("0")); .singletonList("0"));
assertEquals(httpMethod.getHeaders().get("x-ms-meta-key"), Collections.singletonList("value")); assertEquals(httpMethod.getHeaders().get("x-ms-meta-key"), Collections.singletonList("value"));
assertEquals(processor.createResponseParser(method, httpMethod, null).getClass(), assertEquals(processor.createResponseParser(method, httpMethod).getClass(),
ReturnVoidIf2xx.class); ReturnVoidIf2xx.class);
assertEquals(processor.createExceptionParserOrNullIfNotFound(method), null); assertEquals(processor.createExceptionParserOrNullIfNotFound(method), null);
} }

View File

@ -42,7 +42,6 @@ import org.jclouds.blobstore.functions.ReturnVoidOnNotFoundOr404;
import org.jclouds.blobstore.reference.BlobStoreConstants; import org.jclouds.blobstore.reference.BlobStoreConstants;
import org.jclouds.concurrent.WithinThreadExecutorService; import org.jclouds.concurrent.WithinThreadExecutorService;
import org.jclouds.concurrent.config.ExecutorServiceModule; import org.jclouds.concurrent.config.ExecutorServiceModule;
import org.jclouds.http.HttpRequest;
import org.jclouds.http.HttpUtils; import org.jclouds.http.HttpUtils;
import org.jclouds.http.config.JavaUrlHttpCommandExecutorServiceModule; import org.jclouds.http.config.JavaUrlHttpCommandExecutorServiceModule;
import org.jclouds.http.functions.ParseETagHeader; import org.jclouds.http.functions.ParseETagHeader;
@ -52,6 +51,7 @@ import org.jclouds.http.functions.ReturnVoidIf2xx;
import org.jclouds.logging.Logger; import org.jclouds.logging.Logger;
import org.jclouds.logging.Logger.LoggerFactory; import org.jclouds.logging.Logger.LoggerFactory;
import org.jclouds.rest.config.RestModule; import org.jclouds.rest.config.RestModule;
import org.jclouds.rest.internal.GeneratedHttpRequest;
import org.jclouds.rest.internal.RestAnnotationProcessor; import org.jclouds.rest.internal.RestAnnotationProcessor;
import org.jclouds.util.Jsr330; import org.jclouds.util.Jsr330;
import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeClass;
@ -75,7 +75,7 @@ public class AzureBlobStoreTest {
public void testListContainers() throws SecurityException, NoSuchMethodException { public void testListContainers() throws SecurityException, NoSuchMethodException {
Method method = AzureBlobStore.class.getMethod("listContainers"); Method method = AzureBlobStore.class.getMethod("listContainers");
HttpRequest httpMethod = processor.createRequest(method, new Object[] {}); GeneratedHttpRequest<AzureBlobStore> httpMethod = processor.createRequest(method, new Object[] {});
assertEquals(httpMethod.getEndpoint().getHost(), "myaccount.blob.core.windows.net"); assertEquals(httpMethod.getEndpoint().getHost(), "myaccount.blob.core.windows.net");
assertEquals(httpMethod.getEndpoint().getPath(), "/"); assertEquals(httpMethod.getEndpoint().getPath(), "/");
assertEquals(httpMethod.getEndpoint().getQuery(), "comp=list"); assertEquals(httpMethod.getEndpoint().getQuery(), "comp=list");
@ -83,7 +83,7 @@ public class AzureBlobStoreTest {
assertEquals(httpMethod.getHeaders().size(), 1); assertEquals(httpMethod.getHeaders().size(), 1);
assertEquals(httpMethod.getHeaders().get("x-ms-version"), Collections assertEquals(httpMethod.getHeaders().get("x-ms-version"), Collections
.singletonList("2009-07-17")); .singletonList("2009-07-17"));
assertEquals(processor.createResponseParser(method, httpMethod, null).getClass(), assertEquals(processor.createResponseParser(method, httpMethod).getClass(),
ParseSax.class); ParseSax.class);
// TODO check generic type of response parser // TODO check generic type of response parser
assertEquals(processor.createExceptionParserOrNullIfNotFound(method), null); assertEquals(processor.createExceptionParserOrNullIfNotFound(method), null);
@ -92,7 +92,7 @@ public class AzureBlobStoreTest {
public void testCreateContainer() throws SecurityException, NoSuchMethodException { public void testCreateContainer() throws SecurityException, NoSuchMethodException {
Method method = AzureBlobStore.class.getMethod("createContainer", String.class); Method method = AzureBlobStore.class.getMethod("createContainer", String.class);
HttpRequest httpMethod = processor.createRequest(method, new Object[] { "container" }); GeneratedHttpRequest<AzureBlobStore> httpMethod = processor.createRequest(method, new Object[] { "container" });
assertEquals(httpMethod.getEndpoint().getHost(), "myaccount.blob.core.windows.net"); assertEquals(httpMethod.getEndpoint().getHost(), "myaccount.blob.core.windows.net");
assertEquals(httpMethod.getEndpoint().getPath(), "/container"); assertEquals(httpMethod.getEndpoint().getPath(), "/container");
assertEquals(httpMethod.getEndpoint().getQuery(), "restype=container"); assertEquals(httpMethod.getEndpoint().getQuery(), "restype=container");
@ -101,7 +101,7 @@ public class AzureBlobStoreTest {
assertEquals(httpMethod.getHeaders().get("x-ms-version"), Collections assertEquals(httpMethod.getHeaders().get("x-ms-version"), Collections
.singletonList("2009-07-17")); .singletonList("2009-07-17"));
assertEquals(httpMethod.getHeaders().get("Content-Length"), Collections.singletonList("0")); assertEquals(httpMethod.getHeaders().get("Content-Length"), Collections.singletonList("0"));
assertEquals(processor.createResponseParser(method, httpMethod, null).getClass(), assertEquals(processor.createResponseParser(method, httpMethod).getClass(),
ReturnTrueIf2xx.class); ReturnTrueIf2xx.class);
// TODO check generic type of response parser // TODO check generic type of response parser
assertEquals(processor.createExceptionParserOrNullIfNotFound(method).getClass(), assertEquals(processor.createExceptionParserOrNullIfNotFound(method).getClass(),
@ -111,7 +111,7 @@ public class AzureBlobStoreTest {
public void testDeleteContainer() throws SecurityException, NoSuchMethodException { public void testDeleteContainer() throws SecurityException, NoSuchMethodException {
Method method = AzureBlobStore.class.getMethod("deleteContainer", String.class); Method method = AzureBlobStore.class.getMethod("deleteContainer", String.class);
HttpRequest httpMethod = processor.createRequest(method, new Object[] { "container" }); GeneratedHttpRequest<AzureBlobStore> httpMethod = processor.createRequest(method, new Object[] { "container" });
assertEquals(httpMethod.getEndpoint().getHost(), "myaccount.blob.core.windows.net"); assertEquals(httpMethod.getEndpoint().getHost(), "myaccount.blob.core.windows.net");
assertEquals(httpMethod.getEndpoint().getPath(), "/container"); assertEquals(httpMethod.getEndpoint().getPath(), "/container");
assertEquals(httpMethod.getEndpoint().getQuery(), "restype=container"); assertEquals(httpMethod.getEndpoint().getQuery(), "restype=container");
@ -119,7 +119,7 @@ public class AzureBlobStoreTest {
assertEquals(httpMethod.getHeaders().size(), 1); assertEquals(httpMethod.getHeaders().size(), 1);
assertEquals(httpMethod.getHeaders().get("x-ms-version"), Collections assertEquals(httpMethod.getHeaders().get("x-ms-version"), Collections
.singletonList("2009-07-17")); .singletonList("2009-07-17"));
assertEquals(processor.createResponseParser(method, httpMethod, null).getClass(), assertEquals(processor.createResponseParser(method, httpMethod).getClass(),
ReturnVoidIf2xx.class); ReturnVoidIf2xx.class);
// TODO check generic type of response parser // TODO check generic type of response parser
assertEquals(processor.createExceptionParserOrNullIfNotFound(method).getClass(), assertEquals(processor.createExceptionParserOrNullIfNotFound(method).getClass(),
@ -129,7 +129,7 @@ public class AzureBlobStoreTest {
public void testListBlobs() throws SecurityException, NoSuchMethodException { public void testListBlobs() throws SecurityException, NoSuchMethodException {
Method method = AzureBlobStore.class.getMethod("listBlobs", String.class); Method method = AzureBlobStore.class.getMethod("listBlobs", String.class);
HttpRequest httpMethod = processor.createRequest(method, new Object[] { "container" }); GeneratedHttpRequest<AzureBlobStore> httpMethod = processor.createRequest(method, new Object[] { "container" });
assertEquals(httpMethod.getEndpoint().getHost(), "myaccount.blob.core.windows.net"); assertEquals(httpMethod.getEndpoint().getHost(), "myaccount.blob.core.windows.net");
assertEquals(httpMethod.getEndpoint().getPath(), "/container"); assertEquals(httpMethod.getEndpoint().getPath(), "/container");
assertEquals(httpMethod.getEndpoint().getQuery(), "restype=container&comp=list"); assertEquals(httpMethod.getEndpoint().getQuery(), "restype=container&comp=list");
@ -137,7 +137,7 @@ public class AzureBlobStoreTest {
assertEquals(httpMethod.getHeaders().size(), 1); assertEquals(httpMethod.getHeaders().size(), 1);
assertEquals(httpMethod.getHeaders().get("x-ms-version"), Collections assertEquals(httpMethod.getHeaders().get("x-ms-version"), Collections
.singletonList("2009-07-17")); .singletonList("2009-07-17"));
assertEquals(processor.createResponseParser(method, httpMethod, null).getClass(), assertEquals(processor.createResponseParser(method, httpMethod).getClass(),
ParseSax.class); ParseSax.class);
// TODO check generic type of response parser // TODO check generic type of response parser
assertEquals(processor.createExceptionParserOrNullIfNotFound(method), null); assertEquals(processor.createExceptionParserOrNullIfNotFound(method), null);
@ -148,7 +148,7 @@ public class AzureBlobStoreTest {
Blob blob = new Blob("test"); Blob blob = new Blob("test");
blob.setData("test"); blob.setData("test");
HttpRequest httpMethod = processor GeneratedHttpRequest<AzureBlobStore> httpMethod = processor
.createRequest(method, new Object[] { "mycontainer", blob }); .createRequest(method, new Object[] { "mycontainer", blob });
assertEquals(httpMethod.getEndpoint().getHost(), "myaccount.blob.core.windows.net"); assertEquals(httpMethod.getEndpoint().getHost(), "myaccount.blob.core.windows.net");
assertEquals(httpMethod.getEndpoint().getPath(), "/mycontainer/test"); assertEquals(httpMethod.getEndpoint().getPath(), "/mycontainer/test");
@ -164,7 +164,7 @@ public class AzureBlobStoreTest {
assertEquals(httpMethod.getHeaders().get("Content-MD5"), Collections.singletonList(HttpUtils assertEquals(httpMethod.getHeaders().get("Content-MD5"), Collections.singletonList(HttpUtils
.toBase64String(HttpUtils.md5("test")))); .toBase64String(HttpUtils.md5("test"))));
assertEquals(httpMethod.getEntity(), "test"); assertEquals(httpMethod.getEntity(), "test");
assertEquals(processor.createResponseParser(method, httpMethod, null).getClass(), assertEquals(processor.createResponseParser(method, httpMethod).getClass(),
ParseETagHeader.class); ParseETagHeader.class);
} }

View File

@ -30,6 +30,9 @@ import java.util.TreeSet;
import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.atomic.AtomicReference;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.HttpHeaders;
import org.jclouds.azure.storage.reference.AzureStorageConstants; import org.jclouds.azure.storage.reference.AzureStorageConstants;
@ -40,9 +43,6 @@ import org.jclouds.http.HttpUtils;
import org.jclouds.util.DateService; import org.jclouds.util.DateService;
import com.google.common.annotations.VisibleForTesting; import com.google.common.annotations.VisibleForTesting;
import javax.inject.Inject;
import javax.inject.Singleton;
import javax.inject.Named;
/** /**
* Signs the Azure Storage request. This will update timestamps at most once per second. * Signs the Azure Storage request. This will update timestamps at most once per second.
@ -101,11 +101,10 @@ public class SharedKeyAuthentication implements HttpRequestFilter {
timeStamp = new AtomicReference<String>(createNewStamp()); timeStamp = new AtomicReference<String>(createNewStamp());
} }
public HttpRequest filter(HttpRequest request) throws HttpException { public void filter(HttpRequest request) throws HttpException {
replaceDateHeader(request); replaceDateHeader(request);
String toSign = createStringToSign(request); String toSign = createStringToSign(request);
calculateAndReplaceAuthHeader(request, toSign); calculateAndReplaceAuthHeader(request, toSign);
return request;
} }
public String createStringToSign(HttpRequest request) { public String createStringToSign(HttpRequest request) {
@ -154,42 +153,45 @@ public class SharedKeyAuthentication implements HttpRequestFilter {
toSign.deleteCharAt(toSign.lastIndexOf(",")); toSign.deleteCharAt(toSign.lastIndexOf(","));
toSign.append("\n"); toSign.append("\n");
} }
// } // }
// // Retrieve all headers for the resource that begin with x-ms-, including the x-ms-date // // Retrieve all headers for the resource that begin with x-ms-, including the x-ms-date
// // header. // // header.
// Set<String> matchingHeaders = Sets.filter(request.getHeaders().keySet(), // Set<String> matchingHeaders = Sets.filter(request.getHeaders().keySet(),
// new Predicate<String>() { // new Predicate<String>() {
// public boolean apply(String input) { // public boolean apply(String input) {
// return input.startsWith("x-ms-"); // return input.startsWith("x-ms-");
// } // }
// }); // });
// //
// // Convert each HTTP header name to lowercase. // // Convert each HTTP header name to lowercase.
// // Sort the container of headers lexicographically by header name, in ascending order. // // Sort the container of headers lexicographically by header name, in ascending order.
// SortedSet<String> lowercaseHeaders = Sets.newTreeSet(Iterables.transform(matchingHeaders, // SortedSet<String> lowercaseHeaders =
// new Function<String, String>() { // Sets.newTreeSet(Iterables.transform(matchingHeaders,
// public String apply(String from) { // new Function<String, String>() {
// return from.toLowerCase(); // public String apply(String from) {
// } // return from.toLowerCase();
// })); // }
// // }));
// for (String header : lowercaseHeaders) { //
// // Combine headers with the same name into one header. The resulting header should be a // for (String header : lowercaseHeaders) {
// // name-value pair of the format "header-name:comma-separated-value-list", without any // // Combine headers with the same name into one header. The resulting header should be a
// // white // // name-value pair of the format "header-name:comma-separated-value-list", without any
// // space between values. // // white
// toSign.append(header).append(":"); // // space between values.
// // Trim any white space around the colon in the header. // toSign.append(header).append(":");
// // TODO: not sure why there would be... // // Trim any white space around the colon in the header.
// for (String value : request.getHeaders().get(header)) // // TODO: not sure why there would be...
// // Replace any breaking white space with a single space. // for (String value : request.getHeaders().get(header))
// toSign.append(value.replaceAll("\r?\n", " ")).append(","); // // Replace any breaking white space with a single space.
// toSign.deleteCharAt(toSign.lastIndexOf(",")); // toSign.append(value.replaceAll("\r?\n", " ")).append(",");
// // Finally, append a new line character to each canonicalized header in the resulting list. // toSign.deleteCharAt(toSign.lastIndexOf(","));
// // Construct the CanonicalizedHeaders string by concatenating all headers in this list into // // Finally, append a new line character to each canonicalized header in the resulting
// // a // list.
// // single string. // // Construct the CanonicalizedHeaders string by concatenating all headers in this list
// toSign.append("\n"); // into
// // a
// // single string.
// toSign.append("\n");
} }
} }

View File

@ -34,6 +34,7 @@ import org.jclouds.azure.storage.reference.AzureStorageConstants;
import org.jclouds.http.HttpRequest; import org.jclouds.http.HttpRequest;
import org.jclouds.http.HttpUtils; import org.jclouds.http.HttpUtils;
import org.jclouds.util.DateService; import org.jclouds.util.DateService;
import org.jclouds.util.Jsr330;
import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider; import org.testng.annotations.DataProvider;
import org.testng.annotations.Test; import org.testng.annotations.Test;
@ -41,7 +42,6 @@ import org.testng.annotations.Test;
import com.google.inject.AbstractModule; import com.google.inject.AbstractModule;
import com.google.inject.Guice; import com.google.inject.Guice;
import com.google.inject.Injector; import com.google.inject.Injector;
import org.jclouds.util.Jsr330;
@Test(groups = "unit", testName = "azurestorage.SharedKeyAuthenticationTest") @Test(groups = "unit", testName = "azurestorage.SharedKeyAuthenticationTest")
public class SharedKeyAuthenticationTest { public class SharedKeyAuthenticationTest {
@ -77,7 +77,9 @@ public class SharedKeyAuthenticationTest {
String signature = request.getFirstHeaderOrNull(HttpHeaders.AUTHORIZATION); String signature = request.getFirstHeaderOrNull(HttpHeaders.AUTHORIZATION);
String date = request.getFirstHeaderOrNull(HttpHeaders.DATE); String date = request.getFirstHeaderOrNull(HttpHeaders.DATE);
int iterations = 1; int iterations = 1;
while (filter.filter(request).getFirstHeaderOrNull(HttpHeaders.DATE).equals(date)) { while (request.getFirstHeaderOrNull(HttpHeaders.DATE).equals(date)) {
date = request.getFirstHeaderOrNull(HttpHeaders.DATE);
filter.filter(request);
iterations++; iterations++;
assertEquals(signature, request.getFirstHeaderOrNull(HttpHeaders.AUTHORIZATION)); assertEquals(signature, request.getFirstHeaderOrNull(HttpHeaders.AUTHORIZATION));
} }

View File

@ -39,7 +39,6 @@ import org.jclouds.azure.storage.options.ListOptions;
import org.jclouds.azure.storage.reference.AzureStorageConstants; import org.jclouds.azure.storage.reference.AzureStorageConstants;
import org.jclouds.concurrent.WithinThreadExecutorService; import org.jclouds.concurrent.WithinThreadExecutorService;
import org.jclouds.concurrent.config.ExecutorServiceModule; import org.jclouds.concurrent.config.ExecutorServiceModule;
import org.jclouds.http.HttpRequest;
import org.jclouds.http.HttpUtils; import org.jclouds.http.HttpUtils;
import org.jclouds.http.config.JavaUrlHttpCommandExecutorServiceModule; import org.jclouds.http.config.JavaUrlHttpCommandExecutorServiceModule;
import org.jclouds.http.functions.ParseSax; import org.jclouds.http.functions.ParseSax;
@ -47,6 +46,7 @@ import org.jclouds.http.functions.ReturnTrueIf2xx;
import org.jclouds.logging.Logger; import org.jclouds.logging.Logger;
import org.jclouds.logging.Logger.LoggerFactory; import org.jclouds.logging.Logger.LoggerFactory;
import org.jclouds.rest.config.RestModule; import org.jclouds.rest.config.RestModule;
import org.jclouds.rest.internal.GeneratedHttpRequest;
import org.jclouds.rest.internal.RestAnnotationProcessor; import org.jclouds.rest.internal.RestAnnotationProcessor;
import org.jclouds.util.Jsr330; import org.jclouds.util.Jsr330;
import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeClass;
@ -74,7 +74,8 @@ public class AzureQueueConnectionTest {
public void testListQueues() throws SecurityException, NoSuchMethodException { public void testListQueues() throws SecurityException, NoSuchMethodException {
Method method = AzureQueueConnection.class.getMethod("listQueues", listOptionsVarargsClass); Method method = AzureQueueConnection.class.getMethod("listQueues", listOptionsVarargsClass);
HttpRequest httpMethod = processor.createRequest(method, new Object[] {}); GeneratedHttpRequest<AzureQueueConnection> httpMethod = processor.createRequest(method,
new Object[] {});
assertEquals(httpMethod.getEndpoint().getHost(), "localhost"); assertEquals(httpMethod.getEndpoint().getHost(), "localhost");
assertEquals(httpMethod.getEndpoint().getPath(), "/"); assertEquals(httpMethod.getEndpoint().getPath(), "/");
assertEquals(httpMethod.getEndpoint().getQuery(), "comp=list"); assertEquals(httpMethod.getEndpoint().getQuery(), "comp=list");
@ -82,8 +83,7 @@ public class AzureQueueConnectionTest {
assertEquals(httpMethod.getHeaders().size(), 1); assertEquals(httpMethod.getHeaders().size(), 1);
assertEquals(httpMethod.getHeaders().get("x-ms-version"), Collections assertEquals(httpMethod.getHeaders().get("x-ms-version"), Collections
.singletonList("2009-07-17")); .singletonList("2009-07-17"));
assertEquals(processor.createResponseParser(method, httpMethod, null).getClass(), assertEquals(processor.createResponseParser(method, httpMethod).getClass(), ParseSax.class);
ParseSax.class);
// TODO check generic type of response parser // TODO check generic type of response parser
assertEquals(processor.createExceptionParserOrNullIfNotFound(method), null); assertEquals(processor.createExceptionParserOrNullIfNotFound(method), null);
} }
@ -91,8 +91,8 @@ public class AzureQueueConnectionTest {
public void testListQueuesOptions() throws SecurityException, NoSuchMethodException { public void testListQueuesOptions() throws SecurityException, NoSuchMethodException {
Method method = AzureQueueConnection.class.getMethod("listQueues", listOptionsVarargsClass); Method method = AzureQueueConnection.class.getMethod("listQueues", listOptionsVarargsClass);
HttpRequest httpMethod = processor.createRequest(method, new Object[] { maxResults(1).marker( GeneratedHttpRequest<AzureQueueConnection> httpMethod = processor.createRequest(method,
"marker").prefix("prefix") }); new Object[] { maxResults(1).marker("marker").prefix("prefix") });
assertEquals(httpMethod.getEndpoint().getHost(), "localhost"); assertEquals(httpMethod.getEndpoint().getHost(), "localhost");
assertEquals(httpMethod.getEndpoint().getPath(), "/"); assertEquals(httpMethod.getEndpoint().getPath(), "/");
assert httpMethod.getEndpoint().getQuery().contains("comp=list"); assert httpMethod.getEndpoint().getQuery().contains("comp=list");
@ -103,8 +103,7 @@ public class AzureQueueConnectionTest {
assertEquals(httpMethod.getHeaders().size(), 1); assertEquals(httpMethod.getHeaders().size(), 1);
assertEquals(httpMethod.getHeaders().get("x-ms-version"), Collections assertEquals(httpMethod.getHeaders().get("x-ms-version"), Collections
.singletonList("2009-07-17")); .singletonList("2009-07-17"));
assertEquals(processor.createResponseParser(method, httpMethod, null).getClass(), assertEquals(processor.createResponseParser(method, httpMethod).getClass(), ParseSax.class);
ParseSax.class);
// TODO check generic type of response parser // TODO check generic type of response parser
assertEquals(processor.createExceptionParserOrNullIfNotFound(method), null); assertEquals(processor.createExceptionParserOrNullIfNotFound(method), null);
} }
@ -113,7 +112,8 @@ public class AzureQueueConnectionTest {
Method method = AzureQueueConnection.class.getMethod("createQueue", String.class, Method method = AzureQueueConnection.class.getMethod("createQueue", String.class,
createOptionsVarargsClass); createOptionsVarargsClass);
HttpRequest httpMethod = processor.createRequest(method, new Object[] { "queue" }); GeneratedHttpRequest<AzureQueueConnection> httpMethod = processor.createRequest(method,
new Object[] { "queue" });
assertEquals(httpMethod.getEndpoint().getHost(), "localhost"); assertEquals(httpMethod.getEndpoint().getHost(), "localhost");
assertEquals(httpMethod.getEndpoint().getPath(), "/queue"); assertEquals(httpMethod.getEndpoint().getPath(), "/queue");
assertEquals(httpMethod.getEndpoint().getQuery(), "restype=queue"); assertEquals(httpMethod.getEndpoint().getQuery(), "restype=queue");
@ -122,7 +122,7 @@ public class AzureQueueConnectionTest {
assertEquals(httpMethod.getHeaders().get("x-ms-version"), Collections assertEquals(httpMethod.getHeaders().get("x-ms-version"), Collections
.singletonList("2009-07-17")); .singletonList("2009-07-17"));
assertEquals(httpMethod.getHeaders().get("Content-Length"), Collections.singletonList("0")); assertEquals(httpMethod.getHeaders().get("Content-Length"), Collections.singletonList("0"));
assertEquals(processor.createResponseParser(method, httpMethod, null).getClass(), assertEquals(processor.createResponseParser(method, httpMethod).getClass(),
ReturnTrueIf2xx.class); ReturnTrueIf2xx.class);
// TODO check generic type of response parser // TODO check generic type of response parser
assertEquals(processor.createExceptionParserOrNullIfNotFound(method), null); assertEquals(processor.createExceptionParserOrNullIfNotFound(method), null);
@ -131,7 +131,8 @@ public class AzureQueueConnectionTest {
public void testDeleteQueue() throws SecurityException, NoSuchMethodException { public void testDeleteQueue() throws SecurityException, NoSuchMethodException {
Method method = AzureQueueConnection.class.getMethod("deleteQueue", String.class); Method method = AzureQueueConnection.class.getMethod("deleteQueue", String.class);
HttpRequest httpMethod = processor.createRequest(method, new Object[] { "queue" }); GeneratedHttpRequest<AzureQueueConnection> httpMethod = processor.createRequest(method,
new Object[] { "queue" });
assertEquals(httpMethod.getEndpoint().getHost(), "localhost"); assertEquals(httpMethod.getEndpoint().getHost(), "localhost");
assertEquals(httpMethod.getEndpoint().getPath(), "/queue"); assertEquals(httpMethod.getEndpoint().getPath(), "/queue");
assertEquals(httpMethod.getEndpoint().getQuery(), "restype=queue"); assertEquals(httpMethod.getEndpoint().getQuery(), "restype=queue");
@ -139,7 +140,7 @@ public class AzureQueueConnectionTest {
assertEquals(httpMethod.getHeaders().size(), 1); assertEquals(httpMethod.getHeaders().size(), 1);
assertEquals(httpMethod.getHeaders().get("x-ms-version"), Collections assertEquals(httpMethod.getHeaders().get("x-ms-version"), Collections
.singletonList("2009-07-17")); .singletonList("2009-07-17"));
assertEquals(processor.createResponseParser(method, httpMethod, null).getClass(), assertEquals(processor.createResponseParser(method, httpMethod).getClass(),
ReturnTrueIf2xx.class); ReturnTrueIf2xx.class);
// TODO check generic type of response parser // TODO check generic type of response parser
assertEquals(processor.createExceptionParserOrNullIfNotFound(method), null); assertEquals(processor.createExceptionParserOrNullIfNotFound(method), null);
@ -149,8 +150,8 @@ public class AzureQueueConnectionTest {
Method method = AzureQueueConnection.class.getMethod("createQueue", String.class, Method method = AzureQueueConnection.class.getMethod("createQueue", String.class,
createOptionsVarargsClass); createOptionsVarargsClass);
HttpRequest httpMethod = processor.createRequest(method, new Object[] { "queue", GeneratedHttpRequest<AzureQueueConnection> httpMethod = processor.createRequest(method,
withMetadata(ImmutableMultimap.of("foo", "bar")) }); new Object[] { "queue", withMetadata(ImmutableMultimap.of("foo", "bar")) });
assertEquals(httpMethod.getEndpoint().getHost(), "localhost"); assertEquals(httpMethod.getEndpoint().getHost(), "localhost");
assertEquals(httpMethod.getEndpoint().getPath(), "/queue"); assertEquals(httpMethod.getEndpoint().getPath(), "/queue");
assertEquals(httpMethod.getEndpoint().getQuery(), "restype=queue"); assertEquals(httpMethod.getEndpoint().getQuery(), "restype=queue");
@ -160,7 +161,7 @@ public class AzureQueueConnectionTest {
.singletonList("2009-07-17")); .singletonList("2009-07-17"));
assertEquals(httpMethod.getHeaders().get("x-ms-meta-foo"), Collections.singletonList("bar")); assertEquals(httpMethod.getHeaders().get("x-ms-meta-foo"), Collections.singletonList("bar"));
assertEquals(httpMethod.getHeaders().get("Content-Length"), Collections.singletonList("0")); assertEquals(httpMethod.getHeaders().get("Content-Length"), Collections.singletonList("0"));
assertEquals(processor.createResponseParser(method, httpMethod, null).getClass(), assertEquals(processor.createResponseParser(method, httpMethod).getClass(),
ReturnTrueIf2xx.class); ReturnTrueIf2xx.class);
// TODO check generic type of response parser // TODO check generic type of response parser
assertEquals(processor.createExceptionParserOrNullIfNotFound(method), null); assertEquals(processor.createExceptionParserOrNullIfNotFound(method), null);

View File

@ -21,7 +21,7 @@
* under the License. * under the License.
* ==================================================================== * ====================================================================
*/ */
package org.jclouds.blobstore.decorators; package org.jclouds.blobstore.binders;
import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkNotNull;
import static org.jclouds.blobstore.reference.BlobStoreConstants.PROPERTY_USER_METADATA_PREFIX; import static org.jclouds.blobstore.reference.BlobStoreConstants.PROPERTY_USER_METADATA_PREFIX;
@ -33,17 +33,17 @@ import javax.ws.rs.core.HttpHeaders;
import org.jclouds.blobstore.domain.Blob; import org.jclouds.blobstore.domain.Blob;
import org.jclouds.http.HttpRequest; import org.jclouds.http.HttpRequest;
import org.jclouds.http.HttpUtils; import org.jclouds.http.HttpUtils;
import org.jclouds.rest.decorators.RequestDecorator; import org.jclouds.rest.Binder;
public class AddBlobEntity implements RequestDecorator { public class BindBlobToEntity implements Binder {
private final String metadataPrefix; private final String metadataPrefix;
@Inject @Inject
public AddBlobEntity(@Named(PROPERTY_USER_METADATA_PREFIX) String metadataPrefix) { public BindBlobToEntity(@Named(PROPERTY_USER_METADATA_PREFIX) String metadataPrefix) {
this.metadataPrefix = metadataPrefix; this.metadataPrefix = metadataPrefix;
} }
public HttpRequest decorateRequest(HttpRequest request, Object entity) { public void bindToRequest(HttpRequest request, Object entity) {
Blob<?> object = (Blob<?>) entity; Blob<?> object = (Blob<?>) entity;
for (String key : object.getMetadata().getUserMetadata().keySet()) { for (String key : object.getMetadata().getUserMetadata().keySet()) {
@ -63,6 +63,5 @@ public class AddBlobEntity implements RequestDecorator {
request.getHeaders().put("Content-MD5", request.getHeaders().put("Content-MD5",
HttpUtils.toBase64String(object.getMetadata().getContentMD5())); HttpUtils.toBase64String(object.getMetadata().getContentMD5()));
} }
return request;
} }
} }

View File

@ -21,7 +21,7 @@
* under the License. * under the License.
* ==================================================================== * ====================================================================
*/ */
package org.jclouds.blobstore.decorators; package org.jclouds.blobstore.binders;
import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkNotNull;
@ -37,7 +37,7 @@ import org.jclouds.blobstore.util.BlobStoreUtils;
import org.jclouds.http.HttpRequest; import org.jclouds.http.HttpRequest;
import org.jclouds.http.MultipartForm; import org.jclouds.http.MultipartForm;
import org.jclouds.http.MultipartForm.Part; import org.jclouds.http.MultipartForm.Part;
import org.jclouds.rest.decorators.RequestDecorator; import org.jclouds.rest.Binder;
import com.google.common.collect.ImmutableMultimap; import com.google.common.collect.ImmutableMultimap;
import com.google.common.collect.Multimap; import com.google.common.collect.Multimap;
@ -46,11 +46,11 @@ import com.google.common.collect.Multimap;
* *
* @author Adrian Cole * @author Adrian Cole
*/ */
public class AddBlobEntityAsMultipartForm implements RequestDecorator { public class BindBlobToMultipartForm implements Binder {
public static final String BOUNDARY = "--JCLOUDS--"; public static final String BOUNDARY = "--JCLOUDS--";
public HttpRequest decorateRequest(HttpRequest request, Object entity) { public void bindToRequest(HttpRequest request, Object entity) {
Blob<?> object = (Blob<?>) entity; Blob<?> object = (Blob<?>) entity;
Key key = BlobStoreUtils.parseKey(new Key("junk", object.getKey())); Key key = BlobStoreUtils.parseKey(new Key("junk", object.getKey()));
Multimap<String, String> partHeaders = ImmutableMultimap.of("Content-Disposition", String Multimap<String, String> partHeaders = ImmutableMultimap.of("Content-Disposition", String
@ -84,6 +84,5 @@ public class AddBlobEntityAsMultipartForm implements RequestDecorator {
"multipart/form-data; boundary=" + BOUNDARY); "multipart/form-data; boundary=" + BOUNDARY);
request.getHeaders().put(HttpHeaders.CONTENT_LENGTH, form.getSize() + ""); request.getHeaders().put(HttpHeaders.CONTENT_LENGTH, form.getSize() + "");
return request;
} }
} }

View File

@ -21,7 +21,7 @@
* under the License. * under the License.
* ==================================================================== * ====================================================================
*/ */
package org.jclouds.blobstore.decorators; package org.jclouds.blobstore.binders;
import static org.jclouds.blobstore.reference.BlobStoreConstants.PROPERTY_USER_METADATA_PREFIX; import static org.jclouds.blobstore.reference.BlobStoreConstants.PROPERTY_USER_METADATA_PREFIX;
@ -31,20 +31,20 @@ import javax.inject.Inject;
import javax.inject.Named; import javax.inject.Named;
import org.jclouds.http.HttpRequest; import org.jclouds.http.HttpRequest;
import org.jclouds.rest.decorators.RequestDecorator; import org.jclouds.rest.Binder;
import com.google.common.collect.Multimap; import com.google.common.collect.Multimap;
public class AddHeadersWithPrefix implements RequestDecorator { public class BindMultimapToHeadersWithPrefix implements Binder {
private final String metadataPrefix; private final String metadataPrefix;
@Inject @Inject
public AddHeadersWithPrefix(@Named(PROPERTY_USER_METADATA_PREFIX) String metadataPrefix) { public BindMultimapToHeadersWithPrefix(@Named(PROPERTY_USER_METADATA_PREFIX) String metadataPrefix) {
this.metadataPrefix = metadataPrefix; this.metadataPrefix = metadataPrefix;
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public HttpRequest decorateRequest( HttpRequest request, Object entity) { public void bindToRequest(HttpRequest request, Object entity) {
Multimap<String, String> userMetadata = (Multimap<String, String>) entity; Multimap<String, String> userMetadata = (Multimap<String, String>) entity;
for (Entry<String, String> entry : userMetadata.entries()) { for (Entry<String, String> entry : userMetadata.entries()) {
if (entry.getKey().startsWith(metadataPrefix)) { if (entry.getKey().startsWith(metadataPrefix)) {
@ -54,7 +54,6 @@ public class AddHeadersWithPrefix implements RequestDecorator {
entry.getValue()); entry.getValue());
} }
} }
return request;
} }
} }

View File

@ -36,9 +36,9 @@ import org.jclouds.blobstore.domain.ContainerMetadata;
import org.jclouds.blobstore.internal.BlobRuntimeException; import org.jclouds.blobstore.internal.BlobRuntimeException;
import org.jclouds.blobstore.reference.BlobStoreConstants; import org.jclouds.blobstore.reference.BlobStoreConstants;
import org.jclouds.blobstore.strategy.ClearContainerStrategy; import org.jclouds.blobstore.strategy.ClearContainerStrategy;
import org.jclouds.http.HttpRequest;
import org.jclouds.http.HttpResponseException; import org.jclouds.http.HttpResponseException;
import org.jclouds.rest.InvocationContext; import org.jclouds.rest.InvocationContext;
import org.jclouds.rest.internal.GeneratedHttpRequest;
import org.jclouds.util.Utils; import org.jclouds.util.Utils;
import com.google.common.base.Function; import com.google.common.base.Function;
@ -62,12 +62,12 @@ public class ClearAndDeleteIfNotEmpty<C extends ContainerMetadata, M extends Blo
@Inject(optional = true) @Inject(optional = true)
@Named(BlobStoreConstants.PROPERTY_BLOBSTORE_TIMEOUT) @Named(BlobStoreConstants.PROPERTY_BLOBSTORE_TIMEOUT)
protected long requestTimeoutMilliseconds = 30000; protected long requestTimeoutMilliseconds = 30000;
private Object[] args;
private HttpRequest request;
private final ClearContainerStrategy<C, M, B> clear; private final ClearContainerStrategy<C, M, B> clear;
private final BlobStore<C, M, B> connection; private final BlobStore<C, M, B> connection;
private GeneratedHttpRequest<?> request;
@Inject @Inject
protected protected
ClearAndDeleteIfNotEmpty(ClearContainerStrategy<C, M, B> clear, BlobStore<C, M, B> connection) { ClearAndDeleteIfNotEmpty(ClearContainerStrategy<C, M, B> clear, BlobStore<C, M, B> connection) {
@ -81,31 +81,21 @@ public class ClearAndDeleteIfNotEmpty<C extends ContainerMetadata, M extends Blo
if (responseException.getResponse().getStatusCode() == 404) { if (responseException.getResponse().getStatusCode() == 404) {
return v; return v;
} else if (responseException.getResponse().getStatusCode() == 409) { } else if (responseException.getResponse().getStatusCode() == 409) {
clear.execute(connection, args[0].toString()); clear.execute(connection, request.getArgs()[0].toString());
try { try {
connection.deleteContainer(args[0].toString()).get(requestTimeoutMilliseconds, connection.deleteContainer(request.getArgs()[0].toString()).get(requestTimeoutMilliseconds,
TimeUnit.MILLISECONDS); TimeUnit.MILLISECONDS);
return v; return v;
} catch (Exception e) { } catch (Exception e) {
Utils.<BlobRuntimeException> rethrowIfRuntimeOrSameType(e); Utils.<BlobRuntimeException> rethrowIfRuntimeOrSameType(e);
throw new BlobRuntimeException("Error deleting container: " + args[0].toString(), e); throw new BlobRuntimeException("Error deleting container: " + request.getArgs()[0].toString(), e);
} }
} }
} }
return null; return null;
} }
public void setContext(GeneratedHttpRequest<?> request) {
public Object[] getArgs() {
return args;
}
public HttpRequest getRequest() {
return request;
}
public void setContext(HttpRequest request, Object[] args) {
this.request = request; this.request = request;
this.args = args;
} }
} }

View File

@ -30,9 +30,9 @@ import javax.ws.rs.core.HttpHeaders;
import org.jclouds.blobstore.domain.Blob; import org.jclouds.blobstore.domain.Blob;
import org.jclouds.blobstore.domain.BlobMetadata; import org.jclouds.blobstore.domain.BlobMetadata;
import org.jclouds.http.HttpException; import org.jclouds.http.HttpException;
import org.jclouds.http.HttpRequest;
import org.jclouds.http.HttpResponse; import org.jclouds.http.HttpResponse;
import org.jclouds.rest.InvocationContext; import org.jclouds.rest.InvocationContext;
import org.jclouds.rest.internal.GeneratedHttpRequest;
import com.google.common.annotations.VisibleForTesting; import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Function; import com.google.common.base.Function;
@ -91,16 +91,8 @@ public class ParseBlobFromHeadersAndHttpContent<M extends BlobMetadata, B extend
} }
} }
public Object[] getArgs() { public void setContext(GeneratedHttpRequest<?> request) {
return metadataParser.getArgs(); metadataParser.setContext(request);
}
public HttpRequest getRequest() {
return metadataParser.getRequest();
}
public void setContext(HttpRequest request, Object[] args) {
metadataParser.setContext(request, args);
} }
} }

View File

@ -29,9 +29,9 @@ import javax.ws.rs.core.HttpHeaders;
import org.jclouds.blobstore.domain.BlobMetadata; import org.jclouds.blobstore.domain.BlobMetadata;
import org.jclouds.http.HttpException; import org.jclouds.http.HttpException;
import org.jclouds.http.HttpRequest;
import org.jclouds.http.HttpResponse; import org.jclouds.http.HttpResponse;
import org.jclouds.rest.InvocationContext; import org.jclouds.rest.InvocationContext;
import org.jclouds.rest.internal.GeneratedHttpRequest;
import com.google.common.annotations.VisibleForTesting; import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Function; import com.google.common.base.Function;
@ -42,8 +42,7 @@ import com.google.common.base.Function;
public class ParseContentTypeFromHeaders<M extends BlobMetadata> implements public class ParseContentTypeFromHeaders<M extends BlobMetadata> implements
Function<HttpResponse, M>, InvocationContext { Function<HttpResponse, M>, InvocationContext {
private final Provider<M> metadataFactory; private final Provider<M> metadataFactory;
private HttpRequest request; private GeneratedHttpRequest<?> request;
private Object[] args;
@Inject @Inject
public ParseContentTypeFromHeaders(Provider<M> metadataFactory) { public ParseContentTypeFromHeaders(Provider<M> metadataFactory) {
@ -60,7 +59,7 @@ public class ParseContentTypeFromHeaders<M extends BlobMetadata> implements
} }
protected String getKeyFor(HttpResponse from) { protected String getKeyFor(HttpResponse from) {
String objectKey = getRequest().getEndpoint().getPath(); String objectKey = request.getEndpoint().getPath();
if (objectKey.startsWith("/")) { if (objectKey.startsWith("/")) {
// Trim initial slash from object key name. // Trim initial slash from object key name.
objectKey = objectKey.substring(1); objectKey = objectKey.substring(1);
@ -82,17 +81,8 @@ public class ParseContentTypeFromHeaders<M extends BlobMetadata> implements
metadata.setContentType(contentType); metadata.setContentType(contentType);
} }
public Object[] getArgs() { public void setContext(GeneratedHttpRequest<?> request) {
return args;
}
public HttpRequest getRequest() {
return request;
}
public void setContext(HttpRequest request, Object[] args) {
this.request = request; this.request = request;
this.args = args;
} }
} }

View File

@ -21,7 +21,7 @@
* under the License. * under the License.
* ==================================================================== * ====================================================================
*/ */
package org.jclouds.blobstore.decorators; package org.jclouds.blobstore.binders;
import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertEquals;
@ -32,7 +32,6 @@ import java.net.URI;
import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MediaType;
import org.jclouds.blobstore.decorators.AddBlobEntityAsMultipartForm;
import org.jclouds.blobstore.domain.Blob; import org.jclouds.blobstore.domain.Blob;
import org.jclouds.blobstore.domain.BlobMetadata; import org.jclouds.blobstore.domain.BlobMetadata;
import org.jclouds.http.HttpRequest; import org.jclouds.http.HttpRequest;
@ -44,10 +43,10 @@ import org.testng.annotations.Test;
* *
* @author Adrian Cole * @author Adrian Cole
*/ */
@Test(testName = "blobstore.AddBlobEntityAsMultipartFormTest") @Test(testName = "blobstore.BindBlobToMultipartFormTest")
public class AddBlobEntityAsMultipartFormTest { public class BindBlobToMultipartFormTest {
public static String BOUNDRY = AddBlobEntityAsMultipartForm.BOUNDARY; public static String BOUNDRY = BindBlobToMultipartForm.BOUNDARY;
public static final String EXPECTS; public static final String EXPECTS;
public static final Blob<BlobMetadata> TEST_BLOB; public static final Blob<BlobMetadata> TEST_BLOB;
@ -65,10 +64,10 @@ public class AddBlobEntityAsMultipartFormTest {
assertEquals(EXPECTS.length(), 131); assertEquals(EXPECTS.length(), 131);
AddBlobEntityAsMultipartForm binder = new AddBlobEntityAsMultipartForm(); BindBlobToMultipartForm binder = new BindBlobToMultipartForm();
HttpRequest request = new HttpRequest("GET", URI.create("http://localhost:8001")); HttpRequest request = new HttpRequest("GET", URI.create("http://localhost:8001"));
binder.decorateRequest(request, TEST_BLOB); binder.bindToRequest(request, TEST_BLOB);
assertEquals(Utils.toStringAndClose((InputStream) request.getEntity()), EXPECTS); assertEquals(Utils.toStringAndClose((InputStream) request.getEntity()), EXPECTS);
assertEquals(request.getFirstHeaderOrNull(HttpHeaders.CONTENT_LENGTH), 131 + ""); assertEquals(request.getFirstHeaderOrNull(HttpHeaders.CONTENT_LENGTH), 131 + "");

View File

@ -23,6 +23,9 @@
*/ */
package org.jclouds.blobstore.functions; package org.jclouds.blobstore.functions;
import static org.easymock.EasyMock.expect;
import static org.easymock.classextension.EasyMock.createMock;
import static org.easymock.classextension.EasyMock.replay;
import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertEquals;
import java.net.URI; import java.net.URI;
@ -34,9 +37,9 @@ import javax.ws.rs.core.MediaType;
import org.jclouds.blobstore.domain.BlobMetadata; import org.jclouds.blobstore.domain.BlobMetadata;
import org.jclouds.http.HttpException; import org.jclouds.http.HttpException;
import org.jclouds.http.HttpRequest;
import org.jclouds.http.HttpResponse; import org.jclouds.http.HttpResponse;
import org.jclouds.http.HttpUtils; import org.jclouds.http.HttpUtils;
import org.jclouds.rest.internal.GeneratedHttpRequest;
import org.jclouds.util.DateService; import org.jclouds.util.DateService;
import org.testng.annotations.BeforeTest; import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test; import org.testng.annotations.Test;
@ -60,9 +63,11 @@ public class ParseBlobMetadataFromHeadersTest {
parser = new ParseSystemAndUserMetadataFromHeaders<BlobMetadata>(new DateService(), "prefix", parser = new ParseSystemAndUserMetadataFromHeaders<BlobMetadata>(new DateService(), "prefix",
blobMetadataProvider); blobMetadataProvider);
parser
.setContext(new HttpRequest("GET", URI.create("http://localhost/key")), GeneratedHttpRequest<?> request = createMock(GeneratedHttpRequest.class);
new Object[] {}); expect(request.getEndpoint()).andReturn(URI.create("http://localhost/key")).anyTimes();
replay(request);
parser.setContext(request);
} }
@Test @Test

View File

@ -44,8 +44,8 @@ public class HttpRequest extends HttpMessage implements Request<URI> {
private List<HttpRequestFilter> requestFilters = Lists.newArrayList(); private List<HttpRequestFilter> requestFilters = Lists.newArrayList();
private final String method; private String method;
private final URI endpoint; private URI endpoint;
private Object entity; private Object entity;
/** /**
@ -56,8 +56,8 @@ public class HttpRequest extends HttpMessage implements Request<URI> {
* If the request is HEAD, this may change to GET due to redirects * If the request is HEAD, this may change to GET due to redirects
*/ */
public HttpRequest(String method, URI endPoint) { public HttpRequest(String method, URI endPoint) {
this.method = checkNotNull(method, "method"); this.setMethod(checkNotNull(method, "method"));
this.endpoint = checkNotNull(endPoint, "endPoint"); this.setEndpoint(checkNotNull(endPoint, "endPoint"));
checkArgument(endPoint.getHost() != null, String.format("endPoint.getHost() is null for %s", checkArgument(endPoint.getHost() != null, String.format("endPoint.getHost() is null for %s",
endPoint)); endPoint));
} }
@ -81,7 +81,7 @@ public class HttpRequest extends HttpMessage implements Request<URI> {
* @param method * @param method
* If the request is HEAD, this may change to GET due to redirects * If the request is HEAD, this may change to GET due to redirects
*/ */
public HttpRequest(String method, URI endPoint, Multimap<String, String> headers, protected HttpRequest(String method, URI endPoint, Multimap<String, String> headers,
@Nullable Object entity) { @Nullable Object entity) {
this(method, endPoint); this(method, endPoint);
setHeaders(checkNotNull(headers, "headers")); setHeaders(checkNotNull(headers, "headers"));
@ -89,7 +89,7 @@ public class HttpRequest extends HttpMessage implements Request<URI> {
} }
public String getRequestLine() { public String getRequestLine() {
return String.format("%s %s HTTP/1.1", getMethod(), endpoint.toASCIIString()); return String.format("%s %s HTTP/1.1", getMethod(), getEndpoint().toASCIIString());
} }
/** /**
@ -122,4 +122,12 @@ public class HttpRequest extends HttpMessage implements Request<URI> {
return requestFilters; return requestFilters;
} }
public void setMethod(String method) {
this.method = method;
}
public void setEndpoint(URI endpoint) {
this.endpoint = endpoint;
}
} }

View File

@ -29,5 +29,5 @@ package org.jclouds.http;
* @author Adrian Cole * @author Adrian Cole
*/ */
public interface HttpRequestFilter { public interface HttpRequestFilter {
HttpRequest filter(HttpRequest request) throws HttpException; void filter(HttpRequest request) throws HttpException;
} }

View File

@ -25,7 +25,6 @@ package org.jclouds.http;
import java.io.InputStream; import java.io.InputStream;
import java.util.Collections; import java.util.Collections;
import java.util.List;
import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future; import java.util.concurrent.Future;
@ -107,15 +106,11 @@ public class TransformingHttpCommandImpl<T> implements TransformingHttpCommand<T
* <p /> * <p />
* This also removes the Host header in order to avoid ssl problems. * This also removes the Host header in order to avoid ssl problems.
*/ */
public HttpRequest setHostAndPort(String host, int port) { // TODO must unit test to ensure public HttpRequest setHostAndPort(String host, int port) {
// request is copied 100%
UriBuilder builder = UriBuilder.fromUri(request.getEndpoint()); UriBuilder builder = UriBuilder.fromUri(request.getEndpoint());
builder.host(host); builder.host(host);
builder.port(port); builder.port(port);
List<HttpRequestFilter> oldFilters = request.getFilters(); request.setEndpoint(builder.build());
request = new HttpRequest(request.getMethod(), builder.build(), request.getHeaders(), request
.getEntity());
request.getFilters().addAll(oldFilters);
request.getHeaders().replaceValues(HttpHeaders.HOST, Collections.singletonList(host)); request.getHeaders().replaceValues(HttpHeaders.HOST, Collections.singletonList(host));
return request; return request;
} }
@ -126,7 +121,7 @@ public class TransformingHttpCommandImpl<T> implements TransformingHttpCommand<T
* @param method * @param method
*/ */
public HttpRequest setMethod(String method) { public HttpRequest setMethod(String method) {
request = new HttpRequest(method, request.getEndpoint(), request.getHeaders()); request.setMethod(method);
return request; return request;
} }

View File

@ -29,6 +29,7 @@ import java.io.UnsupportedEncodingException;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import javax.inject.Singleton;
import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.HttpHeaders;
import org.jclouds.http.HttpException; import org.jclouds.http.HttpException;
@ -36,8 +37,6 @@ import org.jclouds.http.HttpRequest;
import org.jclouds.http.HttpRequestFilter; import org.jclouds.http.HttpRequestFilter;
import org.jclouds.http.HttpUtils; import org.jclouds.http.HttpUtils;
import javax.inject.Singleton;
/** /**
* Uses Basic Authentication to sign the request. * Uses Basic Authentication to sign the request.
* *
@ -56,8 +55,7 @@ public class BasicAuthentication implements HttpRequestFilter {
checkNotNull(password, "password")).getBytes("UTF-8"))); checkNotNull(password, "password")).getBytes("UTF-8")));
} }
public HttpRequest filter(HttpRequest request) throws HttpException { public void filter(HttpRequest request) throws HttpException {
request.getHeaders().replaceValues(HttpHeaders.AUTHORIZATION, credentialList); request.getHeaders().replaceValues(HttpHeaders.AUTHORIZATION, credentialList);
return request;
} }
} }

View File

@ -26,11 +26,11 @@ package org.jclouds.http.functions;
import javax.annotation.Resource; import javax.annotation.Resource;
import org.apache.commons.io.IOUtils; import org.apache.commons.io.IOUtils;
import org.jclouds.http.HttpRequest;
import org.jclouds.http.HttpResponse; import org.jclouds.http.HttpResponse;
import org.jclouds.http.HttpUtils; import org.jclouds.http.HttpUtils;
import org.jclouds.logging.Logger; import org.jclouds.logging.Logger;
import org.jclouds.rest.InvocationContext; import org.jclouds.rest.InvocationContext;
import org.jclouds.rest.internal.GeneratedHttpRequest;
import com.google.common.base.Function; import com.google.common.base.Function;
@ -42,16 +42,16 @@ public class ParseContentMD5FromHeaders implements Function<HttpResponse, byte[]
public static class NoContentMD5Exception extends RuntimeException { public static class NoContentMD5Exception extends RuntimeException {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
private final HttpRequest request; private final GeneratedHttpRequest<?> request;
private final HttpResponse response; private final HttpResponse response;
public NoContentMD5Exception(HttpRequest request, HttpResponse response) { public NoContentMD5Exception(GeneratedHttpRequest<?> request, HttpResponse response) {
super(String.format("no MD5 returned from request: %s; response %s", request, response)); super(String.format("no MD5 returned from request: %s; response %s", request, response));
this.request = request; this.request = request;
this.response = response; this.response = response;
} }
public HttpRequest getRequest() { public GeneratedHttpRequest<?> getRequest() {
return request; return request;
} }
@ -63,8 +63,7 @@ public class ParseContentMD5FromHeaders implements Function<HttpResponse, byte[]
@Resource @Resource
protected Logger logger = Logger.NULL; protected Logger logger = Logger.NULL;
private Object[] args; private GeneratedHttpRequest<?> request;
private HttpRequest request;
public byte[] apply(HttpResponse from) { public byte[] apply(HttpResponse from) {
IOUtils.closeQuietly(from.getContent()); IOUtils.closeQuietly(from.getContent());
@ -75,17 +74,8 @@ public class ParseContentMD5FromHeaders implements Function<HttpResponse, byte[]
throw new NoContentMD5Exception(request, from); throw new NoContentMD5Exception(request, from);
} }
public Object[] getArgs() { public void setContext(GeneratedHttpRequest<?> request) {
return args;
}
public HttpRequest getRequest() {
return request;
}
public void setContext(HttpRequest request, Object[] args) {
this.request = request; this.request = request;
this.args = args;
} }
} }

View File

@ -83,7 +83,7 @@ public abstract class BaseHttpCommandExecutorService<Q> implements HttpCommandEx
Q nativeRequest = null; Q nativeRequest = null;
try { try {
for (HttpRequestFilter filter : request.getFilters()) { for (HttpRequestFilter filter : request.getFilters()) {
request = filter.filter(request); filter.filter(request);
} }
logger.debug("Sending request: %s", request.getRequestLine()); logger.debug("Sending request: %s", request.getRequestLine());
if (request.getEntity() != null && wire.enabled()) if (request.getEntity() != null && wire.enabled())

View File

@ -21,7 +21,7 @@
* under the License. * under the License.
* ==================================================================== * ====================================================================
*/ */
package org.jclouds.rest.decorators; package org.jclouds.rest;
import org.jclouds.http.HttpRequest; import org.jclouds.http.HttpRequest;
@ -30,6 +30,6 @@ import org.jclouds.http.HttpRequest;
* *
* @author Adrian Cole * @author Adrian Cole
*/ */
public interface RequestDecorator { public interface Binder {
public HttpRequest decorateRequest(HttpRequest request, Object input); public void bindToRequest(HttpRequest request, Object input);
} }

View File

@ -25,19 +25,14 @@ package org.jclouds.rest;
import javax.ws.rs.PathParam; import javax.ws.rs.PathParam;
import org.jclouds.http.HttpRequest; import org.jclouds.rest.internal.GeneratedHttpRequest;
/** /**
* Passes parsed Http request and Object [] from the method args used to derive the request into * Passes generated Http request into this object;
* this object;
* *
* @see PathParam * @see PathParam
* @author Adrian Cole * @author Adrian Cole
*/ */
public interface InvocationContext { public interface InvocationContext {
void setContext(HttpRequest request, Object[] args); void setContext(GeneratedHttpRequest<?> request);
Object[] getArgs();
HttpRequest getRequest();
} }

View File

@ -21,7 +21,7 @@
* under the License. * under the License.
* ==================================================================== * ====================================================================
*/ */
package org.jclouds.rest.decorators; package org.jclouds.rest;
import java.util.Map; import java.util.Map;
@ -33,13 +33,13 @@ import org.jclouds.http.HttpRequest;
* @author Adrian Cole * @author Adrian Cole
* *
*/ */
public interface MapRequestDecorator extends RequestDecorator { public interface MapBinder extends Binder {
/** /**
* creates and binds the POST entity to the request using parameters specified. * creates and binds the POST entity to the request using parameters specified.
* *
* @see MapEntityParam * @see MapEntityParam
*/ */
public HttpRequest decorateRequest(HttpRequest request, Map<String, String> postParams); public void bindToRequest(HttpRequest request, Map<String, String> postParams);
} }

View File

@ -29,7 +29,7 @@ import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Retention; import java.lang.annotation.Retention;
import java.lang.annotation.Target; import java.lang.annotation.Target;
import org.jclouds.rest.decorators.RequestDecorator; import org.jclouds.rest.Binder;
/** /**
* Designates that this parameter will modify the request, possibly including adding an entity to * Designates that this parameter will modify the request, possibly including adding an entity to
@ -39,10 +39,10 @@ import org.jclouds.rest.decorators.RequestDecorator;
*/ */
@Target(PARAMETER) @Target(PARAMETER)
@Retention(RUNTIME) @Retention(RUNTIME)
public @interface DecoratorParam { public @interface BinderParam {
/** /**
* how to persist this entity. * how to persist this entity.
*/ */
Class<? extends RequestDecorator> value(); Class<? extends Binder> value();
} }

View File

@ -29,8 +29,6 @@ import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Retention; import java.lang.annotation.Retention;
import java.lang.annotation.Target; import java.lang.annotation.Target;
import org.jclouds.rest.decorators.MapRequestDecorator;
/** /**
* Designates that this parameter will hold the entity for a PUT or POST command. * Designates that this parameter will hold the entity for a PUT or POST command.
* *
@ -41,8 +39,8 @@ import org.jclouds.rest.decorators.MapRequestDecorator;
public @interface MapBinder { public @interface MapBinder {
/** /**
* How to bind {@link MapEntityParam} values, if there is no {@link MapRequestDecorator} in the method * How to bind {@link MapEntityParam} values, if there is no {@link MapBinder} in the method
* definition * definition
*/ */
Class<? extends MapRequestDecorator> value(); Class<? extends org.jclouds.rest.MapBinder> value();
} }

View File

@ -39,7 +39,7 @@ import java.lang.annotation.Target;
public @interface MapEntityParam { public @interface MapEntityParam {
/** /**
* The key used in a map passed to the {@link MapRequestDecorator} associated with the request. * The key used in a map passed to the {@link MapBinder} associated with the request.
*/ */
String value(); String value();
} }

View File

@ -21,7 +21,7 @@
* under the License. * under the License.
* ==================================================================== * ====================================================================
*/ */
package org.jclouds.rest.decorators; package org.jclouds.rest.binders;
import static com.google.common.base.Preconditions.checkState; import static com.google.common.base.Preconditions.checkState;
@ -33,6 +33,7 @@ import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MediaType;
import org.jclouds.http.HttpRequest; import org.jclouds.http.HttpRequest;
import org.jclouds.rest.MapBinder;
import com.google.gson.Gson; import com.google.gson.Gson;
@ -42,16 +43,16 @@ import com.google.gson.Gson;
* @author Adrian Cole * @author Adrian Cole
* @since 4.0 * @since 4.0
*/ */
public class AddAsJsonEntity implements MapRequestDecorator { public class BindToJsonEntity implements MapBinder {
@Inject @Inject
protected Gson gson; protected Gson gson;
public HttpRequest decorateRequest(HttpRequest request, Map<String, String> postParams) { public void bindToRequest(HttpRequest request, Map<String, String> postParams) {
return decorateRequest(request, (Object) postParams); bindToRequest(request, (Object) postParams);
} }
public HttpRequest decorateRequest(HttpRequest request, Object toBind) { public void bindToRequest(HttpRequest request, Object toBind) {
checkState(gson != null, "Program error: gson should have been injected at this point"); checkState(gson != null, "Program error: gson should have been injected at this point");
String json = gson.toJson(toBind); String json = gson.toJson(toBind);
request.setEntity(json); request.setEntity(json);
@ -59,7 +60,6 @@ public class AddAsJsonEntity implements MapRequestDecorator {
Collections.singletonList(json.getBytes().length + "")); Collections.singletonList(json.getBytes().length + ""));
request.getHeaders().replaceValues(HttpHeaders.CONTENT_TYPE, request.getHeaders().replaceValues(HttpHeaders.CONTENT_TYPE,
Collections.singletonList(MediaType.APPLICATION_JSON)); Collections.singletonList(MediaType.APPLICATION_JSON));
return request;
} }
} }

View File

@ -21,12 +21,13 @@
* under the License. * under the License.
* ==================================================================== * ====================================================================
*/ */
package org.jclouds.rest.decorators; package org.jclouds.rest.binders;
import javax.inject.Singleton; import javax.inject.Singleton;
import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.HttpHeaders;
import org.jclouds.http.HttpRequest; import org.jclouds.http.HttpRequest;
import org.jclouds.rest.Binder;
/** /**
* Adds an entity to a request. * Adds an entity to a request.
@ -34,13 +35,12 @@ import org.jclouds.http.HttpRequest;
* @author Adrian Cole * @author Adrian Cole
*/ */
@Singleton @Singleton
public class AddAsStringEntity implements RequestDecorator { public class BindToStringEntity implements Binder {
public HttpRequest decorateRequest(HttpRequest request, Object entity) { public void bindToRequest(HttpRequest request, Object entity) {
String stringEntity = entity.toString(); String stringEntity = entity.toString();
if (request.getFirstHeaderOrNull(HttpHeaders.CONTENT_TYPE) == null) if (request.getFirstHeaderOrNull(HttpHeaders.CONTENT_TYPE) == null)
request.getHeaders().put(HttpHeaders.CONTENT_TYPE, "application/unknown"); request.getHeaders().put(HttpHeaders.CONTENT_TYPE, "application/unknown");
request.getHeaders().put(HttpHeaders.CONTENT_LENGTH, stringEntity.getBytes().length + ""); request.getHeaders().put(HttpHeaders.CONTENT_LENGTH, stringEntity.getBytes().length + "");
request.setEntity(stringEntity); request.setEntity(stringEntity);
return request;
} }
} }

View File

@ -0,0 +1,52 @@
package org.jclouds.rest.internal;
import java.lang.reflect.Method;
import java.net.URI;
import javax.ws.rs.core.UriBuilder;
import org.jclouds.http.HttpRequest;
/**
* Represents a request generated from annotations
*
* @author Adrian Cole
*/
public class GeneratedHttpRequest<T> extends HttpRequest {
private final Class<T> declaring;
private final Method javaMethod;
private final Object[] args;
private final RestAnnotationProcessor<T> processor;
GeneratedHttpRequest(String method, URI endPoint, RestAnnotationProcessor<T> processor,
Class<T> declaring, Method javaMethod, Object... args) {
super(method, endPoint);
this.processor = processor;
this.declaring = declaring;
this.javaMethod = javaMethod;
this.args = args;
}
public Class<T> getDeclaring() {
return declaring;
}
public Method getJavaMethod() {
return javaMethod;
}
public Object[] getArgs() {
return args;
}
public RestAnnotationProcessor<T> getProcessor() {
return processor;
}
public void replaceQueryParam(String name, Object... values) {
UriBuilder builder = UriBuilder.fromUri(getEndpoint());
builder.replaceQueryParam(name, values);
URI newEndpoint = processor.replaceQuery(getEndpoint(), builder.build().getQuery());
setEndpoint(newEndpoint);
}
}

View File

@ -70,8 +70,9 @@ import org.jclouds.http.functions.ReturnVoidIf2xx;
import org.jclouds.http.functions.ParseSax.HandlerWithResult; import org.jclouds.http.functions.ParseSax.HandlerWithResult;
import org.jclouds.http.options.HttpRequestOptions; import org.jclouds.http.options.HttpRequestOptions;
import org.jclouds.logging.Logger; import org.jclouds.logging.Logger;
import org.jclouds.rest.Binder;
import org.jclouds.rest.InvocationContext; import org.jclouds.rest.InvocationContext;
import org.jclouds.rest.annotations.DecoratorParam; import org.jclouds.rest.annotations.BinderParam;
import org.jclouds.rest.annotations.Endpoint; import org.jclouds.rest.annotations.Endpoint;
import org.jclouds.rest.annotations.ExceptionParser; import org.jclouds.rest.annotations.ExceptionParser;
import org.jclouds.rest.annotations.Headers; import org.jclouds.rest.annotations.Headers;
@ -86,8 +87,6 @@ import org.jclouds.rest.annotations.ResponseParser;
import org.jclouds.rest.annotations.SkipEncoding; import org.jclouds.rest.annotations.SkipEncoding;
import org.jclouds.rest.annotations.VirtualHost; import org.jclouds.rest.annotations.VirtualHost;
import org.jclouds.rest.annotations.XMLResponseParser; import org.jclouds.rest.annotations.XMLResponseParser;
import org.jclouds.rest.decorators.MapRequestDecorator;
import org.jclouds.rest.decorators.RequestDecorator;
import com.google.common.annotations.VisibleForTesting; import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Function; import com.google.common.base.Function;
@ -116,7 +115,7 @@ public class RestAnnotationProcessor<T> {
private final Class<T> declaring; private final Class<T> declaring;
private final Map<Method, Map<Integer, Set<Annotation>>> methodToIndexOfParamToDecoratorParamAnnotation = createMethodToIndexOfParamToAnnotation(DecoratorParam.class); private final Map<Method, Map<Integer, Set<Annotation>>> methodToIndexOfParamToDecoratorParamAnnotation = createMethodToIndexOfParamToAnnotation(BinderParam.class);
private final Map<Method, Map<Integer, Set<Annotation>>> methodToIndexOfParamToHeaderParamAnnotations = createMethodToIndexOfParamToAnnotation(HeaderParam.class); private final Map<Method, Map<Integer, Set<Annotation>>> methodToIndexOfParamToHeaderParamAnnotations = createMethodToIndexOfParamToAnnotation(HeaderParam.class);
private final Map<Method, Map<Integer, Set<Annotation>>> methodToIndexOfParamToHostPrefixParamAnnotations = createMethodToIndexOfParamToAnnotation(HostPrefixParam.class); private final Map<Method, Map<Integer, Set<Annotation>>> methodToIndexOfParamToHostPrefixParamAnnotations = createMethodToIndexOfParamToAnnotation(HostPrefixParam.class);
private final Map<Method, Map<Integer, Set<Annotation>>> methodToindexOfParamToEndpointAnnotations = createMethodToIndexOfParamToAnnotation(Endpoint.class); private final Map<Method, Map<Integer, Set<Annotation>>> methodToindexOfParamToEndpointAnnotations = createMethodToIndexOfParamToAnnotation(Endpoint.class);
@ -184,8 +183,8 @@ public class RestAnnotationProcessor<T> {
private final ParseSax.Factory parserFactory; private final ParseSax.Factory parserFactory;
@VisibleForTesting @VisibleForTesting
public Function<HttpResponse, ?> createResponseParser(Method method, HttpRequest request, public Function<HttpResponse, ?> createResponseParser(Method method,
Object[] args) { GeneratedHttpRequest<T> request, Object... args) {
Function<HttpResponse, ?> transformer; Function<HttpResponse, ?> transformer;
Class<? extends HandlerWithResult<?>> handler = getXMLTransformerOrNull(method); Class<? extends HandlerWithResult<?>> handler = getXMLTransformerOrNull(method);
if (handler != null) { if (handler != null) {
@ -194,7 +193,7 @@ public class RestAnnotationProcessor<T> {
transformer = injector.getInstance(getParserOrThrowException(method)); transformer = injector.getInstance(getParserOrThrowException(method));
} }
if (transformer instanceof InvocationContext) { if (transformer instanceof InvocationContext) {
((InvocationContext) transformer).setContext(request, args); ((InvocationContext) transformer).setContext(request);
} }
return transformer; return transformer;
} }
@ -216,6 +215,11 @@ public class RestAnnotationProcessor<T> {
this.injector = injector; this.injector = injector;
this.parserFactory = parserFactory; this.parserFactory = parserFactory;
seedCache(declaring); seedCache(declaring);
if (declaring.isAnnotationPresent(SkipEncoding.class)) {
skipEncode = declaring.getAnnotation(SkipEncoding.class).value();
} else {
skipEncode = new char[] {};
}
} }
public Method getDelegateOrNull(Method in) { public Method getDelegateOrNull(Method in) {
@ -292,8 +296,9 @@ public class RestAnnotationProcessor<T> {
} }
final Injector injector; final Injector injector;
final char[] skipEncode;
public HttpRequest createRequest(Method method, Object[] args) { public GeneratedHttpRequest<T> createRequest(Method method, Object... args) {
URI endpoint = getEndpointFor(method, args); URI endpoint = getEndpointFor(method, args);
String httpMethod = getHttpMethodOrConstantOrThrowException(method); String httpMethod = getHttpMethodOrConstantOrThrowException(method);
@ -302,18 +307,13 @@ public class RestAnnotationProcessor<T> {
builder.path(declaring); builder.path(declaring);
builder.path(method); builder.path(method);
Multimap<String, String> tokenValues; Multimap<String, String> tokenValues = encodeValues(getPathParamKeyValues(method, args),
if (declaring.isAnnotationPresent(SkipEncoding.class)) { skipEncode);
tokenValues = encodeValues(getPathParamKeyValues(method, args), declaring.getAnnotation(
SkipEncoding.class).value());
} else {
tokenValues = encodeValues(getPathParamKeyValues(method, args));
}
addQueryParams(method, args, builder, tokenValues.entries()); addQueryParams(builder, tokenValues.entries(), method, args);
addMatrixParams(method, args, builder, tokenValues.entries()); addMatrixParams(builder, tokenValues.entries(), method, args);
Multimap<String, String> headers = buildHeaders(method, args, tokenValues.entries()); Multimap<String, String> headers = buildHeaders(tokenValues.entries(), method, args);
String stringEntity = null; String stringEntity = null;
HttpRequestOptions options = findOptionsIn(method, args); HttpRequestOptions options = findOptionsIn(method, args);
@ -349,7 +349,11 @@ public class RestAnnotationProcessor<T> {
throw new IllegalStateException(e); throw new IllegalStateException(e);
} }
HttpRequest request = new HttpRequest(httpMethod, endPoint, headers); endPoint = replaceQuery(endPoint, endPoint.getQuery());
GeneratedHttpRequest<T> request = new GeneratedHttpRequest<T>(httpMethod, endPoint, this,
declaring, method, args);
request.setHeaders(headers);
addHostHeaderIfAnnotatedWithVirtualHost(headers, request.getEndpoint().getHost(), method); addHostHeaderIfAnnotatedWithVirtualHost(headers, request.getEndpoint().getHost(), method);
addFiltersIfAnnotated(method, request); addFiltersIfAnnotated(method, request);
if (stringEntity != null) { if (stringEntity != null) {
@ -357,11 +361,26 @@ public class RestAnnotationProcessor<T> {
if (headers.get(HttpHeaders.CONTENT_TYPE) != null) if (headers.get(HttpHeaders.CONTENT_TYPE) != null)
headers.put(HttpHeaders.CONTENT_TYPE, "application/unknown"); headers.put(HttpHeaders.CONTENT_TYPE, "application/unknown");
} }
return decorateRequest(method, args, request); decorateRequest(request);
return request;
} }
private void addMatrixParams(Method method, Object[] args, UriBuilder builder, @VisibleForTesting
Collection<Entry<String, String>> tokenValues) { URI replaceQuery(URI endPoint, String query) {
return replaceQuery(endPoint, query, skipEncode);
}
@VisibleForTesting
static URI replaceQuery(URI endPoint, String query, char... skipEncode) {
UriBuilder qbuilder = UriBuilder.fromUri(endPoint);
String unencodedQuery = query == null ? null : unEncode(query, skipEncode);
qbuilder.replaceQuery(unencodedQuery);
endPoint = qbuilder.build();
return endPoint;
}
private void addMatrixParams(UriBuilder builder, Collection<Entry<String, String>> tokenValues,
Method method, Object... args) {
if (declaring.isAnnotationPresent(MatrixParams.class)) { if (declaring.isAnnotationPresent(MatrixParams.class)) {
MatrixParams query = declaring.getAnnotation(MatrixParams.class); MatrixParams query = declaring.getAnnotation(MatrixParams.class);
addMatrix(builder, query, tokenValues); addMatrix(builder, query, tokenValues);
@ -377,8 +396,8 @@ public class RestAnnotationProcessor<T> {
} }
} }
private void addQueryParams(Method method, Object[] args, UriBuilder builder, private void addQueryParams(UriBuilder builder, Collection<Entry<String, String>> tokenValues,
Collection<Entry<String, String>> tokenValues) { Method method, Object... args) {
if (declaring.isAnnotationPresent(QueryParams.class)) { if (declaring.isAnnotationPresent(QueryParams.class)) {
QueryParams query = declaring.getAnnotation(QueryParams.class); QueryParams query = declaring.getAnnotation(QueryParams.class);
addQuery(builder, query, tokenValues); addQuery(builder, query, tokenValues);
@ -438,10 +457,10 @@ public class RestAnnotationProcessor<T> {
} }
@VisibleForTesting @VisibleForTesting
URI getEndpointInParametersOrNull(Method method, Object[] args) { URI getEndpointInParametersOrNull(Method method, Object... args) {
Map<Integer, Set<Annotation>> map = indexWithOnlyOneAnnotation(method, "@Endpoint", Map<Integer, Set<Annotation>> map = indexWithOnlyOneAnnotation(method, "@Endpoint",
methodToindexOfParamToEndpointAnnotations); methodToindexOfParamToEndpointAnnotations);
if (map.size() == 1) { if (map.size() == 1 && args.length > 0) {
Endpoint annotation = (Endpoint) map.values().iterator().next().iterator().next(); Endpoint annotation = (Endpoint) map.values().iterator().next().iterator().next();
int index = map.keySet().iterator().next(); int index = map.keySet().iterator().next();
checkState( checkState(
@ -459,7 +478,7 @@ public class RestAnnotationProcessor<T> {
return null; return null;
} }
private UriBuilder addHostPrefixIfPresent(URI endpoint, Method method, Object[] args) { private UriBuilder addHostPrefixIfPresent(URI endpoint, Method method, Object... args) {
Map<Integer, Set<Annotation>> map = indexWithOnlyOneAnnotation(method, "@HostPrefixParam", Map<Integer, Set<Annotation>> map = indexWithOnlyOneAnnotation(method, "@HostPrefixParam",
methodToIndexOfParamToHostPrefixParamAnnotations); methodToIndexOfParamToHostPrefixParamAnnotations);
UriBuilder builder = UriBuilder.fromUri(endpoint); UriBuilder builder = UriBuilder.fromUri(endpoint);
@ -528,27 +547,27 @@ public class RestAnnotationProcessor<T> {
return null; return null;
} }
public MapRequestDecorator getMapEntityBinderOrNull(Method method, Object[] args) { public org.jclouds.rest.MapBinder getMapEntityBinderOrNull(Method method, Object... args) {
if (args != null) { if (args != null) {
for (Object arg : args) { for (Object arg : args) {
if (arg instanceof Object[]) { if (arg instanceof Object[]) {
Object[] postBinders = (Object[]) arg; Object[] postBinders = (Object[]) arg;
if (postBinders.length == 0) { if (postBinders.length == 0) {
} else if (postBinders.length == 1) { } else if (postBinders.length == 1) {
if (postBinders[0] instanceof MapRequestDecorator) { if (postBinders[0] instanceof org.jclouds.rest.MapBinder) {
MapRequestDecorator binder = (MapRequestDecorator) postBinders[0]; org.jclouds.rest.MapBinder binder = (org.jclouds.rest.MapBinder) postBinders[0];
injector.injectMembers(binder); injector.injectMembers(binder);
return binder; return binder;
} }
} else { } else {
if (postBinders[0] instanceof MapRequestDecorator) { if (postBinders[0] instanceof org.jclouds.rest.MapBinder) {
throw new IllegalArgumentException( throw new IllegalArgumentException(
"we currently do not support multiple varargs postBinders in: " "we currently do not support multiple varargs postBinders in: "
+ method.getName()); + method.getName());
} }
} }
} else if (arg instanceof MapRequestDecorator) { } else if (arg instanceof org.jclouds.rest.MapBinder) {
MapRequestDecorator binder = (MapRequestDecorator) arg; org.jclouds.rest.MapBinder binder = (org.jclouds.rest.MapBinder) arg;
injector.injectMembers(binder); injector.injectMembers(binder);
return binder; return binder;
} }
@ -595,33 +614,34 @@ public class RestAnnotationProcessor<T> {
} }
} }
public HttpRequest decorateRequest(Method method, Object[] args, HttpRequest request) { public void decorateRequest(GeneratedHttpRequest<T> request) {
MapRequestDecorator mapBinder = getMapEntityBinderOrNull(method, args); org.jclouds.rest.MapBinder mapBinder = getMapEntityBinderOrNull(request.getJavaMethod(),
Map<String, String> mapParams = buildPostParams(method, args); request.getArgs());
Map<String, String> mapParams = buildPostParams(request.getJavaMethod(), request.getArgs());
// MapEntityBinder is only useful if there are parameters. We guard here in case the // MapEntityBinder is only useful if there are parameters. We guard here in case the
// MapEntityBinder is also an EntityBinder. If so, it can be used with or without // MapEntityBinder is also an EntityBinder. If so, it can be used with or without
// parameters. // parameters.
if (mapBinder != null) { if (mapBinder != null) {
mapBinder.decorateRequest(request, mapParams); mapBinder.bindToRequest(request, mapParams);
return request; return;
} }
for (Entry<Integer, Set<Annotation>> entry : Maps.filterValues( for (Entry<Integer, Set<Annotation>> entry : Maps.filterValues(
methodToIndexOfParamToDecoratorParamAnnotation.get(method), methodToIndexOfParamToDecoratorParamAnnotation.get(request.getJavaMethod()),
new Predicate<Set<Annotation>>() { new Predicate<Set<Annotation>>() {
public boolean apply(Set<Annotation> input) { public boolean apply(Set<Annotation> input) {
return input.size() >= 1; return input.size() >= 1;
} }
}).entrySet()) { }).entrySet()) {
DecoratorParam entityAnnotation = (DecoratorParam) entry.getValue().iterator().next(); BinderParam entityAnnotation = (BinderParam) entry.getValue().iterator().next();
RequestDecorator binder = injector.getInstance(entityAnnotation.value()); Binder binder = injector.getInstance(entityAnnotation.value());
Object input = args[entry.getKey()]; Object input = request.getArgs()[entry.getKey()];
if (input.getClass().isArray()) { if (input.getClass().isArray()) {
Object[] entityArray = (Object[]) input; Object[] entityArray = (Object[]) input;
input = entityArray.length > 0 ? entityArray[0] : null; input = entityArray.length > 0 ? entityArray[0] : null;
} }
Object oldEntity = request.getEntity(); Object oldEntity = request.getEntity();
request = binder.decorateRequest(request, input); binder.bindToRequest(request, input);
if (oldEntity != null && !oldEntity.equals(request.getEntity())) { if (oldEntity != null && !oldEntity.equals(request.getEntity())) {
throw new IllegalStateException(String.format( throw new IllegalStateException(String.format(
"binder %s replaced the previous entity on request: %s", binder, request)); "binder %s replaced the previous entity on request: %s", binder, request));
@ -631,7 +651,6 @@ public class RestAnnotationProcessor<T> {
request.getHeaders().replaceValues(HttpHeaders.CONTENT_LENGTH, request.getHeaders().replaceValues(HttpHeaders.CONTENT_LENGTH,
Collections.singletonList(0 + "")); Collections.singletonList(0 + ""));
} }
return request;
} }
protected Map<Integer, Set<Annotation>> indexWithOnlyOneAnnotation(Method method, protected Map<Integer, Set<Annotation>> indexWithOnlyOneAnnotation(Method method,
@ -651,7 +670,7 @@ public class RestAnnotationProcessor<T> {
return indexToEntityAnnotation; return indexToEntityAnnotation;
} }
private HttpRequestOptions findOptionsIn(Method method, Object[] args) { private HttpRequestOptions findOptionsIn(Method method, Object... args) {
for (int index : methodToIndexesOfOptions.get(method)) { for (int index : methodToIndexesOfOptions.get(method)) {
if (args.length >= index + 1) {// accomodate varargs if (args.length >= index + 1) {// accomodate varargs
if (args[index] instanceof Object[]) { if (args[index] instanceof Object[]) {
@ -678,8 +697,8 @@ public class RestAnnotationProcessor<T> {
return null; return null;
} }
public Multimap<String, String> buildHeaders(Method method, final Object[] args, public Multimap<String, String> buildHeaders(Collection<Entry<String, String>> tokenValues,
Collection<Entry<String, String>> tokenValues) { Method method, final Object... args) {
Multimap<String, String> headers = HashMultimap.create(); Multimap<String, String> headers = HashMultimap.create();
addHeaderIfAnnotationPresentOnMethod(headers, method, tokenValues); addHeaderIfAnnotationPresentOnMethod(headers, method, tokenValues);
Map<Integer, Set<Annotation>> indexToHeaderParam = methodToIndexOfParamToHeaderParamAnnotations Map<Integer, Set<Annotation>> indexToHeaderParam = methodToIndexOfParamToHeaderParamAnnotations
@ -755,7 +774,7 @@ public class RestAnnotationProcessor<T> {
return out; return out;
} }
private Multimap<String, String> getPathParamKeyValues(Method method, Object[] args) { private Multimap<String, String> getPathParamKeyValues(Method method, Object... args) {
Multimap<String, String> pathParamValues = HashMultimap.create(); Multimap<String, String> pathParamValues = HashMultimap.create();
pathParamValues.putAll(constants); pathParamValues.putAll(constants);
Map<Integer, Set<Annotation>> indexToPathParam = methodToindexOfParamToPathParamAnnotations Map<Integer, Set<Annotation>> indexToPathParam = methodToindexOfParamToPathParamAnnotations
@ -798,10 +817,8 @@ public class RestAnnotationProcessor<T> {
// Web browsers do not always handle '+' characters well, use the well-supported // Web browsers do not always handle '+' characters well, use the well-supported
// '%20' instead. // '%20' instead.
value = value.replaceAll("\\+", "%20"); value = value.replaceAll("\\+", "%20");
for (char c : skipEncode) { if (skipEncode.length > 0) {
String toSkip = Character.toString(c); value = unEncode(value, skipEncode);
String encodedValueToSkip = URLEncoder.encode(toSkip, "UTF-8");
value = value.replaceAll(encodedValueToSkip, toSkip);
} }
encoded.put(entry.getKey(), value); encoded.put(entry.getKey(), value);
} catch (UnsupportedEncodingException e) { } catch (UnsupportedEncodingException e) {
@ -811,7 +828,21 @@ public class RestAnnotationProcessor<T> {
return encoded; return encoded;
} }
private Multimap<String, String> getMatrixParamKeyValues(Method method, Object[] args) { @VisibleForTesting
static String unEncode(String value, final char... skipEncode) {
for (char c : skipEncode) {
String toSkip = Character.toString(c);
try {
String encodedValueToSkip = URLEncoder.encode(toSkip, "UTF-8");
value = value.replaceAll(encodedValueToSkip, toSkip);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("jclouds only supports UTF-8", e);
}
}
return value;
}
private Multimap<String, String> getMatrixParamKeyValues(Method method, Object... args) {
Multimap<String, String> queryParamValues = HashMultimap.create(); Multimap<String, String> queryParamValues = HashMultimap.create();
queryParamValues.putAll(constants); queryParamValues.putAll(constants);
Map<Integer, Set<Annotation>> indexToMatrixParam = methodToindexOfParamToMatrixParamAnnotations Map<Integer, Set<Annotation>> indexToMatrixParam = methodToindexOfParamToMatrixParamAnnotations
@ -826,7 +857,7 @@ public class RestAnnotationProcessor<T> {
return queryParamValues; return queryParamValues;
} }
private Multimap<String, String> getQueryParamKeyValues(Method method, Object[] args) { private Multimap<String, String> getQueryParamKeyValues(Method method, Object... args) {
Multimap<String, String> queryParamValues = HashMultimap.create(); Multimap<String, String> queryParamValues = HashMultimap.create();
queryParamValues.putAll(constants); queryParamValues.putAll(constants);
Map<Integer, Set<Annotation>> indexToQueryParam = methodToindexOfParamToQueryParamAnnotations Map<Integer, Set<Annotation>> indexToQueryParam = methodToindexOfParamToQueryParamAnnotations
@ -841,7 +872,7 @@ public class RestAnnotationProcessor<T> {
return queryParamValues; return queryParamValues;
} }
private Map<String, String> buildPostParams(Method method, Object[] args) { private Map<String, String> buildPostParams(Method method, Object... args) {
Map<String, String> postParams = Maps.newHashMap(); Map<String, String> postParams = Maps.newHashMap();
Map<Integer, Set<Annotation>> indexToPathParam = methodToindexOfParamToPostParamAnnotations Map<Integer, Set<Annotation>> indexToPathParam = methodToindexOfParamToPostParamAnnotations
.get(method); .get(method);
@ -865,7 +896,7 @@ public class RestAnnotationProcessor<T> {
return postParams; return postParams;
} }
public URI getEndpointFor(Method method, Object[] args) { public URI getEndpointFor(Method method, Object... args) {
URI endpoint = getEndpointInParametersOrNull(method, args); URI endpoint = getEndpointInParametersOrNull(method, args);
if (endpoint == null) { if (endpoint == null) {
Endpoint annotation; Endpoint annotation;

View File

@ -42,7 +42,6 @@ import javax.inject.Singleton;
import org.jclouds.concurrent.FutureExceptionParser; import org.jclouds.concurrent.FutureExceptionParser;
import org.jclouds.http.HttpConstants; import org.jclouds.http.HttpConstants;
import org.jclouds.http.HttpRequest;
import org.jclouds.http.HttpResponse; import org.jclouds.http.HttpResponse;
import org.jclouds.http.TransformingHttpCommand; import org.jclouds.http.TransformingHttpCommand;
import org.jclouds.logging.Logger; import org.jclouds.logging.Logger;
@ -89,13 +88,13 @@ public class RestClientProxy<T> implements InvocationHandler {
.createExceptionParserOrNullIfNotFound(method); .createExceptionParserOrNullIfNotFound(method);
// in case there is an exception creating the request, we should at least pass in args // in case there is an exception creating the request, we should at least pass in args
if (exceptionParser instanceof InvocationContext) { if (exceptionParser instanceof InvocationContext) {
((InvocationContext) exceptionParser).setContext(null, args); ((InvocationContext) exceptionParser).setContext(null);
} }
HttpRequest request; GeneratedHttpRequest<T> request;
try { try {
request = util.createRequest(method, args); request = util.createRequest(method, args);
if (exceptionParser instanceof InvocationContext) { if (exceptionParser instanceof InvocationContext) {
((InvocationContext) exceptionParser).setContext(request, args); ((InvocationContext) exceptionParser).setContext(request);
} }
} catch (RuntimeException e) { } catch (RuntimeException e) {
if (exceptionParser != null) { if (exceptionParser != null) {

View File

@ -41,7 +41,7 @@ import org.jclouds.cloud.ConfiguresCloudConnection;
import org.jclouds.cloud.internal.CloudContextImpl; import org.jclouds.cloud.internal.CloudContextImpl;
import org.jclouds.lifecycle.Closer; import org.jclouds.lifecycle.Closer;
import org.jclouds.rest.RestClientFactory; import org.jclouds.rest.RestClientFactory;
import org.jclouds.rest.RestAnnotationProcessorTest.Localhost; import org.jclouds.rest.internal.RestAnnotationProcessorTest.Localhost;
import org.jclouds.util.Jsr330; import org.jclouds.util.Jsr330;
import org.jclouds.util.Utils; import org.jclouds.util.Utils;
import org.mortbay.jetty.Handler; import org.mortbay.jetty.Handler;

View File

@ -35,16 +35,16 @@ import javax.ws.rs.PathParam;
import org.jclouds.http.functions.ParseSax; import org.jclouds.http.functions.ParseSax;
import org.jclouds.http.options.HttpRequestOptions; import org.jclouds.http.options.HttpRequestOptions;
import org.jclouds.rest.RestAnnotationProcessorTest.Localhost; import org.jclouds.rest.annotations.BinderParam;
import org.jclouds.rest.annotations.DecoratorParam;
import org.jclouds.rest.annotations.Endpoint; import org.jclouds.rest.annotations.Endpoint;
import org.jclouds.rest.annotations.ExceptionParser; import org.jclouds.rest.annotations.ExceptionParser;
import org.jclouds.rest.annotations.MapBinder; import org.jclouds.rest.annotations.MapBinder;
import org.jclouds.rest.annotations.MapEntityParam; import org.jclouds.rest.annotations.MapEntityParam;
import org.jclouds.rest.annotations.RequestFilters; import org.jclouds.rest.annotations.RequestFilters;
import org.jclouds.rest.annotations.XMLResponseParser; import org.jclouds.rest.annotations.XMLResponseParser;
import org.jclouds.rest.decorators.AddAsJsonEntity; import org.jclouds.rest.binders.BindToJsonEntity;
import org.jclouds.rest.decorators.AddAsStringEntity; import org.jclouds.rest.binders.BindToStringEntity;
import org.jclouds.rest.internal.RestAnnotationProcessorTest.Localhost;
import com.google.common.base.Function; import com.google.common.base.Function;
@ -88,15 +88,17 @@ public interface IntegrationTestClient {
@PUT @PUT
@Path("objects/{id}") @Path("objects/{id}")
Future<String> upload(@PathParam("id") String id, @DecoratorParam(AddAsStringEntity.class) String toPut); Future<String> upload(@PathParam("id") String id,
@BinderParam(BindToStringEntity.class) String toPut);
@POST @POST
@Path("objects/{id}") @Path("objects/{id}")
Future<String> post(@PathParam("id") String id, @DecoratorParam(AddAsStringEntity.class) String toPut); Future<String> post(@PathParam("id") String id,
@BinderParam(BindToStringEntity.class) String toPut);
@POST @POST
@Path("objects/{id}") @Path("objects/{id}")
@MapBinder(AddAsJsonEntity.class) @MapBinder(BindToJsonEntity.class)
Future<String> postJson(@PathParam("id") String id, @MapEntityParam("key") String toPut); Future<String> postJson(@PathParam("id") String id, @MapEntityParam("key") String toPut);
@GET @GET
@ -105,11 +107,10 @@ public interface IntegrationTestClient {
Future<String> downloadFilter(@PathParam("id") String id, @HeaderParam("filterme") String header); Future<String> downloadFilter(@PathParam("id") String id, @HeaderParam("filterme") String header);
static class Filter implements HttpRequestFilter { static class Filter implements HttpRequestFilter {
public HttpRequest filter(HttpRequest request) throws HttpException { public void filter(HttpRequest request) throws HttpException {
if (request.getHeaders().containsKey("filterme")) { if (request.getHeaders().containsKey("filterme")) {
request.getHeaders().put("test", "test"); request.getHeaders().put("test", "test");
} }
return request;
} }
} }

View File

@ -49,7 +49,6 @@ import com.google.common.base.Function;
@Test(groups = "unit", testName = "core.BackoffLimitedRetryHandler") @Test(groups = "unit", testName = "core.BackoffLimitedRetryHandler")
public class BackoffLimitedRetryHandlerTest { public class BackoffLimitedRetryHandlerTest {
private static final URI END_POINT = URI.create("http://localhost:8080");
BackoffLimitedRetryHandler handler = new BackoffLimitedRetryHandler(); BackoffLimitedRetryHandler handler = new BackoffLimitedRetryHandler();
@ -146,7 +145,7 @@ public class BackoffLimitedRetryHandlerTest {
assertEquals(response.getContent().read(), -1); assertEquals(response.getContent().read(), -1);
} }
private final HttpRequest request = new HttpRequest("HEAD", END_POINT); private final HttpRequest request = new HttpRequest("GET", URI.create("http://localhost"));
private HttpCommand createCommand() { private HttpCommand createCommand() {
HttpCommand command = new TransformingHttpCommandImpl<String>(executorService, request, HttpCommand command = new TransformingHttpCommandImpl<String>(executorService, request,

View File

@ -21,7 +21,7 @@
* under the License. * under the License.
* ==================================================================== * ====================================================================
*/ */
package org.jclouds.rest; package org.jclouds.rest.internal;
import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkNotNull;
import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertEquals;
@ -72,7 +72,8 @@ import org.jclouds.http.options.GetOptions;
import org.jclouds.http.options.HttpRequestOptions; import org.jclouds.http.options.HttpRequestOptions;
import org.jclouds.logging.Logger; import org.jclouds.logging.Logger;
import org.jclouds.logging.Logger.LoggerFactory; import org.jclouds.logging.Logger.LoggerFactory;
import org.jclouds.rest.annotations.DecoratorParam; import org.jclouds.rest.InvocationContext;
import org.jclouds.rest.annotations.BinderParam;
import org.jclouds.rest.annotations.Endpoint; import org.jclouds.rest.annotations.Endpoint;
import org.jclouds.rest.annotations.Headers; import org.jclouds.rest.annotations.Headers;
import org.jclouds.rest.annotations.HostPrefixParam; import org.jclouds.rest.annotations.HostPrefixParam;
@ -85,11 +86,9 @@ import org.jclouds.rest.annotations.RequestFilters;
import org.jclouds.rest.annotations.ResponseParser; import org.jclouds.rest.annotations.ResponseParser;
import org.jclouds.rest.annotations.SkipEncoding; import org.jclouds.rest.annotations.SkipEncoding;
import org.jclouds.rest.annotations.VirtualHost; import org.jclouds.rest.annotations.VirtualHost;
import org.jclouds.rest.binders.BindToJsonEntity;
import org.jclouds.rest.binders.BindToStringEntity;
import org.jclouds.rest.config.RestModule; import org.jclouds.rest.config.RestModule;
import org.jclouds.rest.decorators.AddAsJsonEntity;
import org.jclouds.rest.decorators.AddAsStringEntity;
import org.jclouds.rest.decorators.MapRequestDecorator;
import org.jclouds.rest.internal.RestAnnotationProcessor;
import org.jclouds.util.DateService; import org.jclouds.util.DateService;
import org.jclouds.util.Jsr330; import org.jclouds.util.Jsr330;
import org.joda.time.DateTime; import org.joda.time.DateTime;
@ -153,6 +152,16 @@ public class RestAnnotationProcessorTest {
} }
} }
public void testUnEncodeQuery() {
URI expects = URI
.create("http://services.nirvanix.com/ws/Metadata/SetMetadata.ashx?output=json&path=adriancole-blobstore.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-blobstore.testObjectOperations&metadata=chef%3Asushi&metadata=foo%3Abar&sessionToken=775ef26e-0740-4707-ad92-afe9814bc436");
URI value = RestAnnotationProcessor.replaceQuery(start, start.getQuery(), '/', ':');
assertEquals(value, expects);
}
public void testQuery() throws SecurityException, NoSuchMethodException { public void testQuery() throws SecurityException, NoSuchMethodException {
Method method = TestQuery.class.getMethod("foo"); Method method = TestQuery.class.getMethod("foo");
HttpRequest httpMethod = factory(TestQuery.class).createRequest(method, new Object[] {}); HttpRequest httpMethod = factory(TestQuery.class).createRequest(method, new Object[] {});
@ -312,22 +321,22 @@ public class RestAnnotationProcessorTest {
@Endpoint(Localhost.class) @Endpoint(Localhost.class)
public class TestPost { public class TestPost {
@POST @POST
public void post(@DecoratorParam(AddAsStringEntity.class) String content) { public void post(@BinderParam(BindToStringEntity.class) String content) {
} }
@POST @POST
public void postAsJson(@DecoratorParam(AddAsJsonEntity.class) String content) { public void postAsJson(@BinderParam(BindToJsonEntity.class) String content) {
} }
@POST @POST
@Path("{foo}") @Path("{foo}")
public void postWithPath(@PathParam("foo") @MapEntityParam("fooble") String path, public void postWithPath(@PathParam("foo") @MapEntityParam("fooble") String path,
MapRequestDecorator content) { MapBinder content) {
} }
@POST @POST
@Path("{foo}") @Path("{foo}")
@MapBinder(AddAsJsonEntity.class) @MapBinder(BindToJsonEntity.class)
public void postWithMethodBinder(@PathParam("foo") @MapEntityParam("fooble") String path) { public void postWithMethodBinder(@PathParam("foo") @MapEntityParam("fooble") String path) {
} }
} }
@ -363,17 +372,14 @@ public class RestAnnotationProcessorTest {
} }
public void testCreatePostWithPathRequest() throws SecurityException, NoSuchMethodException { public void testCreatePostWithPathRequest() throws SecurityException, NoSuchMethodException {
Method method = TestPost.class.getMethod("postWithPath", String.class, Method method = TestPost.class.getMethod("postWithPath", String.class, MapBinder.class);
MapRequestDecorator.class);
HttpRequest httpMethod = factory(TestPost.class).createRequest(method, HttpRequest httpMethod = factory(TestPost.class).createRequest(method,
new Object[] { "data", new MapRequestDecorator() { new Object[] { "data", new org.jclouds.rest.MapBinder() {
public HttpRequest decorateRequest(HttpRequest request, public void bindToRequest(HttpRequest request, Map<String, String> postParams) {
Map<String, String> postParams) {
request.setEntity(postParams.get("fooble")); request.setEntity(postParams.get("fooble"));
return request;
} }
public HttpRequest decorateRequest(HttpRequest request, Object toBind) { public void bindToRequest(HttpRequest request, Object toBind) {
throw new RuntimeException("this shouldn't be used in POST"); throw new RuntimeException("this shouldn't be used in POST");
} }
} }); } });
@ -404,7 +410,7 @@ public class RestAnnotationProcessorTest {
public class TestPut { public class TestPut {
@PUT @PUT
@Path("{foo}") @Path("{foo}")
@MapBinder(AddAsJsonEntity.class) @MapBinder(BindToJsonEntity.class)
public void putWithMethodBinder(@PathParam("foo") @MapEntityParam("fooble") String path) { public void putWithMethodBinder(@PathParam("foo") @MapEntityParam("fooble") String path) {
} }
@ -412,12 +418,12 @@ public class RestAnnotationProcessorTest {
@Path("{foo}") @Path("{foo}")
@Produces(MediaType.TEXT_PLAIN) @Produces(MediaType.TEXT_PLAIN)
public void putWithMethodBinderProduces( public void putWithMethodBinderProduces(
@PathParam("foo") @DecoratorParam(AddAsStringEntity.class) String path) { @PathParam("foo") @BinderParam(BindToStringEntity.class) String path) {
} }
@PUT @PUT
@Path("{foo}") @Path("{foo}")
@MapBinder(AddAsJsonEntity.class) @MapBinder(BindToJsonEntity.class)
@Consumes(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON)
public void putWithMethodBinderConsumes( public void putWithMethodBinderConsumes(
@PathParam("foo") @MapEntityParam("fooble") String path) { @PathParam("foo") @MapEntityParam("fooble") String path) {
@ -474,14 +480,12 @@ public class RestAnnotationProcessorTest {
} }
static class TestRequestFilter1 implements HttpRequestFilter { static class TestRequestFilter1 implements HttpRequestFilter {
public HttpRequest filter(HttpRequest request) throws HttpException { public void filter(HttpRequest request) throws HttpException {
return null;
} }
} }
static class TestRequestFilter2 implements HttpRequestFilter { static class TestRequestFilter2 implements HttpRequestFilter {
public HttpRequest filter(HttpRequest request) throws HttpException { public void filter(HttpRequest request) throws HttpException {
return null;
} }
} }
@ -965,20 +969,10 @@ public class RestAnnotationProcessorTest {
public static class ReturnStringIf200Context extends ReturnStringIf200 implements public static class ReturnStringIf200Context extends ReturnStringIf200 implements
InvocationContext { InvocationContext {
private Object[] args; public HttpRequest request;
private HttpRequest request;
public Object[] getArgs() { public void setContext(GeneratedHttpRequest<?> request) {
return args;
}
public HttpRequest getRequest() {
return request;
}
public void setContext(HttpRequest request, Object[] args) {
this.request = request; this.request = request;
this.args = args;
} }
} }
@ -991,14 +985,13 @@ public class RestAnnotationProcessorTest {
} }
public void oneTransformerWithContext() throws SecurityException, NoSuchMethodException { public void oneTransformerWithContext() throws SecurityException, NoSuchMethodException {
RestAnnotationProcessor<TestTransformers> processor = factory(TestTransformers.class);
Method method = TestTransformers.class.getMethod("oneTransformerWithContext"); Method method = TestTransformers.class.getMethod("oneTransformerWithContext");
HttpRequest request = new HttpRequest("GET", URI.create("http://localhost")); GeneratedHttpRequest<TestTransformers> request = new GeneratedHttpRequest<TestTransformers>(
Object[] args = new Object[] {}; "GET", URI.create("http://localhost"), processor, TestTransformers.class, method);
Function<HttpResponse, ?> transformer = factory(TestTransformers.class).createResponseParser( Function<HttpResponse, ?> transformer = processor.createResponseParser(method, request);
method, request, args);
assertEquals(transformer.getClass(), ReturnStringIf200Context.class); assertEquals(transformer.getClass(), ReturnStringIf200Context.class);
assertEquals(((ReturnStringIf200Context) transformer).getArgs(), args); assertEquals(((ReturnStringIf200Context) transformer).request, request);
assertEquals(((ReturnStringIf200Context) transformer).getRequest(), request);
} }
@SuppressWarnings("static-access") @SuppressWarnings("static-access")
@ -1050,7 +1043,7 @@ public class RestAnnotationProcessorTest {
@PUT @PUT
@Path("/{id}") @Path("/{id}")
public Future<String> put(@PathParam("id") @ParamParser(FirstCharacter.class) String id, public Future<String> put(@PathParam("id") @ParamParser(FirstCharacter.class) String id,
@DecoratorParam(AddAsStringEntity.class) String payload) { @BinderParam(BindToStringEntity.class) String payload) {
return null; return null;
} }
@ -1066,7 +1059,7 @@ public class RestAnnotationProcessorTest {
@Headers(keys = "foo", values = "--{id}--") @Headers(keys = "foo", values = "--{id}--")
@ResponseParser(ReturnTrueIf2xx.class) @ResponseParser(ReturnTrueIf2xx.class)
public Future<String> putHeader(@PathParam("id") String id, public Future<String> putHeader(@PathParam("id") String id,
@DecoratorParam(AddAsStringEntity.class) String payload) { @BinderParam(BindToStringEntity.class) String payload) {
return null; return null;
} }
} }
@ -1347,8 +1340,8 @@ public class RestAnnotationProcessorTest {
@Test @Test
public void testOneHeader() throws SecurityException, NoSuchMethodException { public void testOneHeader() throws SecurityException, NoSuchMethodException {
Method method = TestHeaders.class.getMethod("oneHeader", String.class); Method method = TestHeaders.class.getMethod("oneHeader", String.class);
Multimap<String, String> headers = factory(TestHeaders.class).buildHeaders(method, Multimap<String, String> headers = factory(TestHeaders.class).buildHeaders(
new Object[] { "robot" }, ImmutableMultimap.<String, String> of().entries()); ImmutableMultimap.<String, String> of().entries(), method, "robot");
assertEquals(headers.size(), 1); assertEquals(headers.size(), 1);
assertEquals(headers.get("header"), Collections.singletonList("robot")); assertEquals(headers.get("header"), Collections.singletonList("robot"));
} }
@ -1356,8 +1349,8 @@ public class RestAnnotationProcessorTest {
@Test @Test
public void testOneIntHeader() throws SecurityException, NoSuchMethodException { public void testOneIntHeader() throws SecurityException, NoSuchMethodException {
Method method = TestHeaders.class.getMethod("oneIntHeader", int.class); Method method = TestHeaders.class.getMethod("oneIntHeader", int.class);
Multimap<String, String> headers = factory(TestHeaders.class).buildHeaders(method, Multimap<String, String> headers = factory(TestHeaders.class).buildHeaders(
new Object[] { 1 }, ImmutableMultimap.<String, String> of().entries()); ImmutableMultimap.<String, String> of().entries(), method, 1);
assertEquals(headers.size(), 1); assertEquals(headers.size(), 1);
assertEquals(headers.get("header"), Collections.singletonList("1")); assertEquals(headers.get("header"), Collections.singletonList("1"));
} }
@ -1366,8 +1359,8 @@ public class RestAnnotationProcessorTest {
public void testTwoDifferentHeaders() throws SecurityException, NoSuchMethodException { public void testTwoDifferentHeaders() throws SecurityException, NoSuchMethodException {
Method method = TestHeaders.class Method method = TestHeaders.class
.getMethod("twoDifferentHeaders", String.class, String.class); .getMethod("twoDifferentHeaders", String.class, String.class);
Multimap<String, String> headers = factory(TestHeaders.class).buildHeaders(method, Multimap<String, String> headers = factory(TestHeaders.class).buildHeaders(
new Object[] { "robot", "egg" }, ImmutableMultimap.<String, String> of().entries()); ImmutableMultimap.<String, String> of().entries(), method, "robot", "egg");
assertEquals(headers.size(), 2); assertEquals(headers.size(), 2);
assertEquals(headers.get("header1"), Collections.singletonList("robot")); assertEquals(headers.get("header1"), Collections.singletonList("robot"));
assertEquals(headers.get("header2"), Collections.singletonList("egg")); assertEquals(headers.get("header2"), Collections.singletonList("egg"));
@ -1376,8 +1369,8 @@ public class RestAnnotationProcessorTest {
@Test @Test
public void testTwoSameHeaders() throws SecurityException, NoSuchMethodException { public void testTwoSameHeaders() throws SecurityException, NoSuchMethodException {
Method method = TestHeaders.class.getMethod("twoSameHeaders", String.class, String.class); Method method = TestHeaders.class.getMethod("twoSameHeaders", String.class, String.class);
Multimap<String, String> headers = factory(TestHeaders.class).buildHeaders(method, Multimap<String, String> headers = factory(TestHeaders.class).buildHeaders(
new Object[] { "robot", "egg" }, ImmutableMultimap.<String, String> of().entries()); ImmutableMultimap.<String, String> of().entries(), method, "robot", "egg");
assertEquals(headers.size(), 2); assertEquals(headers.size(), 2);
Collection<String> values = headers.get("header"); Collection<String> values = headers.get("header");
assert values.contains("robot"); assert values.contains("robot");
@ -1387,38 +1380,42 @@ public class RestAnnotationProcessorTest {
@Endpoint(Localhost.class) @Endpoint(Localhost.class)
public interface TestEntity { public interface TestEntity {
@PUT @PUT
public void put(@DecoratorParam(AddAsStringEntity.class) String content); public void put(@BinderParam(BindToStringEntity.class) String content);
@PUT @PUT
@Path("{foo}") @Path("{foo}")
public Future<Void> putWithPath(@PathParam("foo") String path, public Future<Void> putWithPath(@PathParam("foo") String path,
@DecoratorParam(AddAsStringEntity.class) String content); @BinderParam(BindToStringEntity.class) String content);
@PUT @PUT
public void twoEntities(@DecoratorParam(AddAsStringEntity.class) String entity1, public void twoEntities(@BinderParam(BindToStringEntity.class) String entity1,
@DecoratorParam(AddAsStringEntity.class) String entity2); @BinderParam(BindToStringEntity.class) String entity2);
} }
@Test @Test
public void testPut() throws SecurityException, NoSuchMethodException { public void testPut() throws SecurityException, NoSuchMethodException {
RestAnnotationProcessor<TestEntity> processor = factory(TestEntity.class);
Method method = TestEntity.class.getMethod("put", String.class); Method method = TestEntity.class.getMethod("put", String.class);
HttpRequest request = new HttpRequest(HttpMethod.PUT, URI.create("http://localhost:8080")); GeneratedHttpRequest<TestEntity> request = new GeneratedHttpRequest<TestEntity>("GET", URI
factory(TestEntity.class).decorateRequest(method, new Object[] { "test" }, request); .create("http://localhost"), processor, TestEntity.class, method, "test");
processor.decorateRequest(request);
assertEquals(request.getEntity(), "test"); assertEquals(request.getEntity(), "test");
assertEquals(request.getHeaders().get(HttpHeaders.CONTENT_TYPE), Collections assertEquals(request.getHeaders().get(HttpHeaders.CONTENT_TYPE), Collections
.singletonList("application/unknown")); .singletonList("application/unknown"));
assertEquals(request.getHeaders().get(HttpHeaders.CONTENT_LENGTH), Collections assertEquals(request.getHeaders().get(HttpHeaders.CONTENT_LENGTH), Collections
.singletonList("test".getBytes().length + "")); .singletonList("test".getBytes().length + ""));
assertEquals( assertEquals(processor.createResponseParser(method, request).getClass(),
factory(TestEntity.class).createResponseParser(method, request, null).getClass(),
ReturnVoidIf2xx.class); ReturnVoidIf2xx.class);
} }
@Test @Test
public void putWithPath() throws SecurityException, NoSuchMethodException { public void putWithPath() throws SecurityException, NoSuchMethodException {
RestAnnotationProcessor<TestEntity> processor = factory(TestEntity.class);
Method method = TestEntity.class.getMethod("putWithPath", String.class, String.class); Method method = TestEntity.class.getMethod("putWithPath", String.class, String.class);
HttpRequest request = new HttpRequest(HttpMethod.PUT, URI.create("http://localhost:8080")); GeneratedHttpRequest<TestEntity> request = new GeneratedHttpRequest<TestEntity>("GET", URI
factory(TestEntity.class).decorateRequest(method, new Object[] { "rabble", "test" }, request); .create("http://localhost"), processor, TestEntity.class, method, "rabble", "test");
processor.decorateRequest(request);
assertEquals(request.getEntity(), "test"); assertEquals(request.getEntity(), "test");
assertEquals(request.getHeaders().get(HttpHeaders.CONTENT_TYPE), Collections assertEquals(request.getHeaders().get(HttpHeaders.CONTENT_TYPE), Collections
.singletonList("application/unknown")); .singletonList("application/unknown"));
@ -1428,10 +1425,11 @@ public class RestAnnotationProcessorTest {
@Test(expectedExceptions = IllegalStateException.class) @Test(expectedExceptions = IllegalStateException.class)
public void testPutTwoEntities() throws SecurityException, NoSuchMethodException { public void testPutTwoEntities() throws SecurityException, NoSuchMethodException {
RestAnnotationProcessor<TestEntity> processor = factory(TestEntity.class);
Method method = TestEntity.class.getMethod("twoEntities", String.class, String.class); Method method = TestEntity.class.getMethod("twoEntities", String.class, String.class);
HttpRequest request = new HttpRequest(HttpMethod.PUT, URI.create("http://localhost:8080")); GeneratedHttpRequest<TestEntity> request = new GeneratedHttpRequest<TestEntity>("GET", URI
factory(TestEntity.class) .create("http://localhost"), processor, TestEntity.class, method, "test", "ralphie");
.decorateRequest(method, new Object[] { "test", "ralphie" }, request); processor.decorateRequest(request);
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")

View File

@ -168,16 +168,15 @@ public class GaeHttpCommandExecutorServiceTest {
HttpRequest request = new HttpRequest(HttpMethod.GET, endPoint); HttpRequest request = new HttpRequest(HttpMethod.GET, endPoint);
request.setEntity(new Date()); request.setEntity(new Date());
client.convert(request); client.convert(request);
} }
@Test @Test
@Parameters("basedir") @Parameters("basedir")
void testConvertRequestFileContent(String basedir) throws IOException { void testConvertRequestFileContent(String basedir) throws IOException {
HttpRequest request = new HttpRequest(HttpMethod.GET, endPoint);
File file = new File(basedir, "target/testfiles/hoot"); File file = new File(basedir, "target/testfiles/hoot");
file.getParentFile().mkdirs(); file.getParentFile().mkdirs();
IOUtils.write("hoot!", new FileOutputStream(file)); IOUtils.write("hoot!", new FileOutputStream(file));
HttpRequest request = new HttpRequest(HttpMethod.GET, endPoint);
request.setEntity(file); request.setEntity(file);
testHoot(request); testHoot(request);
} }

View File

@ -94,7 +94,7 @@ public class NioHttpCommandExecutionHandler implements NHttpRequestExecutionHand
if (rendezvous != null) { if (rendezvous != null) {
HttpRequest request = rendezvous.getCommand().getRequest(); HttpRequest request = rendezvous.getCommand().getRequest();
for (HttpRequestFilter filter : request.getFilters()) { for (HttpRequestFilter filter : request.getFilters()) {
request = filter.filter(request); filter.filter(request);
} }
logger.debug("Sending request: %s", request.getRequestLine()); logger.debug("Sending request: %s", request.getRequestLine());
if (request.getEntity() != null && wire.enabled()) if (request.getEntity() != null && wire.enabled())

View File

@ -38,8 +38,8 @@ import org.jclouds.blobstore.functions.ReturnVoidOnNotFoundOr404;
import org.jclouds.blobstore.functions.ThrowKeyNotFoundOn404; import org.jclouds.blobstore.functions.ThrowKeyNotFoundOn404;
import org.jclouds.http.filters.BasicAuthentication; import org.jclouds.http.filters.BasicAuthentication;
import org.jclouds.http.options.GetOptions; import org.jclouds.http.options.GetOptions;
import org.jclouds.mezeo.pcs2.decorators.AddDataAndLength; import org.jclouds.mezeo.pcs2.binders.BindContainerNameToXmlEntity;
import org.jclouds.mezeo.pcs2.decorators.AddContainerNameAsXmlEntity; import org.jclouds.mezeo.pcs2.binders.BindDataToEntity;
import org.jclouds.mezeo.pcs2.domain.ContainerMetadata; import org.jclouds.mezeo.pcs2.domain.ContainerMetadata;
import org.jclouds.mezeo.pcs2.domain.FileMetadata; import org.jclouds.mezeo.pcs2.domain.FileMetadata;
import org.jclouds.mezeo.pcs2.domain.PCSFile; import org.jclouds.mezeo.pcs2.domain.PCSFile;
@ -57,7 +57,7 @@ import org.jclouds.mezeo.pcs2.functions.ReturnTrueIfContainerAlreadyExists;
import org.jclouds.mezeo.pcs2.xml.CachingFileListToContainerMetadataListHandler; import org.jclouds.mezeo.pcs2.xml.CachingFileListToContainerMetadataListHandler;
import org.jclouds.mezeo.pcs2.xml.FileListToFileMetadataListHandler; import org.jclouds.mezeo.pcs2.xml.FileListToFileMetadataListHandler;
import org.jclouds.mezeo.pcs2.xml.FileMetadataHandler; import org.jclouds.mezeo.pcs2.xml.FileMetadataHandler;
import org.jclouds.rest.annotations.DecoratorParam; import org.jclouds.rest.annotations.BinderParam;
import org.jclouds.rest.annotations.Endpoint; import org.jclouds.rest.annotations.Endpoint;
import org.jclouds.rest.annotations.ExceptionParser; import org.jclouds.rest.annotations.ExceptionParser;
import org.jclouds.rest.annotations.Headers; import org.jclouds.rest.annotations.Headers;
@ -98,7 +98,7 @@ public interface PCSBlobStore extends BlobStore<ContainerMetadata, FileMetadata,
@Path("/contents") @Path("/contents")
@Endpoint(RootContainer.class) @Endpoint(RootContainer.class)
@ExceptionParser(ReturnTrueIfContainerAlreadyExists.class) @ExceptionParser(ReturnTrueIfContainerAlreadyExists.class)
Future<Boolean> createContainer(@DecoratorParam(AddContainerNameAsXmlEntity.class) String container); Future<Boolean> createContainer(@BinderParam(BindContainerNameToXmlEntity.class) String container);
@DELETE @DELETE
@ExceptionParser(ReturnVoidOnNotFoundOr404.class) @ExceptionParser(ReturnVoidOnNotFoundOr404.class)
@ -124,7 +124,7 @@ public interface PCSBlobStore extends BlobStore<ContainerMetadata, FileMetadata,
@PathParam("fileResourceId") @PathParam("fileResourceId")
@ParamParser(CreateSubFolderIfNotExistsAndNewFileResource.class) @ParamParser(CreateSubFolderIfNotExistsAndNewFileResource.class)
Future<byte[]> putBlob(String containerName, Future<byte[]> putBlob(String containerName,
@DecoratorParam(AddDataAndLength.class) PCSFile object); @BinderParam(BindDataToEntity.class) PCSFile object);
// @POST // @POST
// @Path("/containers/{containerResourceId}/contents") // @Path("/containers/{containerResourceId}/contents")

View File

@ -34,13 +34,13 @@ import javax.ws.rs.POST;
import javax.ws.rs.PUT; import javax.ws.rs.PUT;
import javax.ws.rs.Path; import javax.ws.rs.Path;
import org.jclouds.blobstore.decorators.AddBlobEntityAsMultipartForm; import org.jclouds.blobstore.binders.BindBlobToMultipartForm;
import org.jclouds.blobstore.functions.ReturnVoidOnNotFoundOr404; import org.jclouds.blobstore.functions.ReturnVoidOnNotFoundOr404;
import org.jclouds.blobstore.functions.ThrowKeyNotFoundOn404; import org.jclouds.blobstore.functions.ThrowKeyNotFoundOn404;
import org.jclouds.http.filters.BasicAuthentication; import org.jclouds.http.filters.BasicAuthentication;
import org.jclouds.mezeo.pcs2.decorators.AddDataAndLength; import org.jclouds.mezeo.pcs2.binders.BindContainerNameToXmlEntity;
import org.jclouds.mezeo.pcs2.decorators.AddContainerNameAsXmlEntity; import org.jclouds.mezeo.pcs2.binders.BindDataToEntity;
import org.jclouds.mezeo.pcs2.decorators.AddFileInfoAsXmlEntity; import org.jclouds.mezeo.pcs2.binders.BindFileInfoToXmlEntity;
import org.jclouds.mezeo.pcs2.domain.ContainerMetadata; import org.jclouds.mezeo.pcs2.domain.ContainerMetadata;
import org.jclouds.mezeo.pcs2.domain.FileMetadata; import org.jclouds.mezeo.pcs2.domain.FileMetadata;
import org.jclouds.mezeo.pcs2.domain.PCSFile; import org.jclouds.mezeo.pcs2.domain.PCSFile;
@ -48,7 +48,7 @@ import org.jclouds.mezeo.pcs2.endpoints.RootContainer;
import org.jclouds.mezeo.pcs2.options.PutBlockOptions; import org.jclouds.mezeo.pcs2.options.PutBlockOptions;
import org.jclouds.mezeo.pcs2.xml.FileListToContainerMetadataListHandler; import org.jclouds.mezeo.pcs2.xml.FileListToContainerMetadataListHandler;
import org.jclouds.mezeo.pcs2.xml.FileListToFileMetadataListHandler; import org.jclouds.mezeo.pcs2.xml.FileListToFileMetadataListHandler;
import org.jclouds.rest.annotations.DecoratorParam; import org.jclouds.rest.annotations.BinderParam;
import org.jclouds.rest.annotations.Endpoint; import org.jclouds.rest.annotations.Endpoint;
import org.jclouds.rest.annotations.ExceptionParser; import org.jclouds.rest.annotations.ExceptionParser;
import org.jclouds.rest.annotations.Headers; import org.jclouds.rest.annotations.Headers;
@ -79,12 +79,12 @@ public interface PCSConnection {
@POST @POST
@Path("/contents") @Path("/contents")
@Endpoint(RootContainer.class) @Endpoint(RootContainer.class)
Future<URI> createContainer(@DecoratorParam(AddContainerNameAsXmlEntity.class) String container); Future<URI> createContainer(@BinderParam(BindContainerNameToXmlEntity.class) String container);
@POST @POST
@Path("/contents") @Path("/contents")
Future<URI> createContainer(@Endpoint URI parent, Future<URI> createContainer(@Endpoint URI parent,
@DecoratorParam(AddContainerNameAsXmlEntity.class) String container); @BinderParam(BindContainerNameToXmlEntity.class) String container);
@DELETE @DELETE
@ExceptionParser(ReturnVoidOnNotFoundOr404.class) @ExceptionParser(ReturnVoidOnNotFoundOr404.class)
@ -105,17 +105,17 @@ public interface PCSConnection {
@POST @POST
@Path("/contents") @Path("/contents")
Future<URI> uploadFile(@Endpoint URI container, Future<URI> uploadFile(@Endpoint URI container,
@DecoratorParam(AddBlobEntityAsMultipartForm.class) PCSFile object); @BinderParam(BindBlobToMultipartForm.class) PCSFile object);
@POST @POST
@Path("/contents") @Path("/contents")
Future<URI> createFile(@Endpoint URI container, Future<URI> createFile(@Endpoint URI container,
@DecoratorParam(AddFileInfoAsXmlEntity.class) PCSFile object); @BinderParam(BindFileInfoToXmlEntity.class) PCSFile object);
@PUT @PUT
@Path("/content") @Path("/content")
Future<Void> uploadBlock(@Endpoint URI file, Future<Void> uploadBlock(@Endpoint URI file,
@DecoratorParam(AddDataAndLength.class) PCSFile object, PutBlockOptions ... options); @BinderParam(BindDataToEntity.class) PCSFile object, PutBlockOptions... options);
@DELETE @DELETE
@ExceptionParser(ReturnVoidOnNotFoundOr404.class) @ExceptionParser(ReturnVoidOnNotFoundOr404.class)

View File

@ -33,12 +33,12 @@ import javax.ws.rs.PathParam;
import org.jclouds.http.filters.BasicAuthentication; import org.jclouds.http.filters.BasicAuthentication;
import org.jclouds.mezeo.pcs2.functions.AddEntryIntoMultiMap; import org.jclouds.mezeo.pcs2.functions.AddEntryIntoMultiMap;
import org.jclouds.rest.annotations.DecoratorParam; import org.jclouds.rest.annotations.BinderParam;
import org.jclouds.rest.annotations.Endpoint; import org.jclouds.rest.annotations.Endpoint;
import org.jclouds.rest.annotations.RequestFilters; import org.jclouds.rest.annotations.RequestFilters;
import org.jclouds.rest.annotations.ResponseParser; import org.jclouds.rest.annotations.ResponseParser;
import org.jclouds.rest.annotations.SkipEncoding; import org.jclouds.rest.annotations.SkipEncoding;
import org.jclouds.rest.decorators.AddAsStringEntity; import org.jclouds.rest.binders.BindToStringEntity;
import com.google.common.collect.Multimap; import com.google.common.collect.Multimap;
@ -59,7 +59,7 @@ public interface PCSUtil {
@Endpoint(PCS.class) @Endpoint(PCS.class)
@Path("/files/{fileResourceId}/metadata/{key}") @Path("/files/{fileResourceId}/metadata/{key}")
Future<Void> putMetadata(@PathParam("fileResourceId") String resourceId, Future<Void> putMetadata(@PathParam("fileResourceId") String resourceId,
@PathParam("key") String key, @DecoratorParam(AddAsStringEntity.class) String value); @PathParam("key") String key, @BinderParam(BindToStringEntity.class) String value);
@GET @GET
@ResponseParser(AddEntryIntoMultiMap.class) @ResponseParser(AddEntryIntoMultiMap.class)

View File

@ -21,29 +21,28 @@
* under the License. * under the License.
* ==================================================================== * ====================================================================
*/ */
package org.jclouds.mezeo.pcs2.decorators; package org.jclouds.mezeo.pcs2.binders;
import java.util.Collections; import java.util.Collections;
import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.HttpHeaders;
import org.jclouds.http.HttpRequest; import org.jclouds.http.HttpRequest;
import org.jclouds.rest.decorators.RequestDecorator; import org.jclouds.rest.Binder;
/** /**
* *
* @author Adrian Cole * @author Adrian Cole
* *
*/ */
public class AddContainerNameAsXmlEntity implements RequestDecorator { public class BindContainerNameToXmlEntity implements Binder {
public HttpRequest decorateRequest(HttpRequest request, Object toBind) { public void bindToRequest(HttpRequest request, Object toBind) {
String container = String.format("<container><name>%s</name></container>", toBind); String container = String.format("<container><name>%s</name></container>", toBind);
request.setEntity(container); request.setEntity(container);
request.getHeaders().replaceValues(HttpHeaders.CONTENT_LENGTH, request.getHeaders().replaceValues(HttpHeaders.CONTENT_LENGTH,
Collections.singletonList(container.getBytes().length + "")); Collections.singletonList(container.getBytes().length + ""));
request.getHeaders().replaceValues(HttpHeaders.CONTENT_TYPE, request.getHeaders().replaceValues(HttpHeaders.CONTENT_TYPE,
Collections.singletonList("application/vnd.csp.container-info+xml")); Collections.singletonList("application/vnd.csp.container-info+xml"));
return request;
} }
} }

View File

@ -1,4 +1,4 @@
package org.jclouds.mezeo.pcs2.decorators; package org.jclouds.mezeo.pcs2.binders;
import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkNotNull;
@ -6,14 +6,13 @@ import javax.ws.rs.core.HttpHeaders;
import org.jclouds.blobstore.domain.Blob; import org.jclouds.blobstore.domain.Blob;
import org.jclouds.http.HttpRequest; import org.jclouds.http.HttpRequest;
import org.jclouds.rest.decorators.RequestDecorator; import org.jclouds.rest.Binder;
public class AddDataAndLength implements RequestDecorator { public class BindDataToEntity implements Binder {
public HttpRequest decorateRequest(HttpRequest request, Object entity) { public void bindToRequest(HttpRequest request, Object entity) {
Blob<?> object = (Blob<?>) entity; Blob<?> object = (Blob<?>) entity;
request.setEntity(checkNotNull(object.getData(), "object.getContent()")); request.setEntity(checkNotNull(object.getData(), "object.getContent()"));
request.getHeaders().put(HttpHeaders.CONTENT_LENGTH, object.getMetadata().getSize() + ""); request.getHeaders().put(HttpHeaders.CONTENT_LENGTH, object.getMetadata().getSize() + "");
return request;
} }
} }

View File

@ -21,7 +21,7 @@
* under the License. * under the License.
* ==================================================================== * ====================================================================
*/ */
package org.jclouds.mezeo.pcs2.decorators; package org.jclouds.mezeo.pcs2.binders;
import java.util.Collections; import java.util.Collections;
@ -31,16 +31,16 @@ import org.jclouds.blobstore.domain.Blob;
import org.jclouds.blobstore.domain.Key; import org.jclouds.blobstore.domain.Key;
import org.jclouds.blobstore.util.BlobStoreUtils; import org.jclouds.blobstore.util.BlobStoreUtils;
import org.jclouds.http.HttpRequest; import org.jclouds.http.HttpRequest;
import org.jclouds.rest.decorators.RequestDecorator; import org.jclouds.rest.Binder;
/** /**
* *
* @author Adrian Cole * @author Adrian Cole
* *
*/ */
public class AddFileInfoAsXmlEntity implements RequestDecorator { public class BindFileInfoToXmlEntity implements Binder {
public HttpRequest decorateRequest(HttpRequest request, Object toBind) { public void bindToRequest(HttpRequest request, Object toBind) {
Blob<?> blob = (Blob<?>) toBind; Blob<?> blob = (Blob<?>) toBind;
String bareKey = BlobStoreUtils.parseKey(new Key("trash", blob.getKey())).getKey(); String bareKey = BlobStoreUtils.parseKey(new Key("trash", blob.getKey())).getKey();
String file = String.format( String file = String.format(
@ -51,6 +51,5 @@ public class AddFileInfoAsXmlEntity implements RequestDecorator {
Collections.singletonList(file.getBytes().length + "")); Collections.singletonList(file.getBytes().length + ""));
request.getHeaders().replaceValues(HttpHeaders.CONTENT_TYPE, request.getHeaders().replaceValues(HttpHeaders.CONTENT_TYPE,
Collections.singletonList("application/vnd.csp.file-info+xml")); Collections.singletonList("application/vnd.csp.file-info+xml"));
return request;
} }
} }

View File

@ -6,10 +6,10 @@ import java.lang.reflect.Constructor;
import javax.inject.Inject; import javax.inject.Inject;
import org.jclouds.http.HttpRequest;
import org.jclouds.http.HttpResponse; import org.jclouds.http.HttpResponse;
import org.jclouds.http.functions.ReturnStringIf200; import org.jclouds.http.functions.ReturnStringIf200;
import org.jclouds.rest.InvocationContext; import org.jclouds.rest.InvocationContext;
import org.jclouds.rest.internal.GeneratedHttpRequest;
import com.google.common.base.Function; import com.google.common.base.Function;
import com.google.common.collect.Multimap; import com.google.common.collect.Multimap;
@ -20,15 +20,13 @@ import com.google.common.collect.Multimap;
*/ */
public class AddEntryIntoMultiMap implements Function<HttpResponse, Void>, InvocationContext { public class AddEntryIntoMultiMap implements Function<HttpResponse, Void>, InvocationContext {
ReturnStringIf200 returnIf200; ReturnStringIf200 returnIf200;
private GeneratedHttpRequest<?> request;
@Inject @Inject
private AddEntryIntoMultiMap(ReturnStringIf200 returnIf200) { private AddEntryIntoMultiMap(ReturnStringIf200 returnIf200) {
this.returnIf200 = returnIf200; this.returnIf200 = returnIf200;
} }
private Object[] args;
private HttpRequest request;
static final Void v; static final Void v;
static { static {
Constructor<Void> cv; Constructor<Void> cv;
@ -45,10 +43,10 @@ public class AddEntryIntoMultiMap implements Function<HttpResponse, Void>, Invoc
public Void apply(HttpResponse from) public Void apply(HttpResponse from)
{ {
checkState(args != null, "args should be initialized at this point"); checkState(request.getArgs() != null, "args should be initialized at this point");
Multimap<String, String> map = null; Multimap<String, String> map = null;
String key = null; String key = null;
for (Object arg : args) { for (Object arg : request.getArgs()) {
if (arg instanceof Multimap) if (arg instanceof Multimap)
map = (Multimap<String, String>) arg; map = (Multimap<String, String>) arg;
else if (arg instanceof String) else if (arg instanceof String)
@ -61,17 +59,8 @@ public class AddEntryIntoMultiMap implements Function<HttpResponse, Void>, Invoc
return v; return v;
} }
public Object[] getArgs() { public void setContext(GeneratedHttpRequest<?> request) {
return args;
}
public HttpRequest getRequest() {
return request;
}
public void setContext(HttpRequest request, Object[] args) {
this.request = request; this.request = request;
this.args = args;
} }
} }

View File

@ -41,13 +41,13 @@ import org.apache.commons.io.IOUtils;
import org.jclouds.blobstore.domain.Key; import org.jclouds.blobstore.domain.Key;
import org.jclouds.blobstore.internal.BlobRuntimeException; import org.jclouds.blobstore.internal.BlobRuntimeException;
import org.jclouds.blobstore.reference.BlobStoreConstants; import org.jclouds.blobstore.reference.BlobStoreConstants;
import org.jclouds.http.HttpRequest;
import org.jclouds.http.HttpResponse; import org.jclouds.http.HttpResponse;
import org.jclouds.logging.Logger; import org.jclouds.logging.Logger;
import org.jclouds.mezeo.pcs2.PCSUtil; import org.jclouds.mezeo.pcs2.PCSUtil;
import org.jclouds.mezeo.pcs2.domain.PCSFile; import org.jclouds.mezeo.pcs2.domain.PCSFile;
import org.jclouds.mezeo.pcs2.util.PCSUtils; import org.jclouds.mezeo.pcs2.util.PCSUtils;
import org.jclouds.rest.InvocationContext; import org.jclouds.rest.InvocationContext;
import org.jclouds.rest.internal.GeneratedHttpRequest;
import org.jclouds.util.Utils; import org.jclouds.util.Utils;
import com.google.common.base.Function; import com.google.common.base.Function;
@ -65,8 +65,6 @@ public class AddMetadataAndParseResourceIdIntoBytes implements Function<HttpResp
@Resource @Resource
protected Logger logger = Logger.NULL; protected Logger logger = Logger.NULL;
private Object[] args;
private HttpRequest request;
/** /**
* maximum duration of an blob Request * maximum duration of an blob Request
@ -74,6 +72,7 @@ public class AddMetadataAndParseResourceIdIntoBytes implements Function<HttpResp
@Inject(optional = true) @Inject(optional = true)
@Named(BlobStoreConstants.PROPERTY_BLOBSTORE_TIMEOUT) @Named(BlobStoreConstants.PROPERTY_BLOBSTORE_TIMEOUT)
protected long requestTimeoutMilliseconds = 30000; protected long requestTimeoutMilliseconds = 30000;
private GeneratedHttpRequest<?> request;
@Inject @Inject
public AddMetadataAndParseResourceIdIntoBytes(ConcurrentMap<Key, String> fileCache, PCSUtil util) { public AddMetadataAndParseResourceIdIntoBytes(ConcurrentMap<Key, String> fileCache, PCSUtil util) {
@ -85,11 +84,11 @@ public class AddMetadataAndParseResourceIdIntoBytes implements Function<HttpResp
if (from.getStatusCode() > 204) if (from.getStatusCode() > 204)
throw new BlobRuntimeException("Incorrect code for: " + from); throw new BlobRuntimeException("Incorrect code for: " + from);
checkState(request != null, "request should be initialized at this point"); checkState(request != null, "request should be initialized at this point");
checkState(args != null, "args should be initialized at this point"); checkState(request.getArgs() != null, "request.getArgs() should be initialized at this point");
checkArgument(args[0] instanceof String, "arg[0] must be a container name"); checkArgument(request.getArgs()[0] instanceof String, "arg[0] must be a container name");
checkArgument(args[1] instanceof PCSFile, "arg[1] must be a pcsfile"); checkArgument(request.getArgs()[1] instanceof PCSFile, "arg[1] must be a pcsfile");
String container = args[0].toString(); String container = request.getArgs()[0].toString();
PCSFile file = (PCSFile) args[1]; PCSFile file = (PCSFile) request.getArgs()[1];
Key key = new Key(container, file.getKey()); Key key = new Key(container, file.getKey());
String id = checkNotNull(fileCache.get(key), String.format( String id = checkNotNull(fileCache.get(key), String.format(
@ -113,17 +112,8 @@ public class AddMetadataAndParseResourceIdIntoBytes implements Function<HttpResp
return PCSUtils.getETag(id); return PCSUtils.getETag(id);
} }
public Object[] getArgs() { public void setContext(GeneratedHttpRequest<?> request) {
return args;
}
public HttpRequest getRequest() {
return request;
}
public void setContext(HttpRequest request, Object[] args) {
this.request = request; this.request = request;
this.args = args;
} }
} }

View File

@ -29,11 +29,11 @@ import javax.inject.Inject;
import org.jclouds.blobstore.domain.Key; import org.jclouds.blobstore.domain.Key;
import org.jclouds.blobstore.functions.ParseContentTypeFromHeaders; import org.jclouds.blobstore.functions.ParseContentTypeFromHeaders;
import org.jclouds.http.HttpRequest;
import org.jclouds.http.HttpResponse; import org.jclouds.http.HttpResponse;
import org.jclouds.mezeo.pcs2.domain.FileMetadata; import org.jclouds.mezeo.pcs2.domain.FileMetadata;
import org.jclouds.mezeo.pcs2.domain.PCSFile; import org.jclouds.mezeo.pcs2.domain.PCSFile;
import org.jclouds.rest.InvocationContext; import org.jclouds.rest.InvocationContext;
import org.jclouds.rest.internal.GeneratedHttpRequest;
import com.google.common.base.Function; import com.google.common.base.Function;
@ -47,8 +47,7 @@ public class AssembleBlobFromContentAndMetadataCache implements Function<HttpRes
InvocationContext { InvocationContext {
private final ConcurrentMap<Key, FileMetadata> cache; private final ConcurrentMap<Key, FileMetadata> cache;
private HttpRequest request; private GeneratedHttpRequest<?> request;
private Object[] args;
@Inject @Inject
public AssembleBlobFromContentAndMetadataCache(ConcurrentMap<Key, FileMetadata> cache) { public AssembleBlobFromContentAndMetadataCache(ConcurrentMap<Key, FileMetadata> cache) {
@ -56,23 +55,15 @@ public class AssembleBlobFromContentAndMetadataCache implements Function<HttpRes
} }
public PCSFile apply(HttpResponse from) { public PCSFile apply(HttpResponse from) {
FileMetadata metadata = cache.get(new Key(getArgs()[0].toString(), this.getArgs()[1].toString())); FileMetadata metadata = cache.get(new Key(request.getArgs()[0].toString(),
request.getArgs()[1].toString()));
PCSFile blob = new PCSFile(metadata); PCSFile blob = new PCSFile(metadata);
blob.setData(from.getContent()); blob.setData(from.getContent());
blob.setContentLength(metadata.getSize()); blob.setContentLength(metadata.getSize());
return blob; return blob;
} }
public Object[] getArgs() { public void setContext(GeneratedHttpRequest<?> request) {
return args;
}
public HttpRequest getRequest() {
return request;
}
public void setContext(HttpRequest request, Object[] args) {
this.args = args;
this.request = request; this.request = request;
} }

View File

@ -28,9 +28,9 @@ import java.util.concurrent.ConcurrentMap;
import javax.inject.Inject; import javax.inject.Inject;
import org.apache.commons.io.IOUtils; import org.apache.commons.io.IOUtils;
import org.jclouds.http.HttpRequest;
import org.jclouds.http.HttpResponse; import org.jclouds.http.HttpResponse;
import org.jclouds.rest.InvocationContext; import org.jclouds.rest.InvocationContext;
import org.jclouds.rest.internal.GeneratedHttpRequest;
import com.google.common.base.Function; import com.google.common.base.Function;
@ -39,11 +39,10 @@ import com.google.common.base.Function;
* *
* @author Adrian Cole * @author Adrian Cole
*/ */
public class InvalidateContainerNameCacheAndReturnTrueIf2xx implements Function<HttpResponse, Boolean>, public class InvalidateContainerNameCacheAndReturnTrueIf2xx implements
InvocationContext { Function<HttpResponse, Boolean>, InvocationContext {
private final ConcurrentMap<String, String> cache; private final ConcurrentMap<String, String> cache;
private HttpRequest request; private GeneratedHttpRequest<?> request;
private Object[] args;
@Inject @Inject
public InvalidateContainerNameCacheAndReturnTrueIf2xx(ConcurrentMap<String, String> cache) { public InvalidateContainerNameCacheAndReturnTrueIf2xx(ConcurrentMap<String, String> cache) {
@ -56,20 +55,11 @@ public class InvalidateContainerNameCacheAndReturnTrueIf2xx implements Function<
if (code >= 300 || code < 200) { if (code >= 300 || code < 200) {
throw new IllegalStateException("incorrect code for this operation: " + from); throw new IllegalStateException("incorrect code for this operation: " + from);
} }
cache.remove(getArgs()[0]); cache.remove(request.getArgs()[0]);
return true; return true;
} }
public Object[] getArgs() { public void setContext(GeneratedHttpRequest<?> request) {
return args;
}
public HttpRequest getRequest() {
return request;
}
public void setContext(HttpRequest request, Object[] args) {
this.args = args;
this.request = request; this.request = request;
} }

View File

@ -29,10 +29,10 @@ import javax.inject.Inject;
import org.apache.commons.io.IOUtils; import org.apache.commons.io.IOUtils;
import org.jclouds.blobstore.domain.Key; import org.jclouds.blobstore.domain.Key;
import org.jclouds.http.HttpRequest;
import org.jclouds.http.HttpResponse; import org.jclouds.http.HttpResponse;
import org.jclouds.mezeo.pcs2.domain.FileMetadata; import org.jclouds.mezeo.pcs2.domain.FileMetadata;
import org.jclouds.rest.InvocationContext; import org.jclouds.rest.InvocationContext;
import org.jclouds.rest.internal.GeneratedHttpRequest;
import com.google.common.base.Function; import com.google.common.base.Function;
@ -45,8 +45,7 @@ public class InvalidatePCSKeyCacheAndReturnVoidIf2xx implements Function<HttpRes
InvocationContext { InvocationContext {
private final ConcurrentMap<Key, String> cache; private final ConcurrentMap<Key, String> cache;
private final ConcurrentMap<Key, FileMetadata> mdCache; private final ConcurrentMap<Key, FileMetadata> mdCache;
private HttpRequest request; private GeneratedHttpRequest<?> request;
private Object[] args;
@Inject @Inject
public InvalidatePCSKeyCacheAndReturnVoidIf2xx(ConcurrentMap<Key, String> cache, public InvalidatePCSKeyCacheAndReturnVoidIf2xx(ConcurrentMap<Key, String> cache,
@ -61,22 +60,13 @@ public class InvalidatePCSKeyCacheAndReturnVoidIf2xx implements Function<HttpRes
if (code >= 300 || code < 200) { if (code >= 300 || code < 200) {
throw new IllegalStateException("incorrect code for this operation: " + from); throw new IllegalStateException("incorrect code for this operation: " + from);
} }
Key key = new Key(getArgs()[0].toString(), getArgs()[1].toString()); Key key = new Key(request.getArgs()[0].toString(), request.getArgs()[1].toString());
cache.remove(key); cache.remove(key);
mdCache.remove(key); mdCache.remove(key);
return null; return null;
} }
public Object[] getArgs() { public void setContext(GeneratedHttpRequest<?> request) {
return args;
}
public HttpRequest getRequest() {
return request;
}
public void setContext(HttpRequest request, Object[] args) {
this.args = args;
this.request = request; this.request = request;
} }

View File

@ -47,7 +47,6 @@ import org.jclouds.blobstore.functions.ThrowKeyNotFoundOn404;
import org.jclouds.blobstore.integration.internal.StubBlobStore; import org.jclouds.blobstore.integration.internal.StubBlobStore;
import org.jclouds.concurrent.WithinThreadExecutorService; import org.jclouds.concurrent.WithinThreadExecutorService;
import org.jclouds.concurrent.config.ExecutorServiceModule; import org.jclouds.concurrent.config.ExecutorServiceModule;
import org.jclouds.http.HttpRequest;
import org.jclouds.http.config.JavaUrlHttpCommandExecutorServiceModule; import org.jclouds.http.config.JavaUrlHttpCommandExecutorServiceModule;
import org.jclouds.http.filters.BasicAuthentication; import org.jclouds.http.filters.BasicAuthentication;
import org.jclouds.http.functions.ParseSax; import org.jclouds.http.functions.ParseSax;
@ -69,6 +68,7 @@ import org.jclouds.mezeo.pcs2.functions.InvalidatePCSKeyCacheAndReturnVoidIf2xx;
import org.jclouds.mezeo.pcs2.functions.ReturnFalseIfContainerNotFound; import org.jclouds.mezeo.pcs2.functions.ReturnFalseIfContainerNotFound;
import org.jclouds.mezeo.pcs2.options.PutBlockOptions; import org.jclouds.mezeo.pcs2.options.PutBlockOptions;
import org.jclouds.rest.config.RestModule; import org.jclouds.rest.config.RestModule;
import org.jclouds.rest.internal.GeneratedHttpRequest;
import org.jclouds.rest.internal.RestAnnotationProcessor; import org.jclouds.rest.internal.RestAnnotationProcessor;
import org.jclouds.util.DateService; import org.jclouds.util.DateService;
import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeClass;
@ -216,15 +216,15 @@ public class PCSBlobStoreTest {
public void testListContainers() throws SecurityException, NoSuchMethodException { public void testListContainers() throws SecurityException, NoSuchMethodException {
Method method = PCSBlobStore.class.getMethod("listContainers"); Method method = PCSBlobStore.class.getMethod("listContainers");
HttpRequest httpMethod = processor.createRequest(method, new Object[] {}); GeneratedHttpRequest<PCSBlobStore> httpMethod = processor.createRequest(method,
new Object[] {});
assertEquals(httpMethod.getEndpoint().getHost(), "localhost"); assertEquals(httpMethod.getEndpoint().getHost(), "localhost");
assertEquals(httpMethod.getEndpoint().getPath(), "/root/contents"); assertEquals(httpMethod.getEndpoint().getPath(), "/root/contents");
assertEquals(httpMethod.getEndpoint().getQuery(), null); assertEquals(httpMethod.getEndpoint().getQuery(), null);
assertEquals(httpMethod.getMethod(), HttpMethod.GET); assertEquals(httpMethod.getMethod(), HttpMethod.GET);
assertEquals(httpMethod.getHeaders().size(), 1); assertEquals(httpMethod.getHeaders().size(), 1);
assertEquals(httpMethod.getHeaders().get("X-Cloud-Depth"), Collections.singletonList("2")); assertEquals(httpMethod.getHeaders().get("X-Cloud-Depth"), Collections.singletonList("2"));
assertEquals(processor.createResponseParser(method, httpMethod, null).getClass(), assertEquals(processor.createResponseParser(method, httpMethod).getClass(), ParseSax.class);
ParseSax.class);
// TODO check generic type of response parser // TODO check generic type of response parser
assertEquals(processor.createExceptionParserOrNullIfNotFound(method), null); assertEquals(processor.createExceptionParserOrNullIfNotFound(method), null);
} }
@ -232,7 +232,8 @@ public class PCSBlobStoreTest {
public void testCreateContainer() throws SecurityException, NoSuchMethodException, IOException { public void testCreateContainer() throws SecurityException, NoSuchMethodException, IOException {
Method method = PCSBlobStore.class.getMethod("createContainer", String.class); Method method = PCSBlobStore.class.getMethod("createContainer", String.class);
HttpRequest httpMethod = processor.createRequest(method, new Object[] { "container" }); GeneratedHttpRequest<PCSBlobStore> httpMethod = processor.createRequest(method,
new Object[] { "container" });
assertEquals(httpMethod.getEndpoint().getHost(), "localhost"); assertEquals(httpMethod.getEndpoint().getHost(), "localhost");
assertEquals(httpMethod.getEndpoint().getPath(), "/root/contents"); assertEquals(httpMethod.getEndpoint().getPath(), "/root/contents");
assertEquals(httpMethod.getEndpoint().getQuery(), null); assertEquals(httpMethod.getEndpoint().getQuery(), null);
@ -243,7 +244,7 @@ public class PCSBlobStoreTest {
assertEquals(httpMethod.getHeaders().get(HttpHeaders.CONTENT_TYPE), Collections assertEquals(httpMethod.getHeaders().get(HttpHeaders.CONTENT_TYPE), Collections
.singletonList("application/vnd.csp.container-info+xml")); .singletonList("application/vnd.csp.container-info+xml"));
assertEquals(httpMethod.getEntity(), "<container><name>container</name></container>"); assertEquals(httpMethod.getEntity(), "<container><name>container</name></container>");
assertEquals(processor.createResponseParser(method, httpMethod, null).getClass(), assertEquals(processor.createResponseParser(method, httpMethod).getClass(),
ReturnTrueIf2xx.class); ReturnTrueIf2xx.class);
// TODO check generic type of response parser // TODO check generic type of response parser
} }
@ -251,14 +252,15 @@ public class PCSBlobStoreTest {
public void testDeleteContainer() throws SecurityException, NoSuchMethodException { public void testDeleteContainer() throws SecurityException, NoSuchMethodException {
Method method = PCSBlobStore.class.getMethod("deleteContainer", String.class); Method method = PCSBlobStore.class.getMethod("deleteContainer", String.class);
HttpRequest httpMethod = processor.createRequest(method, new Object[] { "mycontainer" }); GeneratedHttpRequest<PCSBlobStore> httpMethod = processor.createRequest(method,
new Object[] { "mycontainer" });
assertEquals(httpMethod.getEndpoint().getHost(), "localhost"); assertEquals(httpMethod.getEndpoint().getHost(), "localhost");
assertEquals(httpMethod.getEndpoint().getPath(), assertEquals(httpMethod.getEndpoint().getPath(),
"/containers/7F143552-AAF5-11DE-BBB0-0BC388ED913B"); "/containers/7F143552-AAF5-11DE-BBB0-0BC388ED913B");
assertEquals(httpMethod.getEndpoint().getQuery(), null); assertEquals(httpMethod.getEndpoint().getQuery(), null);
assertEquals(httpMethod.getMethod(), HttpMethod.DELETE); assertEquals(httpMethod.getMethod(), HttpMethod.DELETE);
assertEquals(httpMethod.getHeaders().size(), 0); assertEquals(httpMethod.getHeaders().size(), 0);
assertEquals(processor.createResponseParser(method, httpMethod, null).getClass(), assertEquals(processor.createResponseParser(method, httpMethod).getClass(),
InvalidateContainerNameCacheAndReturnTrueIf2xx.class); InvalidateContainerNameCacheAndReturnTrueIf2xx.class);
assertEquals(processor.createExceptionParserOrNullIfNotFound(method).getClass(), assertEquals(processor.createExceptionParserOrNullIfNotFound(method).getClass(),
ReturnVoidOnNotFoundOr404.class); ReturnVoidOnNotFoundOr404.class);
@ -267,14 +269,15 @@ public class PCSBlobStoreTest {
public void testContainerExists() throws SecurityException, NoSuchMethodException { public void testContainerExists() throws SecurityException, NoSuchMethodException {
Method method = PCSBlobStore.class.getMethod("containerExists", String.class); Method method = PCSBlobStore.class.getMethod("containerExists", String.class);
HttpRequest httpMethod = processor.createRequest(method, new Object[] { "mycontainer" }); GeneratedHttpRequest<PCSBlobStore> httpMethod = processor.createRequest(method,
new Object[] { "mycontainer" });
assertEquals(httpMethod.getEndpoint().getHost(), "localhost"); assertEquals(httpMethod.getEndpoint().getHost(), "localhost");
assertEquals(httpMethod.getEndpoint().getPath(), assertEquals(httpMethod.getEndpoint().getPath(),
"/containers/7F143552-AAF5-11DE-BBB0-0BC388ED913B"); "/containers/7F143552-AAF5-11DE-BBB0-0BC388ED913B");
assertEquals(httpMethod.getEndpoint().getQuery(), null); assertEquals(httpMethod.getEndpoint().getQuery(), null);
assertEquals(httpMethod.getMethod(), HttpMethod.GET); assertEquals(httpMethod.getMethod(), HttpMethod.GET);
assertEquals(httpMethod.getHeaders().size(), 0); assertEquals(httpMethod.getHeaders().size(), 0);
assertEquals(processor.createResponseParser(method, httpMethod, null).getClass(), assertEquals(processor.createResponseParser(method, httpMethod).getClass(),
ReturnTrueIf2xx.class); ReturnTrueIf2xx.class);
assertEquals(processor.createExceptionParserOrNullIfNotFound(method).getClass(), assertEquals(processor.createExceptionParserOrNullIfNotFound(method).getClass(),
ReturnFalseIfContainerNotFound.class); ReturnFalseIfContainerNotFound.class);
@ -283,7 +286,8 @@ public class PCSBlobStoreTest {
public void testListBlobs() throws SecurityException, NoSuchMethodException { public void testListBlobs() throws SecurityException, NoSuchMethodException {
Method method = PCSBlobStore.class.getMethod("listBlobs", String.class); Method method = PCSBlobStore.class.getMethod("listBlobs", String.class);
HttpRequest httpMethod = processor.createRequest(method, new Object[] { "mycontainer" }); GeneratedHttpRequest<PCSBlobStore> httpMethod = processor.createRequest(method,
new Object[] { "mycontainer" });
assertEquals(httpMethod.getEndpoint().getHost(), "localhost"); assertEquals(httpMethod.getEndpoint().getHost(), "localhost");
assertEquals(httpMethod.getEndpoint().getPath(), assertEquals(httpMethod.getEndpoint().getPath(),
"/containers/7F143552-AAF5-11DE-BBB0-0BC388ED913B/contents"); "/containers/7F143552-AAF5-11DE-BBB0-0BC388ED913B/contents");
@ -291,8 +295,7 @@ public class PCSBlobStoreTest {
assertEquals(httpMethod.getMethod(), HttpMethod.GET); assertEquals(httpMethod.getMethod(), HttpMethod.GET);
assertEquals(httpMethod.getHeaders().size(), 1); assertEquals(httpMethod.getHeaders().size(), 1);
assertEquals(httpMethod.getHeaders().get("X-Cloud-Depth"), Collections.singletonList("2")); assertEquals(httpMethod.getHeaders().get("X-Cloud-Depth"), Collections.singletonList("2"));
assertEquals(processor.createResponseParser(method, httpMethod, null).getClass(), assertEquals(processor.createResponseParser(method, httpMethod).getClass(), ParseSax.class);
ParseSax.class);
// TODO check generic type of response parser // TODO check generic type of response parser
assertEquals(processor.createExceptionParserOrNullIfNotFound(method), null); assertEquals(processor.createExceptionParserOrNullIfNotFound(method), null);
} }
@ -301,8 +304,8 @@ public class PCSBlobStoreTest {
Method method = PCSBlobStore.class.getMethod("putBlob", String.class, PCSFile.class); Method method = PCSBlobStore.class.getMethod("putBlob", String.class, PCSFile.class);
PCSFile file = new PCSFile("hello"); PCSFile file = new PCSFile("hello");
file.setData("wonkers"); file.setData("wonkers");
HttpRequest httpMethod = processor GeneratedHttpRequest<PCSBlobStore> httpMethod = processor.createRequest(method, new Object[] {
.createRequest(method, new Object[] { "mycontainer", file }); "mycontainer", file });
assertEquals(httpMethod.getEndpoint().getHost(), "localhost"); assertEquals(httpMethod.getEndpoint().getHost(), "localhost");
assertEquals(httpMethod.getEndpoint().getPath(), "/files/o/content"); assertEquals(httpMethod.getEndpoint().getPath(), "/files/o/content");
assertEquals(httpMethod.getEndpoint().getQuery(), null); assertEquals(httpMethod.getEndpoint().getQuery(), null);
@ -311,22 +314,22 @@ public class PCSBlobStoreTest {
assertEquals(httpMethod.getHeaders().get(HttpHeaders.CONTENT_LENGTH), Collections assertEquals(httpMethod.getHeaders().get(HttpHeaders.CONTENT_LENGTH), Collections
.singletonList(file.getData().toString().getBytes().length + "")); .singletonList(file.getData().toString().getBytes().length + ""));
assertEquals(httpMethod.getEntity(), file.getData()); assertEquals(httpMethod.getEntity(), file.getData());
assertEquals(processor.createResponseParser(method, httpMethod, null).getClass(), assertEquals(processor.createResponseParser(method, httpMethod).getClass(),
AddMetadataAndParseResourceIdIntoBytes.class); AddMetadataAndParseResourceIdIntoBytes.class);
} }
public void testRemoveBlob() throws SecurityException, NoSuchMethodException, IOException { public void testRemoveBlob() throws SecurityException, NoSuchMethodException, IOException {
Method method = PCSBlobStore.class.getMethod("removeBlob", String.class, String.class); Method method = PCSBlobStore.class.getMethod("removeBlob", String.class, String.class);
HttpRequest httpMethod = processor.createRequest(method, new Object[] { "mycontainer", GeneratedHttpRequest<PCSBlobStore> httpMethod = processor.createRequest(method, new Object[] {
"testfile.txt" }); "mycontainer", "testfile.txt" });
assertEquals(httpMethod.getEndpoint().getHost(), "localhost"); assertEquals(httpMethod.getEndpoint().getHost(), "localhost");
assertEquals(httpMethod.getEndpoint().getPath(), assertEquals(httpMethod.getEndpoint().getPath(),
"/files/9E4C5AFA-A98B-11DE-8B4C-C3884B4A2DA3"); "/files/9E4C5AFA-A98B-11DE-8B4C-C3884B4A2DA3");
assertEquals(httpMethod.getEndpoint().getQuery(), null); assertEquals(httpMethod.getEndpoint().getQuery(), null);
assertEquals(httpMethod.getMethod(), HttpMethod.DELETE); assertEquals(httpMethod.getMethod(), HttpMethod.DELETE);
assertEquals(httpMethod.getHeaders().size(), 0); assertEquals(httpMethod.getHeaders().size(), 0);
assertEquals(processor.createResponseParser(method, httpMethod, null).getClass(), assertEquals(processor.createResponseParser(method, httpMethod).getClass(),
InvalidatePCSKeyCacheAndReturnVoidIf2xx.class); InvalidatePCSKeyCacheAndReturnVoidIf2xx.class);
assertEquals(processor.createExceptionParserOrNullIfNotFound(method).getClass(), assertEquals(processor.createExceptionParserOrNullIfNotFound(method).getClass(),
ReturnVoidOnNotFoundOr404.class); ReturnVoidOnNotFoundOr404.class);
@ -335,14 +338,14 @@ public class PCSBlobStoreTest {
public void testGetBlob() throws SecurityException, NoSuchMethodException, IOException { public void testGetBlob() throws SecurityException, NoSuchMethodException, IOException {
Method method = PCSBlobStore.class.getMethod("getBlob", String.class, String.class); Method method = PCSBlobStore.class.getMethod("getBlob", String.class, String.class);
HttpRequest httpMethod = processor.createRequest(method, new Object[] { "mycontainer", GeneratedHttpRequest<PCSBlobStore> httpMethod = processor.createRequest(method, new Object[] {
"testfile.txt" }); "mycontainer", "testfile.txt" });
assertEquals(httpMethod.getEndpoint().getHost(), "localhost"); assertEquals(httpMethod.getEndpoint().getHost(), "localhost");
assertEquals(httpMethod.getEndpoint().getPath(), "/webdav/mycontainer/testfile.txt"); assertEquals(httpMethod.getEndpoint().getPath(), "/webdav/mycontainer/testfile.txt");
assertEquals(httpMethod.getEndpoint().getQuery(), null); assertEquals(httpMethod.getEndpoint().getQuery(), null);
assertEquals(httpMethod.getMethod(), HttpMethod.GET); assertEquals(httpMethod.getMethod(), HttpMethod.GET);
assertEquals(httpMethod.getHeaders().size(), 0); assertEquals(httpMethod.getHeaders().size(), 0);
assertEquals(processor.createResponseParser(method, httpMethod, null).getClass(), assertEquals(processor.createResponseParser(method, httpMethod).getClass(),
AssembleBlobFromContentAndMetadataCache.class); AssembleBlobFromContentAndMetadataCache.class);
assertEquals(processor.createExceptionParserOrNullIfNotFound(method).getClass(), assertEquals(processor.createExceptionParserOrNullIfNotFound(method).getClass(),
ThrowKeyNotFoundOn404.class); ThrowKeyNotFoundOn404.class);
@ -352,14 +355,14 @@ public class PCSBlobStoreTest {
Method method = PCSBlobStore.class.getMethod("getBlob", String.class, String.class, Method method = PCSBlobStore.class.getMethod("getBlob", String.class, String.class,
GetOptions.class); GetOptions.class);
HttpRequest httpMethod = processor.createRequest(method, new Object[] { "mycontainer", GeneratedHttpRequest<PCSBlobStore> httpMethod = processor.createRequest(method, new Object[] {
"testfile.txt", new GetOptions() }); "mycontainer", "testfile.txt", new GetOptions() });
assertEquals(httpMethod.getEndpoint().getHost(), "localhost"); assertEquals(httpMethod.getEndpoint().getHost(), "localhost");
assertEquals(httpMethod.getEndpoint().getPath(), "/webdav/mycontainer/testfile.txt"); assertEquals(httpMethod.getEndpoint().getPath(), "/webdav/mycontainer/testfile.txt");
assertEquals(httpMethod.getEndpoint().getQuery(), null); assertEquals(httpMethod.getEndpoint().getQuery(), null);
assertEquals(httpMethod.getMethod(), HttpMethod.GET); assertEquals(httpMethod.getMethod(), HttpMethod.GET);
assertEquals(httpMethod.getHeaders().size(), 0); assertEquals(httpMethod.getHeaders().size(), 0);
assertEquals(processor.createResponseParser(method, httpMethod, null).getClass(), assertEquals(processor.createResponseParser(method, httpMethod).getClass(),
AssembleBlobFromContentAndMetadataCache.class); AssembleBlobFromContentAndMetadataCache.class);
assertEquals(processor.createExceptionParserOrNullIfNotFound(method).getClass(), assertEquals(processor.createExceptionParserOrNullIfNotFound(method).getClass(),
ThrowKeyNotFoundOn404.class); ThrowKeyNotFoundOn404.class);
@ -368,15 +371,14 @@ public class PCSBlobStoreTest {
public void testGetBlobMetadata() throws SecurityException, NoSuchMethodException, IOException { public void testGetBlobMetadata() throws SecurityException, NoSuchMethodException, IOException {
Method method = PCSBlobStore.class.getMethod("blobMetadata", String.class, String.class); Method method = PCSBlobStore.class.getMethod("blobMetadata", String.class, String.class);
HttpRequest httpMethod = processor.createRequest(method, new Object[] { "mycontainer", GeneratedHttpRequest<PCSBlobStore> httpMethod = processor.createRequest(method, new Object[] {
"testfile.txt" }); "mycontainer", "testfile.txt" });
assertEquals(httpMethod.getEndpoint().getHost(), "localhost"); assertEquals(httpMethod.getEndpoint().getHost(), "localhost");
assertEquals(httpMethod.getEndpoint().getPath(), assertEquals(httpMethod.getEndpoint().getPath(),
"/files/9E4C5AFA-A98B-11DE-8B4C-C3884B4A2DA3"); "/files/9E4C5AFA-A98B-11DE-8B4C-C3884B4A2DA3");
assertEquals(httpMethod.getEndpoint().getQuery(), null); assertEquals(httpMethod.getEndpoint().getQuery(), null);
assertEquals(httpMethod.getMethod(), HttpMethod.GET); assertEquals(httpMethod.getMethod(), HttpMethod.GET);
assertEquals(processor.createResponseParser(method, httpMethod, null).getClass(), assertEquals(processor.createResponseParser(method, httpMethod).getClass(), ParseSax.class);
ParseSax.class);
assertEquals(httpMethod.getHeaders().size(), 1); assertEquals(httpMethod.getHeaders().size(), 1);
assertEquals(httpMethod.getHeaders().get("X-Cloud-Depth"), Collections.singletonList("2")); assertEquals(httpMethod.getHeaders().get("X-Cloud-Depth"), Collections.singletonList("2"));
// TODO check generic type of response parser // TODO check generic type of response parser
@ -387,8 +389,8 @@ public class PCSBlobStoreTest {
public void testPutMetadata() throws SecurityException, NoSuchMethodException { public void testPutMetadata() throws SecurityException, NoSuchMethodException {
Method method = PCSUtil.class.getMethod("putMetadata", String.class, String.class, Method method = PCSUtil.class.getMethod("putMetadata", String.class, String.class,
String.class); String.class);
HttpRequest httpMethod = utilProcessor.createRequest(method, new Object[] { "id", "pow", GeneratedHttpRequest<PCSUtil> httpMethod = utilProcessor.createRequest(method, new Object[] {
"bar" }); "id", "pow", "bar" });
assertEquals(httpMethod.getEndpoint().getHost(), "localhost"); assertEquals(httpMethod.getEndpoint().getHost(), "localhost");
assertEquals(httpMethod.getEndpoint().getPath(), "/files/id/metadata/pow"); assertEquals(httpMethod.getEndpoint().getPath(), "/files/id/metadata/pow");
assertEquals(httpMethod.getMethod(), HttpMethod.PUT); assertEquals(httpMethod.getMethod(), HttpMethod.PUT);
@ -398,8 +400,8 @@ public class PCSBlobStoreTest {
assertEquals(httpMethod.getHeaders().get(HttpHeaders.CONTENT_TYPE), Collections assertEquals(httpMethod.getHeaders().get(HttpHeaders.CONTENT_TYPE), Collections
.singletonList("application/unknown")); .singletonList("application/unknown"));
assertEquals("bar", httpMethod.getEntity()); assertEquals("bar", httpMethod.getEntity());
assertEquals(processor.createExceptionParserOrNullIfNotFound(method), null); assertEquals(utilProcessor.createExceptionParserOrNullIfNotFound(method), null);
assertEquals(processor.createResponseParser(method, httpMethod, null).getClass(), assertEquals(utilProcessor.createResponseParser(method, httpMethod).getClass(),
ReturnVoidIf2xx.class); ReturnVoidIf2xx.class);
} }
@ -407,15 +409,15 @@ public class PCSBlobStoreTest {
Method method = PCSUtil.class.getMethod("addEntryToMultiMap", Multimap.class, String.class, Method method = PCSUtil.class.getMethod("addEntryToMultiMap", Multimap.class, String.class,
URI.class); URI.class);
HttpRequest httpMethod = utilProcessor GeneratedHttpRequest<PCSUtil> httpMethod = utilProcessor
.createRequest(method, new Object[] { ImmutableMultimap.of("key", "value"), .createRequest(method, new Object[] { ImmutableMultimap.of("key", "value"),
"newkey", URI.create("http://localhost/pow") }); "newkey", URI.create("http://localhost/pow") });
assertEquals(httpMethod.getEndpoint().getHost(), "localhost"); assertEquals(httpMethod.getEndpoint().getHost(), "localhost");
assertEquals(httpMethod.getEndpoint().getPath(), "/pow"); assertEquals(httpMethod.getEndpoint().getPath(), "/pow");
assertEquals(httpMethod.getMethod(), HttpMethod.GET); assertEquals(httpMethod.getMethod(), HttpMethod.GET);
assertEquals(httpMethod.getHeaders().size(), 0); assertEquals(httpMethod.getHeaders().size(), 0);
assertEquals(processor.createExceptionParserOrNullIfNotFound(method), null); assertEquals(utilProcessor.createExceptionParserOrNullIfNotFound(method), null);
assertEquals(processor.createResponseParser(method, httpMethod, null).getClass(), assertEquals(utilProcessor.createResponseParser(method, httpMethod).getClass(),
AddEntryIntoMultiMap.class); AddEntryIntoMultiMap.class);
} }

View File

@ -39,11 +39,10 @@ import javax.inject.Singleton;
import javax.ws.rs.HttpMethod; import javax.ws.rs.HttpMethod;
import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.HttpHeaders;
import org.jclouds.blobstore.decorators.AddBlobEntityAsMultipartFormTest; import org.jclouds.blobstore.binders.BindBlobToMultipartFormTest;
import org.jclouds.blobstore.functions.ReturnVoidOnNotFoundOr404; import org.jclouds.blobstore.functions.ReturnVoidOnNotFoundOr404;
import org.jclouds.concurrent.WithinThreadExecutorService; import org.jclouds.concurrent.WithinThreadExecutorService;
import org.jclouds.concurrent.config.ExecutorServiceModule; import org.jclouds.concurrent.config.ExecutorServiceModule;
import org.jclouds.http.HttpRequest;
import org.jclouds.http.config.JavaUrlHttpCommandExecutorServiceModule; import org.jclouds.http.config.JavaUrlHttpCommandExecutorServiceModule;
import org.jclouds.http.filters.BasicAuthentication; import org.jclouds.http.filters.BasicAuthentication;
import org.jclouds.http.functions.ParseSax; import org.jclouds.http.functions.ParseSax;
@ -56,6 +55,7 @@ import org.jclouds.mezeo.pcs2.domain.FileMetadata;
import org.jclouds.mezeo.pcs2.domain.PCSFile; import org.jclouds.mezeo.pcs2.domain.PCSFile;
import org.jclouds.mezeo.pcs2.endpoints.RootContainer; import org.jclouds.mezeo.pcs2.endpoints.RootContainer;
import org.jclouds.rest.config.RestModule; import org.jclouds.rest.config.RestModule;
import org.jclouds.rest.internal.GeneratedHttpRequest;
import org.jclouds.rest.internal.RestAnnotationProcessor; import org.jclouds.rest.internal.RestAnnotationProcessor;
import org.jclouds.util.Utils; import org.jclouds.util.Utils;
import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeClass;
@ -80,14 +80,14 @@ public class PCSConnectionTest {
public void testListContainers() throws SecurityException, NoSuchMethodException { public void testListContainers() throws SecurityException, NoSuchMethodException {
Method method = PCSConnection.class.getMethod("listContainers"); Method method = PCSConnection.class.getMethod("listContainers");
HttpRequest httpMethod = processor.createRequest(method, new Object[] {}); GeneratedHttpRequest<PCSConnection> httpMethod = processor.createRequest(method, new Object[] {});
assertEquals(httpMethod.getEndpoint().getHost(), "localhost"); assertEquals(httpMethod.getEndpoint().getHost(), "localhost");
assertEquals(httpMethod.getEndpoint().getPath(), "/root/contents"); assertEquals(httpMethod.getEndpoint().getPath(), "/root/contents");
assertEquals(httpMethod.getEndpoint().getQuery(), null); assertEquals(httpMethod.getEndpoint().getQuery(), null);
assertEquals(httpMethod.getMethod(), HttpMethod.GET); assertEquals(httpMethod.getMethod(), HttpMethod.GET);
assertEquals(httpMethod.getHeaders().size(), 1); assertEquals(httpMethod.getHeaders().size(), 1);
assertEquals(httpMethod.getHeaders().get("X-Cloud-Depth"), Collections.singletonList("2")); assertEquals(httpMethod.getHeaders().get("X-Cloud-Depth"), Collections.singletonList("2"));
assertEquals(processor.createResponseParser(method, httpMethod, null).getClass(), assertEquals(processor.createResponseParser(method, httpMethod).getClass(),
ParseSax.class); ParseSax.class);
// TODO check generic type of response parser // TODO check generic type of response parser
assertEquals(processor.createExceptionParserOrNullIfNotFound(method), null); assertEquals(processor.createExceptionParserOrNullIfNotFound(method), null);
@ -96,7 +96,7 @@ public class PCSConnectionTest {
public void testCreateContainer() throws SecurityException, NoSuchMethodException, IOException { public void testCreateContainer() throws SecurityException, NoSuchMethodException, IOException {
Method method = PCSConnection.class.getMethod("createContainer", String.class); Method method = PCSConnection.class.getMethod("createContainer", String.class);
HttpRequest httpMethod = processor.createRequest(method, new Object[] { "container" }); GeneratedHttpRequest<PCSConnection> httpMethod = processor.createRequest(method, new Object[] { "container" });
assertEquals(httpMethod.getEndpoint().getHost(), "localhost"); assertEquals(httpMethod.getEndpoint().getHost(), "localhost");
assertEquals(httpMethod.getEndpoint().getPath(), "/root/contents"); assertEquals(httpMethod.getEndpoint().getPath(), "/root/contents");
assertEquals(httpMethod.getEndpoint().getQuery(), null); assertEquals(httpMethod.getEndpoint().getQuery(), null);
@ -107,7 +107,7 @@ public class PCSConnectionTest {
assertEquals(httpMethod.getHeaders().get(HttpHeaders.CONTENT_TYPE), Collections assertEquals(httpMethod.getHeaders().get(HttpHeaders.CONTENT_TYPE), Collections
.singletonList("application/vnd.csp.container-info+xml")); .singletonList("application/vnd.csp.container-info+xml"));
assertEquals(httpMethod.getEntity(), "<container><name>container</name></container>"); assertEquals(httpMethod.getEntity(), "<container><name>container</name></container>");
assertEquals(processor.createResponseParser(method, httpMethod, null).getClass(), assertEquals(processor.createResponseParser(method, httpMethod).getClass(),
ParseURIList.class); ParseURIList.class);
// TODO check generic type of response parser // TODO check generic type of response parser
} }
@ -115,14 +115,14 @@ public class PCSConnectionTest {
public void testDeleteContainer() throws SecurityException, NoSuchMethodException { public void testDeleteContainer() throws SecurityException, NoSuchMethodException {
Method method = PCSConnection.class.getMethod("deleteContainer", URI.class); Method method = PCSConnection.class.getMethod("deleteContainer", URI.class);
HttpRequest httpMethod = processor.createRequest(method, new Object[] { URI GeneratedHttpRequest<PCSConnection> httpMethod = processor.createRequest(method, new Object[] { URI
.create("http://localhost/container/1234") }); .create("http://localhost/container/1234") });
assertEquals(httpMethod.getEndpoint().getHost(), "localhost"); assertEquals(httpMethod.getEndpoint().getHost(), "localhost");
assertEquals(httpMethod.getEndpoint().getPath(), "/container/1234"); assertEquals(httpMethod.getEndpoint().getPath(), "/container/1234");
assertEquals(httpMethod.getEndpoint().getQuery(), null); assertEquals(httpMethod.getEndpoint().getQuery(), null);
assertEquals(httpMethod.getMethod(), HttpMethod.DELETE); assertEquals(httpMethod.getMethod(), HttpMethod.DELETE);
assertEquals(httpMethod.getHeaders().size(), 0); assertEquals(httpMethod.getHeaders().size(), 0);
assertEquals(processor.createResponseParser(method, httpMethod, null).getClass(), assertEquals(processor.createResponseParser(method, httpMethod).getClass(),
ReturnVoidIf2xx.class); ReturnVoidIf2xx.class);
assertEquals(processor.createExceptionParserOrNullIfNotFound(method).getClass(), assertEquals(processor.createExceptionParserOrNullIfNotFound(method).getClass(),
ReturnVoidOnNotFoundOr404.class); ReturnVoidOnNotFoundOr404.class);
@ -131,7 +131,7 @@ public class PCSConnectionTest {
public void testListFiles() throws SecurityException, NoSuchMethodException { public void testListFiles() throws SecurityException, NoSuchMethodException {
Method method = PCSConnection.class.getMethod("listFiles", URI.class); Method method = PCSConnection.class.getMethod("listFiles", URI.class);
HttpRequest httpMethod = processor.createRequest(method, new Object[] { URI GeneratedHttpRequest<PCSConnection> httpMethod = processor.createRequest(method, new Object[] { URI
.create("http://localhost/mycontainer") }); .create("http://localhost/mycontainer") });
assertEquals(httpMethod.getEndpoint().getHost(), "localhost"); assertEquals(httpMethod.getEndpoint().getHost(), "localhost");
assertEquals(httpMethod.getEndpoint().getPath(), "/mycontainer/contents"); assertEquals(httpMethod.getEndpoint().getPath(), "/mycontainer/contents");
@ -139,7 +139,7 @@ public class PCSConnectionTest {
assertEquals(httpMethod.getMethod(), HttpMethod.GET); assertEquals(httpMethod.getMethod(), HttpMethod.GET);
assertEquals(httpMethod.getHeaders().size(), 1); assertEquals(httpMethod.getHeaders().size(), 1);
assertEquals(httpMethod.getHeaders().get("X-Cloud-Depth"), Collections.singletonList("2")); assertEquals(httpMethod.getHeaders().get("X-Cloud-Depth"), Collections.singletonList("2"));
assertEquals(processor.createResponseParser(method, httpMethod, null).getClass(), assertEquals(processor.createResponseParser(method, httpMethod).getClass(),
ParseSax.class); ParseSax.class);
// TODO check generic type of response parser // TODO check generic type of response parser
assertEquals(processor.createExceptionParserOrNullIfNotFound(method), null); assertEquals(processor.createExceptionParserOrNullIfNotFound(method), null);
@ -148,7 +148,7 @@ public class PCSConnectionTest {
public void testListContainersURI() throws SecurityException, NoSuchMethodException { public void testListContainersURI() throws SecurityException, NoSuchMethodException {
Method method = PCSConnection.class.getMethod("listContainers", URI.class); Method method = PCSConnection.class.getMethod("listContainers", URI.class);
HttpRequest httpMethod = processor.createRequest(method, new Object[] { URI GeneratedHttpRequest<PCSConnection> httpMethod = processor.createRequest(method, new Object[] { URI
.create("http://localhost/mycontainer") }); .create("http://localhost/mycontainer") });
assertEquals(httpMethod.getEndpoint().getHost(), "localhost"); assertEquals(httpMethod.getEndpoint().getHost(), "localhost");
assertEquals(httpMethod.getEndpoint().getPath(), "/mycontainer/contents"); assertEquals(httpMethod.getEndpoint().getPath(), "/mycontainer/contents");
@ -156,7 +156,7 @@ public class PCSConnectionTest {
assertEquals(httpMethod.getMethod(), HttpMethod.GET); assertEquals(httpMethod.getMethod(), HttpMethod.GET);
assertEquals(httpMethod.getHeaders().size(), 1); assertEquals(httpMethod.getHeaders().size(), 1);
assertEquals(httpMethod.getHeaders().get("X-Cloud-Depth"), Collections.singletonList("2")); assertEquals(httpMethod.getHeaders().get("X-Cloud-Depth"), Collections.singletonList("2"));
assertEquals(processor.createResponseParser(method, httpMethod, null).getClass(), assertEquals(processor.createResponseParser(method, httpMethod).getClass(),
ParseSax.class); ParseSax.class);
// TODO check generic type of response parser // TODO check generic type of response parser
assertEquals(processor.createExceptionParserOrNullIfNotFound(method), null); assertEquals(processor.createExceptionParserOrNullIfNotFound(method), null);
@ -165,50 +165,50 @@ public class PCSConnectionTest {
public void testUploadFile() throws SecurityException, NoSuchMethodException, IOException { public void testUploadFile() throws SecurityException, NoSuchMethodException, IOException {
Method method = PCSConnection.class.getMethod("uploadFile", URI.class, PCSFile.class); Method method = PCSConnection.class.getMethod("uploadFile", URI.class, PCSFile.class);
HttpRequest httpMethod = processor.createRequest(method, new Object[] { GeneratedHttpRequest<PCSConnection> httpMethod = processor.createRequest(method, new Object[] {
URI.create("http://localhost/mycontainer"), URI.create("http://localhost/mycontainer"),
AddBlobEntityAsMultipartFormTest.TEST_BLOB }); BindBlobToMultipartFormTest.TEST_BLOB });
assertEquals(httpMethod.getEndpoint().getHost(), "localhost"); assertEquals(httpMethod.getEndpoint().getHost(), "localhost");
assertEquals(httpMethod.getEndpoint().getPath(), "/mycontainer/contents"); assertEquals(httpMethod.getEndpoint().getPath(), "/mycontainer/contents");
assertEquals(httpMethod.getEndpoint().getQuery(), null); assertEquals(httpMethod.getEndpoint().getQuery(), null);
assertEquals(httpMethod.getMethod(), HttpMethod.POST); assertEquals(httpMethod.getMethod(), HttpMethod.POST);
assertEquals(httpMethod.getHeaders().size(), 2); assertEquals(httpMethod.getHeaders().size(), 2);
assertEquals(httpMethod.getHeaders().get(HttpHeaders.CONTENT_LENGTH), Collections assertEquals(httpMethod.getHeaders().get(HttpHeaders.CONTENT_LENGTH), Collections
.singletonList(AddBlobEntityAsMultipartFormTest.EXPECTS.length() + "")); .singletonList(BindBlobToMultipartFormTest.EXPECTS.length() + ""));
assertEquals(httpMethod.getHeaders().get(HttpHeaders.CONTENT_TYPE), Collections assertEquals(httpMethod.getHeaders().get(HttpHeaders.CONTENT_TYPE), Collections
.singletonList("multipart/form-data; boundary=" .singletonList("multipart/form-data; boundary="
+ AddBlobEntityAsMultipartFormTest.BOUNDRY)); + BindBlobToMultipartFormTest.BOUNDRY));
assertEquals(Utils.toStringAndClose((InputStream) httpMethod.getEntity()), assertEquals(Utils.toStringAndClose((InputStream) httpMethod.getEntity()),
AddBlobEntityAsMultipartFormTest.EXPECTS); BindBlobToMultipartFormTest.EXPECTS);
assertEquals(processor.createResponseParser(method, httpMethod, null).getClass(), assertEquals(processor.createResponseParser(method, httpMethod).getClass(),
ParseURIList.class); ParseURIList.class);
} }
public void testDownloadFile() throws SecurityException, NoSuchMethodException, IOException { public void testDownloadFile() throws SecurityException, NoSuchMethodException, IOException {
Method method = PCSConnection.class.getMethod("downloadFile", URI.class); Method method = PCSConnection.class.getMethod("downloadFile", URI.class);
HttpRequest httpMethod = processor.createRequest(method, new Object[] { URI GeneratedHttpRequest<PCSConnection> httpMethod = processor.createRequest(method, new Object[] { URI
.create("http://localhost/container") }); .create("http://localhost/container") });
assertEquals(httpMethod.getEndpoint().getHost(), "localhost"); assertEquals(httpMethod.getEndpoint().getHost(), "localhost");
assertEquals(httpMethod.getEndpoint().getPath(), "/container/content"); assertEquals(httpMethod.getEndpoint().getPath(), "/container/content");
assertEquals(httpMethod.getEndpoint().getQuery(), null); assertEquals(httpMethod.getEndpoint().getQuery(), null);
assertEquals(httpMethod.getMethod(), HttpMethod.GET); assertEquals(httpMethod.getMethod(), HttpMethod.GET);
assertEquals(httpMethod.getHeaders().size(), 0); assertEquals(httpMethod.getHeaders().size(), 0);
assertEquals(processor.createResponseParser(method, httpMethod, null).getClass(), assertEquals(processor.createResponseParser(method, httpMethod).getClass(),
ReturnInputStream.class); ReturnInputStream.class);
} }
public void testDeleteFile() throws SecurityException, NoSuchMethodException, IOException { public void testDeleteFile() throws SecurityException, NoSuchMethodException, IOException {
Method method = PCSConnection.class.getMethod("deleteFile", URI.class); Method method = PCSConnection.class.getMethod("deleteFile", URI.class);
HttpRequest httpMethod = processor.createRequest(method, new Object[] { URI GeneratedHttpRequest<PCSConnection> httpMethod = processor.createRequest(method, new Object[] { URI
.create("http://localhost/contents/file") }); .create("http://localhost/contents/file") });
assertEquals(httpMethod.getEndpoint().getHost(), "localhost"); assertEquals(httpMethod.getEndpoint().getHost(), "localhost");
assertEquals(httpMethod.getEndpoint().getPath(), "/contents/file"); assertEquals(httpMethod.getEndpoint().getPath(), "/contents/file");
assertEquals(httpMethod.getEndpoint().getQuery(), null); assertEquals(httpMethod.getEndpoint().getQuery(), null);
assertEquals(httpMethod.getMethod(), HttpMethod.DELETE); assertEquals(httpMethod.getMethod(), HttpMethod.DELETE);
assertEquals(httpMethod.getHeaders().size(), 0); assertEquals(httpMethod.getHeaders().size(), 0);
assertEquals(processor.createResponseParser(method, httpMethod, null).getClass(), assertEquals(processor.createResponseParser(method, httpMethod).getClass(),
ReturnVoidIf2xx.class); ReturnVoidIf2xx.class);
assertEquals(processor.createExceptionParserOrNullIfNotFound(method).getClass(), assertEquals(processor.createExceptionParserOrNullIfNotFound(method).getClass(),
ReturnVoidOnNotFoundOr404.class); ReturnVoidOnNotFoundOr404.class);

View File

@ -21,7 +21,7 @@
* under the License. * under the License.
* ==================================================================== * ====================================================================
*/ */
package org.jclouds.mezeo.pcs2.decorators; package org.jclouds.mezeo.pcs2.binders;
import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertEquals;
@ -33,17 +33,17 @@ import org.jclouds.http.HttpRequest;
import org.testng.annotations.Test; import org.testng.annotations.Test;
/** /**
* Tests behavior of {@code AddContainerNameAsXmlEntity} * Tests behavior of {@code BindContainerNameToXmlEntity}
* *
* @author Adrian Cole * @author Adrian Cole
*/ */
@Test(groups = "unit", testName = "pcs2.AddContainerNameAsXmlEntityTest") @Test(groups = "unit", testName = "pcs2.BindContainerNameToXmlEntityTest")
public class AddContainerNameAsXmlEntityTest { public class BindContainerNameToXmlEntityTest {
public void test() { public void test() {
AddContainerNameAsXmlEntity binder = new AddContainerNameAsXmlEntity(); BindContainerNameToXmlEntity binder = new BindContainerNameToXmlEntity();
HttpRequest request = new HttpRequest("GET", URI.create("http://localhost")); HttpRequest request = new HttpRequest("GET", URI.create("http://localhost"));
binder.decorateRequest(request, "foo"); binder.bindToRequest(request, "foo");
assertEquals(request.getEntity(), "<container><name>foo</name></container>"); assertEquals(request.getEntity(), "<container><name>foo</name></container>");
assertEquals(request.getFirstHeaderOrNull(HttpHeaders.CONTENT_LENGTH), assertEquals(request.getFirstHeaderOrNull(HttpHeaders.CONTENT_LENGTH),
"<container><name>foo</name></container>".getBytes().length + ""); "<container><name>foo</name></container>".getBytes().length + "");

View File

@ -21,7 +21,7 @@
* under the License. * under the License.
* ==================================================================== * ====================================================================
*/ */
package org.jclouds.mezeo.pcs2.decorators; package org.jclouds.mezeo.pcs2.binders;
import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertEquals;
@ -34,18 +34,18 @@ import org.jclouds.mezeo.pcs2.domain.PCSFile;
import org.testng.annotations.Test; import org.testng.annotations.Test;
/** /**
* Tests behavior of {@code AddFileInfoAsXmlEntity} * Tests behavior of {@code BindFileInfoToXmlEntity}
* *
* @author Adrian Cole * @author Adrian Cole
*/ */
@Test(groups = "unit", testName = "pcs2.AddFileInfoAsXmlEntityTest") @Test(groups = "unit", testName = "pcs2.BindFileInfoToXmlEntityTest")
public class AddFileInfoAsXmlEntityTest { public class BindFileInfoToXmlEntityTest {
public void test() { public void test() {
AddFileInfoAsXmlEntity binder = new AddFileInfoAsXmlEntity(); BindFileInfoToXmlEntity binder = new BindFileInfoToXmlEntity();
HttpRequest request = new HttpRequest("GET", URI.create("http://localhost")); HttpRequest request = new HttpRequest("GET", URI.create("http://localhost"));
PCSFile file = new PCSFile("foo"); PCSFile file = new PCSFile("foo");
binder.decorateRequest(request, file); binder.bindToRequest(request, file);
assertEquals( assertEquals(
request.getEntity(), request.getEntity(),
"<file><name>foo</name><mime_type>application/octet-stream</mime_type><public>false</public></file>"); "<file><name>foo</name><mime_type>application/octet-stream</mime_type><public>false</public></file>");
@ -60,10 +60,10 @@ public class AddFileInfoAsXmlEntityTest {
} }
public void testCompound() { public void testCompound() {
AddFileInfoAsXmlEntity binder = new AddFileInfoAsXmlEntity(); BindFileInfoToXmlEntity binder = new BindFileInfoToXmlEntity();
HttpRequest request = new HttpRequest("GET", URI.create("http://localhost")); HttpRequest request = new HttpRequest("GET", URI.create("http://localhost"));
PCSFile file = new PCSFile("subdir/foo"); PCSFile file = new PCSFile("subdir/foo");
binder.decorateRequest(request, file); binder.bindToRequest(request, file);
assertEquals( assertEquals(
request.getEntity(), request.getEntity(),
"<file><name>foo</name><mime_type>application/octet-stream</mime_type><public>false</public></file>"); "<file><name>foo</name><mime_type>application/octet-stream</mime_type><public>false</public></file>");

View File

@ -30,24 +30,38 @@ import static org.easymock.classextension.EasyMock.replay;
import static org.easymock.classextension.EasyMock.verify; import static org.easymock.classextension.EasyMock.verify;
import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertEquals;
import java.lang.reflect.Method;
import java.net.URI; import java.net.URI;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.Future; import java.util.concurrent.Future;
import javax.ws.rs.POST;
import javax.ws.rs.ext.RuntimeDelegate; import javax.ws.rs.ext.RuntimeDelegate;
import org.apache.commons.io.IOUtils; import org.apache.commons.io.IOUtils;
import org.jclouds.blobstore.domain.Key; import org.jclouds.blobstore.domain.Key;
import org.jclouds.http.HttpRequest; import org.jclouds.concurrent.WithinThreadExecutorService;
import org.jclouds.concurrent.config.ExecutorServiceModule;
import org.jclouds.http.HttpResponse; import org.jclouds.http.HttpResponse;
import org.jclouds.http.HttpUtils; import org.jclouds.http.HttpUtils;
import org.jclouds.http.config.JavaUrlHttpCommandExecutorServiceModule;
import org.jclouds.logging.Logger;
import org.jclouds.logging.Logger.LoggerFactory;
import org.jclouds.mezeo.pcs2.PCSUtil; import org.jclouds.mezeo.pcs2.PCSUtil;
import org.jclouds.mezeo.pcs2.domain.PCSFile; import org.jclouds.mezeo.pcs2.domain.PCSFile;
import org.jclouds.rest.annotations.Endpoint;
import org.jclouds.rest.config.RestModule;
import org.jclouds.rest.internal.RestAnnotationProcessor;
import org.jclouds.rest.internal.RuntimeDelegateImpl; import org.jclouds.rest.internal.RuntimeDelegateImpl;
import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test; import org.testng.annotations.Test;
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.TypeLiteral;
/** /**
* Tests behavior of {@code UseResourceIdAsETag} * Tests behavior of {@code UseResourceIdAsETag}
* *
@ -60,6 +74,13 @@ public class AddMetadataAndParseResourceIdIntoBytesTest {
} }
HttpResponse response = new HttpResponse(); HttpResponse response = new HttpResponse();
ConcurrentMap<Key, String> fileCache; ConcurrentMap<Key, String> fileCache;
private RestAnnotationProcessor<org.jclouds.mezeo.pcs2.functions.AddMetadataAndParseResourceIdIntoBytesTest.TestService> factory;
private Method method;
private static interface TestService {
@POST
public void foo(String container, PCSFile file, @Endpoint URI endpoint);
}
@BeforeClass @BeforeClass
void setupMap() { void setupMap() {
@ -71,10 +92,12 @@ public class AddMetadataAndParseResourceIdIntoBytesTest {
PCSUtil createPCSUtil() { PCSUtil createPCSUtil() {
PCSUtil connection = createMock(PCSUtil.class); PCSUtil connection = createMock(PCSUtil.class);
final Future<Void> voidF = createMock(Future.class); final Future<Void> voidF = createMock(Future.class);
expect(connection.putMetadata(eq("7F143552-AAF5-11DE-BBB0-0BC388ED913B"), eq("foo"), eq("bar"))) expect(
.andReturn(voidF); connection.putMetadata(eq("7F143552-AAF5-11DE-BBB0-0BC388ED913B"), eq("foo"),
expect(connection.putMetadata(eq("7F143552-AAF5-11DE-BBB0-0BC388ED913B"), eq("biz"), eq("baz"))) eq("bar"))).andReturn(voidF);
.andReturn(voidF); expect(
connection.putMetadata(eq("7F143552-AAF5-11DE-BBB0-0BC388ED913B"), eq("biz"),
eq("baz"))).andReturn(voidF);
replay(connection); replay(connection);
return connection; return connection;
} }
@ -91,7 +114,6 @@ public class AddMetadataAndParseResourceIdIntoBytesTest {
public void testNoRequest() { public void testNoRequest() {
AddMetadataAndParseResourceIdIntoBytes function = new AddMetadataAndParseResourceIdIntoBytes( AddMetadataAndParseResourceIdIntoBytes function = new AddMetadataAndParseResourceIdIntoBytes(
fileCache, createPCSUtil()); fileCache, createPCSUtil());
function.setContext(null, new Object[] {"container", new PCSFile("key") });
function.apply(response); function.apply(response);
} }
@ -99,8 +121,8 @@ public class AddMetadataAndParseResourceIdIntoBytesTest {
PCSUtil connection = createPCSUtil(); PCSUtil connection = createPCSUtil();
AddMetadataAndParseResourceIdIntoBytes function = new AddMetadataAndParseResourceIdIntoBytes( AddMetadataAndParseResourceIdIntoBytes function = new AddMetadataAndParseResourceIdIntoBytes(
fileCache, connection); fileCache, connection);
function.setContext(new HttpRequest("GET", URI.create("http://localhost:8080")), function.setContext(factory.createRequest(method, "container", new PCSFile("key"), URI
new Object[] { "container", new PCSFile("key") }); .create("http://localhost:8080")));
response.setContent(IOUtils response.setContent(IOUtils
.toInputStream("http://localhost/contents/7F143552-AAF5-11DE-BBB0-0BC388ED913B")); .toInputStream("http://localhost/contents/7F143552-AAF5-11DE-BBB0-0BC388ED913B"));
byte[] eTag = function.apply(response); byte[] eTag = function.apply(response);
@ -117,8 +139,8 @@ public class AddMetadataAndParseResourceIdIntoBytesTest {
pcsFile.getMetadata().getUserMetadata().put("foo", "bar"); pcsFile.getMetadata().getUserMetadata().put("foo", "bar");
pcsFile.getMetadata().getUserMetadata().put("biz", "baz"); pcsFile.getMetadata().getUserMetadata().put("biz", "baz");
function.setContext(new HttpRequest("GET", URI.create("http://localhost:8080")), function.setContext(factory.createRequest(method, "container", pcsFile, URI
new Object[] { "container", pcsFile }); .create("http://localhost:8080")));
response.setContent(IOUtils response.setContent(IOUtils
.toInputStream("http://localhost/contents/7F143552-AAF5-11DE-BBB0-0BC388ED913B")); .toInputStream("http://localhost/contents/7F143552-AAF5-11DE-BBB0-0BC388ED913B"));
byte[] eTag = function.apply(response); byte[] eTag = function.apply(response);
@ -128,4 +150,33 @@ public class AddMetadataAndParseResourceIdIntoBytesTest {
verify(connection); verify(connection);
} }
/**
* before class, as we need to ensure that the filter is threadsafe.
*
* @throws NoSuchMethodException
* @throws SecurityException
*
*/
@BeforeClass
protected void createFilter() throws SecurityException, NoSuchMethodException {
Injector injector = Guice.createInjector(new RestModule(), new ExecutorServiceModule(
new WithinThreadExecutorService()), new JavaUrlHttpCommandExecutorServiceModule(),
new AbstractModule() {
protected void configure() {
RuntimeDelegate.setInstance(new RuntimeDelegateImpl());
bind(Logger.LoggerFactory.class).toInstance(new LoggerFactory() {
public Logger getLogger(String category) {
return Logger.NULL;
}
});
}
});
factory = injector.getInstance(com.google.inject.Key
.get(new TypeLiteral<RestAnnotationProcessor<TestService>>() {
}));
method = TestService.class.getMethod("foo", String.class, PCSFile.class, URI.class);
}
} }

View File

@ -33,15 +33,15 @@ import javax.ws.rs.Path;
import javax.ws.rs.PathParam; import javax.ws.rs.PathParam;
import javax.ws.rs.QueryParam; import javax.ws.rs.QueryParam;
import org.jclouds.blobstore.decorators.AddBlobEntityAsMultipartForm; import org.jclouds.blobstore.binders.BindBlobToMultipartForm;
import org.jclouds.blobstore.domain.Blob; import org.jclouds.blobstore.domain.Blob;
import org.jclouds.blobstore.domain.BlobMetadata; import org.jclouds.blobstore.domain.BlobMetadata;
import org.jclouds.nirvanix.sdn.decorators.AddMetadataAsQueryParams; import org.jclouds.nirvanix.sdn.binders.BindMetadataToQueryParams;
import org.jclouds.nirvanix.sdn.domain.UploadInfo; import org.jclouds.nirvanix.sdn.domain.UploadInfo;
import org.jclouds.nirvanix.sdn.filters.AddSessionTokenToRequest; import org.jclouds.nirvanix.sdn.filters.AddSessionTokenToRequest;
import org.jclouds.nirvanix.sdn.functions.ParseUploadInfoFromJsonResponse; import org.jclouds.nirvanix.sdn.functions.ParseUploadInfoFromJsonResponse;
import org.jclouds.nirvanix.sdn.reference.SDNQueryParams; import org.jclouds.nirvanix.sdn.reference.SDNQueryParams;
import org.jclouds.rest.annotations.DecoratorParam; import org.jclouds.rest.annotations.BinderParam;
import org.jclouds.rest.annotations.Endpoint; import org.jclouds.rest.annotations.Endpoint;
import org.jclouds.rest.annotations.QueryParams; import org.jclouds.rest.annotations.QueryParams;
import org.jclouds.rest.annotations.RequestFilters; import org.jclouds.rest.annotations.RequestFilters;
@ -78,12 +78,22 @@ public interface SDNConnection {
Future<Void> upload(@Endpoint URI endpoint, Future<Void> upload(@Endpoint URI endpoint,
@QueryParam(SDNQueryParams.UPLOADTOKEN) String uploadToken, @QueryParam(SDNQueryParams.UPLOADTOKEN) String uploadToken,
@QueryParam(SDNQueryParams.DESTFOLDERPATH) String folderPath, @QueryParam(SDNQueryParams.DESTFOLDERPATH) String folderPath,
@DecoratorParam(AddBlobEntityAsMultipartForm.class) Blob<BlobMetadata> blob); @BinderParam(BindBlobToMultipartForm.class) Blob<BlobMetadata> blob);
/**
* The SetMetadata method is used to set specified metadata for a file or folder.
*/
@PUT @PUT
@Path("/Metadata/SetMetadata.ashx") @Path("/Metadata/SetMetadata.ashx")
@QueryParams(keys = SDNQueryParams.PATH, values = "{container}/{key}") @QueryParams(keys = SDNQueryParams.PATH, values = "{path}")
Future<Void> setMetadata(@PathParam("container") String container, @PathParam("key") String key, Future<Void> setMetadata(@PathParam("path") String path,
@DecoratorParam(AddMetadataAsQueryParams.class) Multimap<String, String> metadata); @BinderParam(BindMetadataToQueryParams.class) Multimap<String, String> metadata);
/**
* The GetMetadata method is used to retrieve all metadata from a file or folder.
*/
@GET
@Path("/Metadata/GetMetadata.ashx")
@QueryParams(keys = SDNQueryParams.PATH, values = "{path}")
Future<String> getMetadata(@PathParam("path") String path);
} }

View File

@ -1,4 +1,4 @@
package org.jclouds.nirvanix.sdn.decorators; package org.jclouds.nirvanix.sdn.binders;
import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkNotNull;
@ -6,34 +6,27 @@ import static com.google.common.base.Preconditions.checkNotNull;
import java.util.List; import java.util.List;
import java.util.Map.Entry; import java.util.Map.Entry;
import javax.ws.rs.core.UriBuilder;
import org.jclouds.http.HttpRequest; import org.jclouds.http.HttpRequest;
import org.jclouds.http.HttpRequestFilter; import org.jclouds.rest.Binder;
import org.jclouds.rest.decorators.RequestDecorator; import org.jclouds.rest.internal.GeneratedHttpRequest;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import com.google.common.collect.Multimap; import com.google.common.collect.Multimap;
public class AddMetadataAsQueryParams implements RequestDecorator { public class BindMetadataToQueryParams implements Binder {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public HttpRequest decorateRequest(HttpRequest request, Object input) { public void bindToRequest(HttpRequest request, Object input) {
checkArgument(checkNotNull(request, "input") instanceof GeneratedHttpRequest,
"this decorator is only valid for GeneratedHttpRequests!");
checkArgument(checkNotNull(input, "input") instanceof Multimap, checkArgument(checkNotNull(input, "input") instanceof Multimap,
"this decorator is only valid for Multimaps!"); "this decorator is only valid for Multimaps!");
UriBuilder builder = UriBuilder.fromUri(request.getEndpoint());
Multimap<String, String> userMetadata = (Multimap<String, String>) input; Multimap<String, String> userMetadata = (Multimap<String, String>) input;
List<String> metadata = Lists.newArrayList(); List<String> metadata = Lists.newArrayList();
for (Entry<String, String> entry : userMetadata.entries()) { for (Entry<String, String> entry : userMetadata.entries()) {
metadata.add(String.format("%s:%s", entry.getKey().toLowerCase(), entry.getValue())); metadata.add(String.format("%s:%s", entry.getKey().toLowerCase(), entry.getValue()));
} }
builder.replaceQueryParam("metadata", metadata.toArray()); ((GeneratedHttpRequest)request).replaceQueryParam("metadata", metadata.toArray());
List<HttpRequestFilter> oldFilters = request.getFilters();
request = new HttpRequest(request.getMethod(), builder.build(), request.getHeaders(), request
.getEntity());
request.getFilters().addAll(oldFilters);
return request;
} }
} }

View File

@ -1,19 +1,21 @@
package org.jclouds.nirvanix.sdn.filters; package org.jclouds.nirvanix.sdn.filters;
import java.util.List; import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.atomic.AtomicReference;
import javax.inject.Inject; import javax.inject.Inject;
import javax.inject.Provider; import javax.inject.Provider;
import javax.inject.Singleton; import javax.inject.Singleton;
import javax.ws.rs.core.UriBuilder;
import org.jclouds.http.HttpException; import org.jclouds.http.HttpException;
import org.jclouds.http.HttpRequest; import org.jclouds.http.HttpRequest;
import org.jclouds.http.HttpRequestFilter; import org.jclouds.http.HttpRequestFilter;
import org.jclouds.nirvanix.sdn.SessionToken; import org.jclouds.nirvanix.sdn.SessionToken;
import org.jclouds.nirvanix.sdn.reference.SDNQueryParams; import org.jclouds.nirvanix.sdn.reference.SDNQueryParams;
import org.jclouds.rest.internal.GeneratedHttpRequest;
/** /**
* Adds the Session Token to the request. This will update the Session Token before 20 minutes is * Adds the Session Token to the request. This will update the Session Token before 20 minutes is
@ -65,14 +67,12 @@ public class AddSessionTokenToRequest implements HttpRequestFilter {
authToken = new AtomicReference<String>(); authToken = new AtomicReference<String>();
} }
public HttpRequest filter(HttpRequest request) throws HttpException { public void filter(HttpRequest request) throws HttpException {
UriBuilder builder = UriBuilder.fromUri(request.getEndpoint()); checkArgument(checkNotNull(request, "input") instanceof GeneratedHttpRequest<?>,
builder.replaceQueryParam(SDNQueryParams.SESSIONTOKEN, getSessionToken()); "this decorator is only valid for GeneratedHttpRequests!");
List<HttpRequestFilter> oldFilters = request.getFilters(); ((GeneratedHttpRequest<?>) request).replaceQueryParam(SDNQueryParams.SESSIONTOKEN,
request = new HttpRequest(request.getMethod(), builder.build(), request.getHeaders(), request getSessionToken());
.getEntity());
request.getFilters().addAll(oldFilters);
return request;
} }
} }

View File

@ -16,6 +16,9 @@ import org.jclouds.nirvanix.sdn.domain.UploadInfo;
import org.testng.annotations.BeforeGroups; import org.testng.annotations.BeforeGroups;
import org.testng.annotations.Test; import org.testng.annotations.Test;
import com.google.common.collect.ImmutableMultimap;
import com.google.common.collect.Multimap;
/** /**
* Tests behavior of {@code SDNConnection} * Tests behavior of {@code SDNConnection}
* *
@ -47,11 +50,17 @@ public class SDNConnectionLiveTest {
assertNotNull(uploadInfo.getHost()); assertNotNull(uploadInfo.getHost());
assertNotNull(uploadInfo.getToken()); assertNotNull(uploadInfo.getToken());
connection.upload(uploadInfo.getHost(), uploadInfo.getToken(), "container", connection.upload(uploadInfo.getHost(), uploadInfo.getToken(), containerName,
new Blob<BlobMetadata>("key", "value")).get(30, TimeUnit.SECONDS); new Blob<BlobMetadata>("key", "value")).get(30, TimeUnit.SECONDS);
// Multimap<String, String> metadata = ImmutableMultimap.of("chef", "sushi");
// who knows... 403 error; connection.setMetadata("container", "key", metadata).get(30, String metadataS = connection.getMetadata(containerName).get(30, TimeUnit.SECONDS);
// TimeUnit.SECONDS); System.err.println(metadataS);
Multimap<String, String> metadata = ImmutableMultimap.of("chef", "sushi", "foo", "bar");
connection.setMetadata(containerName, metadata).get(30, TimeUnit.SECONDS);
metadataS = connection.getMetadata(containerName).get(30, TimeUnit.SECONDS);
System.err.println(metadataS);
} }
} }

View File

@ -34,18 +34,19 @@ import java.util.Collections;
import javax.ws.rs.HttpMethod; import javax.ws.rs.HttpMethod;
import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.HttpHeaders;
import org.jclouds.blobstore.decorators.AddBlobEntityAsMultipartFormTest; import org.jclouds.blobstore.binders.BindBlobToMultipartFormTest;
import org.jclouds.blobstore.domain.Blob; import org.jclouds.blobstore.domain.Blob;
import org.jclouds.blobstore.domain.BlobMetadata; import org.jclouds.blobstore.domain.BlobMetadata;
import org.jclouds.concurrent.WithinThreadExecutorService; import org.jclouds.concurrent.WithinThreadExecutorService;
import org.jclouds.concurrent.config.ExecutorServiceModule; import org.jclouds.concurrent.config.ExecutorServiceModule;
import org.jclouds.http.HttpRequest;
import org.jclouds.http.config.JavaUrlHttpCommandExecutorServiceModule; import org.jclouds.http.config.JavaUrlHttpCommandExecutorServiceModule;
import org.jclouds.http.functions.ReturnStringIf200;
import org.jclouds.http.functions.ReturnVoidIf2xx; import org.jclouds.http.functions.ReturnVoidIf2xx;
import org.jclouds.logging.Logger; import org.jclouds.logging.Logger;
import org.jclouds.logging.Logger.LoggerFactory; import org.jclouds.logging.Logger.LoggerFactory;
import org.jclouds.nirvanix.sdn.functions.ParseUploadInfoFromJsonResponse; import org.jclouds.nirvanix.sdn.functions.ParseUploadInfoFromJsonResponse;
import org.jclouds.rest.config.RestModule; import org.jclouds.rest.config.RestModule;
import org.jclouds.rest.internal.GeneratedHttpRequest;
import org.jclouds.rest.internal.RestAnnotationProcessor; import org.jclouds.rest.internal.RestAnnotationProcessor;
import org.jclouds.util.Utils; import org.jclouds.util.Utils;
import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeClass;
@ -72,8 +73,8 @@ public class SDNConnectionTest {
public void testGetStorageNode() throws SecurityException, NoSuchMethodException { public void testGetStorageNode() throws SecurityException, NoSuchMethodException {
Method method = SDNConnection.class.getMethod("getStorageNode", String.class, long.class); Method method = SDNConnection.class.getMethod("getStorageNode", String.class, long.class);
HttpRequest httpMethod = processor.createRequest(method, new Object[] { "adriansmovies", GeneratedHttpRequest<?> httpMethod = processor.createRequest(method, new Object[] {
734859264 }); "adriansmovies", 734859264 });
assertEquals(httpMethod.getEndpoint().getHost(), "localhost"); assertEquals(httpMethod.getEndpoint().getHost(), "localhost");
assertEquals(httpMethod.getEndpoint().getPath(), "/IMFS/GetStorageNode.ashx"); assertEquals(httpMethod.getEndpoint().getPath(), "/IMFS/GetStorageNode.ashx");
assertEquals(httpMethod.getEndpoint().getQuery(), assertEquals(httpMethod.getEndpoint().getQuery(),
@ -87,9 +88,9 @@ public class SDNConnectionTest {
public void testUpload() throws SecurityException, NoSuchMethodException, IOException { public void testUpload() throws SecurityException, NoSuchMethodException, IOException {
Method method = SDNConnection.class.getMethod("upload", URI.class, String.class, Method method = SDNConnection.class.getMethod("upload", URI.class, String.class,
String.class, Blob.class); String.class, Blob.class);
Blob<BlobMetadata> blob = AddBlobEntityAsMultipartFormTest.TEST_BLOB; Blob<BlobMetadata> blob = BindBlobToMultipartFormTest.TEST_BLOB;
HttpRequest httpMethod = processor.createRequest(method, new Object[] { GeneratedHttpRequest<SDNConnection> httpMethod = processor.createRequest(method,
URI.create("http://uploader"), "token", "adriansmovies", blob }); new Object[] { URI.create("http://uploader"), "token", "adriansmovies", blob });
assertEquals(httpMethod.getEndpoint().getHost(), "uploader"); assertEquals(httpMethod.getEndpoint().getHost(), "uploader");
assertEquals(httpMethod.getEndpoint().getPath(), "/Upload.ashx"); assertEquals(httpMethod.getEndpoint().getPath(), "/Upload.ashx");
assertEquals(httpMethod.getEndpoint().getQuery(), assertEquals(httpMethod.getEndpoint().getQuery(),
@ -97,21 +98,21 @@ public class SDNConnectionTest {
assertEquals(httpMethod.getMethod(), HttpMethod.POST); assertEquals(httpMethod.getMethod(), HttpMethod.POST);
assertEquals(httpMethod.getHeaders().size(), 2); assertEquals(httpMethod.getHeaders().size(), 2);
assertEquals(httpMethod.getHeaders().get(HttpHeaders.CONTENT_LENGTH), Collections assertEquals(httpMethod.getHeaders().get(HttpHeaders.CONTENT_LENGTH), Collections
.singletonList(AddBlobEntityAsMultipartFormTest.EXPECTS.length() + "")); .singletonList(BindBlobToMultipartFormTest.EXPECTS.length() + ""));
assertEquals(httpMethod.getHeaders().get(HttpHeaders.CONTENT_TYPE), Collections assertEquals(httpMethod.getHeaders().get(HttpHeaders.CONTENT_TYPE), Collections
.singletonList("multipart/form-data; boundary=" .singletonList("multipart/form-data; boundary="
+ AddBlobEntityAsMultipartFormTest.BOUNDRY)); + BindBlobToMultipartFormTest.BOUNDRY));
assertEquals(Utils.toStringAndClose((InputStream) httpMethod.getEntity()), assertEquals(Utils.toStringAndClose((InputStream) httpMethod.getEntity()),
AddBlobEntityAsMultipartFormTest.EXPECTS); BindBlobToMultipartFormTest.EXPECTS);
assertEquals(processor.createResponseParser(method, httpMethod, null).getClass(), assertEquals(processor.createResponseParser(method, httpMethod).getClass(),
ReturnVoidIf2xx.class); ReturnVoidIf2xx.class);
} }
public void testSetMetadata() throws SecurityException, NoSuchMethodException, IOException { public void testSetMetadata() throws SecurityException, NoSuchMethodException, IOException {
Method method = SDNConnection.class.getMethod("setMetadata", String.class, String.class, Method method = SDNConnection.class.getMethod("setMetadata", String.class, Multimap.class);
Multimap.class); GeneratedHttpRequest<SDNConnection> httpMethod = processor
HttpRequest httpMethod = processor.createRequest(method, new Object[] { "adriansmovies", .createRequest(method, new Object[] { "adriansmovies/sushi.avi",
"sushi.avi", ImmutableMultimap.of("Chef", "Kawasaki") }); ImmutableMultimap.of("Chef", "Kawasaki") });
assertEquals(httpMethod.getEndpoint().getHost(), "localhost"); assertEquals(httpMethod.getEndpoint().getHost(), "localhost");
assertEquals(httpMethod.getEndpoint().getPath(), "/Metadata/SetMetadata.ashx"); assertEquals(httpMethod.getEndpoint().getPath(), "/Metadata/SetMetadata.ashx");
assertEquals(httpMethod.getEndpoint().getQuery(), assertEquals(httpMethod.getEndpoint().getQuery(),
@ -121,10 +122,24 @@ public class SDNConnectionTest {
assertEquals(httpMethod.getHeaders().get(HttpHeaders.CONTENT_LENGTH), Collections assertEquals(httpMethod.getHeaders().get(HttpHeaders.CONTENT_LENGTH), Collections
.singletonList(0 + "")); .singletonList(0 + ""));
assertEquals(httpMethod.getEntity(), null); assertEquals(httpMethod.getEntity(), null);
assertEquals(processor.createResponseParser(method, httpMethod, null).getClass(), assertEquals(processor.createResponseParser(method, httpMethod).getClass(),
ReturnVoidIf2xx.class); ReturnVoidIf2xx.class);
} }
public void testGetMetadata() throws SecurityException, NoSuchMethodException, IOException {
Method method = SDNConnection.class.getMethod("getMetadata", String.class);
GeneratedHttpRequest<SDNConnection> httpMethod = processor.createRequest(method,
new Object[] { "adriansmovies/sushi.avi" });
assertEquals(httpMethod.getEndpoint().getHost(), "localhost");
assertEquals(httpMethod.getEndpoint().getPath(), "/Metadata/GetMetadata.ashx");
assertEquals(httpMethod.getEndpoint().getQuery(), "output=json&path=adriansmovies/sushi.avi");
assertEquals(httpMethod.getMethod(), HttpMethod.GET);
assertEquals(httpMethod.getHeaders().size(), 0);
assertEquals(httpMethod.getEntity(), null);
assertEquals(processor.createResponseParser(method, httpMethod).getClass(),
ReturnStringIf200.class);
}
@BeforeClass @BeforeClass
void setupFactory() { void setupFactory() {
Injector injector = Guice.createInjector(new AbstractModule() { Injector injector = Guice.createInjector(new AbstractModule() {

View File

@ -0,0 +1,53 @@
package org.jclouds.nirvanix.sdn.binders;
import static org.easymock.classextension.EasyMock.createMock;
import static org.easymock.classextension.EasyMock.replay;
import java.io.File;
import java.net.URI;
import javax.ws.rs.HttpMethod;
import javax.ws.rs.ext.RuntimeDelegate;
import org.jclouds.http.HttpRequest;
import org.jclouds.rest.internal.GeneratedHttpRequest;
import org.jclouds.rest.internal.RuntimeDelegateImpl;
import org.testng.annotations.Test;
import com.google.common.collect.ImmutableMultimap;
/**
* Tests behavior of {@code BindMetadataToQueryParams}
*
* @author Adrian Cole
*/
@Test(groups = "unit", testName = "sdn.BindMetadataToQueryParamsTest")
public class BindMetadataToQueryParamsTest {
static {
RuntimeDelegate.setInstance(new RuntimeDelegateImpl());
}
@Test(expectedExceptions = IllegalArgumentException.class)
public void testMustBeMap() {
BindMetadataToQueryParams binder = new BindMetadataToQueryParams();
HttpRequest request = new HttpRequest(HttpMethod.POST, URI.create("http://localhost"));
binder.bindToRequest(request, new File("foo"));
}
@Test
public void testCorrect() throws SecurityException, NoSuchMethodException {
BindMetadataToQueryParams binder = new BindMetadataToQueryParams();
GeneratedHttpRequest<?> request = createMock(GeneratedHttpRequest.class);
request.replaceQueryParam("metadata", "imagename:foo", "serverid:2");
replay(request);
binder.bindToRequest(request, ImmutableMultimap.of("imageName", "foo", "serverId", "2"));
}
@Test(expectedExceptions = { NullPointerException.class, IllegalStateException.class })
public void testNullIsBad() {
BindMetadataToQueryParams binder = new BindMetadataToQueryParams();
GeneratedHttpRequest<?> request = createMock(GeneratedHttpRequest.class);
binder.bindToRequest(request, null);
}
}

View File

@ -1,49 +0,0 @@
package org.jclouds.nirvanix.sdn.decorators;
import static org.testng.Assert.assertEquals;
import java.io.File;
import java.net.URI;
import javax.ws.rs.HttpMethod;
import javax.ws.rs.ext.RuntimeDelegate;
import org.jclouds.http.HttpRequest;
import org.jclouds.rest.internal.RuntimeDelegateImpl;
import org.testng.annotations.Test;
import com.google.common.collect.ImmutableMultimap;
/**
* Tests behavior of {@code AddMetadataAsQueryParams}
*
* @author Adrian Cole
*/
@Test(groups = "unit", testName = "sdn.AddMetadataAsQueryParamsTest")
public class AddMetadataAsQueryParamsTest {
static {
RuntimeDelegate.setInstance(new RuntimeDelegateImpl());
}
@Test(expectedExceptions = IllegalArgumentException.class)
public void testMustBeMap() {
AddMetadataAsQueryParams binder = new AddMetadataAsQueryParams();
HttpRequest request = new HttpRequest(HttpMethod.POST, URI.create("http://localhost"));
request = binder.decorateRequest(request, new File("foo"));
}
@Test
public void testCorrect() {
AddMetadataAsQueryParams binder = new AddMetadataAsQueryParams();
HttpRequest request = new HttpRequest(HttpMethod.PUT, URI.create("http://localhost"));
request = binder.decorateRequest(request, ImmutableMultimap.of("imageName", "foo", "serverId", "2") );
assertEquals(request.getEndpoint().getQuery(), "metadata=imagename:foo&metadata=serverid:2");
}
@Test(expectedExceptions = { NullPointerException.class, IllegalStateException.class })
public void testNullIsBad() {
AddMetadataAsQueryParams binder = new AddMetadataAsQueryParams();
HttpRequest request = new HttpRequest(HttpMethod.PUT, URI.create("http://localhost"));
request = binder.decorateRequest(request,null );
}
}

View File

@ -25,13 +25,22 @@ package org.jclouds.nirvanix.sdn.filters;
import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertEquals;
import java.lang.reflect.Method;
import java.net.URI; import java.net.URI;
import javax.ws.rs.HttpMethod; import javax.ws.rs.POST;
import javax.ws.rs.ext.RuntimeDelegate; import javax.ws.rs.ext.RuntimeDelegate;
import org.jclouds.concurrent.WithinThreadExecutorService;
import org.jclouds.concurrent.config.ExecutorServiceModule;
import org.jclouds.http.HttpRequest; import org.jclouds.http.HttpRequest;
import org.jclouds.http.config.JavaUrlHttpCommandExecutorServiceModule;
import org.jclouds.logging.Logger;
import org.jclouds.logging.Logger.LoggerFactory;
import org.jclouds.nirvanix.sdn.SessionToken; import org.jclouds.nirvanix.sdn.SessionToken;
import org.jclouds.rest.annotations.Endpoint;
import org.jclouds.rest.config.RestModule;
import org.jclouds.rest.internal.RestAnnotationProcessor;
import org.jclouds.rest.internal.RuntimeDelegateImpl; import org.jclouds.rest.internal.RuntimeDelegateImpl;
import org.jclouds.util.DateService; import org.jclouds.util.DateService;
import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeClass;
@ -41,7 +50,9 @@ import org.testng.annotations.Test;
import com.google.inject.AbstractModule; import com.google.inject.AbstractModule;
import com.google.inject.Guice; import com.google.inject.Guice;
import com.google.inject.Injector; import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.Provides; import com.google.inject.Provides;
import com.google.inject.TypeLiteral;
@Test(groups = "unit", testName = "sdn.AddSessionTokenToRequestTest") @Test(groups = "unit", testName = "sdn.AddSessionTokenToRequestTest")
public class AddSessionTokenToRequestTest { public class AddSessionTokenToRequestTest {
@ -49,11 +60,23 @@ public class AddSessionTokenToRequestTest {
private Injector injector; private Injector injector;
private AddSessionTokenToRequest filter; private AddSessionTokenToRequest filter;
private static interface TestService {
@POST
public void foo(@Endpoint URI endpoint);
}
@DataProvider @DataProvider
public Object[][] dataProvider() { public Object[][] dataProvider() throws SecurityException, NoSuchMethodException {
return new Object[][] { { new HttpRequest(HttpMethod.GET, URI.create("https://host:443")) },
{ new HttpRequest(HttpMethod.GET, URI.create("https://host/path")) }, RestAnnotationProcessor<TestService> factory = injector.getInstance(Key
{ new HttpRequest(HttpMethod.GET, URI.create("https://host/?query")) .get(new TypeLiteral<RestAnnotationProcessor<TestService>>() {
}));
Method method = TestService.class.getMethod("foo", URI.class);
return new Object[][] {
{ factory.createRequest(method, new Object[] { URI.create("https://host:443") }) },
{ factory.createRequest(method, new Object[] { URI.create("https://host/path") }) },
{ factory.createRequest(method, new Object[] { URI.create("https://host/?query") })
} }; } };
} }
@ -63,7 +86,7 @@ public class AddSessionTokenToRequestTest {
String token = filter.getSessionToken(); String token = filter.getSessionToken();
String query = request.getEndpoint().getQuery(); String query = request.getEndpoint().getQuery();
request = filter.filter(request); filter.filter(request);
assertEquals(request.getEndpoint().getQuery(), query == null ? "sessionToken=" + token assertEquals(request.getEndpoint().getQuery(), query == null ? "sessionToken=" + token
: query + "&sessionToken=" + token); : query + "&sessionToken=" + token);
} }
@ -82,11 +105,18 @@ public class AddSessionTokenToRequestTest {
*/ */
@BeforeClass @BeforeClass
protected void createFilter() { protected void createFilter() {
injector = Guice.createInjector(new AbstractModule() { injector = Guice.createInjector(new RestModule(), new ExecutorServiceModule(
new WithinThreadExecutorService()), new JavaUrlHttpCommandExecutorServiceModule(),
new AbstractModule() {
protected void configure() { protected void configure() {
RuntimeDelegate.setInstance(new RuntimeDelegateImpl()); RuntimeDelegate.setInstance(new RuntimeDelegateImpl());
bind(DateService.class); bind(DateService.class);
bind(Logger.LoggerFactory.class).toInstance(new LoggerFactory() {
public Logger getLogger(String category) {
return Logger.NULL;
}
});
} }
@SuppressWarnings("unused") @SuppressWarnings("unused")

View File

@ -35,7 +35,7 @@ import javax.ws.rs.Path;
import javax.ws.rs.PathParam; import javax.ws.rs.PathParam;
import org.jclouds.blobstore.BlobStore; import org.jclouds.blobstore.BlobStore;
import org.jclouds.blobstore.decorators.AddBlobEntity; import org.jclouds.blobstore.binders.BindBlobToEntity;
import org.jclouds.blobstore.domain.Blob; import org.jclouds.blobstore.domain.Blob;
import org.jclouds.blobstore.domain.BlobMetadata; import org.jclouds.blobstore.domain.BlobMetadata;
import org.jclouds.blobstore.functions.BlobKey; import org.jclouds.blobstore.functions.BlobKey;
@ -53,7 +53,7 @@ import org.jclouds.rackspace.cloudfiles.functions.ParseObjectFromHeadersAndHttpC
import org.jclouds.rackspace.cloudfiles.functions.ParseObjectMetadataFromHeaders; import org.jclouds.rackspace.cloudfiles.functions.ParseObjectMetadataFromHeaders;
import org.jclouds.rackspace.cloudfiles.options.ListContainerOptions; import org.jclouds.rackspace.cloudfiles.options.ListContainerOptions;
import org.jclouds.rackspace.filters.AuthenticateRequest; import org.jclouds.rackspace.filters.AuthenticateRequest;
import org.jclouds.rest.annotations.DecoratorParam; import org.jclouds.rest.annotations.BinderParam;
import org.jclouds.rest.annotations.Endpoint; import org.jclouds.rest.annotations.Endpoint;
import org.jclouds.rest.annotations.ExceptionParser; import org.jclouds.rest.annotations.ExceptionParser;
import org.jclouds.rest.annotations.ParamParser; import org.jclouds.rest.annotations.ParamParser;
@ -113,7 +113,7 @@ public interface CloudFilesBlobStore extends
@ResponseParser(ParseETagHeader.class) @ResponseParser(ParseETagHeader.class)
Future<byte[]> putBlob( Future<byte[]> putBlob(
@PathParam("container") String container, @PathParam("container") String container,
@PathParam("key") @ParamParser(BlobKey.class) @DecoratorParam(AddBlobEntity.class) Blob<BlobMetadata> object); @PathParam("key") @ParamParser(BlobKey.class) @BinderParam(BindBlobToEntity.class) Blob<BlobMetadata> object);
@GET @GET
@ResponseParser(ParseObjectFromHeadersAndHttpContent.class) @ResponseParser(ParseObjectFromHeadersAndHttpContent.class)

View File

@ -36,8 +36,8 @@ import javax.ws.rs.PUT;
import javax.ws.rs.Path; import javax.ws.rs.Path;
import javax.ws.rs.PathParam; import javax.ws.rs.PathParam;
import org.jclouds.blobstore.decorators.AddBlobEntity; import org.jclouds.blobstore.binders.BindBlobToEntity;
import org.jclouds.blobstore.decorators.AddHeadersWithPrefix; import org.jclouds.blobstore.binders.BindMultimapToHeadersWithPrefix;
import org.jclouds.blobstore.domain.Blob; import org.jclouds.blobstore.domain.Blob;
import org.jclouds.blobstore.domain.BlobMetadata; import org.jclouds.blobstore.domain.BlobMetadata;
import org.jclouds.blobstore.functions.BlobKey; import org.jclouds.blobstore.functions.BlobKey;
@ -64,7 +64,7 @@ import org.jclouds.rackspace.cloudfiles.options.ListCdnContainerOptions;
import org.jclouds.rackspace.cloudfiles.options.ListContainerOptions; import org.jclouds.rackspace.cloudfiles.options.ListContainerOptions;
import org.jclouds.rackspace.cloudfiles.reference.CloudFilesHeaders; import org.jclouds.rackspace.cloudfiles.reference.CloudFilesHeaders;
import org.jclouds.rackspace.filters.AuthenticateRequest; import org.jclouds.rackspace.filters.AuthenticateRequest;
import org.jclouds.rest.annotations.DecoratorParam; import org.jclouds.rest.annotations.BinderParam;
import org.jclouds.rest.annotations.Endpoint; import org.jclouds.rest.annotations.Endpoint;
import org.jclouds.rest.annotations.ExceptionParser; import org.jclouds.rest.annotations.ExceptionParser;
import org.jclouds.rest.annotations.Headers; import org.jclouds.rest.annotations.Headers;
@ -141,7 +141,7 @@ public interface CloudFilesConnection {
@Path("{container}/{key}") @Path("{container}/{key}")
boolean setObjectMetadata(@PathParam("container") String container, boolean setObjectMetadata(@PathParam("container") String container,
@PathParam("key") String key, @PathParam("key") String key,
@DecoratorParam(AddHeadersWithPrefix.class) Multimap<String, String> userMetadata); @BinderParam(BindMultimapToHeadersWithPrefix.class) Multimap<String, String> userMetadata);
@GET @GET
@ResponseParser(ParseContainerCDNMetadataListFromGsonResponse.class) @ResponseParser(ParseContainerCDNMetadataListFromGsonResponse.class)
@ -205,7 +205,7 @@ public interface CloudFilesConnection {
@ResponseParser(ParseETagHeader.class) @ResponseParser(ParseETagHeader.class)
Future<byte[]> putObject( Future<byte[]> putObject(
@PathParam("container") String container, @PathParam("container") String container,
@PathParam("key") @ParamParser(BlobKey.class) @DecoratorParam(AddBlobEntity.class) Blob<BlobMetadata> object); @PathParam("key") @ParamParser(BlobKey.class) @BinderParam(BindBlobToEntity.class) Blob<BlobMetadata> object);
@GET @GET
@ResponseParser(ParseObjectFromHeadersAndHttpContent.class) @ResponseParser(ParseObjectFromHeadersAndHttpContent.class)

View File

@ -21,7 +21,7 @@
* under the License. * under the License.
* ==================================================================== * ====================================================================
*/ */
package org.jclouds.rackspace.cloudfiles.decorators; package org.jclouds.rackspace.cloudfiles.binders;
import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkArgument;
import static org.jclouds.blobstore.reference.BlobStoreConstants.PROPERTY_USER_METADATA_PREFIX; import static org.jclouds.blobstore.reference.BlobStoreConstants.PROPERTY_USER_METADATA_PREFIX;
@ -30,18 +30,18 @@ import javax.inject.Inject;
import javax.inject.Named; import javax.inject.Named;
import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.HttpHeaders;
import org.jclouds.blobstore.decorators.AddBlobEntity; import org.jclouds.blobstore.binders.BindBlobToEntity;
import org.jclouds.blobstore.domain.Blob; import org.jclouds.blobstore.domain.Blob;
import org.jclouds.http.HttpRequest; import org.jclouds.http.HttpRequest;
import org.jclouds.http.HttpUtils; import org.jclouds.http.HttpUtils;
public class AddCFObjectEntity extends AddBlobEntity { public class BindCFObjectAsEntity extends BindBlobToEntity {
@Inject @Inject
public AddCFObjectEntity(@Named(PROPERTY_USER_METADATA_PREFIX) String metadataPrefix) { public BindCFObjectAsEntity(@Named(PROPERTY_USER_METADATA_PREFIX) String metadataPrefix) {
super(metadataPrefix); super(metadataPrefix);
} }
public HttpRequest decorateRequest(HttpRequest request, Object entity) { public void bindToRequest(HttpRequest request, Object entity) {
Blob<?> object = (Blob<?>) entity; Blob<?> object = (Blob<?>) entity;
if (object.getMetadata().getSize() >= 0) { if (object.getMetadata().getSize() >= 0) {
checkArgument(object.getContentLength() <= 5 * 1024 * 1024 * 1024, checkArgument(object.getContentLength() <= 5 * 1024 * 1024 * 1024,
@ -58,6 +58,6 @@ public class AddCFObjectEntity extends AddBlobEntity {
request.getHeaders().put(HttpHeaders.ETAG, request.getHeaders().put(HttpHeaders.ETAG,
HttpUtils.toBase64String(object.getMetadata().getContentMD5())); HttpUtils.toBase64String(object.getMetadata().getContentMD5()));
} }
return super.decorateRequest(request, entity); super.bindToRequest(request, entity);
} }
} }

View File

@ -37,15 +37,15 @@ import javax.ws.rs.PathParam;
import org.jclouds.http.functions.ReturnFalseOn404; import org.jclouds.http.functions.ReturnFalseOn404;
import org.jclouds.rackspace.CloudServers; import org.jclouds.rackspace.CloudServers;
import org.jclouds.rackspace.cloudservers.decorators.AddBackupScheduleAsJsonEntity; import org.jclouds.rackspace.cloudservers.binders.BindAdminPassToJsonEntity;
import org.jclouds.rackspace.cloudservers.decorators.AddAdminPassAsJsonEntity; import org.jclouds.rackspace.cloudservers.binders.BindBackupScheduleToJsonEntity;
import org.jclouds.rackspace.cloudservers.decorators.AddServerNameAsJsonEntity; import org.jclouds.rackspace.cloudservers.binders.BindConfirmResizeToJsonEntity;
import org.jclouds.rackspace.cloudservers.decorators.AddConfirmResizeAsJsonEntity; import org.jclouds.rackspace.cloudservers.binders.BindCreateImageToJsonEntity;
import org.jclouds.rackspace.cloudservers.decorators.AddCreateImageAsJsonEntity; import org.jclouds.rackspace.cloudservers.binders.BindRebootTypeToJsonEntity;
import org.jclouds.rackspace.cloudservers.decorators.AddRebootTypeAsJsonEntity; import org.jclouds.rackspace.cloudservers.binders.BindResizeFlavorToJsonEntity;
import org.jclouds.rackspace.cloudservers.decorators.AddResizeFlavorAsJsonEntity; import org.jclouds.rackspace.cloudservers.binders.BindRevertResizeToJsonEntity;
import org.jclouds.rackspace.cloudservers.decorators.AddRevertResizeAsJsonEntity; import org.jclouds.rackspace.cloudservers.binders.BindServerNameToJsonEntity;
import org.jclouds.rackspace.cloudservers.decorators.AddSharedIpGroupAsJsonEntity; import org.jclouds.rackspace.cloudservers.binders.BindSharedIpGroupToJsonEntity;
import org.jclouds.rackspace.cloudservers.domain.Addresses; import org.jclouds.rackspace.cloudservers.domain.Addresses;
import org.jclouds.rackspace.cloudservers.domain.BackupSchedule; import org.jclouds.rackspace.cloudservers.domain.BackupSchedule;
import org.jclouds.rackspace.cloudservers.domain.Flavor; import org.jclouds.rackspace.cloudservers.domain.Flavor;
@ -74,7 +74,7 @@ import org.jclouds.rackspace.cloudservers.options.CreateSharedIpGroupOptions;
import org.jclouds.rackspace.cloudservers.options.ListOptions; import org.jclouds.rackspace.cloudservers.options.ListOptions;
import org.jclouds.rackspace.cloudservers.options.RebuildServerOptions; import org.jclouds.rackspace.cloudservers.options.RebuildServerOptions;
import org.jclouds.rackspace.filters.AuthenticateRequest; import org.jclouds.rackspace.filters.AuthenticateRequest;
import org.jclouds.rest.annotations.DecoratorParam; import org.jclouds.rest.annotations.BinderParam;
import org.jclouds.rest.annotations.Endpoint; import org.jclouds.rest.annotations.Endpoint;
import org.jclouds.rest.annotations.ExceptionParser; import org.jclouds.rest.annotations.ExceptionParser;
import org.jclouds.rest.annotations.MapBinder; import org.jclouds.rest.annotations.MapBinder;
@ -170,7 +170,7 @@ public interface CloudServersConnection {
// TODO:cloudServersFault (400, 500), serviceUnavailable (503), unauthorized (401), badRequest // TODO:cloudServersFault (400, 500), serviceUnavailable (503), unauthorized (401), badRequest
// (400), badMediaType(415),buildInProgress (409), overLimit (403) // (400), badMediaType(415),buildInProgress (409), overLimit (403)
boolean rebootServer(@PathParam("id") int id, boolean rebootServer(@PathParam("id") int id,
@DecoratorParam(AddRebootTypeAsJsonEntity.class) RebootType rebootType); @BinderParam(BindRebootTypeToJsonEntity.class) RebootType rebootType);
/** /**
* The resize function converts an existing server to a different flavor, in essence, scaling the * The resize function converts an existing server to a different flavor, in essence, scaling the
@ -192,7 +192,8 @@ public interface CloudServersConnection {
// TODO:cloudServersFault (400, 500), serviceUnavailable (503), unauthorized (401), badRequest // TODO:cloudServersFault (400, 500), serviceUnavailable (503), unauthorized (401), badRequest
// (400), badMediaType(415), itemNotFound (404), buildInProgress (409), serverCapacityUnavailable // (400), badMediaType(415), itemNotFound (404), buildInProgress (409), serverCapacityUnavailable
// (503), overLimit (413), resizeNotAllowed (403) // (503), overLimit (413), resizeNotAllowed (403)
boolean resizeServer(@PathParam("id") int id, @DecoratorParam(AddResizeFlavorAsJsonEntity.class) int flavorId); boolean resizeServer(@PathParam("id") int id,
@BinderParam(BindResizeFlavorToJsonEntity.class) int flavorId);
/** /**
* The resize function converts an existing server to a different flavor, in essence, scaling the * The resize function converts an existing server to a different flavor, in essence, scaling the
@ -212,7 +213,8 @@ public interface CloudServersConnection {
// TODO:cloudServersFault (400, 500), serviceUnavailable (503), unauthorized (401), badRequest // TODO:cloudServersFault (400, 500), serviceUnavailable (503), unauthorized (401), badRequest
// (400), badMediaType(415), itemNotFound (404), buildInProgress (409), serverCapacityUnavailable // (400), badMediaType(415), itemNotFound (404), buildInProgress (409), serverCapacityUnavailable
// (503), overLimit (413), resizeNotAllowed (403) // (503), overLimit (413), resizeNotAllowed (403)
boolean confirmResizeServer(@PathParam("id") @DecoratorParam(AddConfirmResizeAsJsonEntity.class) int id); boolean confirmResizeServer(
@PathParam("id") @BinderParam(BindConfirmResizeToJsonEntity.class) int id);
/** /**
* The resize function converts an existing server to a different flavor, in essence, scaling the * The resize function converts an existing server to a different flavor, in essence, scaling the
@ -232,7 +234,8 @@ public interface CloudServersConnection {
// TODO:cloudServersFault (400, 500), serviceUnavailable (503), unauthorized (401), badRequest // TODO:cloudServersFault (400, 500), serviceUnavailable (503), unauthorized (401), badRequest
// (400), badMediaType(415), itemNotFound (404), buildInProgress (409), serverCapacityUnavailable // (400), badMediaType(415), itemNotFound (404), buildInProgress (409), serverCapacityUnavailable
// (503), overLimit (413), resizeNotAllowed (403) // (503), overLimit (413), resizeNotAllowed (403)
boolean revertResizeServer(@PathParam("id") @DecoratorParam(AddRevertResizeAsJsonEntity.class) int id); boolean revertResizeServer(
@PathParam("id") @BinderParam(BindRevertResizeToJsonEntity.class) int id);
/** /**
* This operation asynchronously provisions a new server. The progress of this operation depends * This operation asynchronously provisions a new server. The progress of this operation depends
@ -304,11 +307,11 @@ public interface CloudServersConnection {
@PUT @PUT
@ExceptionParser(ReturnFalseOn404.class) @ExceptionParser(ReturnFalseOn404.class)
@Path("/servers/{id}/ips/public/{address}") @Path("/servers/{id}/ips/public/{address}")
@MapBinder(AddSharedIpGroupAsJsonEntity.class) @MapBinder(BindSharedIpGroupToJsonEntity.class)
// TODO: cloudServersFault (400, 500), serviceUnavailable (503), unauthorized (401), badRequest // TODO: cloudServersFault (400, 500), serviceUnavailable (503), unauthorized (401), badRequest
// (400), badMediaType(415), buildInProgress (409), overLimit (413) // (400), badMediaType(415), buildInProgress (409), overLimit (413)
boolean shareIp(@PathParam("address") @ParamParser(IpAddress.class) InetAddress addressToShare, boolean shareIp(@PathParam("address") @ParamParser(IpAddress.class) InetAddress addressToShare,
@PathParam("id") int serverToAssignAddressTo, @PathParam("id") int serverToTosignBindressTo,
@MapEntityParam("sharedIpGroupId") int sharedIpGroup, @MapEntityParam("sharedIpGroupId") int sharedIpGroup,
@MapEntityParam("configureServer") boolean configureServer); @MapEntityParam("configureServer") boolean configureServer);
@ -318,7 +321,7 @@ public interface CloudServersConnection {
* Status Transition: ACTIVE - DELETE_IP - ACTIVE * Status Transition: ACTIVE - DELETE_IP - ACTIVE
* *
* @param addressToShare * @param addressToShare
* @param serverToAssignAddressTo * @param serverToTosignBindressTo
* @return * @return
*/ */
@DELETE @DELETE
@ -329,7 +332,7 @@ public interface CloudServersConnection {
// badMediaType(415), overLimit (413) // badMediaType(415), overLimit (413)
boolean unshareIp( boolean unshareIp(
@PathParam("address") @ParamParser(IpAddress.class) InetAddress addressToShare, @PathParam("address") @ParamParser(IpAddress.class) InetAddress addressToShare,
@PathParam("id") int serverToAssignAddressTo); @PathParam("id") int serverToTosignBindressTo);
/** /**
* This operation allows you to change the administrative password. * This operation allows you to change the administrative password.
@ -344,7 +347,7 @@ public interface CloudServersConnection {
// TODO: cloudServersFault (400, 500), serviceUnavailable (503), unauthorized (401), badRequest // TODO: cloudServersFault (400, 500), serviceUnavailable (503), unauthorized (401), badRequest
// (400), badMediaType(415), buildInProgress (409), overLimit (413) // (400), badMediaType(415), buildInProgress (409), overLimit (413)
boolean changeAdminPass(@PathParam("id") int id, boolean changeAdminPass(@PathParam("id") int id,
@DecoratorParam(AddAdminPassAsJsonEntity.class) String adminPass); @BinderParam(BindAdminPassToJsonEntity.class) String adminPass);
/** /**
* This operation allows you to update the name of the server. This operation changes the name of * This operation allows you to update the name of the server. This operation changes the name of
@ -360,7 +363,7 @@ public interface CloudServersConnection {
// TODO: cloudServersFault (400, 500), serviceUnavailable (503), unauthorized (401), badRequest // TODO: cloudServersFault (400, 500), serviceUnavailable (503), unauthorized (401), badRequest
// (400), badMediaType(415), buildInProgress (409), overLimit (413) // (400), badMediaType(415), buildInProgress (409), overLimit (413)
boolean renameServer(@PathParam("id") int id, boolean renameServer(@PathParam("id") int id,
@DecoratorParam(AddServerNameAsJsonEntity.class) String newName); @BinderParam(BindServerNameToJsonEntity.class) String newName);
/** /**
* *
@ -447,7 +450,7 @@ public interface CloudServersConnection {
@ResponseParser(ParseImageFromJsonResponse.class) @ResponseParser(ParseImageFromJsonResponse.class)
@QueryParams(keys = "format", values = "json") @QueryParams(keys = "format", values = "json")
@ExceptionParser(ReturnImageNotFoundOn404.class) @ExceptionParser(ReturnImageNotFoundOn404.class)
@MapBinder(AddCreateImageAsJsonEntity.class) @MapBinder(BindCreateImageToJsonEntity.class)
@Path("/images") @Path("/images")
// TODO: cloudServersFault (400, 500), serviceUnavailable (503), unauthorized (401), badRequest // TODO: cloudServersFault (400, 500), serviceUnavailable (503), unauthorized (401), badRequest
// (400), badMediaType(415), buildInProgress (409), serverCapacityUnavailable (503), overLimit // (400), badMediaType(415), buildInProgress (409), serverCapacityUnavailable (503), overLimit
@ -554,7 +557,7 @@ public interface CloudServersConnection {
// (400), badMediaType(415), buildInProgress (409), serverCapacityUnavailable (503), // (400), badMediaType(415), buildInProgress (409), serverCapacityUnavailable (503),
// backupOrResizeInProgress(409), resizeNotAllowed (403). overLimit (413) // backupOrResizeInProgress(409), resizeNotAllowed (403). overLimit (413)
boolean replaceBackupSchedule(@PathParam("id") int id, boolean replaceBackupSchedule(@PathParam("id") int id,
@DecoratorParam(AddBackupScheduleAsJsonEntity.class) BackupSchedule backupSchedule); @BinderParam(BindBackupScheduleToJsonEntity.class) BackupSchedule backupSchedule);
/** /**
* List all server addresses * List all server addresses

View File

@ -21,7 +21,7 @@
* under the License. * under the License.
* ==================================================================== * ====================================================================
*/ */
package org.jclouds.rackspace.cloudservers.decorators; package org.jclouds.rackspace.cloudservers.binders;
import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkNotNull;
@ -29,7 +29,7 @@ import static com.google.common.base.Preconditions.checkNotNull;
import java.util.Map; import java.util.Map;
import org.jclouds.http.HttpRequest; import org.jclouds.http.HttpRequest;
import org.jclouds.rest.decorators.AddAsJsonEntity; import org.jclouds.rest.binders.BindToJsonEntity;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
@ -38,17 +38,17 @@ import com.google.common.collect.ImmutableMap;
* @author Adrian Cole * @author Adrian Cole
* *
*/ */
public class AddAdminPassAsJsonEntity extends AddAsJsonEntity { public class BindAdminPassToJsonEntity extends BindToJsonEntity {
@Override @Override
public HttpRequest decorateRequest(HttpRequest request, Map<String, String> postParams) { public void bindToRequest(HttpRequest request, Map<String, String> postParams) {
throw new IllegalStateException("Change Admin Pass is a PUT operation"); throw new IllegalStateException("Change Admin Pass is a PUT operation");
} }
@Override @Override
public HttpRequest decorateRequest(HttpRequest request, Object toBind) { public void bindToRequest(HttpRequest request, Object toBind) {
checkArgument(toBind instanceof String, "this binder is only valid for Strings!"); checkArgument(toBind instanceof String, "this binder is only valid for Strings!");
return super.decorateRequest(request, ImmutableMap.of("server", ImmutableMap.of("adminPass", super.bindToRequest(request, ImmutableMap.of("server", ImmutableMap.of("adminPass",
checkNotNull(toBind, "adminPass")))); checkNotNull(toBind, "adminPass"))));
} }
} }

View File

@ -21,7 +21,7 @@
* under the License. * under the License.
* ==================================================================== * ====================================================================
*/ */
package org.jclouds.rackspace.cloudservers.decorators; package org.jclouds.rackspace.cloudservers.binders;
import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkArgument;
@ -29,7 +29,7 @@ import java.util.Map;
import org.jclouds.http.HttpRequest; import org.jclouds.http.HttpRequest;
import org.jclouds.rackspace.cloudservers.domain.BackupSchedule; import org.jclouds.rackspace.cloudservers.domain.BackupSchedule;
import org.jclouds.rest.decorators.AddAsJsonEntity; import org.jclouds.rest.binders.BindToJsonEntity;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
@ -38,18 +38,18 @@ import com.google.common.collect.ImmutableMap;
* @author Adrian Cole * @author Adrian Cole
* *
*/ */
public class AddBackupScheduleAsJsonEntity extends AddAsJsonEntity { public class BindBackupScheduleToJsonEntity extends BindToJsonEntity {
@Override @Override
public HttpRequest decorateRequest(HttpRequest request, Map<String, String> postParams) { public void bindToRequest(HttpRequest request, Map<String, String> postParams) {
throw new IllegalStateException( throw new IllegalStateException(
"Replace Backup Schedule needs an BackupSchedule object, not a Map"); "Replace Backup Schedule needs an BackupSchedule object, not a Map");
} }
@Override @Override
public HttpRequest decorateRequest(HttpRequest request, Object toBind) { public void bindToRequest(HttpRequest request, Object toBind) {
checkArgument(toBind instanceof BackupSchedule, checkArgument(toBind instanceof BackupSchedule,
"this binder is only valid for BackupSchedules!"); "this binder is only valid for BackupSchedules!");
return super.decorateRequest(request, ImmutableMap.of("backupSchedule", toBind)); super.bindToRequest(request, ImmutableMap.of("backupSchedule", toBind));
} }
} }

View File

@ -21,7 +21,7 @@
* under the License. * under the License.
* ==================================================================== * ====================================================================
*/ */
package org.jclouds.rackspace.cloudservers.decorators; package org.jclouds.rackspace.cloudservers.binders;
import java.util.Collections; import java.util.Collections;
@ -29,21 +29,20 @@ import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MediaType;
import org.jclouds.http.HttpRequest; import org.jclouds.http.HttpRequest;
import org.jclouds.rest.decorators.RequestDecorator; import org.jclouds.rest.Binder;
/** /**
* *
* @author Adrian Cole * @author Adrian Cole
* *
*/ */
public class AddConfirmResizeAsJsonEntity implements RequestDecorator { public class BindConfirmResizeToJsonEntity implements Binder {
public HttpRequest decorateRequest(HttpRequest request, Object toBind) { public void bindToRequest(HttpRequest request, Object toBind) {
request.setEntity("{\"confirmResize\":null}"); request.setEntity("{\"confirmResize\":null}");
request.getHeaders().replaceValues(HttpHeaders.CONTENT_LENGTH, request.getHeaders().replaceValues(HttpHeaders.CONTENT_LENGTH,
Collections.singletonList("{\"confirmResize\":null}".getBytes().length + "")); Collections.singletonList("{\"confirmResize\":null}".getBytes().length + ""));
request.getHeaders().replaceValues(HttpHeaders.CONTENT_TYPE, request.getHeaders().replaceValues(HttpHeaders.CONTENT_TYPE,
Collections.singletonList(MediaType.APPLICATION_JSON)); Collections.singletonList(MediaType.APPLICATION_JSON));
return request;
} }
} }

View File

@ -21,14 +21,14 @@
* under the License. * under the License.
* ==================================================================== * ====================================================================
*/ */
package org.jclouds.rackspace.cloudservers.decorators; package org.jclouds.rackspace.cloudservers.binders;
import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkNotNull;
import java.util.Map; import java.util.Map;
import org.jclouds.http.HttpRequest; import org.jclouds.http.HttpRequest;
import org.jclouds.rest.decorators.AddAsJsonEntity; import org.jclouds.rest.binders.BindToJsonEntity;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
@ -37,7 +37,7 @@ import com.google.common.collect.ImmutableMap;
* @author Adrian Cole * @author Adrian Cole
* *
*/ */
public class AddCreateImageAsJsonEntity extends AddAsJsonEntity { public class BindCreateImageToJsonEntity extends BindToJsonEntity {
@SuppressWarnings("unused") @SuppressWarnings("unused")
private class CreateImageRequest { private class CreateImageRequest {
@ -52,15 +52,15 @@ public class AddCreateImageAsJsonEntity extends AddAsJsonEntity {
} }
@Override @Override
public HttpRequest decorateRequest(HttpRequest request, Map<String, String> postParams) { public void bindToRequest(HttpRequest request, Map<String, String> postParams) {
CreateImageRequest createRequest = new CreateImageRequest(Integer CreateImageRequest createRequest = new CreateImageRequest(Integer
.parseInt(checkNotNull(postParams.get("serverId"))), checkNotNull(postParams .parseInt(checkNotNull(postParams.get("serverId"))), checkNotNull(postParams
.get("imageName"))); .get("imageName")));
return super.decorateRequest(request, ImmutableMap.of("image", createRequest)); super.bindToRequest(request, ImmutableMap.of("image", createRequest));
} }
@Override @Override
public HttpRequest decorateRequest(HttpRequest request, Object toBind) { public void bindToRequest(HttpRequest request, Object toBind) {
throw new IllegalArgumentException("image is needs parameters"); throw new IllegalArgumentException("image is needs parameters");
} }
} }

View File

@ -21,7 +21,7 @@
* under the License. * under the License.
* ==================================================================== * ====================================================================
*/ */
package org.jclouds.rackspace.cloudservers.decorators; package org.jclouds.rackspace.cloudservers.binders;
import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkNotNull;
@ -30,7 +30,7 @@ import java.util.Map;
import org.jclouds.http.HttpRequest; import org.jclouds.http.HttpRequest;
import org.jclouds.rackspace.cloudservers.domain.RebootType; import org.jclouds.rackspace.cloudservers.domain.RebootType;
import org.jclouds.rest.decorators.AddAsJsonEntity; import org.jclouds.rest.binders.BindToJsonEntity;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
@ -39,17 +39,17 @@ import com.google.common.collect.ImmutableMap;
* @author Adrian Cole * @author Adrian Cole
* *
*/ */
public class AddRebootTypeAsJsonEntity extends AddAsJsonEntity { public class BindRebootTypeToJsonEntity extends BindToJsonEntity {
@Override @Override
public HttpRequest decorateRequest(HttpRequest request, Map<String, String> postParams) { public void bindToRequest(HttpRequest request, Map<String, String> postParams) {
throw new IllegalStateException("Reboot doesn't take map parameters"); throw new IllegalStateException("Reboot doesn't take map parameters");
} }
@Override @Override
public HttpRequest decorateRequest(HttpRequest request, Object toBind) { public void bindToRequest(HttpRequest request, Object toBind) {
checkArgument(toBind instanceof RebootType, "this binder is only valid for RebootTypes!"); checkArgument(toBind instanceof RebootType, "this binder is only valid for RebootTypes!");
return super.decorateRequest(request, ImmutableMap.of("reboot", ImmutableMap.of("type", super.bindToRequest(request, ImmutableMap.of("reboot", ImmutableMap.of("type",
checkNotNull(toBind, "type")))); checkNotNull(toBind, "type"))));
} }
} }

View File

@ -21,7 +21,7 @@
* under the License. * under the License.
* ==================================================================== * ====================================================================
*/ */
package org.jclouds.rackspace.cloudservers.decorators; package org.jclouds.rackspace.cloudservers.binders;
import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkNotNull;
@ -29,7 +29,7 @@ import static com.google.common.base.Preconditions.checkNotNull;
import java.util.Map; import java.util.Map;
import org.jclouds.http.HttpRequest; import org.jclouds.http.HttpRequest;
import org.jclouds.rest.decorators.AddAsJsonEntity; import org.jclouds.rest.binders.BindToJsonEntity;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
@ -38,17 +38,17 @@ import com.google.common.collect.ImmutableMap;
* @author Adrian Cole * @author Adrian Cole
* *
*/ */
public class AddResizeFlavorAsJsonEntity extends AddAsJsonEntity { public class BindResizeFlavorToJsonEntity extends BindToJsonEntity {
@Override @Override
public HttpRequest decorateRequest(HttpRequest request, Map<String, String> postParams) { public void bindToRequest(HttpRequest request, Map<String, String> postParams) {
throw new IllegalStateException("Resize doesn't take map parameters"); throw new IllegalStateException("Resize doesn't take map parameters");
} }
@Override @Override
public HttpRequest decorateRequest(HttpRequest request, Object toBind) { public void bindToRequest(HttpRequest request, Object toBind) {
checkArgument(toBind instanceof Integer, "this binder is only valid for integers!"); checkArgument(toBind instanceof Integer, "this binder is only valid for integers!");
return super.decorateRequest(request, ImmutableMap.of("resize", ImmutableMap.of("flavorId", super.bindToRequest(request, ImmutableMap.of("resize", ImmutableMap.of("flavorId",
(Integer) checkNotNull(toBind, "flavorId")))); (Integer) checkNotNull(toBind, "flavorId"))));
} }
} }

View File

@ -21,7 +21,7 @@
* under the License. * under the License.
* ==================================================================== * ====================================================================
*/ */
package org.jclouds.rackspace.cloudservers.decorators; package org.jclouds.rackspace.cloudservers.binders;
import java.util.Collections; import java.util.Collections;
@ -29,21 +29,20 @@ import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MediaType;
import org.jclouds.http.HttpRequest; import org.jclouds.http.HttpRequest;
import org.jclouds.rest.decorators.RequestDecorator; import org.jclouds.rest.Binder;
/** /**
* *
* @author Adrian Cole * @author Adrian Cole
* *
*/ */
public class AddRevertResizeAsJsonEntity implements RequestDecorator { public class BindRevertResizeToJsonEntity implements Binder {
public HttpRequest decorateRequest(HttpRequest request, Object toBind) { public void bindToRequest(HttpRequest request, Object toBind) {
request.setEntity("{\"revertResize\":null}"); request.setEntity("{\"revertResize\":null}");
request.getHeaders().replaceValues(HttpHeaders.CONTENT_LENGTH, request.getHeaders().replaceValues(HttpHeaders.CONTENT_LENGTH,
Collections.singletonList("{\"revertResize\":null}".getBytes().length + "")); Collections.singletonList("{\"revertResize\":null}".getBytes().length + ""));
request.getHeaders().replaceValues(HttpHeaders.CONTENT_TYPE, request.getHeaders().replaceValues(HttpHeaders.CONTENT_TYPE,
Collections.singletonList(MediaType.APPLICATION_JSON)); Collections.singletonList(MediaType.APPLICATION_JSON));
return request;
} }
} }

View File

@ -21,7 +21,7 @@
* under the License. * under the License.
* ==================================================================== * ====================================================================
*/ */
package org.jclouds.rackspace.cloudservers.decorators; package org.jclouds.rackspace.cloudservers.binders;
import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkNotNull;
@ -29,7 +29,7 @@ import static com.google.common.base.Preconditions.checkNotNull;
import java.util.Map; import java.util.Map;
import org.jclouds.http.HttpRequest; import org.jclouds.http.HttpRequest;
import org.jclouds.rest.decorators.AddAsJsonEntity; import org.jclouds.rest.binders.BindToJsonEntity;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
@ -38,17 +38,17 @@ import com.google.common.collect.ImmutableMap;
* @author Adrian Cole * @author Adrian Cole
* *
*/ */
public class AddServerNameAsJsonEntity extends AddAsJsonEntity { public class BindServerNameToJsonEntity extends BindToJsonEntity {
@Override @Override
public HttpRequest decorateRequest(HttpRequest request, Map<String, String> postParams) { public void bindToRequest(HttpRequest request, Map<String, String> postParams) {
throw new IllegalStateException("Change Server Name is a PUT operation"); throw new IllegalStateException("Change Server Name is a PUT operation");
} }
@Override @Override
public HttpRequest decorateRequest(HttpRequest request, Object toBind) { public void bindToRequest(HttpRequest request, Object toBind) {
checkArgument(toBind instanceof String, "this binder is only valid for Strings!"); checkArgument(toBind instanceof String, "this binder is only valid for Strings!");
return super.decorateRequest(request, ImmutableMap.of("server", ImmutableMap.of("name", super.bindToRequest(request, ImmutableMap.of("server", ImmutableMap.of("name",
checkNotNull(toBind, "name")))); checkNotNull(toBind, "name"))));
} }
} }

View File

@ -21,14 +21,14 @@
* under the License. * under the License.
* ==================================================================== * ====================================================================
*/ */
package org.jclouds.rackspace.cloudservers.decorators; package org.jclouds.rackspace.cloudservers.binders;
import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkNotNull;
import java.util.Map; import java.util.Map;
import org.jclouds.http.HttpRequest; import org.jclouds.http.HttpRequest;
import org.jclouds.rest.decorators.AddAsJsonEntity; import org.jclouds.rest.binders.BindToJsonEntity;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
@ -37,7 +37,7 @@ import com.google.common.collect.ImmutableMap;
* @author Adrian Cole * @author Adrian Cole
* *
*/ */
public class AddSharedIpGroupAsJsonEntity extends AddAsJsonEntity { public class BindSharedIpGroupToJsonEntity extends BindToJsonEntity {
@SuppressWarnings("unused") @SuppressWarnings("unused")
private class ShareIpRequest { private class ShareIpRequest {
@ -51,17 +51,17 @@ public class AddSharedIpGroupAsJsonEntity extends AddAsJsonEntity {
} }
@Override @Override
public HttpRequest decorateRequest(HttpRequest request, Map<String, String> postParams) { public void bindToRequest(HttpRequest request, Map<String, String> postParams) {
ShareIpRequest createRequest = new ShareIpRequest(Integer.parseInt(checkNotNull(postParams ShareIpRequest createRequest = new ShareIpRequest(Integer.parseInt(checkNotNull(postParams
.get("sharedIpGroupId")))); .get("sharedIpGroupId"))));
if (Boolean.parseBoolean(checkNotNull(postParams.get("configureServer")))) { if (Boolean.parseBoolean(checkNotNull(postParams.get("configureServer")))) {
createRequest.configureServer = new Boolean(true); createRequest.configureServer = new Boolean(true);
} }
return super.decorateRequest(request, ImmutableMap.of("shareIp", createRequest)); super.bindToRequest(request, ImmutableMap.of("shareIp", createRequest));
} }
@Override @Override
public HttpRequest decorateRequest(HttpRequest request, Object toBind) { public void bindToRequest(HttpRequest request, Object toBind) {
throw new IllegalStateException("shareIp is needs parameters"); throw new IllegalStateException("shareIp is needs parameters");
} }
} }

View File

@ -36,7 +36,7 @@ import java.util.Map.Entry;
import org.jclouds.http.HttpRequest; import org.jclouds.http.HttpRequest;
import org.jclouds.http.HttpUtils; import org.jclouds.http.HttpUtils;
import org.jclouds.rackspace.cloudservers.domain.Addresses; import org.jclouds.rackspace.cloudservers.domain.Addresses;
import org.jclouds.rest.decorators.AddAsJsonEntity; import org.jclouds.rest.binders.BindToJsonEntity;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
import com.google.inject.internal.Lists; import com.google.inject.internal.Lists;
@ -47,7 +47,7 @@ import com.google.inject.internal.Maps;
* @author Adrian Cole * @author Adrian Cole
* *
*/ */
public class CreateServerOptions extends AddAsJsonEntity { public class CreateServerOptions extends BindToJsonEntity {
static class File { static class File {
private final String path; private final String path;
@ -98,8 +98,7 @@ public class CreateServerOptions extends AddAsJsonEntity {
private InetAddress publicIp; private InetAddress publicIp;
@Override @Override
public HttpRequest decorateRequest(HttpRequest request, Map<String, String> postParams) { public void bindToRequest(HttpRequest request, Map<String, String> postParams) {
ServerRequest server = new ServerRequest(checkNotNull(postParams.get("name"), ServerRequest server = new ServerRequest(checkNotNull(postParams.get("name"),
"name parameter not present"), Integer.parseInt(checkNotNull(postParams "name parameter not present"), Integer.parseInt(checkNotNull(postParams
.get("imageId"), "imageId parameter not present")), Integer.parseInt(checkNotNull( .get("imageId"), "imageId parameter not present")), Integer.parseInt(checkNotNull(
@ -115,7 +114,7 @@ public class CreateServerOptions extends AddAsJsonEntity {
server.addresses.setPublicAddresses(Collections.singletonList(publicIp)); server.addresses.setPublicAddresses(Collections.singletonList(publicIp));
server.addresses.setPrivateAddresses(null); server.addresses.setPrivateAddresses(null);
} }
return decorateRequest(request, ImmutableMap.of("server", server)); bindToRequest(request, ImmutableMap.of("server", server));
} }
/** /**

View File

@ -29,7 +29,7 @@ import static com.google.common.base.Preconditions.checkNotNull;
import java.util.Map; import java.util.Map;
import org.jclouds.http.HttpRequest; import org.jclouds.http.HttpRequest;
import org.jclouds.rest.decorators.AddAsJsonEntity; import org.jclouds.rest.binders.BindToJsonEntity;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
import com.google.inject.internal.Nullable; import com.google.inject.internal.Nullable;
@ -40,7 +40,7 @@ import com.google.inject.internal.Nullable;
* @author Adrian Cole * @author Adrian Cole
* *
*/ */
public class CreateSharedIpGroupOptions extends AddAsJsonEntity { public class CreateSharedIpGroupOptions extends BindToJsonEntity {
Integer serverId; Integer serverId;
@SuppressWarnings("unused") @SuppressWarnings("unused")
@ -56,14 +56,14 @@ public class CreateSharedIpGroupOptions extends AddAsJsonEntity {
} }
@Override @Override
public HttpRequest decorateRequest(HttpRequest request, Map<String, String> postParams) { public void bindToRequest(HttpRequest request, Map<String, String> postParams) {
SharedIpGroupRequest createRequest = new SharedIpGroupRequest(checkNotNull(postParams SharedIpGroupRequest createRequest = new SharedIpGroupRequest(checkNotNull(postParams
.get("name")), serverId); .get("name")), serverId);
return super.decorateRequest(request, ImmutableMap.of("sharedIpGroup", createRequest)); super.bindToRequest(request, ImmutableMap.of("sharedIpGroup", createRequest));
} }
@Override @Override
public HttpRequest decorateRequest(HttpRequest request, Object toBind) { public void bindToRequest(HttpRequest request, Object toBind) {
throw new IllegalStateException("CreateSharedIpGroup is a POST operation"); throw new IllegalStateException("CreateSharedIpGroup is a POST operation");
} }

View File

@ -28,7 +28,7 @@ import static com.google.common.base.Preconditions.checkArgument;
import java.util.Map; import java.util.Map;
import org.jclouds.http.HttpRequest; import org.jclouds.http.HttpRequest;
import org.jclouds.rest.decorators.AddAsJsonEntity; import org.jclouds.rest.binders.BindToJsonEntity;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
import com.google.inject.internal.Maps; import com.google.inject.internal.Maps;
@ -39,19 +39,19 @@ import com.google.inject.internal.Maps;
* @author Adrian Cole * @author Adrian Cole
* *
*/ */
public class RebuildServerOptions extends AddAsJsonEntity { public class RebuildServerOptions extends BindToJsonEntity {
Integer imageId; Integer imageId;
@Override @Override
public HttpRequest decorateRequest(HttpRequest request, Map<String, String> postParams) { public void bindToRequest(HttpRequest request, Map<String, String> postParams) {
Map<String, Integer> image = Maps.newHashMap(); Map<String, Integer> image = Maps.newHashMap();
if (imageId != null) if (imageId != null)
image.put("imageId", imageId); image.put("imageId", imageId);
return super.decorateRequest(request, ImmutableMap.of("rebuild", image)); super.bindToRequest(request, ImmutableMap.of("rebuild", image));
} }
@Override @Override
public HttpRequest decorateRequest(HttpRequest request, Object toBind) { public void bindToRequest(HttpRequest request, Object toBind) {
throw new IllegalStateException("RebuildServer is a POST operation"); throw new IllegalStateException("RebuildServer is a POST operation");
} }

View File

@ -45,7 +45,6 @@ import javax.ws.rs.core.MediaType;
import org.jclouds.concurrent.WithinThreadExecutorService; import org.jclouds.concurrent.WithinThreadExecutorService;
import org.jclouds.concurrent.config.ExecutorServiceModule; import org.jclouds.concurrent.config.ExecutorServiceModule;
import org.jclouds.http.HttpRequest;
import org.jclouds.http.config.JavaUrlHttpCommandExecutorServiceModule; import org.jclouds.http.config.JavaUrlHttpCommandExecutorServiceModule;
import org.jclouds.http.functions.ReturnFalseOn404; import org.jclouds.http.functions.ReturnFalseOn404;
import org.jclouds.http.functions.ReturnTrueIf2xx; import org.jclouds.http.functions.ReturnTrueIf2xx;
@ -77,6 +76,7 @@ import org.jclouds.rackspace.cloudservers.options.CreateSharedIpGroupOptions;
import org.jclouds.rackspace.cloudservers.options.ListOptions; import org.jclouds.rackspace.cloudservers.options.ListOptions;
import org.jclouds.rackspace.cloudservers.options.RebuildServerOptions; import org.jclouds.rackspace.cloudservers.options.RebuildServerOptions;
import org.jclouds.rest.config.RestModule; import org.jclouds.rest.config.RestModule;
import org.jclouds.rest.internal.GeneratedHttpRequest;
import org.jclouds.rest.internal.RestAnnotationProcessor; import org.jclouds.rest.internal.RestAnnotationProcessor;
import org.joda.time.DateTime; import org.joda.time.DateTime;
import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeClass;
@ -106,7 +106,8 @@ public class CloudServersConnectionTest {
Method method = CloudServersConnection.class.getMethod("createServer", String.class, Method method = CloudServersConnection.class.getMethod("createServer", String.class,
int.class, int.class, createServerOptionsVarargsClass); int.class, int.class, createServerOptionsVarargsClass);
HttpRequest httpMethod = processor.createRequest(method, new Object[] { "ralphie", 2, 1 }); GeneratedHttpRequest<CloudServersConnection> httpMethod = processor.createRequest(method,
new Object[] { "ralphie", 2, 1 });
assertEquals("{\"server\":{\"name\":\"ralphie\",\"imageId\":2,\"flavorId\":1}}", httpMethod assertEquals("{\"server\":{\"name\":\"ralphie\",\"imageId\":2,\"flavorId\":1}}", httpMethod
.getEntity()); .getEntity());
validateCreateServer(method, httpMethod, null); validateCreateServer(method, httpMethod, null);
@ -116,8 +117,8 @@ public class CloudServersConnectionTest {
Method method = CloudServersConnection.class.getMethod("createServer", String.class, Method method = CloudServersConnection.class.getMethod("createServer", String.class,
int.class, int.class, createServerOptionsVarargsClass); int.class, int.class, createServerOptionsVarargsClass);
HttpRequest httpMethod = processor.createRequest(method, new Object[] { "ralphie", 2, 1, GeneratedHttpRequest<CloudServersConnection> httpMethod = processor.createRequest(method,
withSharedIpGroup(2) }); new Object[] { "ralphie", 2, 1, withSharedIpGroup(2) });
assertEquals( assertEquals(
"{\"server\":{\"name\":\"ralphie\",\"imageId\":2,\"flavorId\":1,\"sharedIpGroupId\":2}}", "{\"server\":{\"name\":\"ralphie\",\"imageId\":2,\"flavorId\":1,\"sharedIpGroupId\":2}}",
httpMethod.getEntity()); httpMethod.getEntity());
@ -128,7 +129,8 @@ public class CloudServersConnectionTest {
Method method = CloudServersConnection.class.getMethod("createServer", String.class, Method method = CloudServersConnection.class.getMethod("createServer", String.class,
int.class, int.class, createServerOptionsVarargsClass); int.class, int.class, createServerOptionsVarargsClass);
HttpRequest httpMethod = processor.createRequest(method, new Object[] { "ralphie", 2, 1, GeneratedHttpRequest<CloudServersConnection> httpMethod = processor.createRequest(method,
new Object[] { "ralphie", 2, 1,
new CreateServerOptions[] { withFile("/etc/jclouds", "foo".getBytes()) } }); new CreateServerOptions[] { withFile("/etc/jclouds", "foo".getBytes()) } });
assertEquals( assertEquals(
"{\"server\":{\"name\":\"ralphie\",\"imageId\":2,\"flavorId\":1,\"personality\":[{\"path\":\"/etc/jclouds\",\"contents\":\"Zm9v\"}]}}", "{\"server\":{\"name\":\"ralphie\",\"imageId\":2,\"flavorId\":1,\"personality\":[{\"path\":\"/etc/jclouds\",\"contents\":\"Zm9v\"}]}}",
@ -140,8 +142,8 @@ public class CloudServersConnectionTest {
Method method = CloudServersConnection.class.getMethod("createServer", String.class, Method method = CloudServersConnection.class.getMethod("createServer", String.class,
int.class, int.class, createServerOptionsVarargsClass); int.class, int.class, createServerOptionsVarargsClass);
HttpRequest httpMethod = processor.createRequest(method, new Object[] { "ralphie", 2, 1, GeneratedHttpRequest<CloudServersConnection> httpMethod = processor.createRequest(method,
withMetadata(ImmutableMap.of("foo", "bar")) }); new Object[] { "ralphie", 2, 1, withMetadata(ImmutableMap.of("foo", "bar")) });
assertEquals( assertEquals(
"{\"server\":{\"name\":\"ralphie\",\"imageId\":2,\"flavorId\":1,\"metadata\":{\"foo\":\"bar\"}}}", "{\"server\":{\"name\":\"ralphie\",\"imageId\":2,\"flavorId\":1,\"metadata\":{\"foo\":\"bar\"}}}",
httpMethod.getEntity()); httpMethod.getEntity());
@ -153,7 +155,8 @@ public class CloudServersConnectionTest {
Method method = CloudServersConnection.class.getMethod("createServer", String.class, Method method = CloudServersConnection.class.getMethod("createServer", String.class,
int.class, int.class, createServerOptionsVarargsClass); int.class, int.class, createServerOptionsVarargsClass);
HttpRequest httpMethod = processor.createRequest(method, new Object[] { GeneratedHttpRequest<CloudServersConnection> httpMethod = processor.createRequest(method,
new Object[] {
"ralphie", "ralphie",
2, 2,
1, 1,
@ -165,7 +168,8 @@ public class CloudServersConnectionTest {
validateCreateServer(method, httpMethod, null); validateCreateServer(method, httpMethod, null);
} }
private void validateCreateServer(Method method, HttpRequest httpMethod, Object[] args) { private void validateCreateServer(Method method,
GeneratedHttpRequest<CloudServersConnection> httpMethod, Object[] args) {
assertEquals(httpMethod.getEndpoint().getHost(), "localhost"); assertEquals(httpMethod.getEndpoint().getHost(), "localhost");
assertEquals(httpMethod.getEndpoint().getPath(), "/servers"); assertEquals(httpMethod.getEndpoint().getPath(), "/servers");
assertEquals(httpMethod.getEndpoint().getQuery(), "format=json"); assertEquals(httpMethod.getEndpoint().getQuery(), "format=json");
@ -186,13 +190,14 @@ public class CloudServersConnectionTest {
Method method = CloudServersConnection.class Method method = CloudServersConnection.class
.getMethod("listServers", listOptionsVarargsClass); .getMethod("listServers", listOptionsVarargsClass);
HttpRequest httpMethod = processor.createRequest(method, new Object[] {}); GeneratedHttpRequest<CloudServersConnection> httpMethod = processor.createRequest(method,
new Object[] {});
assertEquals(httpMethod.getEndpoint().getHost(), "localhost"); assertEquals(httpMethod.getEndpoint().getHost(), "localhost");
assertEquals(httpMethod.getEndpoint().getPath(), "/servers"); assertEquals(httpMethod.getEndpoint().getPath(), "/servers");
assertEquals(httpMethod.getEndpoint().getQuery(), "format=json"); assertEquals(httpMethod.getEndpoint().getQuery(), "format=json");
assertEquals(httpMethod.getMethod(), HttpMethod.GET); assertEquals(httpMethod.getMethod(), HttpMethod.GET);
assertEquals(httpMethod.getHeaders().size(), 0); assertEquals(httpMethod.getHeaders().size(), 0);
assertEquals(processor.createResponseParser(method, httpMethod, null).getClass(), assertEquals(processor.createResponseParser(method, httpMethod).getClass(),
ParseServerListFromJsonResponse.class); ParseServerListFromJsonResponse.class);
assertEquals(processor.createExceptionParserOrNullIfNotFound(method), null); assertEquals(processor.createExceptionParserOrNullIfNotFound(method), null);
} }
@ -203,15 +208,15 @@ public class CloudServersConnectionTest {
Method method = CloudServersConnection.class Method method = CloudServersConnection.class
.getMethod("listServers", listOptionsVarargsClass); .getMethod("listServers", listOptionsVarargsClass);
HttpRequest httpMethod = processor.createRequest(method, new Object[] { changesSince(now) GeneratedHttpRequest<CloudServersConnection> httpMethod = processor.createRequest(method,
.maxResults(1).startAt(2) }); new Object[] { changesSince(now).maxResults(1).startAt(2) });
assertEquals(httpMethod.getEndpoint().getHost(), "localhost"); assertEquals(httpMethod.getEndpoint().getHost(), "localhost");
assertEquals(httpMethod.getEndpoint().getPath(), "/servers"); assertEquals(httpMethod.getEndpoint().getPath(), "/servers");
assertEquals(httpMethod.getEndpoint().getQuery(), "format=json" + "&limit=1&changes-since=" assertEquals(httpMethod.getEndpoint().getQuery(), "format=json" + "&limit=1&changes-since="
+ now.getMillis() / 1000 + "&offset=2"); + now.getMillis() / 1000 + "&offset=2");
assertEquals(httpMethod.getMethod(), HttpMethod.GET); assertEquals(httpMethod.getMethod(), HttpMethod.GET);
assertEquals(httpMethod.getHeaders().size(), 0); assertEquals(httpMethod.getHeaders().size(), 0);
assertEquals(processor.createResponseParser(method, httpMethod, null).getClass(), assertEquals(processor.createResponseParser(method, httpMethod).getClass(),
ParseServerListFromJsonResponse.class); ParseServerListFromJsonResponse.class);
assertEquals(processor.createExceptionParserOrNullIfNotFound(method), null); assertEquals(processor.createExceptionParserOrNullIfNotFound(method), null);
} }
@ -220,13 +225,14 @@ public class CloudServersConnectionTest {
Method method = CloudServersConnection.class Method method = CloudServersConnection.class
.getMethod("listServers", listOptionsVarargsClass); .getMethod("listServers", listOptionsVarargsClass);
HttpRequest httpMethod = processor.createRequest(method, new Object[] { withDetails() }); GeneratedHttpRequest<CloudServersConnection> httpMethod = processor.createRequest(method,
new Object[] { withDetails() });
assertEquals(httpMethod.getEndpoint().getHost(), "localhost"); assertEquals(httpMethod.getEndpoint().getHost(), "localhost");
assertEquals(httpMethod.getEndpoint().getPath(), "/servers/detail"); assertEquals(httpMethod.getEndpoint().getPath(), "/servers/detail");
assertEquals(httpMethod.getEndpoint().getQuery(), "format=json"); assertEquals(httpMethod.getEndpoint().getQuery(), "format=json");
assertEquals(httpMethod.getMethod(), HttpMethod.GET); assertEquals(httpMethod.getMethod(), HttpMethod.GET);
assertEquals(httpMethod.getHeaders().size(), 0); assertEquals(httpMethod.getHeaders().size(), 0);
assertEquals(processor.createResponseParser(method, httpMethod, null).getClass(), assertEquals(processor.createResponseParser(method, httpMethod).getClass(),
ParseServerListFromJsonResponse.class); ParseServerListFromJsonResponse.class);
assertEquals(processor.createExceptionParserOrNullIfNotFound(method), null); assertEquals(processor.createExceptionParserOrNullIfNotFound(method), null);
} }
@ -234,13 +240,14 @@ public class CloudServersConnectionTest {
public void testGetServer() throws SecurityException, NoSuchMethodException { public void testGetServer() throws SecurityException, NoSuchMethodException {
Method method = CloudServersConnection.class.getMethod("getServer", int.class); Method method = CloudServersConnection.class.getMethod("getServer", int.class);
HttpRequest httpMethod = processor.createRequest(method, new Object[] { 2 }); GeneratedHttpRequest<CloudServersConnection> httpMethod = processor.createRequest(method,
new Object[] { 2 });
assertEquals(httpMethod.getEndpoint().getHost(), "localhost"); assertEquals(httpMethod.getEndpoint().getHost(), "localhost");
assertEquals(httpMethod.getEndpoint().getPath(), "/servers/2"); assertEquals(httpMethod.getEndpoint().getPath(), "/servers/2");
assertEquals(httpMethod.getEndpoint().getQuery(), "format=json"); assertEquals(httpMethod.getEndpoint().getQuery(), "format=json");
assertEquals(httpMethod.getMethod(), HttpMethod.GET); assertEquals(httpMethod.getMethod(), HttpMethod.GET);
assertEquals(httpMethod.getHeaders().size(), 0); assertEquals(httpMethod.getHeaders().size(), 0);
assertEquals(processor.createResponseParser(method, httpMethod, null).getClass(), assertEquals(processor.createResponseParser(method, httpMethod).getClass(),
ParseServerFromJsonResponse.class); ParseServerFromJsonResponse.class);
assertEquals(processor.createExceptionParserOrNullIfNotFound(method).getClass(), assertEquals(processor.createExceptionParserOrNullIfNotFound(method).getClass(),
ReturnServerNotFoundOn404.class); ReturnServerNotFoundOn404.class);
@ -250,13 +257,14 @@ public class CloudServersConnectionTest {
Method method = CloudServersConnection.class Method method = CloudServersConnection.class
.getMethod("listFlavors", listOptionsVarargsClass); .getMethod("listFlavors", listOptionsVarargsClass);
HttpRequest httpMethod = processor.createRequest(method, new Object[] {}); GeneratedHttpRequest<CloudServersConnection> httpMethod = processor.createRequest(method,
new Object[] {});
assertEquals(httpMethod.getEndpoint().getHost(), "localhost"); assertEquals(httpMethod.getEndpoint().getHost(), "localhost");
assertEquals(httpMethod.getEndpoint().getPath(), "/flavors"); assertEquals(httpMethod.getEndpoint().getPath(), "/flavors");
assertEquals(httpMethod.getEndpoint().getQuery(), "format=json"); assertEquals(httpMethod.getEndpoint().getQuery(), "format=json");
assertEquals(httpMethod.getMethod(), HttpMethod.GET); assertEquals(httpMethod.getMethod(), HttpMethod.GET);
assertEquals(httpMethod.getHeaders().size(), 0); assertEquals(httpMethod.getHeaders().size(), 0);
assertEquals(processor.createResponseParser(method, httpMethod, null).getClass(), assertEquals(processor.createResponseParser(method, httpMethod).getClass(),
ParseFlavorListFromJsonResponse.class); ParseFlavorListFromJsonResponse.class);
assertEquals(processor.createExceptionParserOrNullIfNotFound(method), null); assertEquals(processor.createExceptionParserOrNullIfNotFound(method), null);
} }
@ -265,15 +273,15 @@ public class CloudServersConnectionTest {
Method method = CloudServersConnection.class Method method = CloudServersConnection.class
.getMethod("listFlavors", listOptionsVarargsClass); .getMethod("listFlavors", listOptionsVarargsClass);
HttpRequest httpMethod = processor.createRequest(method, new Object[] { changesSince(now) GeneratedHttpRequest<CloudServersConnection> httpMethod = processor.createRequest(method,
.maxResults(1).startAt(2) }); new Object[] { changesSince(now).maxResults(1).startAt(2) });
assertEquals(httpMethod.getEndpoint().getHost(), "localhost"); assertEquals(httpMethod.getEndpoint().getHost(), "localhost");
assertEquals(httpMethod.getEndpoint().getPath(), "/flavors"); assertEquals(httpMethod.getEndpoint().getPath(), "/flavors");
assertEquals(httpMethod.getEndpoint().getQuery(), "format=json" + "&limit=1&changes-since=" assertEquals(httpMethod.getEndpoint().getQuery(), "format=json" + "&limit=1&changes-since="
+ now.getMillis() / 1000 + "&offset=2"); + now.getMillis() / 1000 + "&offset=2");
assertEquals(httpMethod.getMethod(), HttpMethod.GET); assertEquals(httpMethod.getMethod(), HttpMethod.GET);
assertEquals(httpMethod.getHeaders().size(), 0); assertEquals(httpMethod.getHeaders().size(), 0);
assertEquals(processor.createResponseParser(method, httpMethod, null).getClass(), assertEquals(processor.createResponseParser(method, httpMethod).getClass(),
ParseFlavorListFromJsonResponse.class); ParseFlavorListFromJsonResponse.class);
assertEquals(processor.createExceptionParserOrNullIfNotFound(method), null); assertEquals(processor.createExceptionParserOrNullIfNotFound(method), null);
} }
@ -282,13 +290,14 @@ public class CloudServersConnectionTest {
Method method = CloudServersConnection.class Method method = CloudServersConnection.class
.getMethod("listFlavors", listOptionsVarargsClass); .getMethod("listFlavors", listOptionsVarargsClass);
HttpRequest httpMethod = processor.createRequest(method, new Object[] { withDetails() }); GeneratedHttpRequest<CloudServersConnection> httpMethod = processor.createRequest(method,
new Object[] { withDetails() });
assertEquals(httpMethod.getEndpoint().getHost(), "localhost"); assertEquals(httpMethod.getEndpoint().getHost(), "localhost");
assertEquals(httpMethod.getEndpoint().getPath(), "/flavors/detail"); assertEquals(httpMethod.getEndpoint().getPath(), "/flavors/detail");
assertEquals(httpMethod.getEndpoint().getQuery(), "format=json"); assertEquals(httpMethod.getEndpoint().getQuery(), "format=json");
assertEquals(httpMethod.getMethod(), HttpMethod.GET); assertEquals(httpMethod.getMethod(), HttpMethod.GET);
assertEquals(httpMethod.getHeaders().size(), 0); assertEquals(httpMethod.getHeaders().size(), 0);
assertEquals(processor.createResponseParser(method, httpMethod, null).getClass(), assertEquals(processor.createResponseParser(method, httpMethod).getClass(),
ParseFlavorListFromJsonResponse.class); ParseFlavorListFromJsonResponse.class);
assertEquals(processor.createExceptionParserOrNullIfNotFound(method), null); assertEquals(processor.createExceptionParserOrNullIfNotFound(method), null);
} }
@ -297,15 +306,15 @@ public class CloudServersConnectionTest {
Method method = CloudServersConnection.class Method method = CloudServersConnection.class
.getMethod("listFlavors", listOptionsVarargsClass); .getMethod("listFlavors", listOptionsVarargsClass);
HttpRequest httpMethod = processor.createRequest(method, new Object[] { withDetails() GeneratedHttpRequest<CloudServersConnection> httpMethod = processor.createRequest(method,
.changesSince(now).maxResults(1).startAt(2) }); new Object[] { withDetails().changesSince(now).maxResults(1).startAt(2) });
assertEquals(httpMethod.getEndpoint().getHost(), "localhost"); assertEquals(httpMethod.getEndpoint().getHost(), "localhost");
assertEquals(httpMethod.getEndpoint().getPath(), "/flavors/detail"); assertEquals(httpMethod.getEndpoint().getPath(), "/flavors/detail");
assertEquals(httpMethod.getEndpoint().getQuery(), "format=json" + "&limit=1&changes-since=" assertEquals(httpMethod.getEndpoint().getQuery(), "format=json" + "&limit=1&changes-since="
+ now.getMillis() / 1000 + "&offset=2"); + now.getMillis() / 1000 + "&offset=2");
assertEquals(httpMethod.getMethod(), HttpMethod.GET); assertEquals(httpMethod.getMethod(), HttpMethod.GET);
assertEquals(httpMethod.getHeaders().size(), 0); assertEquals(httpMethod.getHeaders().size(), 0);
assertEquals(processor.createResponseParser(method, httpMethod, null).getClass(), assertEquals(processor.createResponseParser(method, httpMethod).getClass(),
ParseFlavorListFromJsonResponse.class); ParseFlavorListFromJsonResponse.class);
assertEquals(processor.createExceptionParserOrNullIfNotFound(method), null); assertEquals(processor.createExceptionParserOrNullIfNotFound(method), null);
} }
@ -313,13 +322,14 @@ public class CloudServersConnectionTest {
public void testGetFlavor() throws SecurityException, NoSuchMethodException { public void testGetFlavor() throws SecurityException, NoSuchMethodException {
Method method = CloudServersConnection.class.getMethod("getFlavor", int.class); Method method = CloudServersConnection.class.getMethod("getFlavor", int.class);
HttpRequest httpMethod = processor.createRequest(method, new Object[] { 2 }); GeneratedHttpRequest<CloudServersConnection> httpMethod = processor.createRequest(method,
new Object[] { 2 });
assertEquals(httpMethod.getEndpoint().getHost(), "localhost"); assertEquals(httpMethod.getEndpoint().getHost(), "localhost");
assertEquals(httpMethod.getEndpoint().getPath(), "/flavors/2"); assertEquals(httpMethod.getEndpoint().getPath(), "/flavors/2");
assertEquals(httpMethod.getEndpoint().getQuery(), "format=json"); assertEquals(httpMethod.getEndpoint().getQuery(), "format=json");
assertEquals(httpMethod.getMethod(), HttpMethod.GET); assertEquals(httpMethod.getMethod(), HttpMethod.GET);
assertEquals(httpMethod.getHeaders().size(), 0); assertEquals(httpMethod.getHeaders().size(), 0);
assertEquals(processor.createResponseParser(method, httpMethod, null).getClass(), assertEquals(processor.createResponseParser(method, httpMethod).getClass(),
ParseFlavorFromJsonResponse.class); ParseFlavorFromJsonResponse.class);
assertEquals(processor.createExceptionParserOrNullIfNotFound(method).getClass(), assertEquals(processor.createExceptionParserOrNullIfNotFound(method).getClass(),
ReturnFlavorNotFoundOn404.class); ReturnFlavorNotFoundOn404.class);
@ -328,13 +338,14 @@ public class CloudServersConnectionTest {
public void testListImages() throws SecurityException, NoSuchMethodException { public void testListImages() throws SecurityException, NoSuchMethodException {
Method method = CloudServersConnection.class.getMethod("listImages", listOptionsVarargsClass); Method method = CloudServersConnection.class.getMethod("listImages", listOptionsVarargsClass);
HttpRequest httpMethod = processor.createRequest(method, new Object[] {}); GeneratedHttpRequest<CloudServersConnection> httpMethod = processor.createRequest(method,
new Object[] {});
assertEquals(httpMethod.getEndpoint().getHost(), "localhost"); assertEquals(httpMethod.getEndpoint().getHost(), "localhost");
assertEquals(httpMethod.getEndpoint().getPath(), "/images"); assertEquals(httpMethod.getEndpoint().getPath(), "/images");
assertEquals(httpMethod.getEndpoint().getQuery(), "format=json"); assertEquals(httpMethod.getEndpoint().getQuery(), "format=json");
assertEquals(httpMethod.getMethod(), HttpMethod.GET); assertEquals(httpMethod.getMethod(), HttpMethod.GET);
assertEquals(httpMethod.getHeaders().size(), 0); assertEquals(httpMethod.getHeaders().size(), 0);
assertEquals(processor.createResponseParser(method, httpMethod, null).getClass(), assertEquals(processor.createResponseParser(method, httpMethod).getClass(),
ParseImageListFromJsonResponse.class); ParseImageListFromJsonResponse.class);
assertEquals(processor.createExceptionParserOrNullIfNotFound(method), null); assertEquals(processor.createExceptionParserOrNullIfNotFound(method), null);
} }
@ -342,13 +353,14 @@ public class CloudServersConnectionTest {
public void testListImagesDetail() throws SecurityException, NoSuchMethodException { public void testListImagesDetail() throws SecurityException, NoSuchMethodException {
Method method = CloudServersConnection.class.getMethod("listImages", listOptionsVarargsClass); Method method = CloudServersConnection.class.getMethod("listImages", listOptionsVarargsClass);
HttpRequest httpMethod = processor.createRequest(method, new Object[] { withDetails() }); GeneratedHttpRequest<CloudServersConnection> httpMethod = processor.createRequest(method,
new Object[] { withDetails() });
assertEquals(httpMethod.getEndpoint().getHost(), "localhost"); assertEquals(httpMethod.getEndpoint().getHost(), "localhost");
assertEquals(httpMethod.getEndpoint().getPath(), "/images/detail"); assertEquals(httpMethod.getEndpoint().getPath(), "/images/detail");
assertEquals(httpMethod.getEndpoint().getQuery(), "format=json"); assertEquals(httpMethod.getEndpoint().getQuery(), "format=json");
assertEquals(httpMethod.getMethod(), HttpMethod.GET); assertEquals(httpMethod.getMethod(), HttpMethod.GET);
assertEquals(httpMethod.getHeaders().size(), 0); assertEquals(httpMethod.getHeaders().size(), 0);
assertEquals(processor.createResponseParser(method, httpMethod, null).getClass(), assertEquals(processor.createResponseParser(method, httpMethod).getClass(),
ParseImageListFromJsonResponse.class); ParseImageListFromJsonResponse.class);
assertEquals(processor.createExceptionParserOrNullIfNotFound(method), null); assertEquals(processor.createExceptionParserOrNullIfNotFound(method), null);
} }
@ -356,15 +368,15 @@ public class CloudServersConnectionTest {
public void testListImagesOptions() throws SecurityException, NoSuchMethodException { public void testListImagesOptions() throws SecurityException, NoSuchMethodException {
Method method = CloudServersConnection.class.getMethod("listImages", listOptionsVarargsClass); Method method = CloudServersConnection.class.getMethod("listImages", listOptionsVarargsClass);
HttpRequest httpMethod = processor.createRequest(method, new Object[] { changesSince(now) GeneratedHttpRequest<CloudServersConnection> httpMethod = processor.createRequest(method,
.maxResults(1).startAt(2) }); new Object[] { changesSince(now).maxResults(1).startAt(2) });
assertEquals(httpMethod.getEndpoint().getHost(), "localhost"); assertEquals(httpMethod.getEndpoint().getHost(), "localhost");
assertEquals(httpMethod.getEndpoint().getPath(), "/images"); assertEquals(httpMethod.getEndpoint().getPath(), "/images");
assertEquals(httpMethod.getEndpoint().getQuery(), "format=json" + "&limit=1&changes-since=" assertEquals(httpMethod.getEndpoint().getQuery(), "format=json" + "&limit=1&changes-since="
+ now.getMillis() / 1000 + "&offset=2"); + now.getMillis() / 1000 + "&offset=2");
assertEquals(httpMethod.getMethod(), HttpMethod.GET); assertEquals(httpMethod.getMethod(), HttpMethod.GET);
assertEquals(httpMethod.getHeaders().size(), 0); assertEquals(httpMethod.getHeaders().size(), 0);
assertEquals(processor.createResponseParser(method, httpMethod, null).getClass(), assertEquals(processor.createResponseParser(method, httpMethod).getClass(),
ParseImageListFromJsonResponse.class); ParseImageListFromJsonResponse.class);
assertEquals(processor.createExceptionParserOrNullIfNotFound(method), null); assertEquals(processor.createExceptionParserOrNullIfNotFound(method), null);
} }
@ -372,15 +384,15 @@ public class CloudServersConnectionTest {
public void testListImagesDetailOptions() throws SecurityException, NoSuchMethodException { public void testListImagesDetailOptions() throws SecurityException, NoSuchMethodException {
Method method = CloudServersConnection.class.getMethod("listImages", listOptionsVarargsClass); Method method = CloudServersConnection.class.getMethod("listImages", listOptionsVarargsClass);
HttpRequest httpMethod = processor.createRequest(method, new Object[] { withDetails() GeneratedHttpRequest<CloudServersConnection> httpMethod = processor.createRequest(method,
.changesSince(now).maxResults(1).startAt(2) }); new Object[] { withDetails().changesSince(now).maxResults(1).startAt(2) });
assertEquals(httpMethod.getEndpoint().getHost(), "localhost"); assertEquals(httpMethod.getEndpoint().getHost(), "localhost");
assertEquals(httpMethod.getEndpoint().getPath(), "/images/detail"); assertEquals(httpMethod.getEndpoint().getPath(), "/images/detail");
assertEquals(httpMethod.getEndpoint().getQuery(), "format=json" + "&limit=1&changes-since=" assertEquals(httpMethod.getEndpoint().getQuery(), "format=json" + "&limit=1&changes-since="
+ now.getMillis() / 1000 + "&offset=2"); + now.getMillis() / 1000 + "&offset=2");
assertEquals(httpMethod.getMethod(), HttpMethod.GET); assertEquals(httpMethod.getMethod(), HttpMethod.GET);
assertEquals(httpMethod.getHeaders().size(), 0); assertEquals(httpMethod.getHeaders().size(), 0);
assertEquals(processor.createResponseParser(method, httpMethod, null).getClass(), assertEquals(processor.createResponseParser(method, httpMethod).getClass(),
ParseImageListFromJsonResponse.class); ParseImageListFromJsonResponse.class);
assertEquals(processor.createExceptionParserOrNullIfNotFound(method), null); assertEquals(processor.createExceptionParserOrNullIfNotFound(method), null);
} }
@ -388,13 +400,14 @@ public class CloudServersConnectionTest {
public void testGetImage() throws SecurityException, NoSuchMethodException { public void testGetImage() throws SecurityException, NoSuchMethodException {
Method method = CloudServersConnection.class.getMethod("getImage", int.class); Method method = CloudServersConnection.class.getMethod("getImage", int.class);
HttpRequest httpMethod = processor.createRequest(method, new Object[] { 2 }); GeneratedHttpRequest<CloudServersConnection> httpMethod = processor.createRequest(method,
new Object[] { 2 });
assertEquals(httpMethod.getEndpoint().getHost(), "localhost"); assertEquals(httpMethod.getEndpoint().getHost(), "localhost");
assertEquals(httpMethod.getEndpoint().getPath(), "/images/2"); assertEquals(httpMethod.getEndpoint().getPath(), "/images/2");
assertEquals(httpMethod.getEndpoint().getQuery(), "format=json"); assertEquals(httpMethod.getEndpoint().getQuery(), "format=json");
assertEquals(httpMethod.getMethod(), HttpMethod.GET); assertEquals(httpMethod.getMethod(), HttpMethod.GET);
assertEquals(httpMethod.getHeaders().size(), 0); assertEquals(httpMethod.getHeaders().size(), 0);
assertEquals(processor.createResponseParser(method, httpMethod, null).getClass(), assertEquals(processor.createResponseParser(method, httpMethod).getClass(),
ParseImageFromJsonResponse.class); ParseImageFromJsonResponse.class);
assertEquals(processor.createExceptionParserOrNullIfNotFound(method).getClass(), assertEquals(processor.createExceptionParserOrNullIfNotFound(method).getClass(),
ReturnImageNotFoundOn404.class); ReturnImageNotFoundOn404.class);
@ -403,14 +416,15 @@ public class CloudServersConnectionTest {
public void testDeleteServer() throws SecurityException, NoSuchMethodException { public void testDeleteServer() throws SecurityException, NoSuchMethodException {
Method method = CloudServersConnection.class.getMethod("deleteServer", int.class); Method method = CloudServersConnection.class.getMethod("deleteServer", int.class);
HttpRequest httpMethod = processor.createRequest(method, new Object[] { 2 }); GeneratedHttpRequest<CloudServersConnection> httpMethod = processor.createRequest(method,
new Object[] { 2 });
assertEquals(httpMethod.getEndpoint().getHost(), "localhost"); assertEquals(httpMethod.getEndpoint().getHost(), "localhost");
assertEquals(httpMethod.getEndpoint().getPath(), "/servers/2"); assertEquals(httpMethod.getEndpoint().getPath(), "/servers/2");
assertEquals(httpMethod.getMethod(), HttpMethod.DELETE); assertEquals(httpMethod.getMethod(), HttpMethod.DELETE);
assertEquals(httpMethod.getHeaders().size(), 0); assertEquals(httpMethod.getHeaders().size(), 0);
assertEquals(processor.createExceptionParserOrNullIfNotFound(method).getClass(), assertEquals(processor.createExceptionParserOrNullIfNotFound(method).getClass(),
ReturnFalseOn404.class); ReturnFalseOn404.class);
assertEquals(processor.createResponseParser(method, httpMethod, null).getClass(), assertEquals(processor.createResponseParser(method, httpMethod).getClass(),
ReturnTrueIf2xx.class); ReturnTrueIf2xx.class);
} }
@ -419,8 +433,8 @@ public class CloudServersConnectionTest {
Method method = CloudServersConnection.class.getMethod("shareIp", InetAddress.class, Method method = CloudServersConnection.class.getMethod("shareIp", InetAddress.class,
int.class, int.class, boolean.class); int.class, int.class, boolean.class);
HttpRequest httpMethod = processor.createRequest(method, new Object[] { GeneratedHttpRequest<CloudServersConnection> httpMethod = processor.createRequest(method,
InetAddress.getByAddress(new byte[] { 127, 0, 0, 1 }), 2, 3, false }); new Object[] { InetAddress.getByAddress(new byte[] { 127, 0, 0, 1 }), 2, 3, false });
assertEquals(httpMethod.getEndpoint().getHost(), "localhost"); assertEquals(httpMethod.getEndpoint().getHost(), "localhost");
assertEquals(httpMethod.getEndpoint().getPath(), "/servers/2/ips/public/127.0.0.1"); assertEquals(httpMethod.getEndpoint().getPath(), "/servers/2/ips/public/127.0.0.1");
assertEquals(httpMethod.getMethod(), HttpMethod.PUT); assertEquals(httpMethod.getMethod(), HttpMethod.PUT);
@ -432,7 +446,7 @@ public class CloudServersConnectionTest {
assertEquals("{\"shareIp\":{\"sharedIpGroupId\":3}}", httpMethod.getEntity()); assertEquals("{\"shareIp\":{\"sharedIpGroupId\":3}}", httpMethod.getEntity());
assertEquals(processor.createExceptionParserOrNullIfNotFound(method).getClass(), assertEquals(processor.createExceptionParserOrNullIfNotFound(method).getClass(),
ReturnFalseOn404.class); ReturnFalseOn404.class);
assertEquals(processor.createResponseParser(method, httpMethod, null).getClass(), assertEquals(processor.createResponseParser(method, httpMethod).getClass(),
ReturnTrueIf2xx.class); ReturnTrueIf2xx.class);
} }
@ -441,8 +455,8 @@ public class CloudServersConnectionTest {
Method method = CloudServersConnection.class.getMethod("shareIp", InetAddress.class, Method method = CloudServersConnection.class.getMethod("shareIp", InetAddress.class,
int.class, int.class, boolean.class); int.class, int.class, boolean.class);
HttpRequest httpMethod = processor.createRequest(method, new Object[] { GeneratedHttpRequest<CloudServersConnection> httpMethod = processor.createRequest(method,
InetAddress.getByAddress(new byte[] { 127, 0, 0, 1 }), 2, 3, true }); new Object[] { InetAddress.getByAddress(new byte[] { 127, 0, 0, 1 }), 2, 3, true });
assertEquals(httpMethod.getEndpoint().getHost(), "localhost"); assertEquals(httpMethod.getEndpoint().getHost(), "localhost");
assertEquals(httpMethod.getEndpoint().getPath(), "/servers/2/ips/public/127.0.0.1"); assertEquals(httpMethod.getEndpoint().getPath(), "/servers/2/ips/public/127.0.0.1");
assertEquals(httpMethod.getMethod(), HttpMethod.PUT); assertEquals(httpMethod.getMethod(), HttpMethod.PUT);
@ -455,7 +469,7 @@ public class CloudServersConnectionTest {
.getEntity()); .getEntity());
assertEquals(processor.createExceptionParserOrNullIfNotFound(method).getClass(), assertEquals(processor.createExceptionParserOrNullIfNotFound(method).getClass(),
ReturnFalseOn404.class); ReturnFalseOn404.class);
assertEquals(processor.createResponseParser(method, httpMethod, null).getClass(), assertEquals(processor.createResponseParser(method, httpMethod).getClass(),
ReturnTrueIf2xx.class); ReturnTrueIf2xx.class);
} }
@ -464,15 +478,15 @@ public class CloudServersConnectionTest {
Method method = CloudServersConnection.class.getMethod("unshareIp", InetAddress.class, Method method = CloudServersConnection.class.getMethod("unshareIp", InetAddress.class,
int.class); int.class);
HttpRequest httpMethod = processor.createRequest(method, new Object[] { GeneratedHttpRequest<CloudServersConnection> httpMethod = processor.createRequest(method,
InetAddress.getByAddress(new byte[] { 127, 0, 0, 1 }), 2, 3, false }); new Object[] { InetAddress.getByAddress(new byte[] { 127, 0, 0, 1 }), 2, 3, false });
assertEquals(httpMethod.getEndpoint().getHost(), "localhost"); assertEquals(httpMethod.getEndpoint().getHost(), "localhost");
assertEquals(httpMethod.getEndpoint().getPath(), "/servers/2/ips/public/127.0.0.1"); assertEquals(httpMethod.getEndpoint().getPath(), "/servers/2/ips/public/127.0.0.1");
assertEquals(httpMethod.getMethod(), HttpMethod.DELETE); assertEquals(httpMethod.getMethod(), HttpMethod.DELETE);
assertEquals(httpMethod.getHeaders().size(), 0); assertEquals(httpMethod.getHeaders().size(), 0);
assertEquals(processor.createExceptionParserOrNullIfNotFound(method).getClass(), assertEquals(processor.createExceptionParserOrNullIfNotFound(method).getClass(),
ReturnFalseOn404.class); ReturnFalseOn404.class);
assertEquals(processor.createResponseParser(method, httpMethod, null).getClass(), assertEquals(processor.createResponseParser(method, httpMethod).getClass(),
ReturnTrueIf2xx.class); ReturnTrueIf2xx.class);
} }
@ -480,7 +494,8 @@ public class CloudServersConnectionTest {
Method method = CloudServersConnection.class.getMethod("replaceBackupSchedule", int.class, Method method = CloudServersConnection.class.getMethod("replaceBackupSchedule", int.class,
BackupSchedule.class); BackupSchedule.class);
HttpRequest httpMethod = processor.createRequest(method, new Object[] { 2, GeneratedHttpRequest<CloudServersConnection> httpMethod = processor.createRequest(method,
new Object[] { 2,
new BackupSchedule(WeeklyBackup.MONDAY, DailyBackup.H_0800_1000, true) }); new BackupSchedule(WeeklyBackup.MONDAY, DailyBackup.H_0800_1000, true) });
assertEquals(httpMethod.getEndpoint().getHost(), "localhost"); assertEquals(httpMethod.getEndpoint().getHost(), "localhost");
assertEquals(httpMethod.getEndpoint().getPath(), "/servers/2/backup_schedule"); assertEquals(httpMethod.getEndpoint().getPath(), "/servers/2/backup_schedule");
@ -490,26 +505,26 @@ public class CloudServersConnectionTest {
.singletonList(httpMethod.getEntity().toString().getBytes().length + "")); .singletonList(httpMethod.getEntity().toString().getBytes().length + ""));
assertEquals(httpMethod.getHeaders().get(HttpHeaders.CONTENT_TYPE), Collections assertEquals(httpMethod.getHeaders().get(HttpHeaders.CONTENT_TYPE), Collections
.singletonList(MediaType.APPLICATION_JSON)); .singletonList(MediaType.APPLICATION_JSON));
assertEquals( assertEquals(httpMethod.getEntity(),
httpMethod.getEntity(),
"{\"backupSchedule\":{\"daily\":\"H_0800_1000\",\"enabled\":true,\"weekly\":\"MONDAY\"}}"); "{\"backupSchedule\":{\"daily\":\"H_0800_1000\",\"enabled\":true,\"weekly\":\"MONDAY\"}}");
assertEquals(processor.createExceptionParserOrNullIfNotFound(method).getClass(), assertEquals(processor.createExceptionParserOrNullIfNotFound(method).getClass(),
ReturnFalseOn404.class); ReturnFalseOn404.class);
assertEquals(processor.createResponseParser(method, httpMethod, null).getClass(), assertEquals(processor.createResponseParser(method, httpMethod).getClass(),
ReturnTrueIf2xx.class); ReturnTrueIf2xx.class);
} }
public void testDeleteBackupSchedule() throws SecurityException, NoSuchMethodException { public void testDeleteBackupSchedule() throws SecurityException, NoSuchMethodException {
Method method = CloudServersConnection.class.getMethod("deleteBackupSchedule", int.class); Method method = CloudServersConnection.class.getMethod("deleteBackupSchedule", int.class);
HttpRequest httpMethod = processor.createRequest(method, new Object[] { 2 }); GeneratedHttpRequest<CloudServersConnection> httpMethod = processor.createRequest(method,
new Object[] { 2 });
assertEquals(httpMethod.getEndpoint().getHost(), "localhost"); assertEquals(httpMethod.getEndpoint().getHost(), "localhost");
assertEquals(httpMethod.getEndpoint().getPath(), "/servers/2/backup_schedule"); assertEquals(httpMethod.getEndpoint().getPath(), "/servers/2/backup_schedule");
assertEquals(httpMethod.getMethod(), HttpMethod.DELETE); assertEquals(httpMethod.getMethod(), HttpMethod.DELETE);
assertEquals(httpMethod.getHeaders().size(), 0); assertEquals(httpMethod.getHeaders().size(), 0);
assertEquals(processor.createExceptionParserOrNullIfNotFound(method).getClass(), assertEquals(processor.createExceptionParserOrNullIfNotFound(method).getClass(),
ReturnFalseOn404.class); ReturnFalseOn404.class);
assertEquals(processor.createResponseParser(method, httpMethod, null).getClass(), assertEquals(processor.createResponseParser(method, httpMethod).getClass(),
ReturnTrueIf2xx.class); ReturnTrueIf2xx.class);
} }
@ -517,7 +532,8 @@ public class CloudServersConnectionTest {
Method method = CloudServersConnection.class.getMethod("changeAdminPass", int.class, Method method = CloudServersConnection.class.getMethod("changeAdminPass", int.class,
String.class); String.class);
HttpRequest httpMethod = processor.createRequest(method, new Object[] { 2, "foo" }); GeneratedHttpRequest<CloudServersConnection> httpMethod = processor.createRequest(method,
new Object[] { 2, "foo" });
assertEquals(httpMethod.getEndpoint().getHost(), "localhost"); assertEquals(httpMethod.getEndpoint().getHost(), "localhost");
assertEquals(httpMethod.getEndpoint().getPath(), "/servers/2"); assertEquals(httpMethod.getEndpoint().getPath(), "/servers/2");
assertEquals(httpMethod.getMethod(), HttpMethod.PUT); assertEquals(httpMethod.getMethod(), HttpMethod.PUT);
@ -529,7 +545,7 @@ public class CloudServersConnectionTest {
assertEquals("{\"server\":{\"adminPass\":\"foo\"}}", httpMethod.getEntity()); assertEquals("{\"server\":{\"adminPass\":\"foo\"}}", httpMethod.getEntity());
assertEquals(processor.createExceptionParserOrNullIfNotFound(method).getClass(), assertEquals(processor.createExceptionParserOrNullIfNotFound(method).getClass(),
ReturnFalseOn404.class); ReturnFalseOn404.class);
assertEquals(processor.createResponseParser(method, httpMethod, null).getClass(), assertEquals(processor.createResponseParser(method, httpMethod).getClass(),
ReturnTrueIf2xx.class); ReturnTrueIf2xx.class);
} }
@ -537,7 +553,8 @@ public class CloudServersConnectionTest {
Method method = CloudServersConnection.class.getMethod("renameServer", int.class, Method method = CloudServersConnection.class.getMethod("renameServer", int.class,
String.class); String.class);
HttpRequest httpMethod = processor.createRequest(method, new Object[] { 2, "foo" }); GeneratedHttpRequest<CloudServersConnection> httpMethod = processor.createRequest(method,
new Object[] { 2, "foo" });
assertEquals(httpMethod.getEndpoint().getHost(), "localhost"); assertEquals(httpMethod.getEndpoint().getHost(), "localhost");
assertEquals(httpMethod.getEndpoint().getPath(), "/servers/2"); assertEquals(httpMethod.getEndpoint().getPath(), "/servers/2");
assertEquals(httpMethod.getMethod(), HttpMethod.PUT); assertEquals(httpMethod.getMethod(), HttpMethod.PUT);
@ -549,7 +566,7 @@ public class CloudServersConnectionTest {
assertEquals("{\"server\":{\"name\":\"foo\"}}", httpMethod.getEntity()); assertEquals("{\"server\":{\"name\":\"foo\"}}", httpMethod.getEntity());
assertEquals(processor.createExceptionParserOrNullIfNotFound(method).getClass(), assertEquals(processor.createExceptionParserOrNullIfNotFound(method).getClass(),
ReturnFalseOn404.class); ReturnFalseOn404.class);
assertEquals(processor.createResponseParser(method, httpMethod, null).getClass(), assertEquals(processor.createResponseParser(method, httpMethod).getClass(),
ReturnTrueIf2xx.class); ReturnTrueIf2xx.class);
} }
@ -557,13 +574,14 @@ public class CloudServersConnectionTest {
Method method = CloudServersConnection.class.getMethod("listSharedIpGroups", Method method = CloudServersConnection.class.getMethod("listSharedIpGroups",
listOptionsVarargsClass); listOptionsVarargsClass);
HttpRequest httpMethod = processor.createRequest(method, new Object[] {}); GeneratedHttpRequest<CloudServersConnection> httpMethod = processor.createRequest(method,
new Object[] {});
assertEquals(httpMethod.getEndpoint().getHost(), "localhost"); assertEquals(httpMethod.getEndpoint().getHost(), "localhost");
assertEquals(httpMethod.getEndpoint().getPath(), "/shared_ip_groups"); assertEquals(httpMethod.getEndpoint().getPath(), "/shared_ip_groups");
assertEquals(httpMethod.getEndpoint().getQuery(), "format=json"); assertEquals(httpMethod.getEndpoint().getQuery(), "format=json");
assertEquals(httpMethod.getMethod(), HttpMethod.GET); assertEquals(httpMethod.getMethod(), HttpMethod.GET);
assertEquals(httpMethod.getHeaders().size(), 0); assertEquals(httpMethod.getHeaders().size(), 0);
assertEquals(processor.createResponseParser(method, httpMethod, null).getClass(), assertEquals(processor.createResponseParser(method, httpMethod).getClass(),
ParseSharedIpGroupListFromJsonResponse.class); ParseSharedIpGroupListFromJsonResponse.class);
assertEquals(processor.createExceptionParserOrNullIfNotFound(method), null); assertEquals(processor.createExceptionParserOrNullIfNotFound(method), null);
} }
@ -572,15 +590,15 @@ public class CloudServersConnectionTest {
Method method = CloudServersConnection.class.getMethod("listSharedIpGroups", Method method = CloudServersConnection.class.getMethod("listSharedIpGroups",
listOptionsVarargsClass); listOptionsVarargsClass);
HttpRequest httpMethod = processor.createRequest(method, new Object[] { changesSince(now) GeneratedHttpRequest<CloudServersConnection> httpMethod = processor.createRequest(method,
.maxResults(1).startAt(2) }); new Object[] { changesSince(now).maxResults(1).startAt(2) });
assertEquals(httpMethod.getEndpoint().getHost(), "localhost"); assertEquals(httpMethod.getEndpoint().getHost(), "localhost");
assertEquals(httpMethod.getEndpoint().getPath(), "/shared_ip_groups"); assertEquals(httpMethod.getEndpoint().getPath(), "/shared_ip_groups");
assertEquals(httpMethod.getEndpoint().getQuery(), "format=json" + "&limit=1&changes-since=" assertEquals(httpMethod.getEndpoint().getQuery(), "format=json" + "&limit=1&changes-since="
+ now.getMillis() / 1000 + "&offset=2"); + now.getMillis() / 1000 + "&offset=2");
assertEquals(httpMethod.getMethod(), HttpMethod.GET); assertEquals(httpMethod.getMethod(), HttpMethod.GET);
assertEquals(httpMethod.getHeaders().size(), 0); assertEquals(httpMethod.getHeaders().size(), 0);
assertEquals(processor.createResponseParser(method, httpMethod, null).getClass(), assertEquals(processor.createResponseParser(method, httpMethod).getClass(),
ParseSharedIpGroupListFromJsonResponse.class); ParseSharedIpGroupListFromJsonResponse.class);
assertEquals(processor.createExceptionParserOrNullIfNotFound(method), null); assertEquals(processor.createExceptionParserOrNullIfNotFound(method), null);
} }
@ -589,13 +607,14 @@ public class CloudServersConnectionTest {
Method method = CloudServersConnection.class.getMethod("listSharedIpGroups", Method method = CloudServersConnection.class.getMethod("listSharedIpGroups",
listOptionsVarargsClass); listOptionsVarargsClass);
HttpRequest httpMethod = processor.createRequest(method, new Object[] { withDetails() }); GeneratedHttpRequest<CloudServersConnection> httpMethod = processor.createRequest(method,
new Object[] { withDetails() });
assertEquals(httpMethod.getEndpoint().getHost(), "localhost"); assertEquals(httpMethod.getEndpoint().getHost(), "localhost");
assertEquals(httpMethod.getEndpoint().getPath(), "/shared_ip_groups/detail"); assertEquals(httpMethod.getEndpoint().getPath(), "/shared_ip_groups/detail");
assertEquals(httpMethod.getEndpoint().getQuery(), "format=json"); assertEquals(httpMethod.getEndpoint().getQuery(), "format=json");
assertEquals(httpMethod.getMethod(), HttpMethod.GET); assertEquals(httpMethod.getMethod(), HttpMethod.GET);
assertEquals(httpMethod.getHeaders().size(), 0); assertEquals(httpMethod.getHeaders().size(), 0);
assertEquals(processor.createResponseParser(method, httpMethod, null).getClass(), assertEquals(processor.createResponseParser(method, httpMethod).getClass(),
ParseSharedIpGroupListFromJsonResponse.class); ParseSharedIpGroupListFromJsonResponse.class);
assertEquals(processor.createExceptionParserOrNullIfNotFound(method), null); assertEquals(processor.createExceptionParserOrNullIfNotFound(method), null);
} }
@ -605,15 +624,15 @@ public class CloudServersConnectionTest {
Method method = CloudServersConnection.class.getMethod("listSharedIpGroups", Method method = CloudServersConnection.class.getMethod("listSharedIpGroups",
listOptionsVarargsClass); listOptionsVarargsClass);
HttpRequest httpMethod = processor.createRequest(method, new Object[] { withDetails() GeneratedHttpRequest<CloudServersConnection> httpMethod = processor.createRequest(method,
.changesSince(now).maxResults(1).startAt(2) }); new Object[] { withDetails().changesSince(now).maxResults(1).startAt(2) });
assertEquals(httpMethod.getEndpoint().getHost(), "localhost"); assertEquals(httpMethod.getEndpoint().getHost(), "localhost");
assertEquals(httpMethod.getEndpoint().getPath(), "/shared_ip_groups/detail"); assertEquals(httpMethod.getEndpoint().getPath(), "/shared_ip_groups/detail");
assertEquals(httpMethod.getEndpoint().getQuery(), "format=json" + "&limit=1&changes-since=" assertEquals(httpMethod.getEndpoint().getQuery(), "format=json" + "&limit=1&changes-since="
+ now.getMillis() / 1000 + "&offset=2"); + now.getMillis() / 1000 + "&offset=2");
assertEquals(httpMethod.getMethod(), HttpMethod.GET); assertEquals(httpMethod.getMethod(), HttpMethod.GET);
assertEquals(httpMethod.getHeaders().size(), 0); assertEquals(httpMethod.getHeaders().size(), 0);
assertEquals(processor.createResponseParser(method, httpMethod, null).getClass(), assertEquals(processor.createResponseParser(method, httpMethod).getClass(),
ParseSharedIpGroupListFromJsonResponse.class); ParseSharedIpGroupListFromJsonResponse.class);
assertEquals(processor.createExceptionParserOrNullIfNotFound(method), null); assertEquals(processor.createExceptionParserOrNullIfNotFound(method), null);
} }
@ -621,13 +640,14 @@ public class CloudServersConnectionTest {
public void testGetSharedIpGroup() throws SecurityException, NoSuchMethodException { public void testGetSharedIpGroup() throws SecurityException, NoSuchMethodException {
Method method = CloudServersConnection.class.getMethod("getSharedIpGroup", int.class); Method method = CloudServersConnection.class.getMethod("getSharedIpGroup", int.class);
HttpRequest httpMethod = processor.createRequest(method, new Object[] { 2 }); GeneratedHttpRequest<CloudServersConnection> httpMethod = processor.createRequest(method,
new Object[] { 2 });
assertEquals(httpMethod.getEndpoint().getHost(), "localhost"); assertEquals(httpMethod.getEndpoint().getHost(), "localhost");
assertEquals(httpMethod.getEndpoint().getPath(), "/shared_ip_groups/2"); assertEquals(httpMethod.getEndpoint().getPath(), "/shared_ip_groups/2");
assertEquals(httpMethod.getEndpoint().getQuery(), "format=json"); assertEquals(httpMethod.getEndpoint().getQuery(), "format=json");
assertEquals(httpMethod.getMethod(), HttpMethod.GET); assertEquals(httpMethod.getMethod(), HttpMethod.GET);
assertEquals(httpMethod.getHeaders().size(), 0); assertEquals(httpMethod.getHeaders().size(), 0);
assertEquals(processor.createResponseParser(method, httpMethod, null).getClass(), assertEquals(processor.createResponseParser(method, httpMethod).getClass(),
ParseSharedIpGroupFromJsonResponse.class); ParseSharedIpGroupFromJsonResponse.class);
assertEquals(processor.createExceptionParserOrNullIfNotFound(method).getClass(), assertEquals(processor.createExceptionParserOrNullIfNotFound(method).getClass(),
ReturnSharedIpGroupNotFoundOn404.class); ReturnSharedIpGroupNotFoundOn404.class);
@ -640,7 +660,8 @@ public class CloudServersConnectionTest {
Method method = CloudServersConnection.class.getMethod("createSharedIpGroup", String.class, Method method = CloudServersConnection.class.getMethod("createSharedIpGroup", String.class,
createSharedIpGroupOptionsVarargsClass); createSharedIpGroupOptionsVarargsClass);
HttpRequest httpMethod = processor.createRequest(method, new Object[] { "ralphie" }); GeneratedHttpRequest<CloudServersConnection> httpMethod = processor.createRequest(method,
new Object[] { "ralphie" });
assertEquals("{\"sharedIpGroup\":{\"name\":\"ralphie\"}}", httpMethod.getEntity()); assertEquals("{\"sharedIpGroup\":{\"name\":\"ralphie\"}}", httpMethod.getEntity());
validateCreateSharedIpGroup(method, httpMethod); validateCreateSharedIpGroup(method, httpMethod);
} }
@ -649,14 +670,15 @@ public class CloudServersConnectionTest {
Method method = CloudServersConnection.class.getMethod("createSharedIpGroup", String.class, Method method = CloudServersConnection.class.getMethod("createSharedIpGroup", String.class,
createSharedIpGroupOptionsVarargsClass); createSharedIpGroupOptionsVarargsClass);
HttpRequest httpMethod = processor.createRequest(method, new Object[] { "ralphie", GeneratedHttpRequest<CloudServersConnection> httpMethod = processor.createRequest(method,
withServer(2) }); new Object[] { "ralphie", withServer(2) });
assertEquals("{\"sharedIpGroup\":{\"name\":\"ralphie\",\"server\":2}}", httpMethod assertEquals("{\"sharedIpGroup\":{\"name\":\"ralphie\",\"server\":2}}", httpMethod
.getEntity()); .getEntity());
validateCreateSharedIpGroup(method, httpMethod); validateCreateSharedIpGroup(method, httpMethod);
} }
private void validateCreateSharedIpGroup(Method method, HttpRequest httpMethod) { private void validateCreateSharedIpGroup(Method method,
GeneratedHttpRequest<CloudServersConnection> httpMethod) {
assertEquals(httpMethod.getEndpoint().getHost(), "localhost"); assertEquals(httpMethod.getEndpoint().getHost(), "localhost");
assertEquals(httpMethod.getEndpoint().getPath(), "/shared_ip_groups"); assertEquals(httpMethod.getEndpoint().getPath(), "/shared_ip_groups");
assertEquals(httpMethod.getEndpoint().getQuery(), "format=json"); assertEquals(httpMethod.getEndpoint().getQuery(), "format=json");
@ -666,7 +688,7 @@ public class CloudServersConnectionTest {
.singletonList(httpMethod.getEntity().toString().getBytes().length + "")); .singletonList(httpMethod.getEntity().toString().getBytes().length + ""));
assertEquals(httpMethod.getHeaders().get(HttpHeaders.CONTENT_TYPE), Collections assertEquals(httpMethod.getHeaders().get(HttpHeaders.CONTENT_TYPE), Collections
.singletonList(MediaType.APPLICATION_JSON)); .singletonList(MediaType.APPLICATION_JSON));
assertEquals(processor.createResponseParser(method, httpMethod, null).getClass(), assertEquals(processor.createResponseParser(method, httpMethod).getClass(),
ParseSharedIpGroupFromJsonResponse.class); ParseSharedIpGroupFromJsonResponse.class);
assertEquals(processor.createExceptionParserOrNullIfNotFound(method), null); assertEquals(processor.createExceptionParserOrNullIfNotFound(method), null);
assertNotNull(processor.getMapEntityBinderOrNull(method, new Object[] { "", assertNotNull(processor.getMapEntityBinderOrNull(method, new Object[] { "",
@ -676,66 +698,71 @@ public class CloudServersConnectionTest {
public void testDeleteSharedIpGroup() throws SecurityException, NoSuchMethodException { public void testDeleteSharedIpGroup() throws SecurityException, NoSuchMethodException {
Method method = CloudServersConnection.class.getMethod("deleteSharedIpGroup", int.class); Method method = CloudServersConnection.class.getMethod("deleteSharedIpGroup", int.class);
HttpRequest httpMethod = processor.createRequest(method, new Object[] { 2 }); GeneratedHttpRequest<CloudServersConnection> httpMethod = processor.createRequest(method,
new Object[] { 2 });
assertEquals(httpMethod.getEndpoint().getHost(), "localhost"); assertEquals(httpMethod.getEndpoint().getHost(), "localhost");
assertEquals(httpMethod.getEndpoint().getPath(), "/shared_ip_groups/2"); assertEquals(httpMethod.getEndpoint().getPath(), "/shared_ip_groups/2");
assertEquals(httpMethod.getMethod(), HttpMethod.DELETE); assertEquals(httpMethod.getMethod(), HttpMethod.DELETE);
assertEquals(httpMethod.getHeaders().size(), 0); assertEquals(httpMethod.getHeaders().size(), 0);
assertEquals(processor.createExceptionParserOrNullIfNotFound(method).getClass(), assertEquals(processor.createExceptionParserOrNullIfNotFound(method).getClass(),
ReturnFalseOn404.class); ReturnFalseOn404.class);
assertEquals(processor.createResponseParser(method, httpMethod, null).getClass(), assertEquals(processor.createResponseParser(method, httpMethod).getClass(),
ReturnTrueIf2xx.class); ReturnTrueIf2xx.class);
} }
public void testListAddresses() throws SecurityException, NoSuchMethodException { public void testListAddresses() throws SecurityException, NoSuchMethodException {
Method method = CloudServersConnection.class.getMethod("listAddresses", int.class); Method method = CloudServersConnection.class.getMethod("listAddresses", int.class);
HttpRequest httpMethod = processor.createRequest(method, new Object[] { 2 }); GeneratedHttpRequest<CloudServersConnection> httpMethod = processor.createRequest(method,
new Object[] { 2 });
assertEquals(httpMethod.getEndpoint().getHost(), "localhost"); assertEquals(httpMethod.getEndpoint().getHost(), "localhost");
assertEquals(httpMethod.getEndpoint().getPath(), "/servers/2/ips"); assertEquals(httpMethod.getEndpoint().getPath(), "/servers/2/ips");
assertEquals(httpMethod.getEndpoint().getQuery(), "format=json"); assertEquals(httpMethod.getEndpoint().getQuery(), "format=json");
assertEquals(httpMethod.getMethod(), HttpMethod.GET); assertEquals(httpMethod.getMethod(), HttpMethod.GET);
assertEquals(httpMethod.getHeaders().size(), 0); assertEquals(httpMethod.getHeaders().size(), 0);
assertEquals(processor.createResponseParser(method, httpMethod, null).getClass(), assertEquals(processor.createResponseParser(method, httpMethod).getClass(),
ParseAddressesFromJsonResponse.class); ParseAddressesFromJsonResponse.class);
} }
public void testListPublicAddresses() throws SecurityException, NoSuchMethodException { public void testListPublicAddresses() throws SecurityException, NoSuchMethodException {
Method method = CloudServersConnection.class.getMethod("listPublicAddresses", int.class); Method method = CloudServersConnection.class.getMethod("listPublicAddresses", int.class);
HttpRequest httpMethod = processor.createRequest(method, new Object[] { 2 }); GeneratedHttpRequest<CloudServersConnection> httpMethod = processor.createRequest(method,
new Object[] { 2 });
assertEquals(httpMethod.getEndpoint().getHost(), "localhost"); assertEquals(httpMethod.getEndpoint().getHost(), "localhost");
assertEquals(httpMethod.getEndpoint().getPath(), "/servers/2/ips/public"); assertEquals(httpMethod.getEndpoint().getPath(), "/servers/2/ips/public");
assertEquals(httpMethod.getEndpoint().getQuery(), "format=json"); assertEquals(httpMethod.getEndpoint().getQuery(), "format=json");
assertEquals(httpMethod.getMethod(), HttpMethod.GET); assertEquals(httpMethod.getMethod(), HttpMethod.GET);
assertEquals(httpMethod.getHeaders().size(), 0); assertEquals(httpMethod.getHeaders().size(), 0);
assertEquals(processor.createResponseParser(method, httpMethod, null).getClass(), assertEquals(processor.createResponseParser(method, httpMethod).getClass(),
ParseInetAddressListFromJsonResponse.class); ParseInetAddressListFromJsonResponse.class);
} }
public void testListPrivateAddresses() throws SecurityException, NoSuchMethodException { public void testListPrivateAddresses() throws SecurityException, NoSuchMethodException {
Method method = CloudServersConnection.class.getMethod("listPrivateAddresses", int.class); Method method = CloudServersConnection.class.getMethod("listPrivateAddresses", int.class);
HttpRequest httpMethod = processor.createRequest(method, new Object[] { 2 }); GeneratedHttpRequest<CloudServersConnection> httpMethod = processor.createRequest(method,
new Object[] { 2 });
assertEquals(httpMethod.getEndpoint().getHost(), "localhost"); assertEquals(httpMethod.getEndpoint().getHost(), "localhost");
assertEquals(httpMethod.getEndpoint().getPath(), "/servers/2/ips/private"); assertEquals(httpMethod.getEndpoint().getPath(), "/servers/2/ips/private");
assertEquals(httpMethod.getEndpoint().getQuery(), "format=json"); assertEquals(httpMethod.getEndpoint().getQuery(), "format=json");
assertEquals(httpMethod.getMethod(), HttpMethod.GET); assertEquals(httpMethod.getMethod(), HttpMethod.GET);
assertEquals(httpMethod.getHeaders().size(), 0); assertEquals(httpMethod.getHeaders().size(), 0);
assertEquals(processor.createResponseParser(method, httpMethod, null).getClass(), assertEquals(processor.createResponseParser(method, httpMethod).getClass(),
ParseInetAddressListFromJsonResponse.class); ParseInetAddressListFromJsonResponse.class);
} }
public void testListBackupSchedule() throws SecurityException, NoSuchMethodException { public void testListBackupSchedule() throws SecurityException, NoSuchMethodException {
Method method = CloudServersConnection.class.getMethod("listBackupSchedule", int.class); Method method = CloudServersConnection.class.getMethod("listBackupSchedule", int.class);
HttpRequest httpMethod = processor.createRequest(method, new Object[] { 2 }); GeneratedHttpRequest<CloudServersConnection> httpMethod = processor.createRequest(method,
new Object[] { 2 });
assertEquals(httpMethod.getEndpoint().getHost(), "localhost"); assertEquals(httpMethod.getEndpoint().getHost(), "localhost");
assertEquals(httpMethod.getEndpoint().getPath(), "/servers/2/backup_schedule"); assertEquals(httpMethod.getEndpoint().getPath(), "/servers/2/backup_schedule");
assertEquals(httpMethod.getEndpoint().getQuery(), "format=json"); assertEquals(httpMethod.getEndpoint().getQuery(), "format=json");
assertEquals(httpMethod.getMethod(), HttpMethod.GET); assertEquals(httpMethod.getMethod(), HttpMethod.GET);
assertEquals(httpMethod.getHeaders().size(), 0); assertEquals(httpMethod.getHeaders().size(), 0);
assertEquals(processor.createResponseParser(method, httpMethod, null).getClass(), assertEquals(processor.createResponseParser(method, httpMethod).getClass(),
ParseBackupScheduleFromJsonResponse.class); ParseBackupScheduleFromJsonResponse.class);
} }
@ -743,7 +770,8 @@ public class CloudServersConnectionTest {
Method method = CloudServersConnection.class.getMethod("createImageFromServer", String.class, Method method = CloudServersConnection.class.getMethod("createImageFromServer", String.class,
int.class); int.class);
HttpRequest httpMethod = processor.createRequest(method, new Object[] { "ralphie", 2 }); GeneratedHttpRequest<CloudServersConnection> httpMethod = processor.createRequest(method,
new Object[] { "ralphie", 2 });
assertEquals("{\"image\":{\"serverId\":2,\"name\":\"ralphie\"}}", httpMethod.getEntity()); assertEquals("{\"image\":{\"serverId\":2,\"name\":\"ralphie\"}}", httpMethod.getEntity());
assertEquals(httpMethod.getEndpoint().getHost(), "localhost"); assertEquals(httpMethod.getEndpoint().getHost(), "localhost");
assertEquals(httpMethod.getEndpoint().getPath(), "/images"); assertEquals(httpMethod.getEndpoint().getPath(), "/images");
@ -754,7 +782,7 @@ public class CloudServersConnectionTest {
.singletonList(httpMethod.getEntity().toString().getBytes().length + "")); .singletonList(httpMethod.getEntity().toString().getBytes().length + ""));
assertEquals(httpMethod.getHeaders().get(HttpHeaders.CONTENT_TYPE), Collections assertEquals(httpMethod.getHeaders().get(HttpHeaders.CONTENT_TYPE), Collections
.singletonList(MediaType.APPLICATION_JSON)); .singletonList(MediaType.APPLICATION_JSON));
assertEquals(processor.createResponseParser(method, httpMethod, null).getClass(), assertEquals(processor.createResponseParser(method, httpMethod).getClass(),
ParseImageFromJsonResponse.class); ParseImageFromJsonResponse.class);
assertNotNull(processor.createExceptionParserOrNullIfNotFound(method)); assertNotNull(processor.createExceptionParserOrNullIfNotFound(method));
assertNotNull(processor.getMapEntityBinderOrNull(method, new Object[] { "", 2 })); assertNotNull(processor.getMapEntityBinderOrNull(method, new Object[] { "", 2 }));
@ -767,7 +795,8 @@ public class CloudServersConnectionTest {
Method method = CloudServersConnection.class.getMethod("rebuildServer", int.class, Method method = CloudServersConnection.class.getMethod("rebuildServer", int.class,
rebuildServerOptionsVarargsClass); rebuildServerOptionsVarargsClass);
HttpRequest httpMethod = processor.createRequest(method, new Object[] { 3 }); GeneratedHttpRequest<CloudServersConnection> httpMethod = processor.createRequest(method,
new Object[] { 3 });
assertEquals("{\"rebuild\":{}}", httpMethod.getEntity()); assertEquals("{\"rebuild\":{}}", httpMethod.getEntity());
validateRebuildServer(method, httpMethod); validateRebuildServer(method, httpMethod);
} }
@ -776,12 +805,14 @@ public class CloudServersConnectionTest {
Method method = CloudServersConnection.class.getMethod("rebuildServer", int.class, Method method = CloudServersConnection.class.getMethod("rebuildServer", int.class,
rebuildServerOptionsVarargsClass); rebuildServerOptionsVarargsClass);
HttpRequest httpMethod = processor.createRequest(method, new Object[] { 3, withImage(2) }); GeneratedHttpRequest<CloudServersConnection> httpMethod = processor.createRequest(method,
new Object[] { 3, withImage(2) });
assertEquals("{\"rebuild\":{\"imageId\":2}}", httpMethod.getEntity()); assertEquals("{\"rebuild\":{\"imageId\":2}}", httpMethod.getEntity());
validateRebuildServer(method, httpMethod); validateRebuildServer(method, httpMethod);
} }
private void validateRebuildServer(Method method, HttpRequest httpMethod) { private void validateRebuildServer(Method method,
GeneratedHttpRequest<CloudServersConnection> httpMethod) {
assertEquals(httpMethod.getEndpoint().getHost(), "localhost"); assertEquals(httpMethod.getEndpoint().getHost(), "localhost");
assertEquals(httpMethod.getEndpoint().getPath(), "/servers/3/action"); assertEquals(httpMethod.getEndpoint().getPath(), "/servers/3/action");
assertEquals(httpMethod.getEndpoint().getQuery(), "format=json"); assertEquals(httpMethod.getEndpoint().getQuery(), "format=json");
@ -793,7 +824,7 @@ public class CloudServersConnectionTest {
.singletonList(MediaType.APPLICATION_JSON)); .singletonList(MediaType.APPLICATION_JSON));
assertEquals(processor.createExceptionParserOrNullIfNotFound(method).getClass(), assertEquals(processor.createExceptionParserOrNullIfNotFound(method).getClass(),
ReturnFalseOn404.class); ReturnFalseOn404.class);
assertEquals(processor.createResponseParser(method, httpMethod, null).getClass(), assertEquals(processor.createResponseParser(method, httpMethod).getClass(),
ReturnTrueIf2xx.class); ReturnTrueIf2xx.class);
assertNotNull(processor.getMapEntityBinderOrNull(method, new Object[] { "", assertNotNull(processor.getMapEntityBinderOrNull(method, new Object[] { "",
new RebuildServerOptions[] { withImage(2) } })); new RebuildServerOptions[] { withImage(2) } }));
@ -803,7 +834,8 @@ public class CloudServersConnectionTest {
Method method = CloudServersConnection.class.getMethod("rebootServer", int.class, Method method = CloudServersConnection.class.getMethod("rebootServer", int.class,
RebootType.class); RebootType.class);
HttpRequest httpMethod = processor.createRequest(method, new Object[] { 2, RebootType.HARD }); GeneratedHttpRequest<CloudServersConnection> httpMethod = processor.createRequest(method,
new Object[] { 2, RebootType.HARD });
assertEquals(httpMethod.getEndpoint().getHost(), "localhost"); assertEquals(httpMethod.getEndpoint().getHost(), "localhost");
assertEquals(httpMethod.getEndpoint().getPath(), "/servers/2/action"); assertEquals(httpMethod.getEndpoint().getPath(), "/servers/2/action");
assertEquals(httpMethod.getMethod(), HttpMethod.POST); assertEquals(httpMethod.getMethod(), HttpMethod.POST);
@ -815,14 +847,15 @@ public class CloudServersConnectionTest {
assertEquals("{\"reboot\":{\"type\":\"HARD\"}}", httpMethod.getEntity()); assertEquals("{\"reboot\":{\"type\":\"HARD\"}}", httpMethod.getEntity());
assertEquals(processor.createExceptionParserOrNullIfNotFound(method).getClass(), assertEquals(processor.createExceptionParserOrNullIfNotFound(method).getClass(),
ReturnFalseOn404.class); ReturnFalseOn404.class);
assertEquals(processor.createResponseParser(method, httpMethod, null).getClass(), assertEquals(processor.createResponseParser(method, httpMethod).getClass(),
ReturnTrueIf2xx.class); ReturnTrueIf2xx.class);
} }
public void testResize() throws SecurityException, NoSuchMethodException { public void testResize() throws SecurityException, NoSuchMethodException {
Method method = CloudServersConnection.class.getMethod("resizeServer", int.class, int.class); Method method = CloudServersConnection.class.getMethod("resizeServer", int.class, int.class);
HttpRequest httpMethod = processor.createRequest(method, new Object[] { 2, 3 }); GeneratedHttpRequest<CloudServersConnection> httpMethod = processor.createRequest(method,
new Object[] { 2, 3 });
assertEquals(httpMethod.getEndpoint().getHost(), "localhost"); assertEquals(httpMethod.getEndpoint().getHost(), "localhost");
assertEquals(httpMethod.getEndpoint().getPath(), "/servers/2/action"); assertEquals(httpMethod.getEndpoint().getPath(), "/servers/2/action");
assertEquals(httpMethod.getMethod(), HttpMethod.POST); assertEquals(httpMethod.getMethod(), HttpMethod.POST);
@ -834,14 +867,15 @@ public class CloudServersConnectionTest {
assertEquals("{\"resize\":{\"flavorId\":3}}", httpMethod.getEntity()); assertEquals("{\"resize\":{\"flavorId\":3}}", httpMethod.getEntity());
assertEquals(processor.createExceptionParserOrNullIfNotFound(method).getClass(), assertEquals(processor.createExceptionParserOrNullIfNotFound(method).getClass(),
ReturnFalseOn404.class); ReturnFalseOn404.class);
assertEquals(processor.createResponseParser(method, httpMethod, null).getClass(), assertEquals(processor.createResponseParser(method, httpMethod).getClass(),
ReturnTrueIf2xx.class); ReturnTrueIf2xx.class);
} }
public void testConfirmResize() throws SecurityException, NoSuchMethodException { public void testConfirmResize() throws SecurityException, NoSuchMethodException {
Method method = CloudServersConnection.class.getMethod("confirmResizeServer", int.class); Method method = CloudServersConnection.class.getMethod("confirmResizeServer", int.class);
HttpRequest httpMethod = processor.createRequest(method, new Object[] { 2 }); GeneratedHttpRequest<CloudServersConnection> httpMethod = processor.createRequest(method,
new Object[] { 2 });
assertEquals(httpMethod.getEndpoint().getHost(), "localhost"); assertEquals(httpMethod.getEndpoint().getHost(), "localhost");
assertEquals(httpMethod.getEndpoint().getPath(), "/servers/2/action"); assertEquals(httpMethod.getEndpoint().getPath(), "/servers/2/action");
assertEquals(httpMethod.getMethod(), HttpMethod.POST); assertEquals(httpMethod.getMethod(), HttpMethod.POST);
@ -853,13 +887,14 @@ public class CloudServersConnectionTest {
assertEquals("{\"confirmResize\":null}", httpMethod.getEntity()); assertEquals("{\"confirmResize\":null}", httpMethod.getEntity());
assertEquals(processor.createExceptionParserOrNullIfNotFound(method).getClass(), assertEquals(processor.createExceptionParserOrNullIfNotFound(method).getClass(),
ReturnFalseOn404.class); ReturnFalseOn404.class);
assertEquals(processor.createResponseParser(method, httpMethod, null).getClass(), assertEquals(processor.createResponseParser(method, httpMethod).getClass(),
ReturnTrueIf2xx.class); ReturnTrueIf2xx.class);
} }
public void testRevertResize() throws SecurityException, NoSuchMethodException { public void testRevertResize() throws SecurityException, NoSuchMethodException {
Method method = CloudServersConnection.class.getMethod("revertResizeServer", int.class); Method method = CloudServersConnection.class.getMethod("revertResizeServer", int.class);
HttpRequest httpMethod = processor.createRequest(method, new Object[] { 2 }); GeneratedHttpRequest<CloudServersConnection> httpMethod = processor.createRequest(method,
new Object[] { 2 });
assertEquals(httpMethod.getEndpoint().getHost(), "localhost"); assertEquals(httpMethod.getEndpoint().getHost(), "localhost");
assertEquals(httpMethod.getEndpoint().getPath(), "/servers/2/action"); assertEquals(httpMethod.getEndpoint().getPath(), "/servers/2/action");
assertEquals(httpMethod.getMethod(), HttpMethod.POST); assertEquals(httpMethod.getMethod(), HttpMethod.POST);
@ -871,7 +906,7 @@ public class CloudServersConnectionTest {
assertEquals("{\"revertResize\":null}", httpMethod.getEntity()); assertEquals("{\"revertResize\":null}", httpMethod.getEntity());
assertEquals(processor.createExceptionParserOrNullIfNotFound(method).getClass(), assertEquals(processor.createExceptionParserOrNullIfNotFound(method).getClass(),
ReturnFalseOn404.class); ReturnFalseOn404.class);
assertEquals(processor.createResponseParser(method, httpMethod, null).getClass(), assertEquals(processor.createResponseParser(method, httpMethod).getClass(),
ReturnTrueIf2xx.class); ReturnTrueIf2xx.class);
} }

View File

@ -21,7 +21,7 @@
* under the License. * under the License.
* ==================================================================== * ====================================================================
*/ */
package org.jclouds.rackspace.cloudservers.decorators; package org.jclouds.rackspace.cloudservers.binders;
import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertEquals;
@ -39,45 +39,45 @@ import com.google.inject.Guice;
import com.google.inject.Injector; import com.google.inject.Injector;
/** /**
* Tests behavior of {@code AddAdminPassAsJsonEntity} * Tests behavior of {@code BindAdminPassToJsonEntity}
* *
* @author Adrian Cole * @author Adrian Cole
*/ */
@Test(groups = "unit", testName = "cloudservers.AddAdminPassAsJsonEntityTest") @Test(groups = "unit", testName = "cloudservers.BindAdminPassToJsonEntityTest")
public class AddAdminPassAsJsonEntityTest { public class BindAdminPassToJsonEntityTest {
Injector injector = Guice.createInjector(new ParserModule()); Injector injector = Guice.createInjector(new ParserModule());
@Test(expectedExceptions = IllegalStateException.class) @Test(expectedExceptions = IllegalStateException.class)
public void testPostIsIncorrect() { public void testPostIsIncorrect() {
AddAdminPassAsJsonEntity binder = new AddAdminPassAsJsonEntity(); BindAdminPassToJsonEntity binder = new BindAdminPassToJsonEntity();
injector.injectMembers(binder); injector.injectMembers(binder);
HttpRequest request = new HttpRequest(HttpMethod.POST, URI.create("http://localhost")); HttpRequest request = new HttpRequest(HttpMethod.POST, URI.create("http://localhost"));
binder.decorateRequest(request, ImmutableMap.of("adminPass", "foo")); binder.bindToRequest(request, ImmutableMap.of("adminPass", "foo"));
} }
@Test(expectedExceptions = IllegalArgumentException.class) @Test(expectedExceptions = IllegalArgumentException.class)
public void testMustBeString() { public void testMustBeString() {
AddAdminPassAsJsonEntity binder = new AddAdminPassAsJsonEntity(); BindAdminPassToJsonEntity binder = new BindAdminPassToJsonEntity();
injector.injectMembers(binder); injector.injectMembers(binder);
HttpRequest request = new HttpRequest(HttpMethod.POST, URI.create("http://localhost")); HttpRequest request = new HttpRequest(HttpMethod.POST, URI.create("http://localhost"));
binder.decorateRequest(request, new File("foo")); binder.bindToRequest(request, new File("foo"));
} }
@Test @Test
public void testCorrect() { public void testCorrect() {
AddAdminPassAsJsonEntity binder = new AddAdminPassAsJsonEntity(); BindAdminPassToJsonEntity binder = new BindAdminPassToJsonEntity();
injector.injectMembers(binder); injector.injectMembers(binder);
HttpRequest request = new HttpRequest(HttpMethod.PUT, URI.create("http://localhost")); HttpRequest request = new HttpRequest(HttpMethod.PUT, URI.create("http://localhost"));
binder.decorateRequest(request, "foo"); binder.bindToRequest(request, "foo");
assertEquals("{\"server\":{\"adminPass\":\"foo\"}}", request.getEntity()); assertEquals("{\"server\":{\"adminPass\":\"foo\"}}", request.getEntity());
} }
@Test(expectedExceptions = { NullPointerException.class, IllegalStateException.class }) @Test(expectedExceptions = { NullPointerException.class, IllegalStateException.class })
public void testNullIsBad() { public void testNullIsBad() {
AddAdminPassAsJsonEntity binder = new AddAdminPassAsJsonEntity(); BindAdminPassToJsonEntity binder = new BindAdminPassToJsonEntity();
injector.injectMembers(binder); injector.injectMembers(binder);
HttpRequest request = new HttpRequest(HttpMethod.PUT, URI.create("http://localhost")); HttpRequest request = new HttpRequest(HttpMethod.PUT, URI.create("http://localhost"));
binder.decorateRequest(request, null); binder.bindToRequest(request, null);
} }
} }

View File

@ -21,7 +21,7 @@
* under the License. * under the License.
* ==================================================================== * ====================================================================
*/ */
package org.jclouds.rackspace.cloudservers.decorators; package org.jclouds.rackspace.cloudservers.binders;
import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertEquals;
@ -39,37 +39,37 @@ import com.google.inject.Guice;
import com.google.inject.Injector; import com.google.inject.Injector;
/** /**
* Tests behavior of {@code AddCreateImageAsJsonEntity} * Tests behavior of {@code BindCreateImageToJsonEntity}
* *
* @author Adrian Cole * @author Adrian Cole
*/ */
@Test(groups = "unit", testName = "cloudservers.AddCreateImageAsJsonEntityTest") @Test(groups = "unit", testName = "cloudservers.BindCreateImageToJsonEntityTest")
public class AddCreateImageAsJsonEntityTest { public class BindCreateImageToJsonEntityTest {
Injector injector = Guice.createInjector(new ParserModule()); Injector injector = Guice.createInjector(new ParserModule());
@Test(expectedExceptions = IllegalArgumentException.class) @Test(expectedExceptions = IllegalArgumentException.class)
public void testMustBeMap() { public void testMustBeMap() {
AddCreateImageAsJsonEntity binder = new AddCreateImageAsJsonEntity(); BindCreateImageToJsonEntity binder = new BindCreateImageToJsonEntity();
injector.injectMembers(binder); injector.injectMembers(binder);
HttpRequest request = new HttpRequest(HttpMethod.POST, URI.create("http://localhost")); HttpRequest request = new HttpRequest(HttpMethod.POST, URI.create("http://localhost"));
binder.decorateRequest(request, new File("foo")); binder.bindToRequest(request, new File("foo"));
} }
@Test @Test
public void testCorrect() { public void testCorrect() {
AddCreateImageAsJsonEntity binder = new AddCreateImageAsJsonEntity(); BindCreateImageToJsonEntity binder = new BindCreateImageToJsonEntity();
injector.injectMembers(binder); injector.injectMembers(binder);
HttpRequest request = new HttpRequest(HttpMethod.PUT, URI.create("http://localhost")); HttpRequest request = new HttpRequest(HttpMethod.PUT, URI.create("http://localhost"));
binder.decorateRequest(request, ImmutableMap.of("imageName", "foo", "serverId", "2")); binder.bindToRequest(request, ImmutableMap.of("imageName", "foo", "serverId", "2"));
assertEquals("{\"image\":{\"serverId\":2,\"name\":\"foo\"}}", request.getEntity()); assertEquals("{\"image\":{\"serverId\":2,\"name\":\"foo\"}}", request.getEntity());
} }
@Test(expectedExceptions = { NullPointerException.class, IllegalStateException.class }) @Test(expectedExceptions = { NullPointerException.class, IllegalStateException.class })
public void testNullIsBad() { public void testNullIsBad() {
AddCreateImageAsJsonEntity binder = new AddCreateImageAsJsonEntity(); BindCreateImageToJsonEntity binder = new BindCreateImageToJsonEntity();
injector.injectMembers(binder); injector.injectMembers(binder);
HttpRequest request = new HttpRequest(HttpMethod.PUT, URI.create("http://localhost")); HttpRequest request = new HttpRequest(HttpMethod.PUT, URI.create("http://localhost"));
binder.decorateRequest(request, null); binder.bindToRequest(request, null);
} }
} }

View File

@ -21,7 +21,7 @@
* under the License. * under the License.
* ==================================================================== * ====================================================================
*/ */
package org.jclouds.rackspace.cloudservers.decorators; package org.jclouds.rackspace.cloudservers.binders;
import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertEquals;
@ -40,54 +40,54 @@ import com.google.inject.Guice;
import com.google.inject.Injector; import com.google.inject.Injector;
/** /**
* Tests behavior of {@code AddRebootTypeAsJsonEntity} * Tests behavior of {@code BindRebootTypeToJsonEntity}
* *
* @author Adrian Cole * @author Adrian Cole
*/ */
@Test(groups = "unit", testName = "cloudservers.AddRebootTypeAsJsonEntityTest") @Test(groups = "unit", testName = "cloudservers.BindRebootTypeToJsonEntityTest")
public class AddRebootTypeAsJsonEntityTest { public class BindRebootTypeToJsonEntityTest {
Injector injector = Guice.createInjector(new ParserModule()); Injector injector = Guice.createInjector(new ParserModule());
@Test(expectedExceptions = IllegalStateException.class) @Test(expectedExceptions = IllegalStateException.class)
public void testPostIsIncorrect() { public void testPostIsIncorrect() {
AddRebootTypeAsJsonEntity binder = new AddRebootTypeAsJsonEntity(); BindRebootTypeToJsonEntity binder = new BindRebootTypeToJsonEntity();
injector.injectMembers(binder); injector.injectMembers(binder);
HttpRequest request = new HttpRequest(HttpMethod.POST, URI.create("http://localhost")); HttpRequest request = new HttpRequest(HttpMethod.POST, URI.create("http://localhost"));
binder.decorateRequest(request, ImmutableMap.of("adminPass", "foo")); binder.bindToRequest(request, ImmutableMap.of("adminPass", "foo"));
} }
@Test(expectedExceptions = IllegalArgumentException.class) @Test(expectedExceptions = IllegalArgumentException.class)
public void testMustBeRebootType() { public void testMustBeRebootType() {
AddRebootTypeAsJsonEntity binder = new AddRebootTypeAsJsonEntity(); BindRebootTypeToJsonEntity binder = new BindRebootTypeToJsonEntity();
injector.injectMembers(binder); injector.injectMembers(binder);
HttpRequest request = new HttpRequest(HttpMethod.POST, URI.create("http://localhost")); HttpRequest request = new HttpRequest(HttpMethod.POST, URI.create("http://localhost"));
binder.decorateRequest(request, new File("foo")); binder.bindToRequest(request, new File("foo"));
} }
@Test @Test
public void testHard() { public void testHard() {
AddRebootTypeAsJsonEntity binder = new AddRebootTypeAsJsonEntity(); BindRebootTypeToJsonEntity binder = new BindRebootTypeToJsonEntity();
injector.injectMembers(binder); injector.injectMembers(binder);
HttpRequest request = new HttpRequest(HttpMethod.POST, URI.create("http://localhost")); HttpRequest request = new HttpRequest(HttpMethod.POST, URI.create("http://localhost"));
binder.decorateRequest(request, RebootType.HARD); binder.bindToRequest(request, RebootType.HARD);
assertEquals("{\"reboot\":{\"type\":\"HARD\"}}", request.getEntity()); assertEquals("{\"reboot\":{\"type\":\"HARD\"}}", request.getEntity());
} }
@Test @Test
public void testSoft() { public void testSoft() {
AddRebootTypeAsJsonEntity binder = new AddRebootTypeAsJsonEntity(); BindRebootTypeToJsonEntity binder = new BindRebootTypeToJsonEntity();
injector.injectMembers(binder); injector.injectMembers(binder);
HttpRequest request = new HttpRequest(HttpMethod.POST, URI.create("http://localhost")); HttpRequest request = new HttpRequest(HttpMethod.POST, URI.create("http://localhost"));
binder.decorateRequest(request, RebootType.SOFT); binder.bindToRequest(request, RebootType.SOFT);
assertEquals("{\"reboot\":{\"type\":\"SOFT\"}}", request.getEntity()); assertEquals("{\"reboot\":{\"type\":\"SOFT\"}}", request.getEntity());
} }
@Test(expectedExceptions = { NullPointerException.class, IllegalStateException.class }) @Test(expectedExceptions = { NullPointerException.class, IllegalStateException.class })
public void testNullIsBad() { public void testNullIsBad() {
AddRebootTypeAsJsonEntity binder = new AddRebootTypeAsJsonEntity(); BindRebootTypeToJsonEntity binder = new BindRebootTypeToJsonEntity();
injector.injectMembers(binder); injector.injectMembers(binder);
HttpRequest request = new HttpRequest(HttpMethod.POST, URI.create("http://localhost")); HttpRequest request = new HttpRequest(HttpMethod.POST, URI.create("http://localhost"));
binder.decorateRequest(request, null); binder.bindToRequest(request, null);
} }
} }

View File

@ -21,8 +21,7 @@
* under the License. * under the License.
* ==================================================================== * ====================================================================
*/ */
package org.jclouds.rackspace.cloudservers.decorators; package org.jclouds.rackspace.cloudservers.binders;
import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertEquals;
import java.io.File; import java.io.File;
@ -38,46 +37,47 @@ import com.google.common.collect.ImmutableMap;
import com.google.inject.Guice; import com.google.inject.Guice;
import com.google.inject.Injector; import com.google.inject.Injector;
/** /**
* Tests behavior of {@code AddServerNameAsJsonEntity} * Tests behavior of {@code BindServerNameToJsonEntity}
* *
* @author Adrian Cole * @author Adrian Cole
*/ */
@Test(groups = "unit", testName = "cloudservers.AddServerNameAsJsonEntityTest") @Test(groups = "unit", testName = "cloudservers.BindServerNameToJsonEntityTest")
public class AddServerNameAsJsonEntityTest { public class BindServerNameToJsonEntityTest {
Injector injector = Guice.createInjector(new ParserModule()); Injector injector = Guice.createInjector(new ParserModule());
@Test(expectedExceptions = IllegalStateException.class) @Test(expectedExceptions = IllegalStateException.class)
public void testPostIsIncorrect() { public void testPostIsIncorrect() {
AddServerNameAsJsonEntity binder = new AddServerNameAsJsonEntity(); BindServerNameToJsonEntity binder = new BindServerNameToJsonEntity();
injector.injectMembers(binder); injector.injectMembers(binder);
HttpRequest request = new HttpRequest(HttpMethod.POST, URI.create("http://localhost")); HttpRequest request = new HttpRequest(HttpMethod.POST, URI.create("http://localhost"));
binder.decorateRequest(request, ImmutableMap.of("name", "foo")); binder.bindToRequest(request, ImmutableMap.of("name", "foo"));
} }
@Test(expectedExceptions = IllegalArgumentException.class) @Test(expectedExceptions = IllegalArgumentException.class)
public void testMustBeString() { public void testMustBeString() {
AddServerNameAsJsonEntity binder = new AddServerNameAsJsonEntity(); BindServerNameToJsonEntity binder = new BindServerNameToJsonEntity();
injector.injectMembers(binder); injector.injectMembers(binder);
HttpRequest request = new HttpRequest(HttpMethod.POST, URI.create("http://localhost")); HttpRequest request = new HttpRequest(HttpMethod.POST, URI.create("http://localhost"));
binder.decorateRequest(request, new File("foo")); binder.bindToRequest(request, new File("foo"));
} }
@Test @Test
public void testCorrect() { public void testCorrect() {
AddServerNameAsJsonEntity binder = new AddServerNameAsJsonEntity(); BindServerNameToJsonEntity binder = new BindServerNameToJsonEntity();
injector.injectMembers(binder); injector.injectMembers(binder);
HttpRequest request = new HttpRequest(HttpMethod.PUT, URI.create("http://localhost")); HttpRequest request = new HttpRequest(HttpMethod.PUT, URI.create("http://localhost"));
binder.decorateRequest(request, "foo"); binder.bindToRequest(request, "foo");
assertEquals("{\"server\":{\"name\":\"foo\"}}", request.getEntity()); assertEquals("{\"server\":{\"name\":\"foo\"}}", request.getEntity());
} }
@Test(expectedExceptions = { NullPointerException.class, IllegalStateException.class }) @Test(expectedExceptions = { NullPointerException.class, IllegalStateException.class })
public void testNullIsBad() { public void testNullIsBad() {
AddServerNameAsJsonEntity binder = new AddServerNameAsJsonEntity(); BindServerNameToJsonEntity binder = new BindServerNameToJsonEntity();
injector.injectMembers(binder); injector.injectMembers(binder);
HttpRequest request = new HttpRequest(HttpMethod.PUT, URI.create("http://localhost")); HttpRequest request = new HttpRequest(HttpMethod.PUT, URI.create("http://localhost"));
binder.decorateRequest(request, null); binder.bindToRequest(request, null);
} }
} }

View File

@ -63,7 +63,7 @@ public class CreateServerOptionsTest {
private HttpRequest buildRequest(CreateServerOptions options) { private HttpRequest buildRequest(CreateServerOptions options) {
injector.injectMembers(options); injector.injectMembers(options);
HttpRequest request = new HttpRequest(HttpMethod.POST, URI.create("http://localhost")); HttpRequest request = new HttpRequest(HttpMethod.POST, URI.create("http://localhost"));
options.decorateRequest(request, ImmutableMap.of("name", "foo", "imageId", "1", "flavorId", options.bindToRequest(request, ImmutableMap.of("name", "foo", "imageId", "1", "flavorId",
"2")); "2"));
return request; return request;
} }

View File

@ -58,7 +58,7 @@ public class CreateSharedIpGroupOptionsTest {
private HttpRequest buildRequest(CreateSharedIpGroupOptions options) { private HttpRequest buildRequest(CreateSharedIpGroupOptions options) {
injector.injectMembers(options); injector.injectMembers(options);
HttpRequest request = new HttpRequest(HttpMethod.POST, URI.create("http://localhost")); HttpRequest request = new HttpRequest(HttpMethod.POST, URI.create("http://localhost"));
options.decorateRequest(request, ImmutableMap.of("name", "foo")); options.bindToRequest(request, ImmutableMap.of("name", "foo"));
return request; return request;
} }

View File

@ -58,7 +58,7 @@ public class RebuildServerOptionsTest {
private HttpRequest buildRequest(RebuildServerOptions options) { private HttpRequest buildRequest(RebuildServerOptions options) {
injector.injectMembers(options); injector.injectMembers(options);
HttpRequest request = new HttpRequest(HttpMethod.POST, URI.create("http://localhost")); HttpRequest request = new HttpRequest(HttpMethod.POST, URI.create("http://localhost"));
options.decorateRequest(request, new HashMap<String, String>()); options.bindToRequest(request, new HashMap<String, String>());
return request; return request;
} }

View File

@ -27,16 +27,16 @@ import java.util.Collections;
import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.atomic.AtomicReference;
import javax.inject.Inject;
import javax.inject.Provider;
import javax.inject.Singleton;
import org.jclouds.http.HttpException; import org.jclouds.http.HttpException;
import org.jclouds.http.HttpRequest; import org.jclouds.http.HttpRequest;
import org.jclouds.http.HttpRequestFilter; import org.jclouds.http.HttpRequestFilter;
import org.jclouds.rackspace.Authentication; import org.jclouds.rackspace.Authentication;
import org.jclouds.rackspace.reference.RackspaceHeaders; import org.jclouds.rackspace.reference.RackspaceHeaders;
import javax.inject.Inject;
import javax.inject.Provider;
import javax.inject.Singleton;
/** /**
* Signs the Rackspace request. This will update the Authentication Token before 24 hours is up. * Signs the Rackspace request. This will update the Authentication Token before 24 hours is up.
* *
@ -88,10 +88,9 @@ public class AuthenticateRequest implements HttpRequestFilter {
authToken = new AtomicReference<String>(); authToken = new AtomicReference<String>();
} }
public HttpRequest filter(HttpRequest request) throws HttpException { public void filter(HttpRequest request) throws HttpException {
request.getHeaders().replaceValues(RackspaceHeaders.AUTH_TOKEN, request.getHeaders().replaceValues(RackspaceHeaders.AUTH_TOKEN,
Collections.singletonList(getAuthToken())); Collections.singletonList(getAuthToken()));
return request;
} }
} }