Issue 292: added simple http client

This commit is contained in:
Adrian Cole 2010-06-25 10:45:15 -07:00
parent 5afc44b2b7
commit 055c56dc08
49 changed files with 2277 additions and 1390 deletions

View File

@ -29,6 +29,8 @@ import org.jclouds.atmosonline.saas.AtmosStorageClient;
import org.jclouds.atmosonline.saas.reference.AtmosStorageConstants;
import org.jclouds.http.RequiresHttp;
import org.jclouds.lifecycle.Closer;
import org.jclouds.rest.HttpAsyncClient;
import org.jclouds.rest.HttpClient;
import org.jclouds.rest.RestContext;
import org.jclouds.rest.internal.RestContextImpl;
@ -48,12 +50,13 @@ public class AtmosStorageContextModule extends AbstractModule {
@Provides
@Singleton
RestContext<AtmosStorageClient, AtmosStorageAsyncClient> provideContext(Closer closer,
AtmosStorageAsyncClient async, AtmosStorageClient defaultApi,
@AtmosStorage URI endPoint,
@Named(AtmosStorageConstants.PROPERTY_EMCSAAS_UID) String account) {
return new RestContextImpl<AtmosStorageClient, AtmosStorageAsyncClient>(closer, async,
defaultApi, endPoint, account);
RestContext<AtmosStorageClient, AtmosStorageAsyncClient> provideContext(
Closer closer, HttpClient http, HttpAsyncClient asyncHttp,
AtmosStorageAsyncClient async, AtmosStorageClient defaultApi,
@AtmosStorage URI endPoint,
@Named(AtmosStorageConstants.PROPERTY_EMCSAAS_UID) String account) {
return new RestContextImpl<AtmosStorageClient, AtmosStorageAsyncClient>(
closer, http, asyncHttp, defaultApi, async, endPoint, account);
}
}

View File

@ -30,6 +30,8 @@ import org.jclouds.aws.reference.AWSConstants;
import org.jclouds.http.functions.config.ParserModule.CDateAdapter;
import org.jclouds.http.functions.config.ParserModule.DateAdapter;
import org.jclouds.lifecycle.Closer;
import org.jclouds.rest.HttpAsyncClient;
import org.jclouds.rest.HttpClient;
import org.jclouds.rest.RestContext;
import org.jclouds.rest.internal.RestContextImpl;
@ -50,10 +52,11 @@ public class EC2ContextModule extends AbstractModule {
@Provides
@Singleton
RestContext<EC2Client, EC2AsyncClient> provideContext(Closer closer,
EC2AsyncClient defaultApi, EC2Client synchApi, @EC2 URI endPoint,
HttpClient http, HttpAsyncClient asyncHttp, EC2AsyncClient defaultApi,
EC2Client synchApi, @EC2 URI endPoint,
@Named(AWSConstants.PROPERTY_AWS_ACCESSKEYID) String account) {
return new RestContextImpl<EC2Client, EC2AsyncClient>(closer, defaultApi,
synchApi, endPoint, account);
return new RestContextImpl<EC2Client, EC2AsyncClient>(closer, http,
asyncHttp, synchApi, defaultApi, endPoint, account);
}
}

View File

@ -28,6 +28,8 @@ import org.jclouds.aws.s3.S3;
import org.jclouds.aws.s3.S3AsyncClient;
import org.jclouds.aws.s3.S3Client;
import org.jclouds.lifecycle.Closer;
import org.jclouds.rest.HttpAsyncClient;
import org.jclouds.rest.HttpClient;
import org.jclouds.rest.RestContext;
import org.jclouds.rest.internal.RestContextImpl;
@ -47,11 +49,12 @@ public class S3ContextModule extends AbstractModule {
@Provides
@Singleton
RestContext<S3Client, S3AsyncClient> provideContext(Closer closer, S3AsyncClient defaultApi,
S3Client syncApi, @S3 URI endPoint,
@Named(AWSConstants.PROPERTY_AWS_ACCESSKEYID) String account) {
return new RestContextImpl<S3Client, S3AsyncClient>(closer, defaultApi, syncApi, endPoint,
account);
RestContext<S3Client, S3AsyncClient> provideContext(Closer closer,
HttpClient http, HttpAsyncClient asyncHttp, S3AsyncClient defaultApi,
S3Client syncApi, @S3 URI endPoint,
@Named(AWSConstants.PROPERTY_AWS_ACCESSKEYID) String account) {
return new RestContextImpl<S3Client, S3AsyncClient>(closer, http,
asyncHttp, syncApi, defaultApi, endPoint, account);
}
}

View File

@ -30,6 +30,8 @@ import org.jclouds.aws.sqs.SQSClient;
import org.jclouds.http.functions.config.ParserModule.CDateAdapter;
import org.jclouds.http.functions.config.ParserModule.DateAdapter;
import org.jclouds.lifecycle.Closer;
import org.jclouds.rest.HttpAsyncClient;
import org.jclouds.rest.HttpClient;
import org.jclouds.rest.RestContext;
import org.jclouds.rest.internal.RestContextImpl;
@ -52,11 +54,12 @@ public class SQSContextModule extends AbstractModule {
@Provides
@Singleton
RestContext<SQSClient, SQSAsyncClient> provideContext(Closer closer, SQSAsyncClient defaultApi,
SQSClient synchApi, @SQS URI endPoint,
@Named(AWSConstants.PROPERTY_AWS_ACCESSKEYID) String account) {
return new RestContextImpl<SQSClient, SQSAsyncClient>(closer, defaultApi, synchApi, endPoint,
account);
RestContext<SQSClient, SQSAsyncClient> provideContext(Closer closer,
HttpClient http, HttpAsyncClient asyncHttp, SQSAsyncClient defaultApi,
SQSClient synchApi, @SQS URI endPoint,
@Named(AWSConstants.PROPERTY_AWS_ACCESSKEYID) String account) {
return new RestContextImpl<SQSClient, SQSAsyncClient>(closer, http,
asyncHttp, synchApi, defaultApi, endPoint, account);
}
}

View File

@ -39,7 +39,8 @@ import com.google.inject.TypeLiteral;
* @author Adrian Cole
*/
@ConfiguresRestClient
public class S3StubClientModule extends RestClientModule<S3Client, S3AsyncClient> {
public class S3StubClientModule extends
RestClientModule<S3Client, S3AsyncClient> {
public S3StubClientModule() {
super(S3Client.class, S3AsyncClient.class);
@ -50,7 +51,8 @@ public class S3StubClientModule extends RestClientModule<S3Client, S3AsyncClient
install(new S3ObjectModule());
install(new ParserModule());
install(new TransientBlobStoreModule());
bind(URI.class).annotatedWith(S3.class).toInstance(URI.create("https://localhost/s3stub"));
bind(URI.class).annotatedWith(S3.class).toInstance(
URI.create("https://localhost/s3stub"));
bind(String.class).annotatedWith(S3.class).toInstance(Region.US_STANDARD);
bind(new TypeLiteral<Set<String>>() {
}).annotatedWith(S3.class).toInstance(Region.ALL_S3);
@ -60,5 +62,4 @@ public class S3StubClientModule extends RestClientModule<S3Client, S3AsyncClient
protected void bindAsyncClient() {
bind(S3AsyncClient.class).to(StubS3AsyncClient.class).asEagerSingleton();
}
}

View File

@ -29,6 +29,8 @@ import org.jclouds.azure.storage.blob.AzureBlobClient;
import org.jclouds.azure.storage.reference.AzureStorageConstants;
import org.jclouds.http.RequiresHttp;
import org.jclouds.lifecycle.Closer;
import org.jclouds.rest.HttpAsyncClient;
import org.jclouds.rest.HttpClient;
import org.jclouds.rest.RestContext;
import org.jclouds.rest.internal.RestContextImpl;
@ -48,11 +50,16 @@ public class AzureBlobContextModule extends AbstractModule {
@Provides
@Singleton
RestContext<AzureBlobClient, AzureBlobAsyncClient> provideContext(Closer closer,
AzureBlobAsyncClient asyncApi, AzureBlobClient defaultApi, @AzureBlob URI endPoint,
@Named(AzureStorageConstants.PROPERTY_AZURESTORAGE_ACCOUNT) String account) {
return new RestContextImpl<AzureBlobClient, AzureBlobAsyncClient>(closer, asyncApi,
defaultApi, endPoint, account);
RestContext<AzureBlobClient, AzureBlobAsyncClient> provideContext(
Closer closer,
HttpClient http,
HttpAsyncClient asyncHttp,
AzureBlobAsyncClient asyncApi,
AzureBlobClient defaultApi,
@AzureBlob URI endPoint,
@Named(AzureStorageConstants.PROPERTY_AZURESTORAGE_ACCOUNT) String account) {
return new RestContextImpl<AzureBlobClient, AzureBlobAsyncClient>(closer,
http, asyncHttp, defaultApi, asyncApi, endPoint, account);
}
}

View File

@ -29,6 +29,8 @@ import org.jclouds.azure.storage.queue.AzureQueueClient;
import org.jclouds.azure.storage.reference.AzureStorageConstants;
import org.jclouds.http.RequiresHttp;
import org.jclouds.lifecycle.Closer;
import org.jclouds.rest.HttpAsyncClient;
import org.jclouds.rest.HttpClient;
import org.jclouds.rest.RestContext;
import org.jclouds.rest.internal.RestContextImpl;
@ -47,11 +49,16 @@ public class AzureQueueContextModule extends AbstractModule {
@Provides
@Singleton
RestContext<AzureQueueClient, AzureQueueAsyncClient> provideContext(Closer closer,
AzureQueueAsyncClient asynchApi, AzureQueueClient defaultApi, @AzureQueue URI endPoint,
@Named(AzureStorageConstants.PROPERTY_AZURESTORAGE_ACCOUNT) String account) {
return new RestContextImpl<AzureQueueClient, AzureQueueAsyncClient>(closer, asynchApi,
defaultApi, endPoint, account);
RestContext<AzureQueueClient, AzureQueueAsyncClient> provideContext(
Closer closer,
HttpClient http,
HttpAsyncClient asyncHttp,
AzureQueueAsyncClient asynchApi,
AzureQueueClient defaultApi,
@AzureQueue URI endPoint,
@Named(AzureStorageConstants.PROPERTY_AZURESTORAGE_ACCOUNT) String account) {
return new RestContextImpl<AzureQueueClient, AzureQueueAsyncClient>(
closer, http, asyncHttp, defaultApi, asynchApi, endPoint, account);
}
}

View File

@ -14,6 +14,8 @@ import org.jclouds.domain.Location;
import org.jclouds.domain.LocationScope;
import org.jclouds.domain.internal.LocationImpl;
import org.jclouds.lifecycle.Closer;
import org.jclouds.rest.HttpAsyncClient;
import org.jclouds.rest.HttpClient;
import org.jclouds.rest.RestContext;
import org.jclouds.rest.config.RestClientModule;
import org.jclouds.rest.internal.RestContextImpl;
@ -23,12 +25,13 @@ import com.google.inject.Scopes;
import com.google.inject.TypeLiteral;
/**
* Configures the {@link TransientBlobStoreContext}; requires {@link TransientAsyncBlobStore} bound.
* Configures the {@link TransientBlobStoreContext}; requires
* {@link TransientAsyncBlobStore} bound.
*
* @author Adrian Cole
*/
public class TransientBlobStoreContextModule extends
RestClientModule<TransientBlobStore, AsyncBlobStore> {
RestClientModule<TransientBlobStore, AsyncBlobStore> {
public TransientBlobStoreContextModule() {
super(TransientBlobStore.class, AsyncBlobStore.class);
@ -40,9 +43,10 @@ public class TransientBlobStoreContextModule extends
install(new BlobStoreObjectModule());
install(new BlobStoreMapModule());
bind(ConsistencyModel.class).toInstance(ConsistencyModel.STRICT);
bind(BlobStoreContext.class).to(
new TypeLiteral<BlobStoreContextImpl<TransientBlobStore, AsyncBlobStore>>() {
}).in(Scopes.SINGLETON);
bind(BlobStoreContext.class)
.to(
new TypeLiteral<BlobStoreContextImpl<TransientBlobStore, AsyncBlobStore>>() {
}).in(Scopes.SINGLETON);
}
@Provides
@ -54,20 +58,25 @@ public class TransientBlobStoreContextModule extends
@Provides
@Singleton
Location provideDefaultLocation() {
return new LocationImpl(LocationScope.PROVIDER, "transient", "transient", null);
}
@Provides
@Singleton
RestContext<TransientBlobStore, AsyncBlobStore> provideContext(Closer closer,
final AsyncBlobStore async, TransientBlobStore sync) {
return new RestContextImpl<TransientBlobStore, AsyncBlobStore>(closer, async, sync, URI
.create("http://localhost/transient"), System.getProperty("user.name"));
return new LocationImpl(LocationScope.PROVIDER, "transient", "transient",
null);
}
@Override
protected void bindAsyncClient() {
bind(AsyncBlobStore.class).to(TransientAsyncBlobStore.class).asEagerSingleton();
bind(AsyncBlobStore.class).to(TransientAsyncBlobStore.class)
.asEagerSingleton();
}
@Provides
@Singleton
RestContext<TransientBlobStore, AsyncBlobStore> provideContext(
Closer closer, HttpClient http, HttpAsyncClient asyncHttp,
TransientBlobStore sync, AsyncBlobStore async) {
return new RestContextImpl<TransientBlobStore, AsyncBlobStore>(closer,
http, asyncHttp, sync, async, URI
.create("http://localhost/transient"), System
.getProperty("user.name"));
}
}

View File

@ -29,13 +29,16 @@ import org.jclouds.blobstore.TransientAsyncBlobStore;
import org.jclouds.blobstore.domain.Blob;
import org.jclouds.domain.Location;
import org.jclouds.internal.ClassMethodArgs;
import com.google.inject.name.Names;
import org.jclouds.rest.HttpAsyncClient;
import org.jclouds.rest.HttpClient;
import org.jclouds.rest.config.BinderUtils;
import com.google.common.collect.ImmutableSet;
import com.google.inject.AbstractModule;
import com.google.inject.Provides;
import com.google.inject.Scopes;
import com.google.inject.TypeLiteral;
import com.google.inject.name.Names;
public class TransientBlobStoreModule extends AbstractModule {
@ -45,17 +48,20 @@ public class TransientBlobStoreModule extends AbstractModule {
@Override
protected void configure() {
bind(new TypeLiteral<ConcurrentMap<String, ConcurrentMap<String, Blob>>>() {
}).toInstance(map);
bind(
new TypeLiteral<ConcurrentMap<String, ConcurrentMap<String, Blob>>>() {
}).toInstance(map);
bind(new TypeLiteral<ConcurrentMap<String, Location>>() {
}).toInstance(containerToLocation);
// delegation on stubs is not currently supported
bind(new TypeLiteral<ConcurrentMap<ClassMethodArgs, Object>>() {
}).annotatedWith(Names.named("async")).toInstance(
new ConcurrentHashMap<ClassMethodArgs, Object>());
new ConcurrentHashMap<ClassMethodArgs, Object>());
bind(TransientAsyncBlobStore.class).in(Scopes.SINGLETON);
bindConstant().annotatedWith(Names.named(Constants.PROPERTY_USER_THREADS)).to(0);
bindConstant().annotatedWith(Names.named(Constants.PROPERTY_IO_WORKER_THREADS)).to(0);
bindConstant()
.annotatedWith(Names.named(Constants.PROPERTY_USER_THREADS)).to(0);
bindConstant().annotatedWith(
Names.named(Constants.PROPERTY_IO_WORKER_THREADS)).to(0);
}
@Provides
@ -63,4 +69,17 @@ public class TransientBlobStoreModule extends AbstractModule {
Set<Location> provideLocations(Location defaultLocation) {
return ImmutableSet.of(defaultLocation);
}
@Provides
@Singleton
HttpClient provideClient() {
return BinderUtils.newNullProxy(HttpClient.class);
}
@Provides
@Singleton
HttpAsyncClient provideAsyncClient() {
return BinderUtils.newNullProxy(HttpAsyncClient.class);
}
}

View File

@ -46,13 +46,15 @@ import java.net.URI;
import javax.inject.Named;
import javax.inject.Singleton;
import org.jclouds.lifecycle.Closer;
import org.jclouds.rest.RestContext;
import org.jclouds.rest.internal.RestContextImpl;
import org.jclouds.boxdotnet.BoxDotNet;
import org.jclouds.boxdotnet.BoxDotNetAsyncClient;
import org.jclouds.boxdotnet.BoxDotNetClient;
import org.jclouds.boxdotnet.reference.BoxDotNetConstants;
import org.jclouds.lifecycle.Closer;
import org.jclouds.rest.HttpAsyncClient;
import org.jclouds.rest.HttpClient;
import org.jclouds.rest.RestContext;
import org.jclouds.rest.internal.RestContextImpl;
import com.google.inject.AbstractModule;
import com.google.inject.Provides;
@ -63,11 +65,11 @@ import com.google.inject.Provides;
* @author Adrian Cole
*/
public class BoxDotNetContextModule extends AbstractModule {
public BoxDotNetContextModule(String providerName) {
// providerName ignored right now
}
@Override
protected void configure() {
// example of how to customize bindings
@ -76,9 +78,13 @@ public class BoxDotNetContextModule extends AbstractModule {
@Provides
@Singleton
RestContext<BoxDotNetClient, BoxDotNetAsyncClient> provideContext(Closer closer, BoxDotNetAsyncClient asyncApi,
BoxDotNetClient syncApi, @BoxDotNet URI endPoint, @Named(BoxDotNetConstants.PROPERTY_BOXDOTNET_USER) String account) {
return new RestContextImpl<BoxDotNetClient, BoxDotNetAsyncClient>(closer, asyncApi, syncApi, endPoint, account);
RestContext<BoxDotNetClient, BoxDotNetAsyncClient> provideContext(
Closer closer, HttpClient http, HttpAsyncClient asyncHttp,
BoxDotNetAsyncClient asyncApi, BoxDotNetClient syncApi,
@BoxDotNet URI endPoint,
@Named(BoxDotNetConstants.PROPERTY_BOXDOTNET_USER) String account) {
return new RestContextImpl<BoxDotNetClient, BoxDotNetAsyncClient>(closer,
http, asyncHttp, syncApi, asyncApi, endPoint, account);
}
}

View File

@ -37,14 +37,18 @@ import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.MediaType;
import org.jclouds.chef.binders.BindChecksumsToJsonPayload;
import org.jclouds.chef.binders.BindClientnameToJsonPayload;
import org.jclouds.chef.binders.BindGenerateKeyForClientToJsonPayload;
import org.jclouds.chef.domain.Sandbox;
import org.jclouds.chef.filters.SignedHeaderAuth;
import org.jclouds.chef.functions.ParseKeyFromJson;
import org.jclouds.chef.functions.ParseKeySetFromJson;
import org.jclouds.chef.functions.ParseSandboxFromJson;
import org.jclouds.rest.annotations.BinderParam;
import org.jclouds.rest.annotations.Endpoint;
import org.jclouds.rest.annotations.ExceptionParser;
import org.jclouds.rest.annotations.Headers;
import org.jclouds.rest.annotations.PartParam;
import org.jclouds.rest.annotations.RequestFilters;
import org.jclouds.rest.annotations.ResponseParser;
@ -65,7 +69,18 @@ import com.google.common.util.concurrent.ListenableFuture;
@Endpoint(Chef.class)
@RequestFilters(SignedHeaderAuth.class)
@Consumes(MediaType.APPLICATION_JSON)
@Headers(keys = "X-Chef-Version", values = "0.9.0")
public interface ChefAsyncClient {
/**
* @see ChefClient#getUploadUrisForContent
*/
@POST
@Path("sandboxes")
@ResponseParser(ParseSandboxFromJson.class)
ListenableFuture<Sandbox> getUploadUrisForContent(
@BinderParam(BindChecksumsToJsonPayload.class) Set<String> checksums);
/**
* @see ChefCookbooks#listCookbooks
*/

View File

@ -45,6 +45,7 @@ import java.io.File;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.jclouds.chef.domain.Sandbox;
import org.jclouds.concurrent.Timeout;
import org.jclouds.http.HttpResponseException;
import org.jclouds.rest.AuthorizationException;
@ -60,6 +61,7 @@ import org.jclouds.rest.ResourceNotFoundException;
*/
@Timeout(duration = 30, timeUnit = TimeUnit.SECONDS)
public interface ChefClient {
Sandbox getUploadUrisForContent(Set<String> checksums);
/**
*

View File

@ -46,13 +46,15 @@ import java.net.URI;
import javax.inject.Named;
import javax.inject.Singleton;
import org.jclouds.lifecycle.Closer;
import org.jclouds.rest.RestContext;
import org.jclouds.rest.internal.RestContextImpl;
import org.jclouds.chef.Chef;
import org.jclouds.chef.ChefAsyncClient;
import org.jclouds.chef.ChefClient;
import org.jclouds.chef.reference.ChefConstants;
import org.jclouds.lifecycle.Closer;
import org.jclouds.rest.HttpAsyncClient;
import org.jclouds.rest.HttpClient;
import org.jclouds.rest.RestContext;
import org.jclouds.rest.internal.RestContextImpl;
import com.google.inject.AbstractModule;
import com.google.inject.Provides;
@ -63,11 +65,11 @@ import com.google.inject.Provides;
* @author Adrian Cole
*/
public class ChefContextModule extends AbstractModule {
public ChefContextModule(String providerName) {
// providerName ignored right now
}
@Override
protected void configure() {
// example of how to customize bindings
@ -76,9 +78,12 @@ public class ChefContextModule extends AbstractModule {
@Provides
@Singleton
RestContext<ChefClient, ChefAsyncClient> provideContext(Closer closer, ChefAsyncClient asyncApi,
ChefClient syncApi, @Chef URI endPoint, @Named(ChefConstants.PROPERTY_CHEF_IDENTITY) String account) {
return new RestContextImpl<ChefClient, ChefAsyncClient>(closer, asyncApi, syncApi, endPoint, account);
RestContext<ChefClient, ChefAsyncClient> provideContext(Closer closer,
HttpClient http, HttpAsyncClient asyncHttp, ChefAsyncClient asyncApi,
ChefClient syncApi, @Chef URI endPoint,
@Named(ChefConstants.PROPERTY_CHEF_IDENTITY) String account) {
return new RestContextImpl<ChefClient, ChefAsyncClient>(closer, http,
asyncHttp, syncApi, asyncApi, endPoint, account);
}
}

View File

@ -99,15 +99,26 @@ public class User implements Comparable<User> {
this.email = email;
}
public void setPassword(String password) {
this.password = password;
}
public String getPassword() {
return password;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((displayName == null) ? 0 : displayName.hashCode());
result = prime * result
+ ((displayName == null) ? 0 : displayName.hashCode());
result = prime * result + ((email == null) ? 0 : email.hashCode());
result = prime * result + ((firstName == null) ? 0 : firstName.hashCode());
result = prime * result
+ ((firstName == null) ? 0 : firstName.hashCode());
result = prime * result + ((lastName == null) ? 0 : lastName.hashCode());
result = prime * result + ((middleName == null) ? 0 : middleName.hashCode());
result = prime * result
+ ((middleName == null) ? 0 : middleName.hashCode());
result = prime * result + ((password == null) ? 0 : password.hashCode());
result = prime * result + ((username == null) ? 0 : username.hashCode());
return result;
@ -162,16 +173,10 @@ public class User implements Comparable<User> {
@Override
public String toString() {
return "User [username=" + username + ", displayName=" + displayName + ", firstName="
+ firstName + ", middleName=" + middleName + ", lastName=" + lastName + ", email="
+ email + "]";
return "User [displayName=" + displayName + ", email=" + email
+ ", firstName=" + firstName + ", lastName=" + lastName
+ ", middleName=" + middleName + ", password=" + password
+ ", username=" + username + "]";
}
public void setPassword(String password) {
this.password = password;
}
public String getPassword() {
return password;
}
}

View File

@ -28,12 +28,14 @@ import static org.testng.Assert.assertEquals;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Set;
import org.jclouds.chef.config.ChefRestClientModule;
import org.jclouds.chef.filters.SignedHeaderAuth;
import org.jclouds.chef.filters.SignedHeaderAuthTest;
import org.jclouds.chef.functions.ParseKeyFromJson;
import org.jclouds.chef.functions.ParseKeySetFromJson;
import org.jclouds.chef.functions.ParseSandboxFromJson;
import org.jclouds.date.TimeStamp;
import org.jclouds.http.functions.CloseContentAndReturn;
import org.jclouds.http.functions.ReturnStringIf200;
@ -48,6 +50,7 @@ import org.jclouds.rest.internal.RestAnnotationProcessor;
import org.testng.annotations.Test;
import com.google.common.base.Supplier;
import com.google.common.collect.ImmutableSet;
import com.google.common.io.Files;
import com.google.inject.Module;
import com.google.inject.TypeLiteral;
@ -61,6 +64,34 @@ import com.google.inject.name.Names;
@Test(groups = "unit", testName = "chef.ChefAsyncClientTest")
public class ChefAsyncClientTest extends RestClientTest<ChefAsyncClient> {
public void testGetUploadUrisForContent() throws SecurityException,
NoSuchMethodException, IOException {
Method method = ChefAsyncClient.class.getMethod(
"getUploadUrisForContent", Set.class);
GeneratedHttpRequest<ChefAsyncClient> httpRequest = processor
.createRequest(method, ImmutableSet.of(
"0189e76ccc476701d6b374e5a1a27347",
"0c5ecd7788cf4f6c7de2a57193897a6c",
"1dda05ed139664f1f89b9dec482b77c0"));
assertRequestLineEquals(httpRequest,
"POST http://localhost:4000/sandboxes HTTP/1.1");
assertHeadersEqual(
httpRequest,
"Accept: application/json\nContent-Length: 135\nContent-Type: application/json\nX-Chef-Version: 0.9.0\n");
assertPayloadEquals(
httpRequest,
"{\"checksums\":{\"0189e76ccc476701d6b374e5a1a27347\":null,\"0c5ecd7788cf4f6c7de2a57193897a6c\":null,\"1dda05ed139664f1f89b9dec482b77c0\":null}}");
assertResponseParserClassEquals(method, httpRequest,
ParseSandboxFromJson.class);
assertSaxResponseParserClassEquals(method, null);
assertExceptionParserClassEquals(method, null);
checkFilters(httpRequest);
}
public void testGetCookbook() throws SecurityException,
NoSuchMethodException, IOException {
Method method = ChefAsyncClient.class.getMethod("getCookbook",
@ -69,7 +100,8 @@ public class ChefAsyncClientTest extends RestClientTest<ChefAsyncClient> {
.createRequest(method, "cookbook");
assertRequestLineEquals(httpRequest,
"GET http://localhost:4000/cookbooks/cookbook HTTP/1.1");
assertHeadersEqual(httpRequest, "Accept: application/json\n");
assertHeadersEqual(httpRequest,
"Accept: application/json\nX-Chef-Version: 0.9.0\n");
assertPayloadEquals(httpRequest, null);
assertResponseParserClassEquals(method, httpRequest,
@ -89,7 +121,8 @@ public class ChefAsyncClientTest extends RestClientTest<ChefAsyncClient> {
.createRequest(method, "cookbook");
assertRequestLineEquals(httpRequest,
"DELETE http://localhost:4000/cookbooks/cookbook HTTP/1.1");
assertHeadersEqual(httpRequest, "Accept: application/json\n");
assertHeadersEqual(httpRequest,
"Accept: application/json\nX-Chef-Version: 0.9.0\n");
assertPayloadEquals(httpRequest, null);
assertResponseParserClassEquals(method, httpRequest,
@ -128,7 +161,7 @@ public class ChefAsyncClientTest extends RestClientTest<ChefAsyncClient> {
httpRequest,
"Accept: application/json\nContent-Length: "
+ (file.getName().length() + 206)
+ "\nContent-Type: multipart/form-data; boundary=--JCLOUDS--\n");
+ "\nContent-Type: multipart/form-data; boundary=--JCLOUDS--\nX-Chef-Version: 0.9.0\n");
assertPayloadEquals(httpRequest, COOOKBOOK_BODY.replace(
"cookbook.tar.gz", file.getName()));
@ -152,7 +185,7 @@ public class ChefAsyncClientTest extends RestClientTest<ChefAsyncClient> {
"POST http://localhost:4000/cookbooks HTTP/1.1");
assertHeadersEqual(
httpRequest,
"Accept: application/json\nContent-Length: 221\nContent-Type: multipart/form-data; boundary=--JCLOUDS--\n");
"Accept: application/json\nContent-Length: 221\nContent-Type: multipart/form-data; boundary=--JCLOUDS--\nX-Chef-Version: 0.9.0\n");
assertPayloadEquals(httpRequest, COOOKBOOK_BODY);
assertResponseParserClassEquals(method, httpRequest,
@ -181,7 +214,7 @@ public class ChefAsyncClientTest extends RestClientTest<ChefAsyncClient> {
httpRequest,
"Accept: application/json\nContent-Length: "
+ (file.getName().length() + 206)
+ "\nContent-Type: multipart/form-data; boundary=--JCLOUDS--\n");
+ "\nContent-Type: multipart/form-data; boundary=--JCLOUDS--\nX-Chef-Version: 0.9.0\n");
assertPayloadEquals(httpRequest, COOOKBOOK_BODY.replace(
"cookbook.tar.gz", file.getName()));
@ -205,7 +238,7 @@ public class ChefAsyncClientTest extends RestClientTest<ChefAsyncClient> {
"PUT http://localhost:4000/cookbooks/cookbook/_content HTTP/1.1");
assertHeadersEqual(
httpRequest,
"Accept: application/json\nContent-Length: 221\nContent-Type: multipart/form-data; boundary=--JCLOUDS--\n");
"Accept: application/json\nContent-Length: 221\nContent-Type: multipart/form-data; boundary=--JCLOUDS--\nX-Chef-Version: 0.9.0\n");
assertPayloadEquals(httpRequest, COOOKBOOK_BODY);
assertResponseParserClassEquals(method, httpRequest,
@ -225,7 +258,8 @@ public class ChefAsyncClientTest extends RestClientTest<ChefAsyncClient> {
assertRequestLineEquals(httpRequest,
"GET http://localhost:4000/cookbooks HTTP/1.1");
assertHeadersEqual(httpRequest, "Accept: application/json\n");
assertHeadersEqual(httpRequest,
"Accept: application/json\nX-Chef-Version: 0.9.0\n");
assertPayloadEquals(httpRequest, null);
assertResponseParserClassEquals(method, httpRequest,
@ -245,7 +279,8 @@ public class ChefAsyncClientTest extends RestClientTest<ChefAsyncClient> {
.createRequest(method, "client");
assertRequestLineEquals(httpRequest,
"HEAD http://localhost:4000/clients/client HTTP/1.1");
assertHeadersEqual(httpRequest, "Accept: application/json\n");
assertHeadersEqual(httpRequest,
"Accept: application/json\nX-Chef-Version: 0.9.0\n");
assertPayloadEquals(httpRequest, null);
assertResponseParserClassEquals(method, httpRequest,
@ -265,7 +300,8 @@ public class ChefAsyncClientTest extends RestClientTest<ChefAsyncClient> {
.createRequest(method, "client");
assertRequestLineEquals(httpRequest,
"DELETE http://localhost:4000/clients/client HTTP/1.1");
assertHeadersEqual(httpRequest, "Accept: application/json\n");
assertHeadersEqual(httpRequest,
"Accept: application/json\nX-Chef-Version: 0.9.0\n");
assertPayloadEquals(httpRequest, null);
assertResponseParserClassEquals(method, httpRequest,
@ -287,7 +323,7 @@ public class ChefAsyncClientTest extends RestClientTest<ChefAsyncClient> {
"PUT http://localhost:4000/clients/client HTTP/1.1");
assertHeadersEqual(
httpRequest,
"Accept: application/json\nContent-Length: 44\nContent-Type: application/json\n");
"Accept: application/json\nContent-Length: 44\nContent-Type: application/json\nX-Chef-Version: 0.9.0\n");
assertPayloadEquals(httpRequest,
"{\"clientname\":\"client\", \"private_key\": true}");
@ -311,7 +347,7 @@ public class ChefAsyncClientTest extends RestClientTest<ChefAsyncClient> {
"POST http://localhost:4000/clients HTTP/1.1");
assertHeadersEqual(
httpRequest,
"Accept: application/json\nContent-Length: 23\nContent-Type: application/json\n");
"Accept: application/json\nContent-Length: 23\nContent-Type: application/json\nX-Chef-Version: 0.9.0\n");
assertPayloadEquals(httpRequest, "{\"clientname\":\"client\"}");
assertResponseParserClassEquals(method, httpRequest,
@ -331,7 +367,8 @@ public class ChefAsyncClientTest extends RestClientTest<ChefAsyncClient> {
assertRequestLineEquals(httpRequest,
"GET http://localhost:4000/clients HTTP/1.1");
assertHeadersEqual(httpRequest, "Accept: application/json\n");
assertHeadersEqual(httpRequest,
"Accept: application/json\nX-Chef-Version: 0.9.0\n");
assertPayloadEquals(httpRequest, null);
assertResponseParserClassEquals(method, httpRequest,

View File

@ -66,8 +66,11 @@ import org.jclouds.domain.internal.LocationImpl;
import org.jclouds.lifecycle.Closer;
import org.jclouds.net.IPSocket;
import org.jclouds.predicates.SocketOpen;
import org.jclouds.rest.HttpAsyncClient;
import org.jclouds.rest.HttpClient;
import org.jclouds.rest.ResourceNotFoundException;
import org.jclouds.rest.RestContext;
import org.jclouds.rest.config.BinderUtils;
import org.jclouds.rest.internal.RestContextImpl;
import com.google.common.base.Predicate;
@ -154,12 +157,26 @@ public class StubComputeServiceContextModule extends AbstractModule {
}
@Provides
@Singleton
HttpClient provideClient() {
return BinderUtils.newNullProxy(HttpClient.class);
}
@Provides
@Singleton
HttpAsyncClient provideAsyncClient() {
return BinderUtils.newNullProxy(HttpAsyncClient.class);
}
@SuppressWarnings("unchecked")
@Provides
@Singleton
RestContext<ConcurrentMap, ConcurrentMap> provideRestContext(Closer closer) {
return new RestContextImpl<ConcurrentMap, ConcurrentMap>(closer, nodes,
nodes, URI.create("http://stub"), System.getProperty("user.name"));
RestContext<ConcurrentMap, ConcurrentMap> provideRestContext(Closer closer,
HttpClient http, HttpAsyncClient asyncHttp) {
return new RestContextImpl<ConcurrentMap, ConcurrentMap>(closer, http,
asyncHttp, nodes, nodes, URI.create("http://stub"), System
.getProperty("user.name"));
}
// NORMAL STUFF

View File

@ -30,7 +30,7 @@ import com.google.common.io.InputSupplier;
public interface Payload extends InputSupplier<InputStream> {
/**
*  Creates a new InputStream object of the payload.
* Creates a new InputStream object of the payload.
*/
InputStream getInput();
@ -45,7 +45,7 @@ public interface Payload extends InputSupplier<InputStream> {
boolean isRepeatable();
/**
*  Writes the payload content to the output stream.
* Writes the payload content to the output stream.
*
* @throws IOException
*/

View File

@ -0,0 +1,59 @@
package org.jclouds.rest;
import java.io.InputStream;
import java.net.URI;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.HEAD;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import org.jclouds.http.Payload;
import org.jclouds.rest.annotations.EndpointParam;
import org.jclouds.rest.annotations.ExceptionParser;
import org.jclouds.rest.functions.ReturnFalseOnNotFoundOr404;
import org.jclouds.rest.functions.ReturnNullOnNotFoundOr404;
import com.google.common.util.concurrent.ListenableFuture;
/**
* Simple rest client
*
* @author Adrian Cole
*/
public interface HttpAsyncClient {
/**
* @see HttpClient#post
*/
@PUT
ListenableFuture<Void> put(@EndpointParam URI location, Payload payload);
/**
* @see HttpClient#post
*/
@POST
ListenableFuture<Void> post(@EndpointParam URI location, Payload payload);
/**
* @see HttpClient#exists
*/
@HEAD
@ExceptionParser(ReturnFalseOnNotFoundOr404.class)
ListenableFuture<Boolean> exists(@EndpointParam URI location);
/**
* @see HttpClient#get
*/
@GET
@ExceptionParser(ReturnNullOnNotFoundOr404.class)
ListenableFuture<InputStream> get(@EndpointParam URI location);
/**
* @see HttpClient#delete
*/
@DELETE
@ExceptionParser(ReturnFalseOnNotFoundOr404.class)
ListenableFuture<Boolean> delete(@EndpointParam URI location);
}

View File

@ -0,0 +1,51 @@
/**
*
* Copyright (C) 2009 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.jclouds.rest;
import java.io.InputStream;
import java.net.URI;
import java.util.concurrent.TimeUnit;
import org.jclouds.concurrent.Timeout;
import org.jclouds.http.Payload;
/**
* Simple client
*
* @author Adrian Cole
*/
@Timeout(duration = 30, timeUnit = TimeUnit.SECONDS)
public interface HttpClient {
void put(URI location, Payload payload);
void post(URI location, Payload payload);
boolean exists(URI location);
/**
* @return null if the resource didn't exist.
*/
InputStream get(URI location);
/**
* @return false if the resource didn't exist.
*/
boolean delete(URI location);
}

View File

@ -28,8 +28,8 @@ import com.google.inject.ImplementedBy;
/**
* Represents an authenticated context to the cloud.
*
* <h2>Note</h2> Please issue {@link #close()} when you are finished with this context in order to
* release resources.
* <h2>Note</h2> Please issue {@link #close()} when you are finished with this
* context in order to release resources.
*
*
* @author Adrian Cole
@ -39,20 +39,26 @@ import com.google.inject.ImplementedBy;
public interface RestContext<S, A> {
/**
* low-level api to the cloud. Threadsafe implementations will return a singleton.
* low-level api to the cloud. Threadsafe implementations will return a
* singleton.
*
* @return a connection to the cloud where all methods return {@link ListenableFuture}s
* @return a connection to the cloud where all methods return
* {@link ListenableFuture}s
*/
A getAsyncApi();
/**
* reflects a tuned connection to the cloud which calls {@link #getAsyncApi()} with predetermined
* timeouts.
* reflects a tuned connection to the cloud which calls
* {@link #getAsyncApi()} with predetermined timeouts.
*
* @return a connection to the cloud where all methods block
*/
S getApi();
HttpAsyncClient asyncHttp();
HttpClient http();
URI getEndPoint();
String getAccount();

View File

@ -0,0 +1,51 @@
/**
*
* Copyright (C) 2009 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.jclouds.rest.config;
import javax.inject.Inject;
import javax.inject.Singleton;
import org.jclouds.rest.AsyncClientFactory;
import com.google.inject.Injector;
import com.google.inject.Provider;
/**
*
* @author Adrian Cole
*/
@Singleton
public class AsyncClientProvider<A> implements Provider<A> {
@Inject
Injector injector;
private final Class<A> asyncClientType;
@Inject
AsyncClientProvider(Class<A> asyncClientType) {
this.asyncClientType = asyncClientType;
}
@Override
@Singleton
public A get() {
return (A) injector.getInstance(AsyncClientFactory.class).create(
asyncClientType);
}
}

View File

@ -0,0 +1,63 @@
/**
*
* Copyright (C) 2009 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.jclouds.rest.config;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Map;
import com.google.inject.Binder;
import com.google.inject.Provider;
/**
*
* @author Adrian Cole
*/
public class BinderUtils {
public static <K, V> void bindClient(Binder binder, Class<K> syncClientType,
Class<V> asyncClientType, Map<Class<?>, Class<?>> delegates) {
Provider<K> asyncProvider = new ClientProvider<K, V>(syncClientType,
asyncClientType, delegates);
binder.requestInjection(asyncProvider);
binder.bind(syncClientType).toProvider(asyncProvider);
}
public static <T> void bindAsyncClient(Binder binder,
Class<T> asyncClientType) {
Provider<T> asyncProvider = new AsyncClientProvider<T>(asyncClientType);
binder.requestInjection(asyncProvider);
binder.bind(asyncClientType).toProvider(asyncProvider);
}
@SuppressWarnings("unchecked")
public static <T> T newNullProxy(Class<T> clazz) {
return (T) Proxy.newProxyInstance(clazz.getClassLoader(),
new Class<?>[] { clazz }, new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
return null;
}
});
}
}

View File

@ -0,0 +1,74 @@
/**
*
* Copyright (C) 2009 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.jclouds.rest.config;
import java.util.Map;
import java.util.concurrent.ConcurrentMap;
import javax.inject.Inject;
import javax.inject.Singleton;
import org.jclouds.concurrent.internal.SyncProxy;
import org.jclouds.internal.ClassMethodArgs;
import com.google.common.base.Throwables;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.Provider;
import com.google.inject.TypeLiteral;
import com.google.inject.name.Names;
/**
*
* @author Adrian Cole
*/
@Singleton
public class ClientProvider<S, A> implements Provider<S> {
@Inject
Injector injector;
private final Class<S> syncClientType;
private final Class<A> asyncClientType;
private final Map<Class<?>, Class<?>> sync2Async;
@Inject
ClientProvider(Class<S> syncClientType, Class<A> asyncClientType,
Map<Class<?>, Class<?>> sync2Async) {
this.asyncClientType = asyncClientType;
this.syncClientType = syncClientType;
this.sync2Async = sync2Async;
}
@Override
@Singleton
public S get() {
A client = (A) injector.getInstance(asyncClientType);
ConcurrentMap<ClassMethodArgs, Object> delegateMap = injector
.getInstance(Key.get(
new TypeLiteral<ConcurrentMap<ClassMethodArgs, Object>>() {
}, Names.named("sync")));
try {
return (S) SyncProxy.proxy(syncClientType, new SyncProxy(
syncClientType, client, delegateMap, sync2Async));
} catch (Exception e) {
Throwables.propagate(e);
assert false : "should have propagated";
return null;
}
}
}

View File

@ -0,0 +1,72 @@
/**
*
* Copyright (C) 2009 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.jclouds.rest.config;
import static com.google.common.base.Preconditions.checkState;
import java.util.Map;
import java.util.concurrent.ConcurrentMap;
import javax.inject.Inject;
import javax.inject.Named;
import org.jclouds.concurrent.internal.SyncProxy;
import org.jclouds.internal.ClassMethodArgs;
import com.google.common.base.Function;
import com.google.common.base.Throwables;
import com.google.inject.Provider;
/**
*
* @author Adrian Cole
*/
public class CreateClientForCaller implements Function<ClassMethodArgs, Object> {
private final ConcurrentMap<ClassMethodArgs, Object> asyncMap;
private final Provider<ConcurrentMap<ClassMethodArgs, Object>> delegateMap;
Map<Class<?>, Class<?>> sync2Async;
@Inject
CreateClientForCaller(
@Named("async") ConcurrentMap<ClassMethodArgs, Object> asyncMap,
@Named("sync") Provider<ConcurrentMap<ClassMethodArgs, Object>> delegateMap) {
this.asyncMap = asyncMap;
this.delegateMap = delegateMap;
}
@SuppressWarnings("unchecked")
public Object apply(final ClassMethodArgs from) {
Class syncClass = from.getMethod().getReturnType();
Class asyncClass = sync2Async.get(syncClass);
checkState(asyncClass != null, "configuration error, sync class "
+ syncClass.getName() + " not mapped to an async class");
Object asyncClient = asyncMap.get(from);
checkState(asyncClient != null, "configuration error, sync client for "
+ from + " not found");
try {
return SyncProxy.proxy(syncClass, new SyncProxy(syncClass,
asyncClient, delegateMap.get(), sync2Async));
} catch (Exception e) {
Throwables.propagate(e);
assert false : "should have propagated";
return null;
}
}
}

View File

@ -18,31 +18,19 @@
*/
package org.jclouds.rest.config;
import static com.google.common.base.Preconditions.checkState;
import java.util.Map;
import java.util.concurrent.ConcurrentMap;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import org.jclouds.concurrent.internal.SyncProxy;
import org.jclouds.internal.ClassMethodArgs;
import org.jclouds.rest.AsyncClientFactory;
import org.jclouds.rest.ConfiguresRestClient;
import com.google.common.base.Function;
import com.google.common.base.Throwables;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.MapMaker;
import com.google.inject.AbstractModule;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.Provider;
import com.google.inject.Provides;
import com.google.inject.TypeLiteral;
import com.google.inject.name.Names;
/**
*
@ -56,15 +44,15 @@ public class RestClientModule<S, A> extends AbstractModule {
protected final Map<Class<?>, Class<?>> delegates;
public RestClientModule(Class<S> syncClientType, Class<A> asyncClientType,
Map<Class<?>, Class<?>> delegates) {
Map<Class<?>, Class<?>> delegates) {
this.asyncClientType = asyncClientType;
this.syncClientType = syncClientType;
this.delegates = delegates;
}
public RestClientModule(Class<S> syncClientType, Class<A> asyncClientType) {
this(syncClientType, asyncClientType, ImmutableMap.<Class<?>, Class<?>> of(syncClientType,
asyncClientType));
this(syncClientType, asyncClientType, ImmutableMap
.<Class<?>, Class<?>> of(syncClientType, asyncClientType));
}
@Override
@ -81,8 +69,10 @@ public class RestClientModule<S, A> extends AbstractModule {
* ex.
*
* <pre>
* bind(HttpRetryHandler.class).annotatedWith(Redirection.class).to(AWSRedirectionRetryHandler.class);
* bind(HttpRetryHandler.class).annotatedWith(ClientError.class).to(AWSClientErrorRetryHandler.class);
* bind(HttpRetryHandler.class).annotatedWith(Redirection.class).to(
* AWSRedirectionRetryHandler.class);
* bind(HttpRetryHandler.class).annotatedWith(ClientError.class).to(
* AWSClientErrorRetryHandler.class);
* </pre>
*
*/
@ -95,9 +85,12 @@ public class RestClientModule<S, A> extends AbstractModule {
* ex.
*
* <pre>
* bind(HttpErrorHandler.class).annotatedWith(Redirection.class).to(ParseAWSErrorFromXmlContent.class);
* bind(HttpErrorHandler.class).annotatedWith(ClientError.class).to(ParseAWSErrorFromXmlContent.class);
* bind(HttpErrorHandler.class).annotatedWith(ServerError.class).to(ParseAWSErrorFromXmlContent.class);
* bind(HttpErrorHandler.class).annotatedWith(Redirection.class).to(
* ParseAWSErrorFromXmlContent.class);
* bind(HttpErrorHandler.class).annotatedWith(ClientError.class).to(
* ParseAWSErrorFromXmlContent.class);
* bind(HttpErrorHandler.class).annotatedWith(ServerError.class).to(
* ParseAWSErrorFromXmlContent.class);
* </pre>
*
*
@ -106,110 +99,21 @@ public class RestClientModule<S, A> extends AbstractModule {
}
protected void bindAsyncClient() {
Provider<A> asyncProvider = new AsyncClientProvider<A>(asyncClientType);
binder().requestInjection(asyncProvider);
bind(asyncClientType).toProvider(asyncProvider);
}
@Singleton
static class AsyncClientProvider<A> implements Provider<A> {
@Inject
Injector injector;
private final Class<A> asyncClientType;
@Inject
AsyncClientProvider(Class<A> asyncClientType) {
this.asyncClientType = asyncClientType;
}
@Override
@Singleton
public A get() {
return (A) injector.getInstance(AsyncClientFactory.class).create(asyncClientType);
}
BinderUtils.bindAsyncClient(binder(), asyncClientType);
}
protected void bindClient() {
Provider<S> asyncProvider = new ClientProvider<S, A>(asyncClientType, syncClientType,
delegates);
binder().requestInjection(asyncProvider);
bind(syncClientType).toProvider(asyncProvider);
}
@Singleton
static class ClientProvider<S, A> implements Provider<S> {
@Inject
Injector injector;
private final Class<S> syncClientType;
private final Class<A> asyncClientType;
private final Map<Class<?>, Class<?>> sync2Async;
@Inject
ClientProvider(Class<A> asyncClientType, Class<S> syncClientType,
Map<Class<?>, Class<?>> sync2Async) {
this.asyncClientType = asyncClientType;
this.syncClientType = syncClientType;
this.sync2Async = sync2Async;
}
@Override
@Singleton
public S get() {
A client = (A) injector.getInstance(asyncClientType);
ConcurrentMap<ClassMethodArgs, Object> delegateMap = injector.getInstance(Key.get(
new TypeLiteral<ConcurrentMap<ClassMethodArgs, Object>>() {
}, Names.named("sync")));
try {
return (S) SyncProxy.proxy(syncClientType, new SyncProxy(syncClientType, client,
delegateMap, sync2Async));
} catch (Exception e) {
Throwables.propagate(e);
assert false : "should have propagated";
return null;
}
}
BinderUtils.bindClient(binder(), syncClientType, asyncClientType,
delegates);
}
@Provides
@Singleton
@Named("sync")
ConcurrentMap<ClassMethodArgs, Object> provideSyncDelegateMap(
CreateClientForCaller createClientForCaller) {
CreateClientForCaller createClientForCaller) {
createClientForCaller.sync2Async = delegates;
return new MapMaker().makeComputingMap(createClientForCaller);
}
static class CreateClientForCaller implements Function<ClassMethodArgs, Object> {
private final ConcurrentMap<ClassMethodArgs, Object> asyncMap;
private final Provider<ConcurrentMap<ClassMethodArgs, Object>> delegateMap;
private Map<Class<?>, Class<?>> sync2Async;
@Inject
CreateClientForCaller(@Named("async") ConcurrentMap<ClassMethodArgs, Object> asyncMap,
@Named("sync") Provider<ConcurrentMap<ClassMethodArgs, Object>> delegateMap) {
this.asyncMap = asyncMap;
this.delegateMap = delegateMap;
}
@SuppressWarnings("unchecked")
public Object apply(final ClassMethodArgs from) {
Class syncClass = from.getMethod().getReturnType();
Class asyncClass = sync2Async.get(syncClass);
checkState(asyncClass != null, "configuration error, sync class " + syncClass.getName()
+ " not mapped to an async class");
Object asyncClient = asyncMap.get(from);
checkState(asyncClient != null, "configuration error, sync client for " + from
+ " not found");
try {
return SyncProxy.proxy(syncClass, new SyncProxy(syncClass, asyncClient, delegateMap
.get(), sync2Async));
} catch (Exception e) {
Throwables.propagate(e);
assert false : "should have propagated";
return null;
}
}
}
}

View File

@ -34,11 +34,14 @@ import org.jclouds.http.TransformingHttpCommandImpl;
import org.jclouds.http.functions.config.ParserModule;
import org.jclouds.internal.ClassMethodArgs;
import org.jclouds.rest.AsyncClientFactory;
import org.jclouds.rest.HttpAsyncClient;
import org.jclouds.rest.HttpClient;
import org.jclouds.rest.internal.AsyncRestClientProxy;
import org.jclouds.rest.internal.GeneratedHttpRequest;
import org.jclouds.rest.internal.RestAnnotationProcessor;
import com.google.common.base.Function;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.MapMaker;
import com.google.inject.AbstractModule;
import com.google.inject.Injector;
@ -59,23 +62,30 @@ public class RestModule extends AbstractModule {
protected void configure() {
install(new ParserModule());
bind(UriBuilder.class).to(UriBuilderImpl.class);
bind(AsyncRestClientProxy.Factory.class).to(Factory.class).in(Scopes.SINGLETON);
bind(AsyncRestClientProxy.Factory.class).to(Factory.class).in(
Scopes.SINGLETON);
BinderUtils.bindAsyncClient(binder(), HttpAsyncClient.class);
BinderUtils.bindClient(binder(), HttpClient.class, HttpAsyncClient.class,
ImmutableMap.<Class<?>, Class<?>> of(HttpClient.class,
HttpAsyncClient.class));
}
@Provides
@Singleton
@Named("async")
ConcurrentMap<ClassMethodArgs, Object> provideAsyncDelegateMap(
CreateAsyncClientForCaller createAsyncClientForCaller) {
CreateAsyncClientForCaller createAsyncClientForCaller) {
return new MapMaker().makeComputingMap(createAsyncClientForCaller);
}
static class CreateAsyncClientForCaller implements Function<ClassMethodArgs, Object> {
static class CreateAsyncClientForCaller implements
Function<ClassMethodArgs, Object> {
private final Injector injector;
private final AsyncRestClientProxy.Factory factory;
@Inject
CreateAsyncClientForCaller(Injector injector, AsyncRestClientProxy.Factory factory) {
CreateAsyncClientForCaller(Injector injector,
AsyncRestClientProxy.Factory factory) {
this.injector = injector;
this.factory = factory;
}
@ -85,16 +95,17 @@ public class RestModule extends AbstractModule {
public Object apply(ClassMethodArgs from) {
Class clazz = from.getAsyncClass();
TypeLiteral typeLiteral = TypeLiteral.get(clazz);
RestAnnotationProcessor util = (RestAnnotationProcessor) injector.getInstance(Key
.get(TypeLiteral.get(Types.newParameterizedType(RestAnnotationProcessor.class,
clazz))));
RestAnnotationProcessor util = (RestAnnotationProcessor) injector
.getInstance(Key.get(TypeLiteral.get(Types.newParameterizedType(
RestAnnotationProcessor.class, clazz))));
util.setCaller(from);
ConcurrentMap<ClassMethodArgs, Object> delegateMap = injector.getInstance(Key.get(
new TypeLiteral<ConcurrentMap<ClassMethodArgs, Object>>() {
}, Names.named("async")));
AsyncRestClientProxy proxy = new AsyncRestClientProxy(injector, factory, util,
typeLiteral, delegateMap);
ConcurrentMap<ClassMethodArgs, Object> delegateMap = injector
.getInstance(Key.get(
new TypeLiteral<ConcurrentMap<ClassMethodArgs, Object>>() {
}, Names.named("async")));
AsyncRestClientProxy proxy = new AsyncRestClientProxy(injector,
factory, util, typeLiteral, delegateMap);
injector.injectMembers(proxy);
return AsyncClientFactory.create(clazz, proxy);
}
@ -108,9 +119,9 @@ public class RestModule extends AbstractModule {
@SuppressWarnings("unchecked")
public TransformingHttpCommand<?> create(GeneratedHttpRequest<?> request,
Function<HttpResponse, ?> transformer) {
return new TransformingHttpCommandImpl(uriBuilderProvider, executorService, request,
transformer);
Function<HttpResponse, ?> transformer) {
return new TransformingHttpCommandImpl(uriBuilderProvider,
executorService, request, transformer);
}
}

View File

@ -27,6 +27,8 @@ import javax.inject.Inject;
import org.jclouds.lifecycle.Closer;
import org.jclouds.logging.Logger;
import org.jclouds.rest.RestContext;
import org.jclouds.rest.HttpAsyncClient;
import org.jclouds.rest.HttpClient;
/**
* @author Adrian Cole
@ -40,9 +42,15 @@ public class RestContextImpl<S, A> implements RestContext<S, A> {
private final Closer closer;
private final URI endPoint;
private final String account;
private final HttpClient simpleClient;
private final HttpAsyncClient simpleAsyncClient;
@Inject
public RestContextImpl(Closer closer, A asyncApi, S syncApi, URI endPoint, String account) {
public RestContextImpl(Closer closer, HttpClient simpleClient,
HttpAsyncClient simpleAsyncClient, S syncApi, A asyncApi,
URI endPoint, String account) {
this.simpleClient = simpleClient;
this.simpleAsyncClient = simpleAsyncClient;
this.asyncApi = asyncApi;
this.syncApi = syncApi;
this.closer = closer;
@ -55,6 +63,7 @@ public class RestContextImpl<S, A> implements RestContext<S, A> {
*
* @see Closer
*/
@Override
public void close() {
try {
closer.close();
@ -63,20 +72,34 @@ public class RestContextImpl<S, A> implements RestContext<S, A> {
}
}
@Override
public String getAccount() {
return account;
}
@Override
public A getAsyncApi() {
return asyncApi;
}
@Override
public S getApi() {
return syncApi;
}
@Override
public URI getEndPoint() {
return endPoint;
}
@Override
public HttpAsyncClient asyncHttp() {
return this.simpleAsyncClient;
}
@Override
public HttpClient http() {
return this.simpleClient;
}
}

View File

@ -27,6 +27,7 @@ import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URI;
import java.security.MessageDigest;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;
@ -42,91 +43,97 @@ import com.google.common.collect.ImmutableMap;
import com.google.common.io.Closeables;
/**
* Tests for functionality all HttpCommandExecutorServices must express. These tests will operate
* against an in-memory http engine, so as to ensure end-to-end functionality works.
* Tests for functionality all HttpCommandExecutorServices must express. These
* tests will operate against an in-memory http engine, so as to ensure
* end-to-end functionality works.
*
* @author Adrian Cole
*/
@Test(threadPoolSize = 10, groups = "integration", sequential = true)
public abstract class BaseHttpCommandExecutorServiceIntegrationTest extends BaseJettyTest {
public abstract class BaseHttpCommandExecutorServiceIntegrationTest extends
BaseJettyTest {
@Test(invocationCount = 25, timeOut = 5000)
public void testRequestFilter() throws MalformedURLException, ExecutionException,
InterruptedException, TimeoutException {
public void testRequestFilter() throws MalformedURLException,
ExecutionException, InterruptedException, TimeoutException {
assertEquals(client.downloadFilter("", "filterme").trim(), "test");
}
// TODO: filtering redirect test
@Test(invocationCount = 25, timeOut = 5000)
public void testGetStringWithHeader() throws MalformedURLException, ExecutionException,
InterruptedException, TimeoutException {
public void testGetStringWithHeader() throws MalformedURLException,
ExecutionException, InterruptedException, TimeoutException {
assertEquals(client.download("", "test").trim(), "test");
}
@Test(invocationCount = 25, timeOut = 5000)
public void testGetString() throws MalformedURLException, ExecutionException,
InterruptedException, TimeoutException {
public void testGetString() throws MalformedURLException,
ExecutionException, InterruptedException, TimeoutException {
assertEquals(client.download("").trim(), XML);
}
@DataProvider(name = "gets")
public Object[][] createData() {
return new Object[][] { { "object" }, { "/path" }, { "sp ace" }, { "unic₪de" },
{ "qu?stion" } };
return new Object[][] { { "object" }, { "/path" }, { "sp ace" },
{ "unic₪de" }, { "qu?stion" } };
}
@Test(invocationCount = 25, timeOut = 5000, dataProvider = "gets")
public void testGetStringSynch(String uri) throws MalformedURLException, ExecutionException,
InterruptedException, TimeoutException {
public void testGetStringSynch(String uri) throws MalformedURLException,
ExecutionException, InterruptedException, TimeoutException {
// TODO why need trim?
assertEquals(client.synch(uri).trim(), XML);
}
@Test(invocationCount = 25, timeOut = 5000)
public void testGetException() throws MalformedURLException, ExecutionException,
InterruptedException, TimeoutException {
assertEquals(client.downloadException("", GetOptions.Builder.tail(1)).trim(), "foo");
public void testGetException() throws MalformedURLException,
ExecutionException, InterruptedException, TimeoutException {
assertEquals(client.downloadException("", GetOptions.Builder.tail(1))
.trim(), "foo");
}
@Test(invocationCount = 25, timeOut = 5000)
public void testGetSynchException() throws MalformedURLException, ExecutionException,
InterruptedException, TimeoutException {
public void testGetSynchException() throws MalformedURLException,
ExecutionException, InterruptedException, TimeoutException {
assertEquals(client.synchException("", "").trim(), "foo");
}
@Test(invocationCount = 25, timeOut = 5000)
public void testGetStringRedirect() throws MalformedURLException, ExecutionException,
InterruptedException, TimeoutException {
public void testGetStringRedirect() throws MalformedURLException,
ExecutionException, InterruptedException, TimeoutException {
assertEquals(client.download("redirect").trim(), XML2);
}
@Test(invocationCount = 100, timeOut = 5000)
public void testGetBigFile() throws MalformedURLException, ExecutionException,
InterruptedException, TimeoutException {
assertEquals(encryptionService.toBase64String(encryptionService.md5(client
.downloadStream("101constitutions"))), md5);
public void testGetBigFile() throws MalformedURLException,
ExecutionException, InterruptedException, TimeoutException {
assertEquals(encryptionService.toBase64String(encryptionService
.md5(context.http().get(
URI.create(String.format("http://localhost:%d/%s", testPort,
"101constitutions"))))), md5);
}
@Test(enabled = false, invocationCount = 25, timeOut = 5000)
public void testGetStringPermanentRedirect() throws MalformedURLException, ExecutionException,
InterruptedException, TimeoutException {
public void testGetStringPermanentRedirect() throws MalformedURLException,
ExecutionException, InterruptedException, TimeoutException {
// GetString get = factory.createGetString("permanentredirect");
// assert get != null;
// client.submit(get);
// assertEquals(get.get(10, TimeUnit.SECONDS).trim(), XML2);
// TODO assert misses are only one, as permanent redirects paths should be remembered.
// TODO assert misses are only one, as permanent redirects paths should be
// remembered.
}
@Test(invocationCount = 25, timeOut = 5000)
public void testPost() throws MalformedURLException, ExecutionException, InterruptedException,
TimeoutException {
public void testPost() throws MalformedURLException, ExecutionException,
InterruptedException, TimeoutException {
assertEquals(client.post("", "foo").trim(), "fooPOST");
}
@Test(invocationCount = 25, timeOut = 10000)
public void testPostAsInputStream() throws MalformedURLException, ExecutionException,
InterruptedException, TimeoutException {
public void testPostAsInputStream() throws MalformedURLException,
ExecutionException, InterruptedException, TimeoutException {
try {
assertEquals(client.postAsInputStream("", "foo").trim(), "fooPOST");
} catch (Exception e) {
@ -135,8 +142,8 @@ public abstract class BaseHttpCommandExecutorServiceIntegrationTest extends Base
}
/**
* Tests sending a big file to the server. Note: this is a heavy test, takes several minutes to
* finish.
* Tests sending a big file to the server. Note: this is a heavy test, takes
* several minutes to finish.
*
* @throws java.io.IOException
*/
@ -150,7 +157,8 @@ public abstract class BaseHttpCommandExecutorServiceIntegrationTest extends Base
f = File.createTempFile(filename, "tmp");
f.deleteOnExit();
long length = (long) (Runtime.getRuntime().freeMemory() * 1.1);
os = new BufferedOutputStream(new FileOutputStream(f.getAbsolutePath()));
os = new BufferedOutputStream(
new FileOutputStream(f.getAbsolutePath()));
MessageDigest eTag = JCEEncryptionService.getDigest();
ByteArrayOutputStream out = new ByteArrayOutputStream();
@ -168,7 +176,8 @@ public abstract class BaseHttpCommandExecutorServiceIntegrationTest extends Base
// upload and verify the response
assertEquals(client.postWithMd5("fileso",
this.encryptionService.toBase64String(eTag.digest()), f).trim(), "created");
this.encryptionService.toBase64String(eTag.digest()), f).trim(),
"created");
} finally {
if (os != null)
@ -192,39 +201,40 @@ public abstract class BaseHttpCommandExecutorServiceIntegrationTest extends Base
}
@Test(invocationCount = 25, timeOut = 5000)
public void testPostBinder() throws MalformedURLException, ExecutionException,
InterruptedException, TimeoutException {
public void testPostBinder() throws MalformedURLException,
ExecutionException, InterruptedException, TimeoutException {
assertEquals(client.postJson("", "foo").trim(), "{\"key\":\"foo\"}POST");
}
@Test(invocationCount = 25, timeOut = 5000)
public void testPut() throws MalformedURLException, ExecutionException, InterruptedException,
TimeoutException {
public void testPut() throws MalformedURLException, ExecutionException,
InterruptedException, TimeoutException {
assertEquals(client.upload("", "foo").trim(), "fooPUT");
}
@Test(invocationCount = 25, timeOut = 5000)
public void testPutRedirect() throws MalformedURLException, ExecutionException,
InterruptedException, TimeoutException {
public void testPutRedirect() throws MalformedURLException,
ExecutionException, InterruptedException, TimeoutException {
assertEquals(client.upload("redirect", "foo").trim(), "fooPUTREDIRECT");
}
@Test(invocationCount = 25, timeOut = 5000)
public void testKillRobotSlowly() throws MalformedURLException, ExecutionException,
InterruptedException, TimeoutException {
assertEquals(client.action("robot", "kill", ImmutableMap.of("death", "slow")).trim(),
"robot->kill:{death=slow}");
public void testKillRobotSlowly() throws MalformedURLException,
ExecutionException, InterruptedException, TimeoutException {
assertEquals(client.action("robot", "kill",
ImmutableMap.of("death", "slow")).trim(),
"robot->kill:{death=slow}");
}
@Test(invocationCount = 25, timeOut = 5000)
public void testHead() throws MalformedURLException, ExecutionException, InterruptedException,
TimeoutException {
public void testHead() throws MalformedURLException, ExecutionException,
InterruptedException, TimeoutException {
assert client.exists("");
}
@Test(invocationCount = 25, timeOut = 5000)
public void testGetAndParseSax() throws MalformedURLException, ExecutionException,
InterruptedException, TimeoutException {
public void testGetAndParseSax() throws MalformedURLException,
ExecutionException, InterruptedException, TimeoutException {
assertEquals(client.downloadAndParse(""), "whoppers");
}
}

View File

@ -43,6 +43,8 @@ import org.jclouds.encryption.internal.JCEEncryptionService;
import org.jclouds.lifecycle.Closer;
import org.jclouds.rest.RestContext;
import org.jclouds.rest.RestContextBuilder;
import org.jclouds.rest.HttpAsyncClient;
import org.jclouds.rest.HttpClient;
import org.jclouds.rest.config.RestClientModule;
import org.jclouds.rest.internal.RestContextImpl;
import org.jclouds.rest.internal.RestAnnotationProcessorTest.Localhost;
@ -68,12 +70,13 @@ import com.google.inject.Provides;
public abstract class BaseJettyTest {
public static final class IntegrationContextBuilder extends
RestContextBuilder<IntegrationTestClient, IntegrationTestAsyncClient> {
RestContextBuilder<IntegrationTestClient, IntegrationTestAsyncClient> {
private final int testPort;
public IntegrationContextBuilder(String providerName, Properties properties, int testPort) {
super(providerName, IntegrationTestClient.class, IntegrationTestAsyncClient.class,
properties);
public IntegrationContextBuilder(String providerName,
Properties properties, int testPort) {
super(providerName, IntegrationTestClient.class,
IntegrationTestAsyncClient.class, properties);
this.testPort = testPort;
}
@ -84,9 +87,10 @@ public abstract class BaseJettyTest {
@Override
protected void addClientModule(List<Module> modules) {
modules.add(new RestClientModule<IntegrationTestClient, IntegrationTestAsyncClient>(
syncClientType, asyncClientType) {
});
modules
.add(new RestClientModule<IntegrationTestClient, IntegrationTestAsyncClient>(
syncClientType, asyncClientType) {
});
}
}
@ -102,17 +106,18 @@ public abstract class BaseJettyTest {
@Override
protected void configure() {
bind(URI.class).annotatedWith(Localhost.class).toInstance(
URI.create("http://localhost:" + testPort));
URI.create("http://localhost:" + testPort));
}
@SuppressWarnings( { "unchecked" })
@Provides
@Singleton
RestContext<IntegrationTestClient, IntegrationTestAsyncClient> provideContext(Closer closer,
IntegrationTestClient aclient, IntegrationTestAsyncClient client,
@Localhost URI endPoint) {
return new RestContextImpl(closer, client, aclient, endPoint, System
.getProperty("user.name"));
RestContext<IntegrationTestClient, IntegrationTestAsyncClient> provideContext(
Closer closer, HttpClient simpleClient,
HttpAsyncClient simpleAsyncClient, IntegrationTestClient client,
IntegrationTestAsyncClient aclient, @Localhost URI endPoint) {
return new RestContextImpl<IntegrationTestClient, IntegrationTestAsyncClient>(
closer, simpleClient, simpleAsyncClient, client, aclient,
endPoint, System.getProperty("user.name"));
}
}
@ -125,40 +130,47 @@ public abstract class BaseJettyTest {
private AtomicInteger cycle = new AtomicInteger(0);
private Server server2;
protected RestContext<IntegrationTestClient, IntegrationTestAsyncClient> context;
private int testPort;
protected int testPort;
protected EncryptionService encryptionService;
protected String md5;
static final Pattern actionPattern = Pattern.compile("/objects/(.*)/action/([a-z]*);?(.*)");
static final Pattern actionPattern = Pattern
.compile("/objects/(.*)/action/([a-z]*);?(.*)");
@BeforeTest
@Parameters( { "test-jetty-port" })
public void setUpJetty(@Optional("8123") final int testPort) throws Exception {
public void setUpJetty(@Optional("8123") final int testPort)
throws Exception {
this.testPort = testPort;
final InputSupplier<InputStream> oneHundredOneConstitutions = getTestDataSupplier();
encryptionService = Guice.createInjector().getInstance(EncryptionService.class);
encryptionService = Guice.createInjector().getInstance(
EncryptionService.class);
md5 = encryptionService.md5Base64(ByteStreams.toByteArray(oneHundredOneConstitutions
.getInput()));
md5 = encryptionService.md5Base64(ByteStreams
.toByteArray(oneHundredOneConstitutions.getInput()));
Handler server1Handler = new AbstractHandler() {
public void handle(String target, HttpServletRequest request,
HttpServletResponse response, int dispatch) throws IOException, ServletException {
HttpServletResponse response, int dispatch) throws IOException,
ServletException {
if (failIfNoContentLength(request, response)) {
return;
} else if (target.indexOf("redirect") > 0) {
response.sendRedirect("http://localhost:" + (testPort + 1) + "/");
response
.sendRedirect("http://localhost:" + (testPort + 1) + "/");
} else if (target.indexOf("101constitutions") > 0) {
response.setContentType("text/plain");
response.setHeader("Content-MD5", md5);
response.setStatus(HttpServletResponse.SC_OK);
ByteStreams.copy(oneHundredOneConstitutions.getInput(), response.getOutputStream());
ByteStreams.copy(oneHundredOneConstitutions.getInput(), response
.getOutputStream());
} else if (request.getMethod().equals("PUT")) {
if (request.getContentLength() > 0) {
response.setStatus(HttpServletResponse.SC_OK);
response.getWriter().println(
Utils.toStringAndClose(request.getInputStream()) + "PUT");
Utils.toStringAndClose(request.getInputStream())
+ "PUT");
} else {
response.sendError(500, "no content");
}
@ -170,8 +182,9 @@ public abstract class BaseJettyTest {
if (request.getContentLength() > 0) {
if (request.getHeader("Content-MD5") != null) {
String expectedMd5 = request.getHeader("Content-MD5");
String realMd5FromRequest = Base64.encodeBytes(new JCEEncryptionService()
.md5(request.getInputStream()));
String realMd5FromRequest = Base64
.encodeBytes(new JCEEncryptionService().md5(request
.getInputStream()));
boolean matched = expectedMd5.equals(realMd5FromRequest);
if (matched) {
response.setContentType("text/xml");
@ -181,7 +194,8 @@ public abstract class BaseJettyTest {
} else {
response.setStatus(HttpServletResponse.SC_OK);
response.getWriter().println(
Utils.toStringAndClose(request.getInputStream()) + "POST");
Utils.toStringAndClose(request.getInputStream())
+ "POST");
}
} else {
handleAction(request, response);
@ -194,7 +208,8 @@ public abstract class BaseJettyTest {
response.getWriter().println("test");
} else if (request.getMethod().equals("HEAD")) {
/*
* NOTE: by HTML specification, HEAD response MUST NOT include a body
* NOTE: by HTML specification, HEAD response MUST NOT include a
* body
*/
response.setContentType("text/xml");
response.setStatus(HttpServletResponse.SC_OK);
@ -216,19 +231,22 @@ public abstract class BaseJettyTest {
Handler server2Handler = new AbstractHandler() {
public void handle(String target, HttpServletRequest request,
HttpServletResponse response, int dispatch) throws IOException, ServletException {
HttpServletResponse response, int dispatch) throws IOException,
ServletException {
if (request.getMethod().equals("PUT")) {
if (request.getContentLength() > 0) {
response.setStatus(HttpServletResponse.SC_OK);
response.getWriter().println(
Utils.toStringAndClose(request.getInputStream()) + "PUTREDIRECT");
Utils.toStringAndClose(request.getInputStream())
+ "PUTREDIRECT");
}
} else if (request.getMethod().equals("POST")) {
if (request.getContentLength() > 0) {
if (request.getHeader("Content-MD5") != null) {
String expectedMd5 = request.getHeader("Content-MD5");
String realMd5FromRequest = Base64.encodeBytes(new JCEEncryptionService()
.md5(request.getInputStream()));
String realMd5FromRequest = Base64
.encodeBytes(new JCEEncryptionService().md5(request
.getInputStream()));
boolean matched = expectedMd5.equals(realMd5FromRequest);
if (matched) {
response.setContentType("text/xml");
@ -238,14 +256,16 @@ public abstract class BaseJettyTest {
} else {
response.setStatus(HttpServletResponse.SC_OK);
response.getWriter().println(
Utils.toStringAndClose(request.getInputStream()) + "POST");
Utils.toStringAndClose(request.getInputStream())
+ "POST");
}
} else {
handleAction(request, response);
}
} else if (request.getMethod().equals("HEAD")) {
/*
* NOTE: by HTML specification, HEAD response MUST NOT include a body
* NOTE: by HTML specification, HEAD response MUST NOT include a
* body
*/
response.setContentType("text/xml");
response.setStatus(HttpServletResponse.SC_OK);
@ -276,7 +296,8 @@ public abstract class BaseJettyTest {
}.build();
addConnectionProperties(properties);
context = newBuilder(testPort, properties, createConnectionModule()).buildContext();
context = newBuilder(testPort, properties, createConnectionModule())
.buildContext();
client = context.getApi();
assert client != null;
@ -284,11 +305,12 @@ public abstract class BaseJettyTest {
}
@SuppressWarnings("unchecked")
public static InputSupplier<InputStream> getTestDataSupplier() throws IOException {
byte[] oneConstitution = ByteStreams.toByteArray(new GZIPInputStream(BaseJettyTest.class
.getResourceAsStream("/const.txt.gz")));
public static InputSupplier<InputStream> getTestDataSupplier()
throws IOException {
byte[] oneConstitution = ByteStreams.toByteArray(new GZIPInputStream(
BaseJettyTest.class.getResourceAsStream("/const.txt.gz")));
InputSupplier<ByteArrayInputStream> constitutionSupplier = ByteStreams
.newInputStreamSupplier(oneConstitution);
.newInputStreamSupplier(oneConstitution);
InputSupplier<InputStream> temp = ByteStreams.join(constitutionSupplier);
@ -299,9 +321,10 @@ public abstract class BaseJettyTest {
}
public static RestContextBuilder<IntegrationTestClient, IntegrationTestAsyncClient> newBuilder(
final int testPort, final Properties properties, Module connectionModule) {
return new IntegrationContextBuilder("integration-test", properties, testPort)
.withModules(connectionModule);
final int testPort, final Properties properties,
Module connectionModule) {
return new IntegrationContextBuilder("integration-test", properties,
testPort).withModules(connectionModule);
}
@AfterTest
@ -323,8 +346,8 @@ public abstract class BaseJettyTest {
* @return
* @throws IOException
*/
protected boolean failEveryTenRequests(HttpServletRequest request, HttpServletResponse response)
throws IOException {
protected boolean failEveryTenRequests(HttpServletRequest request,
HttpServletResponse response) throws IOException {
if (cycle.incrementAndGet() % 10 == 0) {
response.sendError(500);
((Request) request).setHandled(true);
@ -334,7 +357,7 @@ public abstract class BaseJettyTest {
}
protected boolean redirectEveryTwentyRequests(HttpServletRequest request,
HttpServletResponse response) throws IOException {
HttpServletResponse response) throws IOException {
if (cycle.incrementAndGet() % 20 == 0) {
response.sendRedirect("http://localhost:" + (testPort + 1) + "/");
((Request) request).setHandled(true);
@ -343,8 +366,8 @@ public abstract class BaseJettyTest {
return false;
}
protected boolean failIfNoContentLength(HttpServletRequest request, HttpServletResponse response)
throws IOException {
protected boolean failIfNoContentLength(HttpServletRequest request,
HttpServletResponse response) throws IOException {
if (request.getHeader(HttpHeaders.CONTENT_LENGTH) == null) {
response.sendError(500);
((Request) request).setHandled(true);
@ -353,8 +376,8 @@ public abstract class BaseJettyTest {
return false;
}
private void handleAction(HttpServletRequest request, HttpServletResponse response)
throws IOException {
private void handleAction(HttpServletRequest request,
HttpServletResponse response) throws IOException {
final Matcher matcher = actionPattern.matcher(request.getRequestURI());
boolean matchFound = matcher.find();
if (matchFound) {

View File

@ -19,7 +19,6 @@
package org.jclouds.http;
import java.io.File;
import java.io.InputStream;
import java.util.Collections;
import java.util.Map;
@ -67,10 +66,6 @@ public interface IntegrationTestAsyncClient {
@Path("objects/{id}")
ListenableFuture<String> download(@PathParam("id") String id);
@GET
@Path("{path}")
ListenableFuture<InputStream> downloadStream(@PathParam("path") String path);
@GET
@Path("{path}")
ListenableFuture<String> synch(@PathParam("path") String id);

View File

@ -19,7 +19,6 @@
package org.jclouds.http;
import java.io.File;
import java.io.InputStream;
import java.util.Map;
import java.util.concurrent.TimeUnit;
@ -40,8 +39,6 @@ public interface IntegrationTestClient {
String download(String id);
InputStream downloadStream(String id);
String downloadException(String id, HttpRequestOptions options);
String synchException(String id, String header);

View File

@ -81,6 +81,16 @@ public class RestContextBuilderTest {
return null;
}
@Override
public HttpAsyncClient asyncHttp() {
return null;
}
@Override
public HttpClient http() {
return null;
}
}
class TestRestContextBuilder extends RestContextBuilder<String, String> {
@ -111,7 +121,8 @@ public class RestContextBuilderTest {
List<Module> modules = new ArrayList<Module>();
HttpModule module = new HttpModule();
modules.add(module);
new TestRestContextBuilder(new Properties()).addHttpModuleIfNeededAndNotPresent(modules);
new TestRestContextBuilder(new Properties())
.addHttpModuleIfNeededAndNotPresent(modules);
assertEquals(modules.size(), 1);
assertEquals(modules.remove(0), module);
}
@ -121,7 +132,8 @@ public class RestContextBuilderTest {
List<Module> modules = new ArrayList<Module>();
LoggingModule module = new NullLoggingModule();
modules.add(module);
new TestRestContextBuilder(new Properties()).addLoggingModuleIfNotPresent(modules);
new TestRestContextBuilder(new Properties())
.addLoggingModuleIfNotPresent(modules);
assertEquals(modules.size(), 1);
assertEquals(modules.remove(0), module);
}
@ -133,7 +145,8 @@ public class RestContextBuilderTest {
modules.add(loggingModule);
HttpModule httpModule = new HttpModule();
modules.add(httpModule);
TestRestContextBuilder builder = new TestRestContextBuilder(new Properties());
TestRestContextBuilder builder = new TestRestContextBuilder(
new Properties());
builder.addHttpModuleIfNeededAndNotPresent(modules);
builder.addLoggingModuleIfNotPresent(modules);
assertEquals(modules.size(), 2);
@ -144,7 +157,8 @@ public class RestContextBuilderTest {
@Test
public void testAddBothWhenDoesntRequireHttp() {
List<Module> modules = new ArrayList<Module>();
TestRestContextBuilder builder = new TestRestContextBuilder(new Properties());
TestRestContextBuilder builder = new TestRestContextBuilder(
new Properties());
builder.addHttpModuleIfNeededAndNotPresent(modules);
builder.addLoggingModuleIfNotPresent(modules);
assertEquals(modules.size(), 1);
@ -163,7 +177,8 @@ public class RestContextBuilderTest {
public void testAddBothWhenLive() {
List<Module> modules = new ArrayList<Module>();
modules.add(new RequiresHttpModule());
TestRestContextBuilder builder = new TestRestContextBuilder(new Properties());
TestRestContextBuilder builder = new TestRestContextBuilder(
new Properties());
builder.addHttpModuleIfNeededAndNotPresent(modules);
builder.addLoggingModuleIfNotPresent(modules);
assertEquals(modules.size(), 3);
@ -186,7 +201,8 @@ public class RestContextBuilderTest {
protected void configure() {
}
};
TestRestContextBuilder builder = new TestRestContextBuilder(new Properties());
TestRestContextBuilder builder = new TestRestContextBuilder(
new Properties());
builder.withModules(module1, module2);
}

View File

@ -36,6 +36,8 @@ import org.jclouds.gogrid.GoGridClient;
import org.jclouds.gogrid.reference.GoGridConstants;
import org.jclouds.http.functions.config.ParserModule.DateAdapter;
import org.jclouds.lifecycle.Closer;
import org.jclouds.rest.HttpAsyncClient;
import org.jclouds.rest.HttpClient;
import org.jclouds.rest.RestContext;
import org.jclouds.rest.internal.RestContextImpl;
@ -62,21 +64,24 @@ public class GoGridContextModule extends AbstractModule {
@Provides
@Singleton
RestContext<GoGridClient, GoGridAsyncClient> provideContext(Closer closer,
GoGridAsyncClient asyncApi, GoGridClient syncApi, @GoGrid URI endPoint,
@Named(GoGridConstants.PROPERTY_GOGRID_USER) String account) {
return new RestContextImpl<GoGridClient, GoGridAsyncClient>(closer, asyncApi, syncApi,
endPoint, account);
HttpClient http, HttpAsyncClient asyncHttp,
GoGridAsyncClient asyncApi, GoGridClient syncApi,
@GoGrid URI endPoint,
@Named(GoGridConstants.PROPERTY_GOGRID_USER) String account) {
return new RestContextImpl<GoGridClient, GoGridAsyncClient>(closer, http,
asyncHttp, syncApi, asyncApi, endPoint, account);
}
@Singleton
public static class DateSecondsAdapter implements DateAdapter {
public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) {
public JsonElement serialize(Date src, Type typeOfSrc,
JsonSerializationContext context) {
return new JsonPrimitive(src.getTime());
}
public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
public Date deserialize(JsonElement json, Type typeOfT,
JsonDeserializationContext context) throws JsonParseException {
String toParse = json.getAsJsonPrimitive().getAsString();
return new Date(Long.valueOf(toParse));
}

View File

@ -51,6 +51,8 @@ import org.jclouds.ibmdev.IBMDeveloperCloudAsyncClient;
import org.jclouds.ibmdev.IBMDeveloperCloudClient;
import org.jclouds.ibmdev.reference.IBMDeveloperCloudConstants;
import org.jclouds.lifecycle.Closer;
import org.jclouds.rest.HttpAsyncClient;
import org.jclouds.rest.HttpClient;
import org.jclouds.rest.RestContext;
import org.jclouds.rest.internal.RestContextImpl;
@ -58,7 +60,8 @@ import com.google.inject.AbstractModule;
import com.google.inject.Provides;
/**
* Configures the IBMDeveloperCloud connection, including logging and http transport.
* Configures the IBMDeveloperCloud connection, including logging and http
* transport.
*
* @author Adrian Cole
*/
@ -76,12 +79,16 @@ public class IBMDeveloperCloudContextModule extends AbstractModule {
@Provides
@Singleton
RestContext<IBMDeveloperCloudClient, IBMDeveloperCloudAsyncClient> provideContext(Closer closer,
IBMDeveloperCloudAsyncClient asyncApi, IBMDeveloperCloudClient syncApi,
@IBMDeveloperCloud URI endPoint,
@Named(IBMDeveloperCloudConstants.PROPERTY_IBMDEVELOPERCLOUD_USER) String account) {
return new RestContextImpl<IBMDeveloperCloudClient, IBMDeveloperCloudAsyncClient>(closer,
asyncApi, syncApi, endPoint, account);
RestContext<IBMDeveloperCloudClient, IBMDeveloperCloudAsyncClient> provideContext(
Closer closer,
HttpClient http,
HttpAsyncClient asyncHttp,
IBMDeveloperCloudAsyncClient asyncApi,
IBMDeveloperCloudClient syncApi,
@IBMDeveloperCloud URI endPoint,
@Named(IBMDeveloperCloudConstants.PROPERTY_IBMDEVELOPERCLOUD_USER) String account) {
return new RestContextImpl<IBMDeveloperCloudClient, IBMDeveloperCloudAsyncClient>(
closer, http, asyncHttp, syncApi, asyncApi, endPoint, account);
}
}

View File

@ -28,6 +28,8 @@ import org.jclouds.mezeo.pcs2.PCS;
import org.jclouds.mezeo.pcs2.PCSAsyncClient;
import org.jclouds.mezeo.pcs2.PCSClient;
import org.jclouds.mezeo.pcs2.reference.PCSConstants;
import org.jclouds.rest.HttpAsyncClient;
import org.jclouds.rest.HttpClient;
import org.jclouds.rest.RestContext;
import org.jclouds.rest.internal.RestContextImpl;
@ -50,11 +52,12 @@ public class PCSContextModule extends AbstractModule {
@Provides
@Singleton
RestContext<PCSClient, PCSAsyncClient> provideContext(Closer closer, PCSAsyncClient async,
PCSClient defaultApi, @PCS URI endPoint,
@Named(PCSConstants.PROPERTY_PCS2_USER) String account) {
return new RestContextImpl<PCSClient, PCSAsyncClient>(closer, async, defaultApi, endPoint,
account);
RestContext<PCSClient, PCSAsyncClient> provideContext(Closer closer,
HttpClient http, HttpAsyncClient asyncHttp, PCSAsyncClient async,
PCSClient defaultApi, @PCS URI endPoint,
@Named(PCSConstants.PROPERTY_PCS2_USER) String account) {
return new RestContextImpl<PCSClient, PCSAsyncClient>(closer, http,
asyncHttp, defaultApi, async, endPoint, account);
}
}

View File

@ -29,6 +29,8 @@ import org.jclouds.nirvanix.sdn.SDN;
import org.jclouds.nirvanix.sdn.SDNAsyncClient;
import org.jclouds.nirvanix.sdn.SDNClient;
import org.jclouds.nirvanix.sdn.reference.SDNConstants;
import org.jclouds.rest.HttpAsyncClient;
import org.jclouds.rest.HttpClient;
import org.jclouds.rest.RestContext;
import org.jclouds.rest.internal.RestContextImpl;
@ -47,11 +49,12 @@ public class SDNContextModule extends AbstractModule {
@Provides
@Singleton
RestContext<SDNClient, SDNAsyncClient> provideContext(Closer closer, SDNAsyncClient async,
SDNClient defaultApi, @SDN URI endPoint,
@Named(SDNConstants.PROPERTY_SDN_USERNAME) String account) {
return new RestContextImpl<SDNClient, SDNAsyncClient>(closer, async, defaultApi, endPoint,
account);
RestContext<SDNClient, SDNAsyncClient> provideContext(Closer closer,
HttpClient http, HttpAsyncClient asyncHttp, SDNAsyncClient async,
SDNClient defaultApi, @SDN URI endPoint,
@Named(SDNConstants.PROPERTY_SDN_USERNAME) String account) {
return new RestContextImpl<SDNClient, SDNAsyncClient>(closer, http,
asyncHttp, defaultApi, async, endPoint, account);
}
}

View File

@ -28,6 +28,8 @@ import org.jclouds.opscodeplatform.OpscodePlatform;
import org.jclouds.opscodeplatform.OpscodePlatformAsyncClient;
import org.jclouds.opscodeplatform.OpscodePlatformClient;
import org.jclouds.opscodeplatform.reference.OpscodePlatformConstants;
import org.jclouds.rest.HttpAsyncClient;
import org.jclouds.rest.HttpClient;
import org.jclouds.rest.RestContext;
import org.jclouds.rest.internal.RestContextImpl;
@ -35,7 +37,8 @@ import com.google.inject.AbstractModule;
import com.google.inject.Provides;
/**
* Configures the OpscodePlatform connection, including logging and http transport.
* Configures the OpscodePlatform connection, including logging and http
* transport.
*
* @author Adrian Cole
*/
@ -51,12 +54,16 @@ public class OpscodePlatformContextModule extends AbstractModule {
@Provides
@Singleton
RestContext<OpscodePlatformClient, OpscodePlatformAsyncClient> provideContext(Closer closer,
OpscodePlatformAsyncClient asyncApi, OpscodePlatformClient syncApi,
@OpscodePlatform URI endPoint,
@Named(OpscodePlatformConstants.PROPERTY_OPSCODEPLATFORM_ENDPOINT) String account) {
return new RestContextImpl<OpscodePlatformClient, OpscodePlatformAsyncClient>(closer,
asyncApi, syncApi, endPoint, account);
RestContext<OpscodePlatformClient, OpscodePlatformAsyncClient> provideContext(
Closer closer,
HttpClient http,
HttpAsyncClient asyncHttp,
OpscodePlatformAsyncClient asyncApi,
OpscodePlatformClient syncApi,
@OpscodePlatform URI endPoint,
@Named(OpscodePlatformConstants.PROPERTY_OPSCODEPLATFORM_ENDPOINT) String account) {
return new RestContextImpl<OpscodePlatformClient, OpscodePlatformAsyncClient>(
closer, http, asyncHttp, syncApi, asyncApi, endPoint, account);
}
}

View File

@ -28,6 +28,8 @@ import org.jclouds.rackspace.CloudFiles;
import org.jclouds.rackspace.cloudfiles.CloudFilesAsyncClient;
import org.jclouds.rackspace.cloudfiles.CloudFilesClient;
import org.jclouds.rackspace.reference.RackspaceConstants;
import org.jclouds.rest.HttpAsyncClient;
import org.jclouds.rest.HttpClient;
import org.jclouds.rest.RestContext;
import org.jclouds.rest.internal.RestContextImpl;
@ -35,7 +37,8 @@ import com.google.inject.AbstractModule;
import com.google.inject.Provides;
/**
* Configures the {@link CloudFilesContextModule}; requires {@link CloudFilesAsyncClient} bound.
* Configures the {@link CloudFilesContextModule}; requires
* {@link CloudFilesAsyncClient} bound.
*
* @author Adrian Cole
*/
@ -47,11 +50,13 @@ public class CloudFilesContextModule extends AbstractModule {
@Provides
@Singleton
RestContext<CloudFilesClient, CloudFilesAsyncClient> provideContext(Closer closer,
CloudFilesAsyncClient asyncApi, CloudFilesClient defaultApi, @CloudFiles URI endPoint,
@Named(RackspaceConstants.PROPERTY_RACKSPACE_USER) String account) {
return new RestContextImpl<CloudFilesClient, CloudFilesAsyncClient>(closer, asyncApi,
defaultApi, endPoint, account);
RestContext<CloudFilesClient, CloudFilesAsyncClient> provideContext(
Closer closer, HttpClient http, HttpAsyncClient asyncHttp,
CloudFilesAsyncClient asyncApi, CloudFilesClient defaultApi,
@CloudFiles URI endPoint,
@Named(RackspaceConstants.PROPERTY_RACKSPACE_USER) String account) {
return new RestContextImpl<CloudFilesClient, CloudFilesAsyncClient>(
closer, http, asyncHttp, defaultApi, asyncApi, endPoint, account);
}
}

View File

@ -29,6 +29,8 @@ import org.jclouds.rackspace.CloudServers;
import org.jclouds.rackspace.cloudservers.CloudServersAsyncClient;
import org.jclouds.rackspace.cloudservers.CloudServersClient;
import org.jclouds.rackspace.reference.RackspaceConstants;
import org.jclouds.rest.HttpAsyncClient;
import org.jclouds.rest.HttpClient;
import org.jclouds.rest.RestContext;
import org.jclouds.rest.internal.RestContextImpl;
@ -44,12 +46,13 @@ public class CloudServersContextModule extends AbstractModule {
@Provides
@Singleton
RestContext<CloudServersClient, CloudServersAsyncClient> provideContext(Closer closer,
CloudServersAsyncClient asynchApi, CloudServersClient defaultApi,
@CloudServers URI endPoint,
@Named(RackspaceConstants.PROPERTY_RACKSPACE_USER) String account) {
return new RestContextImpl<CloudServersClient, CloudServersAsyncClient>(closer, asynchApi,
defaultApi, endPoint, account);
RestContext<CloudServersClient, CloudServersAsyncClient> provideContext(
Closer closer, HttpClient http, HttpAsyncClient asyncHttp,
CloudServersAsyncClient asynchApi, CloudServersClient defaultApi,
@CloudServers URI endPoint,
@Named(RackspaceConstants.PROPERTY_RACKSPACE_USER) String account) {
return new RestContextImpl<CloudServersClient, CloudServersAsyncClient>(
closer, http, asyncHttp, defaultApi, asynchApi, endPoint, account);
}
}

View File

@ -39,6 +39,8 @@ import org.jclouds.rackspace.reference.RackspaceConstants;
import org.jclouds.rest.AsyncClientFactory;
import org.jclouds.rest.AuthorizationException;
import org.jclouds.rest.ConfiguresRestClient;
import org.jclouds.rest.HttpAsyncClient;
import org.jclouds.rest.HttpClient;
import org.jclouds.rest.RestContext;
import org.jclouds.rest.RestContextBuilder;
import org.jclouds.rest.internal.RestContextImpl;
@ -59,7 +61,8 @@ public class RackspaceAuthenticationLiveTest {
@ConfiguresRestClient
@RequiresHttp
private final class RestRackspaceAuthenticationClientModule extends AbstractModule {
private final class RestRackspaceAuthenticationClientModule extends
AbstractModule {
@SuppressWarnings("unused")
@Provides
@ -74,16 +77,18 @@ public class RackspaceAuthenticationLiveTest {
}
}
private final class RackspaceAuthenticationContextModule extends AbstractModule {
private final class RackspaceAuthenticationContextModule extends
AbstractModule {
@SuppressWarnings( { "unused" })
@Provides
@Singleton
RestContext<RackspaceAuthentication, RackspaceAuthentication> provideContext(Closer closer,
RackspaceAuthentication api, @Authentication URI endPoint,
@Named(RackspaceConstants.PROPERTY_RACKSPACE_USER) String account) {
return new RestContextImpl<RackspaceAuthentication, RackspaceAuthentication>(closer, api,
api, endPoint, account);
RestContext<RackspaceAuthentication, RackspaceAuthentication> provideContext(
Closer closer, HttpClient http, HttpAsyncClient asyncHttp,
RackspaceAuthentication api, @Authentication URI endPoint,
@Named(RackspaceConstants.PROPERTY_RACKSPACE_USER) String account) {
return new RestContextImpl<RackspaceAuthentication, RackspaceAuthentication>(
closer, http, asyncHttp, api, api, endPoint, account);
}
@Override
@ -92,16 +97,18 @@ public class RackspaceAuthenticationLiveTest {
}
}
String account = checkNotNull(System.getProperty("jclouds.test.user"), "jclouds.test.user");
String key = checkNotNull(System.getProperty("jclouds.test.key"), "jclouds.test.key");
String account = checkNotNull(System.getProperty("jclouds.test.user"),
"jclouds.test.user");
String key = checkNotNull(System.getProperty("jclouds.test.key"),
"jclouds.test.key");
private RestContext<RackspaceAuthentication, RackspaceAuthentication> context;
@Test
public void testAuthentication() throws Exception {
RackspaceAuthentication authentication = context.getAsyncApi();
AuthenticationResponse response = authentication.authenticate(account, key).get(10,
TimeUnit.SECONDS);
AuthenticationResponse response = authentication.authenticate(account,
key).get(10, TimeUnit.SECONDS);
assertNotNull(response);
assertNotNull(response.getStorageUrl());
assertNotNull(response.getCDNManagementUrl());
@ -118,8 +125,9 @@ public class RackspaceAuthenticationLiveTest {
@BeforeClass
void setupFactory() {
context = new RestContextBuilder<RackspaceAuthentication, RackspaceAuthentication>(
"rackspace", RackspaceAuthentication.class, RackspaceAuthentication.class,
new RackspacePropertiesBuilder(account, key).build()) {
"rackspace", RackspaceAuthentication.class,
RackspaceAuthentication.class, new RackspacePropertiesBuilder(
account, key).build()) {
@Override
protected void addClientModule(List<Module> modules) {
modules.add(new RestRackspaceAuthenticationClientModule());
@ -127,12 +135,14 @@ public class RackspaceAuthenticationLiveTest {
}
@Override
protected void addContextModule(String providerName, List<Module> modules) {
protected void addContextModule(String providerName,
List<Module> modules) {
modules.add(new RackspaceAuthenticationContextModule());
}
}.withModules(new Log4JLoggingModule(),
new ExecutorServiceModule(sameThreadExecutor(), sameThreadExecutor()))
.buildContext();
}.withModules(
new Log4JLoggingModule(),
new ExecutorServiceModule(sameThreadExecutor(),
sameThreadExecutor())).buildContext();
}
}

View File

@ -26,6 +26,8 @@ import javax.inject.Singleton;
import org.jclouds.http.functions.config.ParserModule.CDateAdapter;
import org.jclouds.http.functions.config.ParserModule.DateAdapter;
import org.jclouds.lifecycle.Closer;
import org.jclouds.rest.HttpAsyncClient;
import org.jclouds.rest.HttpClient;
import org.jclouds.rest.RestContext;
import org.jclouds.rest.internal.RestContextImpl;
import org.jclouds.rimuhosting.miro.RimuHosting;
@ -49,11 +51,13 @@ public class RimuHostingContextModule extends AbstractModule {
@Provides
@Singleton
RestContext<RimuHostingClient, RimuHostingAsyncClient> provideContext(Closer closer,
RimuHostingAsyncClient asyncApi, RimuHostingClient syncApi, @RimuHosting URI endPoint,
@Named(RimuHostingConstants.PROPERTY_RIMUHOSTING_APIKEY) String account) {
return new RestContextImpl<RimuHostingClient, RimuHostingAsyncClient>(closer, asyncApi,
syncApi, endPoint, account);
RestContext<RimuHostingClient, RimuHostingAsyncClient> provideContext(
Closer closer, HttpClient http, HttpAsyncClient asyncHttp,
RimuHostingAsyncClient asyncApi, RimuHostingClient syncApi,
@RimuHosting URI endPoint,
@Named(RimuHostingConstants.PROPERTY_RIMUHOSTING_APIKEY) String account) {
return new RestContextImpl<RimuHostingClient, RimuHostingAsyncClient>(
closer, http, asyncHttp, syncApi, asyncApi, endPoint, account);
}
}

View File

@ -26,6 +26,8 @@ import javax.inject.Singleton;
import org.jclouds.http.functions.config.ParserModule.CDateAdapter;
import org.jclouds.http.functions.config.ParserModule.DateAdapter;
import org.jclouds.lifecycle.Closer;
import org.jclouds.rest.HttpAsyncClient;
import org.jclouds.rest.HttpClient;
import org.jclouds.rest.RestContext;
import org.jclouds.rest.internal.RestContextImpl;
import org.jclouds.twitter.Twitter;
@ -53,10 +55,12 @@ public class TwitterContextModule extends AbstractModule {
@Provides
@Singleton
RestContext<TwitterClient, TwitterAsyncClient> provideContext(Closer closer,
TwitterAsyncClient asyncApi, TwitterClient syncApi, @Twitter URI endPoint,
@Named(TwitterConstants.PROPERTY_TWITTER_USER) String account) {
return new RestContextImpl<TwitterClient, TwitterAsyncClient>(closer, asyncApi, syncApi,
endPoint, account);
HttpClient http, HttpAsyncClient asyncHttp,
TwitterAsyncClient asyncApi, TwitterClient syncApi,
@Twitter URI endPoint,
@Named(TwitterConstants.PROPERTY_TWITTER_USER) String account) {
return new RestContextImpl<TwitterClient, TwitterAsyncClient>(closer,
http, asyncHttp, syncApi, asyncApi, endPoint, account);
}
}

View File

@ -24,6 +24,8 @@ import javax.inject.Named;
import javax.inject.Singleton;
import org.jclouds.lifecycle.Closer;
import org.jclouds.rest.HttpAsyncClient;
import org.jclouds.rest.HttpClient;
import org.jclouds.rest.RestContext;
import org.jclouds.rest.internal.RestContextImpl;
import org.jclouds.vcloud.VCloudAsyncClient;
@ -45,10 +47,12 @@ public class VCloudContextModule extends AbstractModule {
@Provides
@Singleton
RestContext<VCloudClient, VCloudAsyncClient> provideContext(Closer closer,
VCloudAsyncClient asynchApi, VCloudClient defaultApi, @Org URI endPoint,
@Named(VCloudConstants.PROPERTY_VCLOUD_USER) String account) {
return new RestContextImpl<VCloudClient, VCloudAsyncClient>(closer, asynchApi, defaultApi,
endPoint, account);
HttpClient http, HttpAsyncClient asyncHttp,
VCloudAsyncClient asynchApi, VCloudClient defaultApi,
@Org URI endPoint,
@Named(VCloudConstants.PROPERTY_VCLOUD_USER) String account) {
return new RestContextImpl<VCloudClient, VCloudAsyncClient>(closer, http,
asyncHttp, defaultApi, asynchApi, endPoint, account);
}
}

View File

@ -41,6 +41,8 @@ import org.jclouds.lifecycle.Closer;
import org.jclouds.logging.log4j.config.Log4JLoggingModule;
import org.jclouds.rest.AsyncClientFactory;
import org.jclouds.rest.ConfiguresRestClient;
import org.jclouds.rest.HttpAsyncClient;
import org.jclouds.rest.HttpClient;
import org.jclouds.rest.RestContext;
import org.jclouds.rest.RestContextBuilder;
import org.jclouds.rest.internal.RestContextImpl;
@ -64,12 +66,14 @@ public class VCloudLoginLiveTest {
@RequiresHttp
@ConfiguresRestClient
private static final class VCloudLoginRestClientModule extends AbstractModule {
private static final class VCloudLoginRestClientModule extends
AbstractModule {
@SuppressWarnings("unused")
@Provides
@Singleton
protected VCloudLoginAsyncClient provideVCloudLogin(AsyncClientFactory factory) {
protected VCloudLoginAsyncClient provideVCloudLogin(
AsyncClientFactory factory) {
return factory.create(VCloudLoginAsyncClient.class);
}
@ -77,8 +81,10 @@ public class VCloudLoginLiveTest {
@Provides
@Singleton
public BasicAuthentication provideBasicAuthentication(
@Named(PROPERTY_VCLOUD_USER) String user, @Named(PROPERTY_VCLOUD_KEY) String key,
EncryptionService encryptionService) throws UnsupportedEncodingException {
@Named(PROPERTY_VCLOUD_USER) String user,
@Named(PROPERTY_VCLOUD_KEY) String key,
EncryptionService encryptionService)
throws UnsupportedEncodingException {
return new BasicAuthentication(user, key, encryptionService);
}
@ -102,10 +108,11 @@ public class VCloudLoginLiveTest {
@SuppressWarnings( { "unused" })
@Provides
@Singleton
RestContext<VCloudLoginAsyncClient, VCloudLoginAsyncClient> provideContext(Closer closer,
VCloudLoginAsyncClient api, @VCloudLogin URI endPoint) {
return new RestContextImpl<VCloudLoginAsyncClient, VCloudLoginAsyncClient>(closer, api,
api, endPoint, "");
RestContext<VCloudLoginAsyncClient, VCloudLoginAsyncClient> provideContext(
Closer closer, HttpClient http, HttpAsyncClient asyncHttp,
VCloudLoginAsyncClient api, @VCloudLogin URI endPoint) {
return new RestContextImpl<VCloudLoginAsyncClient, VCloudLoginAsyncClient>(
closer, http, asyncHttp, api, api, endPoint, "");
}
@Override
@ -120,7 +127,8 @@ public class VCloudLoginLiveTest {
public void testLogin() throws Exception {
VCloudLoginAsyncClient authentication = context.getAsyncApi();
for (int i = 0; i < 5; i++) {
VCloudSession response = authentication.login().get(45, TimeUnit.SECONDS);
VCloudSession response = authentication.login().get(45,
TimeUnit.SECONDS);
assertNotNull(response);
assertNotNull(response.getVCloudToken());
assertNotNull(response.getOrgs());
@ -129,14 +137,17 @@ public class VCloudLoginLiveTest {
@BeforeClass
void setupFactory() {
String endpoint = checkNotNull(System.getProperty("jclouds.test.endpoint"),
"jclouds.test.endpoint")
+ "/v0.8/login";
String account = checkNotNull(System.getProperty("jclouds.test.user"), "jclouds.test.user");
String key = checkNotNull(System.getProperty("jclouds.test.key"), "jclouds.test.key");
context = new RestContextBuilder<VCloudLoginAsyncClient, VCloudLoginAsyncClient>("vcloud",
VCloudLoginAsyncClient.class, VCloudLoginAsyncClient.class,
new VCloudPropertiesBuilder(URI.create(endpoint), account, key).build()) {
String endpoint = checkNotNull(System
.getProperty("jclouds.test.endpoint"), "jclouds.test.endpoint")
+ "/v0.8/login";
String account = checkNotNull(System.getProperty("jclouds.test.user"),
"jclouds.test.user");
String key = checkNotNull(System.getProperty("jclouds.test.key"),
"jclouds.test.key");
context = new RestContextBuilder<VCloudLoginAsyncClient, VCloudLoginAsyncClient>(
"vcloud", VCloudLoginAsyncClient.class,
VCloudLoginAsyncClient.class, new VCloudPropertiesBuilder(URI
.create(endpoint), account, key).build()) {
public void addContextModule(String providerName, List<Module> modules) {
modules.add(new VCloudLoginContextModule());
@ -147,8 +158,9 @@ public class VCloudLoginLiveTest {
modules.add(new VCloudLoginRestClientModule());
}
}.withModules(new Log4JLoggingModule(),
new ExecutorServiceModule(sameThreadExecutor(), sameThreadExecutor()))
.buildContext();
}.withModules(
new Log4JLoggingModule(),
new ExecutorServiceModule(sameThreadExecutor(),
sameThreadExecutor())).buildContext();
}
}

View File

@ -37,6 +37,8 @@ import org.jclouds.lifecycle.Closer;
import org.jclouds.logging.log4j.config.Log4JLoggingModule;
import org.jclouds.rest.AsyncClientFactory;
import org.jclouds.rest.ConfiguresRestClient;
import org.jclouds.rest.HttpAsyncClient;
import org.jclouds.rest.HttpClient;
import org.jclouds.rest.RestContext;
import org.jclouds.rest.RestContextBuilder;
import org.jclouds.rest.internal.RestContextImpl;
@ -59,11 +61,13 @@ public class VCloudVersionsLiveTest {
@RequiresHttp
@ConfiguresRestClient
private static final class VCloudVersionsRestClientModule extends AbstractModule {
private static final class VCloudVersionsRestClientModule extends
AbstractModule {
@SuppressWarnings("unused")
@Provides
@Singleton
protected VCloudVersionsAsyncClient provideVCloudVersions(AsyncClientFactory factory) {
protected VCloudVersionsAsyncClient provideVCloudVersions(
AsyncClientFactory factory) {
return factory.create(VCloudVersionsAsyncClient.class);
}
@ -86,9 +90,10 @@ public class VCloudVersionsLiveTest {
@Provides
@Singleton
RestContext<VCloudVersionsAsyncClient, VCloudVersionsAsyncClient> provideContext(
Closer closer, VCloudVersionsAsyncClient api, @VCloud URI endPoint) {
return new RestContextImpl<VCloudVersionsAsyncClient, VCloudVersionsAsyncClient>(closer,
api, api, endPoint, "");
Closer closer, HttpClient http, HttpAsyncClient asyncHttp,
VCloudVersionsAsyncClient api, @VCloud URI endPoint) {
return new RestContextImpl<VCloudVersionsAsyncClient, VCloudVersionsAsyncClient>(
closer, http, asyncHttp, api, api, endPoint, "");
}
@Override
@ -103,8 +108,8 @@ public class VCloudVersionsLiveTest {
public void testGetSupportedVersions() throws Exception {
VCloudVersionsAsyncClient authentication = context.getAsyncApi();
for (int i = 0; i < 5; i++) {
SortedMap<String, URI> response = authentication.getSupportedVersions().get(45,
TimeUnit.SECONDS);
SortedMap<String, URI> response = authentication
.getSupportedVersions().get(45, TimeUnit.SECONDS);
assertNotNull(response);
assertNotNull(response.containsKey("0.8"));
}
@ -112,13 +117,16 @@ public class VCloudVersionsLiveTest {
@BeforeClass
void setupFactory() {
String endpoint = checkNotNull(System.getProperty("jclouds.test.endpoint"),
"jclouds.test.endpoint");
String account = checkNotNull(System.getProperty("jclouds.test.user"), "jclouds.test.user");
String key = checkNotNull(System.getProperty("jclouds.test.key"), "jclouds.test.key");
String endpoint = checkNotNull(System
.getProperty("jclouds.test.endpoint"), "jclouds.test.endpoint");
String account = checkNotNull(System.getProperty("jclouds.test.user"),
"jclouds.test.user");
String key = checkNotNull(System.getProperty("jclouds.test.key"),
"jclouds.test.key");
context = new RestContextBuilder<VCloudVersionsAsyncClient, VCloudVersionsAsyncClient>(
"vcloud", VCloudVersionsAsyncClient.class, VCloudVersionsAsyncClient.class,
new VCloudPropertiesBuilder(URI.create(endpoint), account, key).build()) {
"vcloud", VCloudVersionsAsyncClient.class,
VCloudVersionsAsyncClient.class, new VCloudPropertiesBuilder(URI
.create(endpoint), account, key).build()) {
public void addContextModule(String providerName, List<Module> modules) {
@ -130,8 +138,9 @@ public class VCloudVersionsLiveTest {
modules.add(new VCloudVersionsRestClientModule());
}
}.withModules(new Log4JLoggingModule(),
new ExecutorServiceModule(sameThreadExecutor(), sameThreadExecutor()))
.buildContext();
}.withModules(
new Log4JLoggingModule(),
new ExecutorServiceModule(sameThreadExecutor(),
sameThreadExecutor())).buildContext();
}
}

View File

@ -24,6 +24,8 @@ import javax.inject.Named;
import javax.inject.Singleton;
import org.jclouds.lifecycle.Closer;
import org.jclouds.rest.HttpAsyncClient;
import org.jclouds.rest.HttpClient;
import org.jclouds.rest.RestContext;
import org.jclouds.rest.internal.RestContextImpl;
import org.jclouds.vcloud.endpoints.Org;
@ -44,11 +46,13 @@ public class HostingDotComVCloudContextModule extends AbstractModule {
@Provides
@Singleton
RestContext<HostingDotComVCloudClient, HostingDotComVCloudAsyncClient> provideContext(Closer closer,
HostingDotComVCloudAsyncClient asynchApi, HostingDotComVCloudClient defaultApi,
@Org URI endPoint, @Named(VCloudConstants.PROPERTY_VCLOUD_USER) String account) {
return new RestContextImpl<HostingDotComVCloudClient, HostingDotComVCloudAsyncClient>(closer,
asynchApi, defaultApi, endPoint, account);
RestContext<HostingDotComVCloudClient, HostingDotComVCloudAsyncClient> provideContext(
Closer closer, HttpClient http, HttpAsyncClient asyncHttp,
HostingDotComVCloudAsyncClient asynchApi,
HostingDotComVCloudClient defaultApi, @Org URI endPoint,
@Named(VCloudConstants.PROPERTY_VCLOUD_USER) String account) {
return new RestContextImpl<HostingDotComVCloudClient, HostingDotComVCloudAsyncClient>(
closer, http, asyncHttp, defaultApi, asynchApi, endPoint, account);
}
}

View File

@ -24,6 +24,8 @@ import javax.inject.Named;
import javax.inject.Singleton;
import org.jclouds.lifecycle.Closer;
import org.jclouds.rest.HttpAsyncClient;
import org.jclouds.rest.HttpClient;
import org.jclouds.rest.RestContext;
import org.jclouds.rest.internal.RestContextImpl;
import org.jclouds.vcloud.endpoints.Org;
@ -44,11 +46,13 @@ public class TerremarkVCloudContextModule extends AbstractModule {
@Provides
@Singleton
RestContext<TerremarkVCloudClient, TerremarkVCloudAsyncClient> provideContext(Closer closer,
TerremarkVCloudAsyncClient asynchApi, TerremarkVCloudClient defaultApi,
@Org URI endPoint, @Named(VCloudConstants.PROPERTY_VCLOUD_USER) String account) {
return new RestContextImpl<TerremarkVCloudClient, TerremarkVCloudAsyncClient>(closer,
asynchApi, defaultApi, endPoint, account);
RestContext<TerremarkVCloudClient, TerremarkVCloudAsyncClient> provideContext(
Closer closer, HttpClient http, HttpAsyncClient asyncHttp,
TerremarkVCloudAsyncClient asynchApi,
TerremarkVCloudClient defaultApi, @Org URI endPoint,
@Named(VCloudConstants.PROPERTY_VCLOUD_USER) String account) {
return new RestContextImpl<TerremarkVCloudClient, TerremarkVCloudAsyncClient>(
closer, http, asyncHttp, defaultApi, asynchApi, endPoint, account);
}
}