Issue 337: support non-standard http methods

This commit is contained in:
Adrian Cole 2010-08-18 10:49:33 -07:00
parent 0394c29394
commit 8efea1b42d
7 changed files with 266 additions and 184 deletions

View File

@ -29,10 +29,12 @@ import java.io.ByteArrayInputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.OutputStream; import java.io.OutputStream;
import java.lang.reflect.Field;
import java.net.Authenticator; import java.net.Authenticator;
import java.net.HttpURLConnection; import java.net.HttpURLConnection;
import java.net.InetSocketAddress; import java.net.InetSocketAddress;
import java.net.PasswordAuthentication; import java.net.PasswordAuthentication;
import java.net.ProtocolException;
import java.net.Proxy; import java.net.Proxy;
import java.net.ProxySelector; import java.net.ProxySelector;
import java.net.SocketAddress; import java.net.SocketAddress;
@ -60,6 +62,7 @@ import org.jclouds.io.Payload;
import org.jclouds.io.Payloads; import org.jclouds.io.Payloads;
import org.jclouds.logging.Logger; import org.jclouds.logging.Logger;
import com.google.common.base.Throwables;
import com.google.common.collect.LinkedHashMultimap; import com.google.common.collect.LinkedHashMultimap;
import com.google.common.collect.Multimap; import com.google.common.collect.Multimap;
@ -75,16 +78,20 @@ public class JavaUrlHttpCommandExecutorService extends BaseHttpCommandExecutorSe
@Resource @Resource
protected Logger logger = Logger.NULL; protected Logger logger = Logger.NULL;
private final HostnameVerifier verifier; private final HostnameVerifier verifier;
private final Field methodField;
@Inject @Inject
public JavaUrlHttpCommandExecutorService(HttpUtils utils, public JavaUrlHttpCommandExecutorService(HttpUtils utils,
@Named(Constants.PROPERTY_IO_WORKER_THREADS) ExecutorService ioWorkerExecutor, @Named(Constants.PROPERTY_IO_WORKER_THREADS) ExecutorService ioWorkerExecutor,
DelegatingRetryHandler retryHandler, IOExceptionRetryHandler ioRetryHandler, DelegatingRetryHandler retryHandler, IOExceptionRetryHandler ioRetryHandler,
DelegatingErrorHandler errorHandler, HttpWire wire, HostnameVerifier verifier) { DelegatingErrorHandler errorHandler, HttpWire wire, HostnameVerifier verifier) throws SecurityException,
NoSuchFieldException {
super(utils, ioWorkerExecutor, retryHandler, ioRetryHandler, errorHandler, wire); super(utils, ioWorkerExecutor, retryHandler, ioRetryHandler, errorHandler, wire);
if (utils.getMaxConnections() > 0) if (utils.getMaxConnections() > 0)
System.setProperty("http.maxConnections", String.valueOf(checkNotNull(utils, "utils").getMaxConnections())); System.setProperty("http.maxConnections", String.valueOf(checkNotNull(utils, "utils").getMaxConnections()));
this.verifier = checkNotNull(verifier, "verifier"); this.verifier = checkNotNull(verifier, "verifier");
this.methodField = HttpURLConnection.class.getDeclaredField("method");
methodField.setAccessible(true);
} }
@Override @Override
@ -163,7 +170,17 @@ public class JavaUrlHttpCommandExecutorService extends BaseHttpCommandExecutorSe
// ex. Caused by: java.io.IOException: HTTPS hostname wrong: should be // ex. Caused by: java.io.IOException: HTTPS hostname wrong: should be
// <adriancole.s3int0.s3-external-3.amazonaws.com> // <adriancole.s3int0.s3-external-3.amazonaws.com>
connection.setInstanceFollowRedirects(false); connection.setInstanceFollowRedirects(false);
connection.setRequestMethod(request.getMethod().toString()); try {
connection.setRequestMethod(request.getMethod());
} catch (ProtocolException e) {
try {
methodField.set(connection, request.getMethod());
} catch (Exception e1) {
logger.error(e, "could not set request method: ", request.getMethod());
Throwables.propagate(e1);
}
}
for (String header : request.getHeaders().keySet()) { for (String header : request.getHeaders().keySet()) {
for (String value : request.getHeaders().get(header)) { for (String value : request.getHeaders().get(header)) {
connection.setRequestProperty(header, value); connection.setRequestProperty(header, value);

View File

@ -64,13 +64,19 @@ public abstract class BaseHttpCommandExecutorServiceIntegrationTest extends Base
// TODO: filtering redirect test // TODO: filtering redirect test
@Test(invocationCount = 25, timeOut = 5000) @Test(invocationCount = 5, timeOut = 5000)
public void testGetStringWithHeader() throws MalformedURLException, ExecutionException, InterruptedException, public void testGetStringWithHeader() throws MalformedURLException, ExecutionException, InterruptedException,
TimeoutException { TimeoutException {
assertEquals(client.download("", "test").trim(), "test"); assertEquals(client.download("", "test").trim(), "test");
} }
@Test(invocationCount = 25, timeOut = 5000) @Test(invocationCount = 1, timeOut = 5000)
public void testAlternateMethod() throws MalformedURLException, ExecutionException, InterruptedException,
TimeoutException {
assertEquals(client.rowdy("").trim(), XML);
}
@Test(invocationCount = 5, timeOut = 5000)
public void testGetString() throws MalformedURLException, ExecutionException, InterruptedException, TimeoutException { public void testGetString() throws MalformedURLException, ExecutionException, InterruptedException, TimeoutException {
assertEquals(client.download("").trim(), XML); assertEquals(client.download("").trim(), XML);
} }
@ -80,26 +86,26 @@ public abstract class BaseHttpCommandExecutorServiceIntegrationTest extends Base
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") @Test(invocationCount = 5, timeOut = 5000, dataProvider = "gets")
public void testGetStringSynch(String uri) throws MalformedURLException, ExecutionException, InterruptedException, public void testGetStringSynch(String uri) throws MalformedURLException, ExecutionException, InterruptedException,
TimeoutException { TimeoutException {
// TODO why need trim? // TODO why need trim?
assertEquals(client.synch(uri).trim(), XML); assertEquals(client.synch(uri).trim(), XML);
} }
@Test(invocationCount = 25, timeOut = 5000) @Test(invocationCount = 5, timeOut = 5000)
public void testGetException() throws MalformedURLException, ExecutionException, InterruptedException, public void testGetException() throws MalformedURLException, ExecutionException, InterruptedException,
TimeoutException { TimeoutException {
assertEquals(client.downloadException("", GetOptions.Builder.tail(1)).trim(), "foo"); assertEquals(client.downloadException("", GetOptions.Builder.tail(1)).trim(), "foo");
} }
@Test(invocationCount = 25, timeOut = 5000) @Test(invocationCount = 5, timeOut = 5000)
public void testGetSynchException() throws MalformedURLException, ExecutionException, InterruptedException, public void testGetSynchException() throws MalformedURLException, ExecutionException, InterruptedException,
TimeoutException { TimeoutException {
assertEquals(client.synchException("", "").trim(), "foo"); assertEquals(client.synchException("", "").trim(), "foo");
} }
@Test(invocationCount = 25, timeOut = 5000) @Test(invocationCount = 5, timeOut = 5000)
public void testGetStringRedirect() throws MalformedURLException, ExecutionException, InterruptedException, public void testGetStringRedirect() throws MalformedURLException, ExecutionException, InterruptedException,
TimeoutException { TimeoutException {
assertEquals(client.download("redirect").trim(), XML2); assertEquals(client.download("redirect").trim(), XML2);
@ -128,7 +134,7 @@ public abstract class BaseHttpCommandExecutorServiceIntegrationTest extends Base
return input; return input;
} }
@Test(enabled = false, invocationCount = 25, timeOut = 5000) @Test(enabled = false, invocationCount = 5, timeOut = 5000)
public void testGetStringPermanentRedirect() throws MalformedURLException, ExecutionException, InterruptedException, public void testGetStringPermanentRedirect() throws MalformedURLException, ExecutionException, InterruptedException,
TimeoutException { TimeoutException {
// GetString get = factory.createGetString("permanentredirect"); // GetString get = factory.createGetString("permanentredirect");
@ -139,12 +145,12 @@ public abstract class BaseHttpCommandExecutorServiceIntegrationTest extends Base
// remembered. // remembered.
} }
@Test(invocationCount = 25, timeOut = 5000) @Test(invocationCount = 5, timeOut = 5000)
public void testPost() throws MalformedURLException, ExecutionException, InterruptedException, TimeoutException { public void testPost() throws MalformedURLException, ExecutionException, InterruptedException, TimeoutException {
assertEquals(client.post("", "foo").trim(), "fooPOST"); assertEquals(client.post("", "foo").trim(), "fooPOST");
} }
@Test(invocationCount = 25, timeOut = 10000) @Test(invocationCount = 5, timeOut = 10000)
public void testPostAsInputStream() throws MalformedURLException, ExecutionException, InterruptedException, public void testPostAsInputStream() throws MalformedURLException, ExecutionException, InterruptedException,
TimeoutException { TimeoutException {
try { try {
@ -215,35 +221,35 @@ public abstract class BaseHttpCommandExecutorServiceIntegrationTest extends Base
assert postFailures.get() > 0; assert postFailures.get() > 0;
} }
@Test(invocationCount = 25, timeOut = 5000) @Test(invocationCount = 5, timeOut = 5000)
public void testPostBinder() throws MalformedURLException, ExecutionException, InterruptedException, public void testPostBinder() throws MalformedURLException, ExecutionException, InterruptedException,
TimeoutException { TimeoutException {
assertEquals(client.postJson("", "foo").trim(), "{\"key\":\"foo\"}POST"); assertEquals(client.postJson("", "foo").trim(), "{\"key\":\"foo\"}POST");
} }
@Test(invocationCount = 25, timeOut = 5000) @Test(invocationCount = 5, timeOut = 5000)
public void testPut() throws MalformedURLException, ExecutionException, InterruptedException, TimeoutException { public void testPut() throws MalformedURLException, ExecutionException, InterruptedException, TimeoutException {
assertEquals(client.upload("", "foo").trim(), "fooPUT"); assertEquals(client.upload("", "foo").trim(), "fooPUT");
} }
@Test(invocationCount = 25, timeOut = 5000) @Test(invocationCount = 5, timeOut = 5000)
public void testPutRedirect() throws MalformedURLException, ExecutionException, InterruptedException, public void testPutRedirect() throws MalformedURLException, ExecutionException, InterruptedException,
TimeoutException { TimeoutException {
assertEquals(client.upload("redirect", "foo").trim(), "fooPUTREDIRECT"); assertEquals(client.upload("redirect", "foo").trim(), "fooPUTREDIRECT");
} }
@Test(invocationCount = 25, timeOut = 5000) @Test(invocationCount = 5, timeOut = 5000)
public void testKillRobotSlowly() throws MalformedURLException, ExecutionException, InterruptedException, public void testKillRobotSlowly() throws MalformedURLException, ExecutionException, InterruptedException,
TimeoutException { TimeoutException {
assertEquals(client.action("robot", "kill", ImmutableMap.of("death", "slow")).trim(), "robot->kill:{death=slow}"); assertEquals(client.action("robot", "kill", ImmutableMap.of("death", "slow")).trim(), "robot->kill:{death=slow}");
} }
@Test(invocationCount = 25, timeOut = 5000) @Test(invocationCount = 5, timeOut = 5000)
public void testHead() throws MalformedURLException, ExecutionException, InterruptedException, TimeoutException { public void testHead() throws MalformedURLException, ExecutionException, InterruptedException, TimeoutException {
assert client.exists(""); assert client.exists("");
} }
@Test(invocationCount = 25, timeOut = 5000) @Test(invocationCount = 5, timeOut = 5000)
public void testGetAndParseSax() throws MalformedURLException, ExecutionException, InterruptedException, public void testGetAndParseSax() throws MalformedURLException, ExecutionException, InterruptedException,
TimeoutException { TimeoutException {
assertEquals(client.downloadAndParse(""), "whoppers"); assertEquals(client.downloadAndParse(""), "whoppers");

View File

@ -20,11 +20,16 @@
package org.jclouds.http; package org.jclouds.http;
import java.io.File; import java.io.File;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.Map; import java.util.Map;
import javax.ws.rs.GET; import javax.ws.rs.GET;
import javax.ws.rs.HEAD; import javax.ws.rs.HEAD;
import javax.ws.rs.HeaderParam; import javax.ws.rs.HeaderParam;
import javax.ws.rs.HttpMethod;
import javax.ws.rs.POST; import javax.ws.rs.POST;
import javax.ws.rs.PUT; import javax.ws.rs.PUT;
import javax.ws.rs.Path; import javax.ws.rs.Path;
@ -53,6 +58,15 @@ import com.google.common.util.concurrent.ListenableFuture;
* @author Adrian Cole * @author Adrian Cole
*/ */
public interface IntegrationTestAsyncClient { public interface IntegrationTestAsyncClient {
@Target( { ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@HttpMethod("ROWDY")
public @interface ROWDY {
}
@ROWDY
@Path("objects/{id}")
ListenableFuture<String> rowdy(@PathParam("id") String path);
@HEAD @HEAD
@Path("objects/{id}") @Path("objects/{id}")
@ -82,18 +96,15 @@ public interface IntegrationTestAsyncClient {
@GET @GET
@Path("objects/{id}") @Path("objects/{id}")
@ExceptionParser(FooOnException.class) @ExceptionParser(FooOnException.class)
ListenableFuture<String> synchException(@PathParam("id") String id, ListenableFuture<String> synchException(@PathParam("id") String id, @HeaderParam("Range") String header);
@HeaderParam("Range") String header);
@PUT @PUT
@Path("objects/{id}") @Path("objects/{id}")
ListenableFuture<String> upload(@PathParam("id") String id, ListenableFuture<String> upload(@PathParam("id") String id, @BinderParam(BindToStringPayload.class) String toPut);
@BinderParam(BindToStringPayload.class) String toPut);
@POST @POST
@Path("objects/{id}") @Path("objects/{id}")
ListenableFuture<String> post(@PathParam("id") String id, ListenableFuture<String> post(@PathParam("id") String id, @BinderParam(BindToStringPayload.class) String toPut);
@BinderParam(BindToStringPayload.class) String toPut);
@POST @POST
@Path("objects/{id}") @Path("objects/{id}")
@ -111,8 +122,7 @@ public interface IntegrationTestAsyncClient {
@POST @POST
@Path("objects/{id}") @Path("objects/{id}")
ListenableFuture<String> postWithMd5(@PathParam("id") String id, ListenableFuture<String> postWithMd5(@PathParam("id") String id, @HeaderParam("Content-MD5") String base64MD5,
@HeaderParam("Content-MD5") String base64MD5,
@BinderParam(BindToFilePayload.class) File file); @BinderParam(BindToFilePayload.class) File file);
static class BindToFilePayload implements Binder { static class BindToFilePayload implements Binder {
@ -126,8 +136,7 @@ public interface IntegrationTestAsyncClient {
@POST @POST
@Path("objects/{id}") @Path("objects/{id}")
@MapBinder(BindToJsonPayload.class) @MapBinder(BindToJsonPayload.class)
ListenableFuture<String> postJson(@PathParam("id") String id, ListenableFuture<String> postJson(@PathParam("id") String id, @MapPayloadParam("key") String toPut);
@MapPayloadParam("key") String toPut);
@POST @POST
@Path("objects/{id}/action/{action}") @Path("objects/{id}/action/{action}")
@ -137,8 +146,7 @@ public interface IntegrationTestAsyncClient {
@GET @GET
@Path("objects/{id}") @Path("objects/{id}")
@RequestFilters(Filter.class) @RequestFilters(Filter.class)
ListenableFuture<String> downloadFilter(@PathParam("id") String id, ListenableFuture<String> downloadFilter(@PathParam("id") String id, @HeaderParam("filterme") String header);
@HeaderParam("filterme") String header);
static class Filter implements HttpRequestFilter { static class Filter implements HttpRequestFilter {
public void filter(HttpRequest request) throws HttpException { public void filter(HttpRequest request) throws HttpException {

View File

@ -33,6 +33,7 @@ import org.jclouds.http.options.HttpRequestOptions;
*/ */
@Timeout(duration = 40, timeUnit = TimeUnit.SECONDS) @Timeout(duration = 40, timeUnit = TimeUnit.SECONDS)
public interface IntegrationTestClient { public interface IntegrationTestClient {
String rowdy(String path);
boolean exists(String path); boolean exists(String path);

View File

@ -216,7 +216,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public void testDelegateAsync() throws SecurityException, NoSuchMethodException, InterruptedException, public void testDelegateAsync() throws SecurityException, NoSuchMethodException, InterruptedException,
ExecutionException { ExecutionException {
Injector child = injectorForClient(); Injector child = injectorForClient();
TransformingHttpCommandExecutorService mock = child.getInstance(TransformingHttpCommandExecutorService.class); TransformingHttpCommandExecutorService mock = child.getInstance(TransformingHttpCommandExecutorService.class);
@ -231,9 +231,9 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest {
AsyncCaller caller = child.getInstance(AsyncCaller.class); AsyncCaller caller = child.getInstance(AsyncCaller.class);
expect(mock.submit(requestLineEquals("GET http://localhost:9999/goo/client/foo HTTP/1.1"), eq(function))) expect(mock.submit(requestLineEquals("GET http://localhost:9999/goo/client/foo HTTP/1.1"), eq(function)))
.andReturn(createNiceMock(ListenableFuture.class)).atLeastOnce(); .andReturn(createNiceMock(ListenableFuture.class)).atLeastOnce();
expect(mock.submit(requestLineEquals("GET http://localhost:9999/client/foo HTTP/1.1"), eq(function))).andReturn( expect(mock.submit(requestLineEquals("GET http://localhost:9999/client/foo HTTP/1.1"), eq(function))).andReturn(
createNiceMock(ListenableFuture.class)).atLeastOnce(); createNiceMock(ListenableFuture.class)).atLeastOnce();
replay(mock); replay(mock);
caller.getCallee("goo").onePath("foo"); caller.getCallee("goo").onePath("foo");
@ -263,7 +263,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest {
} }
public void testDelegateWithOverridingEndpoint() throws SecurityException, NoSuchMethodException, public void testDelegateWithOverridingEndpoint() throws SecurityException, NoSuchMethodException,
InterruptedException, ExecutionException { InterruptedException, ExecutionException {
Injector child = injectorForClient(); Injector child = injectorForClient();
TransformingHttpCommandExecutorService mock = child.getInstance(TransformingHttpCommandExecutorService.class); TransformingHttpCommandExecutorService mock = child.getInstance(TransformingHttpCommandExecutorService.class);
@ -278,10 +278,10 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest {
Caller caller = child.getInstance(Caller.class); Caller caller = child.getInstance(Caller.class);
expect(mock.submit(requestLineEquals("GET http://localhost:1111/goo/client/foo HTTP/1.1"), eq(function))) expect(mock.submit(requestLineEquals("GET http://localhost:1111/goo/client/foo HTTP/1.1"), eq(function)))
.andReturn(Futures.<Void> immediateFuture(null)).atLeastOnce(); .andReturn(Futures.<Void> immediateFuture(null)).atLeastOnce();
expect(mock.submit(requestLineEquals("GET http://localhost:1111/client/foo HTTP/1.1"), eq(function))).andReturn( expect(mock.submit(requestLineEquals("GET http://localhost:1111/client/foo HTTP/1.1"), eq(function))).andReturn(
Futures.<Void> immediateFuture(null)).atLeastOnce(); Futures.<Void> immediateFuture(null)).atLeastOnce();
replay(mock); replay(mock);
caller.getCallee("goo").onePath("foo"); caller.getCallee("goo").onePath("foo");
@ -294,8 +294,8 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest {
private Injector injectorForClient() { private Injector injectorForClient() {
ContextSpec<Caller, AsyncCaller> contextSpec = contextSpec("test", "http://localhost:9999", "1", "userfoo", null, ContextSpec<Caller, AsyncCaller> contextSpec = contextSpec("test", "http://localhost:9999", "1", "userfoo", null,
Caller.class, AsyncCaller.class, ImmutableSet.<Module> of(new MockModule(), new NullLoggingModule(), Caller.class, AsyncCaller.class, ImmutableSet.<Module> of(new MockModule(), new NullLoggingModule(),
new CallerCalleeModule())); new CallerCalleeModule()));
return createContextBuilder(contextSpec).buildInjector(); return createContextBuilder(contextSpec).buildInjector();
@ -314,7 +314,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public void testDelegateWithPathOnClass() throws SecurityException, NoSuchMethodException, InterruptedException, public void testDelegateWithPathOnClass() throws SecurityException, NoSuchMethodException, InterruptedException,
ExecutionException { ExecutionException {
Injector child = injectorForClient(); Injector child = injectorForClient();
TransformingHttpCommandExecutorService mock = child.getInstance(TransformingHttpCommandExecutorService.class); TransformingHttpCommandExecutorService mock = child.getInstance(TransformingHttpCommandExecutorService.class);
@ -331,10 +331,10 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest {
CallerWithPathOnClass caller = factory.create(CallerWithPathOnClass.class); CallerWithPathOnClass caller = factory.create(CallerWithPathOnClass.class);
expect(mock.submit(requestLineEquals("GET http://localhost:9999/caller/goo/client/foo HTTP/1.1"), eq(function))) expect(mock.submit(requestLineEquals("GET http://localhost:9999/caller/goo/client/foo HTTP/1.1"), eq(function)))
.andReturn(createNiceMock(ListenableFuture.class)).atLeastOnce(); .andReturn(createNiceMock(ListenableFuture.class)).atLeastOnce();
expect(mock.submit(requestLineEquals("GET http://localhost:9999/caller/client/foo HTTP/1.1"), eq(function))) expect(mock.submit(requestLineEquals("GET http://localhost:9999/caller/client/foo HTTP/1.1"), eq(function)))
.andReturn(createNiceMock(ListenableFuture.class)).atLeastOnce(); .andReturn(createNiceMock(ListenableFuture.class)).atLeastOnce();
replay(mock); replay(mock);
caller.getCallee("goo").onePath("foo"); caller.getCallee("goo").onePath("foo");
caller.getCallee().onePath("foo"); caller.getCallee().onePath("foo");
@ -383,10 +383,10 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest {
public void testUnEncodeQuery() { public void testUnEncodeQuery() {
URI expects = URI URI expects = URI
.create("http://services.nirvanix.com/ws/Metadata/SetMetadata.ashx?output=json&path=adriancole-compute.testObjectOperations&metadata=chef:sushi&metadata=foo:bar&sessionToken=775ef26e-0740-4707-ad92-afe9814bc436"); .create("http://services.nirvanix.com/ws/Metadata/SetMetadata.ashx?output=json&path=adriancole-compute.testObjectOperations&metadata=chef:sushi&metadata=foo:bar&sessionToken=775ef26e-0740-4707-ad92-afe9814bc436");
URI start = URI URI start = URI
.create("http://services.nirvanix.com/ws/Metadata/SetMetadata.ashx?output=json&path=adriancole-compute.testObjectOperations&metadata=chef%3Asushi&metadata=foo%3Abar&sessionToken=775ef26e-0740-4707-ad92-afe9814bc436"); .create("http://services.nirvanix.com/ws/Metadata/SetMetadata.ashx?output=json&path=adriancole-compute.testObjectOperations&metadata=chef%3Asushi&metadata=foo%3Abar&sessionToken=775ef26e-0740-4707-ad92-afe9814bc436");
URI value = RestAnnotationProcessor.replaceQuery(uriBuilderProvider, start, start.getQuery(), null, '/', ':'); URI value = RestAnnotationProcessor.replaceQuery(uriBuilderProvider, start, start.getQuery(), null, '/', ':');
assertEquals(value, expects); assertEquals(value, expects);
} }
@ -434,7 +434,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest {
public void testPayloadParamVarargs() throws SecurityException, NoSuchMethodException, IOException { public void testPayloadParamVarargs() throws SecurityException, NoSuchMethodException, IOException {
Method method = TestPayloadParamVarargs.class.getMethod("varargs", Array.newInstance(HttpRequestOptions.class, 0) Method method = TestPayloadParamVarargs.class.getMethod("varargs", Array.newInstance(HttpRequestOptions.class, 0)
.getClass()); .getClass());
verifyTestPostOptions(method); verifyTestPostOptions(method);
} }
@ -527,7 +527,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest {
public void testOverriddenEndpointParameter() throws SecurityException, NoSuchMethodException { public void testOverriddenEndpointParameter() throws SecurityException, NoSuchMethodException {
Method method = TestOverriddenEndpoint.class.getMethod("foo", URI.class); Method method = TestOverriddenEndpoint.class.getMethod("foo", URI.class);
HttpRequest request = factory(TestOverriddenEndpoint.class).createRequest(method, HttpRequest request = factory(TestOverriddenEndpoint.class).createRequest(method,
new Object[] { URI.create("http://wowsa:8001") }); new Object[] { URI.create("http://wowsa:8001") });
assertEquals(request.getEndpoint().getHost(), "wowsa"); assertEquals(request.getEndpoint().getHost(), "wowsa");
assertEquals(request.getEndpoint().getPort(), 8001); assertEquals(request.getEndpoint().getPort(), 8001);
assertEquals(request.getEndpoint().getPath(), ""); assertEquals(request.getEndpoint().getPath(), "");
@ -618,44 +618,44 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest {
@POST @POST
void withParamFileBinaryPart(@FormParam("name") String name, void withParamFileBinaryPart(@FormParam("name") String name,
@PartParam(name = "file", contentType = MediaType.APPLICATION_OCTET_STREAM) File path); @PartParam(name = "file", contentType = MediaType.APPLICATION_OCTET_STREAM) File path);
@POST @POST
void withParamByteArrayBinaryPart( void withParamByteArrayBinaryPart(
@FormParam("name") String name, @FormParam("name") String name,
@PartParam(name = "file", contentType = MediaType.APPLICATION_OCTET_STREAM, filename = "{name}.tar.gz") byte[] content); @PartParam(name = "file", contentType = MediaType.APPLICATION_OCTET_STREAM, filename = "{name}.tar.gz") byte[] content);
} }
public void testMultipartWithStringPart() throws SecurityException, NoSuchMethodException, IOException { public void testMultipartWithStringPart() throws SecurityException, NoSuchMethodException, IOException {
Method method = TestMultipartForm.class.getMethod("withStringPart", String.class); Method method = TestMultipartForm.class.getMethod("withStringPart", String.class);
GeneratedHttpRequest<TestMultipartForm> httpRequest = factory(TestMultipartForm.class).createRequest(method, GeneratedHttpRequest<TestMultipartForm> httpRequest = factory(TestMultipartForm.class).createRequest(method,
"foobledata"); "foobledata");
assertRequestLineEquals(httpRequest, "POST http://localhost:9999 HTTP/1.1"); assertRequestLineEquals(httpRequest, "POST http://localhost:9999 HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, ""); assertNonPayloadHeadersEqual(httpRequest, "");
assertPayloadEquals(httpRequest,// assertPayloadEquals(httpRequest,//
"----JCLOUDS--\r\n" + // "----JCLOUDS--\r\n" + //
"Content-Disposition: form-data; name=\"fooble\"\r\n" + // "Content-Disposition: form-data; name=\"fooble\"\r\n" + //
"\r\n" + // "\r\n" + //
"foobledata\r\n" + // "foobledata\r\n" + //
"----JCLOUDS----\r\n", "multipart/form-data; boundary=--JCLOUDS--", false); "----JCLOUDS----\r\n", "multipart/form-data; boundary=--JCLOUDS--", false);
} }
public void testMultipartWithParamStringPart() throws SecurityException, NoSuchMethodException, IOException { public void testMultipartWithParamStringPart() throws SecurityException, NoSuchMethodException, IOException {
Method method = TestMultipartForm.class.getMethod("withParamStringPart", String.class, String.class); Method method = TestMultipartForm.class.getMethod("withParamStringPart", String.class, String.class);
GeneratedHttpRequest<TestMultipartForm> httpRequest = factory(TestMultipartForm.class).createRequest(method, GeneratedHttpRequest<TestMultipartForm> httpRequest = factory(TestMultipartForm.class).createRequest(method,
"name", "foobledata"); "name", "foobledata");
assertRequestLineEquals(httpRequest, "POST http://localhost:9999 HTTP/1.1"); assertRequestLineEquals(httpRequest, "POST http://localhost:9999 HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, ""); assertNonPayloadHeadersEqual(httpRequest, "");
assertPayloadEquals(httpRequest,// assertPayloadEquals(httpRequest,//
"----JCLOUDS--\r\n" + // "----JCLOUDS--\r\n" + //
"Content-Disposition: form-data; name=\"name\"\r\n" + // "Content-Disposition: form-data; name=\"name\"\r\n" + //
"\r\n" + // "\r\n" + //
"name\r\n" + // / "name\r\n" + // /
"----JCLOUDS--\r\n" + // "----JCLOUDS--\r\n" + //
"Content-Disposition: form-data; name=\"file\"\r\n" + // "Content-Disposition: form-data; name=\"file\"\r\n" + //
"\r\n" + // "\r\n" + //
"foobledata\r\n" + // "foobledata\r\n" + //
"----JCLOUDS----\r\n", "multipart/form-data; boundary=--JCLOUDS--", false); "----JCLOUDS----\r\n", "multipart/form-data; boundary=--JCLOUDS--", false);
} }
public void testMultipartWithParamFilePart() throws SecurityException, NoSuchMethodException, IOException { public void testMultipartWithParamFilePart() throws SecurityException, NoSuchMethodException, IOException {
@ -665,38 +665,38 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest {
file.deleteOnExit(); file.deleteOnExit();
GeneratedHttpRequest<TestMultipartForm> httpRequest = factory(TestMultipartForm.class).createRequest(method, GeneratedHttpRequest<TestMultipartForm> httpRequest = factory(TestMultipartForm.class).createRequest(method,
"name", file); "name", file);
assertRequestLineEquals(httpRequest, "POST http://localhost:9999 HTTP/1.1"); assertRequestLineEquals(httpRequest, "POST http://localhost:9999 HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, ""); assertNonPayloadHeadersEqual(httpRequest, "");
assertPayloadEquals(httpRequest,// assertPayloadEquals(httpRequest,//
"----JCLOUDS--\r\n" + // "----JCLOUDS--\r\n" + //
"Content-Disposition: form-data; name=\"name\"\r\n" + // "Content-Disposition: form-data; name=\"name\"\r\n" + //
"\r\n" + // "\r\n" + //
"name\r\n" + // / "name\r\n" + // /
"----JCLOUDS--\r\n" + // "----JCLOUDS--\r\n" + //
"Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getName() + "\"\r\n" + // "Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getName() + "\"\r\n" + //
"\r\n" + // "\r\n" + //
"foobledata\r\n" + // "foobledata\r\n" + //
"----JCLOUDS----\r\n", "multipart/form-data; boundary=--JCLOUDS--", false); "----JCLOUDS----\r\n", "multipart/form-data; boundary=--JCLOUDS--", false);
} }
public void testMultipartWithParamByteArrayPart() throws SecurityException, NoSuchMethodException, IOException { public void testMultipartWithParamByteArrayPart() throws SecurityException, NoSuchMethodException, IOException {
Method method = TestMultipartForm.class.getMethod("withParamByteArrayBinaryPart", String.class, byte[].class); Method method = TestMultipartForm.class.getMethod("withParamByteArrayBinaryPart", String.class, byte[].class);
GeneratedHttpRequest<TestMultipartForm> httpRequest = factory(TestMultipartForm.class).createRequest(method, GeneratedHttpRequest<TestMultipartForm> httpRequest = factory(TestMultipartForm.class).createRequest(method,
"name", "goo".getBytes()); "name", "goo".getBytes());
assertRequestLineEquals(httpRequest, "POST http://localhost:9999 HTTP/1.1"); assertRequestLineEquals(httpRequest, "POST http://localhost:9999 HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, ""); assertNonPayloadHeadersEqual(httpRequest, "");
assertPayloadEquals(httpRequest,// assertPayloadEquals(httpRequest,//
"----JCLOUDS--\r\n" + // "----JCLOUDS--\r\n" + //
"Content-Disposition: form-data; name=\"name\"\r\n" + // "Content-Disposition: form-data; name=\"name\"\r\n" + //
"\r\n" + // "\r\n" + //
"name\r\n" + // / "name\r\n" + // /
"----JCLOUDS--\r\n" + // "----JCLOUDS--\r\n" + //
"Content-Disposition: form-data; name=\"file\"; filename=\"name.tar.gz\"\r\n" + // "Content-Disposition: form-data; name=\"file\"; filename=\"name.tar.gz\"\r\n" + //
"Content-Type: application/octet-stream\r\n" + // "Content-Type: application/octet-stream\r\n" + //
"\r\n" + // "\r\n" + //
"goo\r\n" + // "goo\r\n" + //
"----JCLOUDS----\r\n", "multipart/form-data; boundary=--JCLOUDS--", false); "----JCLOUDS----\r\n", "multipart/form-data; boundary=--JCLOUDS--", false);
}; };
public void testMultipartWithParamFileBinaryPart() throws SecurityException, NoSuchMethodException, IOException { public void testMultipartWithParamFileBinaryPart() throws SecurityException, NoSuchMethodException, IOException {
@ -706,20 +706,20 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest {
file.deleteOnExit(); file.deleteOnExit();
GeneratedHttpRequest<TestMultipartForm> httpRequest = factory(TestMultipartForm.class).createRequest(method, GeneratedHttpRequest<TestMultipartForm> httpRequest = factory(TestMultipartForm.class).createRequest(method,
"name", file); "name", file);
assertRequestLineEquals(httpRequest, "POST http://localhost:9999 HTTP/1.1"); assertRequestLineEquals(httpRequest, "POST http://localhost:9999 HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, ""); assertNonPayloadHeadersEqual(httpRequest, "");
assertPayloadEquals(httpRequest,// assertPayloadEquals(httpRequest,//
"----JCLOUDS--\r\n" + // "----JCLOUDS--\r\n" + //
"Content-Disposition: form-data; name=\"name\"\r\n" + // "Content-Disposition: form-data; name=\"name\"\r\n" + //
"\r\n" + // "\r\n" + //
"name\r\n" + // / "name\r\n" + // /
"----JCLOUDS--\r\n" + // "----JCLOUDS--\r\n" + //
"Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getName() + "\"\r\n" + // "Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getName() + "\"\r\n" + //
"Content-Type: application/octet-stream\r\n" + // "Content-Type: application/octet-stream\r\n" + //
"\r\n" + // "\r\n" + //
"'(2\r\n" + // "'(2\r\n" + //
"----JCLOUDS----\r\n", "multipart/form-data; boundary=--JCLOUDS--", false); "----JCLOUDS----\r\n", "multipart/form-data; boundary=--JCLOUDS--", false);
} }
public interface TestPut { public interface TestPut {
@ -770,12 +770,31 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest {
@Unwrap @Unwrap
@Consumes(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON)
ListenableFuture<? extends Set<String>> testUnwrap4(); ListenableFuture<? extends Set<String>> testUnwrap4();
@Target( { ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@HttpMethod("ROWDY")
public @interface ROWDY {
}
@ROWDY
@Path("objects/{id}")
ListenableFuture<Boolean> rowdy(@PathParam("id") String path);
} }
static class Wrapper { static class Wrapper {
String foo; String foo;
} }
public void testAlternateHttpMethod() throws SecurityException, NoSuchMethodException, IOException {
Method method = TestPut.class.getMethod("rowdy", String.class);
HttpRequest request = factory(TestPut.class).createRequest(method, "data");
assertRequestLineEquals(request, "ROWDY http://localhost:9999/objects/data HTTP/1.1");
assertNonPayloadHeadersEqual(request, "");
assertPayloadEquals(request, null, null, false);
}
public void testCreatePutWithMethodBinder() throws SecurityException, NoSuchMethodException, IOException { public void testCreatePutWithMethodBinder() throws SecurityException, NoSuchMethodException, IOException {
Method method = TestPut.class.getMethod("putWithMethodBinder", String.class); Method method = TestPut.class.getMethod("putWithMethodBinder", String.class);
HttpRequest request = factory(TestPut.class).createRequest(method, "data"); HttpRequest request = factory(TestPut.class).createRequest(method, "data");
@ -807,7 +826,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest {
// now test that it works! // now test that it works!
Function<HttpResponse, Wrapper> parser = (Function<HttpResponse, Wrapper>) RestAnnotationProcessor Function<HttpResponse, Wrapper> parser = (Function<HttpResponse, Wrapper>) RestAnnotationProcessor
.createResponseParser(parserFactory, injector, method, request); .createResponseParser(parserFactory, injector, method, request);
assertEquals(parser.apply(new HttpResponse(200, "ok", newStringPayload("{ foo:\"bar\"}"))).foo, "bar"); assertEquals(parser.apply(new HttpResponse(200, "ok", newStringPayload("{ foo:\"bar\"}"))).foo, "bar");
@ -822,10 +841,10 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest {
// now test that it works! // now test that it works!
Function<HttpResponse, Map<String, String>> parser = (Function<HttpResponse, Map<String, String>>) RestAnnotationProcessor Function<HttpResponse, Map<String, String>> parser = (Function<HttpResponse, Map<String, String>>) RestAnnotationProcessor
.createResponseParser(parserFactory, injector, method, request); .createResponseParser(parserFactory, injector, method, request);
assertEquals(parser.apply(new HttpResponse(200, "ok", newStringPayload("{ foo:\"bar\"}"))), ImmutableMap.of( assertEquals(parser.apply(new HttpResponse(200, "ok", newStringPayload("{ foo:\"bar\"}"))), ImmutableMap.of(
"foo", "bar")); "foo", "bar"));
} }
@ -838,10 +857,10 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest {
// now test that it works! // now test that it works!
Function<HttpResponse, Map<String, String>> parser = (Function<HttpResponse, Map<String, String>>) RestAnnotationProcessor Function<HttpResponse, Map<String, String>> parser = (Function<HttpResponse, Map<String, String>>) RestAnnotationProcessor
.createResponseParser(parserFactory, injector, method, request); .createResponseParser(parserFactory, injector, method, request);
assertEquals(parser.apply(new HttpResponse(200, "ok", newStringPayload("{ foo:\"bar\"}"))), ImmutableMap.of( assertEquals(parser.apply(new HttpResponse(200, "ok", newStringPayload("{ foo:\"bar\"}"))), ImmutableMap.of(
"foo", "bar")); "foo", "bar"));
} }
@ -854,10 +873,10 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest {
// now test that it works! // now test that it works!
Function<HttpResponse, Map<String, String>> parser = (Function<HttpResponse, Map<String, String>>) RestAnnotationProcessor Function<HttpResponse, Map<String, String>> parser = (Function<HttpResponse, Map<String, String>>) RestAnnotationProcessor
.createResponseParser(parserFactory, injector, method, request); .createResponseParser(parserFactory, injector, method, request);
assertEquals(parser.apply(new HttpResponse(200, "ok", newStringPayload("{ foo:\"bar\"}"))), ImmutableMap.of( assertEquals(parser.apply(new HttpResponse(200, "ok", newStringPayload("{ foo:\"bar\"}"))), ImmutableMap.of(
"foo", "bar")); "foo", "bar"));
} }
@ -870,7 +889,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest {
// now test that it works! // now test that it works!
Function<HttpResponse, Map<String, String>> parser = (Function<HttpResponse, Map<String, String>>) RestAnnotationProcessor Function<HttpResponse, Map<String, String>> parser = (Function<HttpResponse, Map<String, String>>) RestAnnotationProcessor
.createResponseParser(parserFactory, injector, method, request); .createResponseParser(parserFactory, injector, method, request);
assertEquals(parser.apply(new HttpResponse(200, "ok", newStringPayload("{ foo:\"bar\"}"))), "bar"); assertEquals(parser.apply(new HttpResponse(200, "ok", newStringPayload("{ foo:\"bar\"}"))), "bar");
@ -885,7 +904,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest {
// now test that it works! // now test that it works!
Function<HttpResponse, Map<String, String>> parser = (Function<HttpResponse, Map<String, String>>) RestAnnotationProcessor Function<HttpResponse, Map<String, String>> parser = (Function<HttpResponse, Map<String, String>>) RestAnnotationProcessor
.createResponseParser(parserFactory, injector, method, request); .createResponseParser(parserFactory, injector, method, request);
assertEquals(parser.apply(new HttpResponse(200, "ok", newStringPayload("{ foo:\"bar\"}"))), "bar"); assertEquals(parser.apply(new HttpResponse(200, "ok", newStringPayload("{ foo:\"bar\"}"))), "bar");
@ -900,10 +919,10 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest {
// now test that it works! // now test that it works!
Function<HttpResponse, Map<String, String>> parser = (Function<HttpResponse, Map<String, String>>) RestAnnotationProcessor Function<HttpResponse, Map<String, String>> parser = (Function<HttpResponse, Map<String, String>>) RestAnnotationProcessor
.createResponseParser(parserFactory, injector, method, request); .createResponseParser(parserFactory, injector, method, request);
assertEquals(parser.apply(new HttpResponse(200, "ok", newStringPayload("{\"runit\":[\"0.7.0\",\"0.7.1\"]}"))), assertEquals(parser.apply(new HttpResponse(200, "ok", newStringPayload("{\"runit\":[\"0.7.0\",\"0.7.1\"]}"))),
ImmutableSet.of("0.7.0", "0.7.1")); ImmutableSet.of("0.7.0", "0.7.1"));
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@ -915,10 +934,10 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest {
// now test that it works! // now test that it works!
Function<HttpResponse, Map<String, String>> parser = (Function<HttpResponse, Map<String, String>>) RestAnnotationProcessor Function<HttpResponse, Map<String, String>> parser = (Function<HttpResponse, Map<String, String>>) RestAnnotationProcessor
.createResponseParser(parserFactory, injector, method, request); .createResponseParser(parserFactory, injector, method, request);
assertEquals(parser.apply(new HttpResponse(200, "ok", newStringPayload("{\"runit\":[\"0.7.0\",\"0.7.1\"]}"))), assertEquals(parser.apply(new HttpResponse(200, "ok", newStringPayload("{\"runit\":[\"0.7.0\",\"0.7.1\"]}"))),
ImmutableSet.of("0.7.0", "0.7.1")); ImmutableSet.of("0.7.0", "0.7.1"));
} }
static class TestRequestFilter1 implements HttpRequestFilter { static class TestRequestFilter1 implements HttpRequestFilter {
@ -1003,7 +1022,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest {
public void testConstantPathParam() throws SecurityException, NoSuchMethodException, IOException { public void testConstantPathParam() throws SecurityException, NoSuchMethodException, IOException {
Method method = TestConstantPathParam.class.getMethod("twoPaths", String.class, String.class); Method method = TestConstantPathParam.class.getMethod("twoPaths", String.class, String.class);
HttpRequest request = factory(TestConstantPathParam.class).createRequest(method, HttpRequest request = factory(TestConstantPathParam.class).createRequest(method,
new Object[] { "1", "localhost" }); new Object[] { "1", "localhost" });
assertRequestLineEquals(request, "GET http://localhost:9999/v1/ralphie/1/localhost HTTP/1.1"); assertRequestLineEquals(request, "GET http://localhost:9999/v1/ralphie/1/localhost HTTP/1.1");
assertNonPayloadHeadersEqual(request, ""); assertNonPayloadHeadersEqual(request, "");
assertPayloadEquals(request, null, null, false); assertPayloadEquals(request, null, null, false);
@ -1136,7 +1155,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest {
public void testBuildTwoHeader() throws SecurityException, NoSuchMethodException, UnsupportedEncodingException { public void testBuildTwoHeader() throws SecurityException, NoSuchMethodException, UnsupportedEncodingException {
Method oneHeader = TestHeader.class.getMethod("twoHeader", String.class); Method oneHeader = TestHeader.class.getMethod("twoHeader", String.class);
Multimap<String, String> headers = factory(TestHeader.class).createRequest(oneHeader, new Object[] { "robot" }) Multimap<String, String> headers = factory(TestHeader.class).createRequest(oneHeader, new Object[] { "robot" })
.getHeaders(); .getHeaders();
assertEquals(headers.size(), 2); assertEquals(headers.size(), 2);
assertEquals(headers.get("slash"), Collections.singletonList("/robot")); assertEquals(headers.get("slash"), Collections.singletonList("/robot"));
assertEquals(headers.get("hyphen"), Collections.singletonList("-robot")); assertEquals(headers.get("hyphen"), Collections.singletonList("-robot"));
@ -1153,7 +1172,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest {
public void testBuildOneClassHeader() throws SecurityException, NoSuchMethodException, UnsupportedEncodingException { public void testBuildOneClassHeader() throws SecurityException, NoSuchMethodException, UnsupportedEncodingException {
Method oneHeader = TestClassHeader.class.getMethod("oneHeader", String.class); Method oneHeader = TestClassHeader.class.getMethod("oneHeader", String.class);
Multimap<String, String> headers = factory(TestClassHeader.class).createRequest(oneHeader, Multimap<String, String> headers = factory(TestClassHeader.class).createRequest(oneHeader,
new Object[] { "robot" }).getHeaders(); new Object[] { "robot" }).getHeaders();
assertEquals(headers.size(), 1); assertEquals(headers.size(), 1);
assertEquals(headers.get("x-amz-copy-source"), Collections.singletonList("/robot")); assertEquals(headers.get("x-amz-copy-source"), Collections.singletonList("/robot"));
} }
@ -1162,7 +1181,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest {
public void testBuildOneHeader() throws SecurityException, NoSuchMethodException, UnsupportedEncodingException { public void testBuildOneHeader() throws SecurityException, NoSuchMethodException, UnsupportedEncodingException {
Method oneHeader = TestHeader.class.getMethod("oneHeader", String.class); Method oneHeader = TestHeader.class.getMethod("oneHeader", String.class);
Multimap<String, String> headers = factory(TestHeader.class).createRequest(oneHeader, new Object[] { "robot" }) Multimap<String, String> headers = factory(TestHeader.class).createRequest(oneHeader, new Object[] { "robot" })
.getHeaders(); .getHeaders();
assertEquals(headers.size(), 1); assertEquals(headers.size(), 1);
assertEquals(headers.get("x-amz-copy-source"), Collections.singletonList("/robot")); assertEquals(headers.get("x-amz-copy-source"), Collections.singletonList("/robot"));
} }
@ -1171,17 +1190,17 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest {
public void testBuildTwoHeaders() throws SecurityException, NoSuchMethodException, UnsupportedEncodingException { public void testBuildTwoHeaders() throws SecurityException, NoSuchMethodException, UnsupportedEncodingException {
Method twoHeaders = TestHeader.class.getMethod("twoHeaders", String.class, String.class); Method twoHeaders = TestHeader.class.getMethod("twoHeaders", String.class, String.class);
Multimap<String, String> headers = factory(TestHeader.class).createRequest(twoHeaders, Multimap<String, String> headers = factory(TestHeader.class).createRequest(twoHeaders,
new Object[] { "robot", "eggs" }).getHeaders(); new Object[] { "robot", "eggs" }).getHeaders();
assertEquals(headers.size(), 1); assertEquals(headers.size(), 1);
assertEquals(headers.get("x-amz-copy-source"), Collections.singletonList("/robot/eggs")); assertEquals(headers.get("x-amz-copy-source"), Collections.singletonList("/robot/eggs"));
} }
@Test @Test
public void testBuildTwoHeadersOutOfOrder() throws SecurityException, NoSuchMethodException, public void testBuildTwoHeadersOutOfOrder() throws SecurityException, NoSuchMethodException,
UnsupportedEncodingException { UnsupportedEncodingException {
Method twoHeadersOutOfOrder = TestHeader.class.getMethod("twoHeadersOutOfOrder", String.class, String.class); Method twoHeadersOutOfOrder = TestHeader.class.getMethod("twoHeadersOutOfOrder", String.class, String.class);
Multimap<String, String> headers = factory(TestHeader.class).createRequest(twoHeadersOutOfOrder, Multimap<String, String> headers = factory(TestHeader.class).createRequest(twoHeadersOutOfOrder,
new Object[] { "robot", "eggs" }).getHeaders(); new Object[] { "robot", "eggs" }).getHeaders();
assertEquals(headers.size(), 1); assertEquals(headers.size(), 1);
assertEquals(headers.get("x-amz-copy-source"), Collections.singletonList("/eggs/robot")); assertEquals(headers.get("x-amz-copy-source"), Collections.singletonList("/eggs/robot"));
} }
@ -1196,7 +1215,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest {
public void testQueryInOptions() throws SecurityException, NoSuchMethodException, UnsupportedEncodingException { public void testQueryInOptions() throws SecurityException, NoSuchMethodException, UnsupportedEncodingException {
Method oneQuery = TestQueryReplace.class.getMethod("queryInOptions", String.class, TestReplaceQueryOptions.class); Method oneQuery = TestQueryReplace.class.getMethod("queryInOptions", String.class, TestReplaceQueryOptions.class);
String query = factory(TestQueryReplace.class).createRequest(oneQuery, String query = factory(TestQueryReplace.class).createRequest(oneQuery,
new Object[] { "robot", new TestReplaceQueryOptions() }).getEndpoint().getQuery(); new Object[] { "robot", new TestReplaceQueryOptions() }).getEndpoint().getQuery();
assertEquals(query, "x-amz-copy-source=/robot"); assertEquals(query, "x-amz-copy-source=/robot");
} }
@ -1204,13 +1223,13 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest {
@POST @POST
@Path("objects/{id}/action/{action}") @Path("objects/{id}/action/{action}")
ListenableFuture<String> action(@PathParam("id") String id, @PathParam("action") String action, ListenableFuture<String> action(@PathParam("id") String id, @PathParam("action") String action,
@BinderParam(BindMapToMatrixParams.class) Map<String, String> options); @BinderParam(BindMapToMatrixParams.class) Map<String, String> options);
} }
public void testTestMapMatrixParams() throws SecurityException, NoSuchMethodException, UnsupportedEncodingException { public void testTestMapMatrixParams() throws SecurityException, NoSuchMethodException, UnsupportedEncodingException {
Method method = TestMapMatrixParams.class.getMethod("action", String.class, String.class, Map.class); Method method = TestMapMatrixParams.class.getMethod("action", String.class, String.class, Map.class);
HttpRequest request = factory(TestMapMatrixParams.class).createRequest(method, HttpRequest request = factory(TestMapMatrixParams.class).createRequest(method,
new Object[] { "robot", "kill", ImmutableMap.of("death", "slow") }); new Object[] { "robot", "kill", ImmutableMap.of("death", "slow") });
assertRequestLineEquals(request, "POST http://localhost:9999/objects/robot/action/kill;death=slow HTTP/1.1"); assertRequestLineEquals(request, "POST http://localhost:9999/objects/robot/action/kill;death=slow HTTP/1.1");
assertEquals(request.getHeaders().size(), 0); assertEquals(request.getHeaders().size(), 0);
} }
@ -1247,7 +1266,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest {
public void testBuildTwoQuery() throws SecurityException, NoSuchMethodException, UnsupportedEncodingException { public void testBuildTwoQuery() throws SecurityException, NoSuchMethodException, UnsupportedEncodingException {
Method oneQuery = TestQueryReplace.class.getMethod("twoQuery", String.class); Method oneQuery = TestQueryReplace.class.getMethod("twoQuery", String.class);
String query = factory(TestQueryReplace.class).createRequest(oneQuery, new Object[] { "robot" }).getEndpoint() String query = factory(TestQueryReplace.class).createRequest(oneQuery, new Object[] { "robot" }).getEndpoint()
.getQuery(); .getQuery();
assertEquals(query, "slash=/robot&hyphen=-robot"); assertEquals(query, "slash=/robot&hyphen=-robot");
} }
@ -1262,7 +1281,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest {
public void testBuildOneClassQuery() throws SecurityException, NoSuchMethodException, UnsupportedEncodingException { public void testBuildOneClassQuery() throws SecurityException, NoSuchMethodException, UnsupportedEncodingException {
Method oneQuery = TestClassQuery.class.getMethod("oneQuery", String.class); Method oneQuery = TestClassQuery.class.getMethod("oneQuery", String.class);
String query = factory(TestClassQuery.class).createRequest(oneQuery, new Object[] { "robot" }).getEndpoint() String query = factory(TestClassQuery.class).createRequest(oneQuery, new Object[] { "robot" }).getEndpoint()
.getQuery(); .getQuery();
assertEquals(query, "x-amz-copy-source=/robot"); assertEquals(query, "x-amz-copy-source=/robot");
} }
@ -1270,7 +1289,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest {
public void testBuildOneQuery() throws SecurityException, NoSuchMethodException, UnsupportedEncodingException { public void testBuildOneQuery() throws SecurityException, NoSuchMethodException, UnsupportedEncodingException {
Method oneQuery = TestQueryReplace.class.getMethod("oneQuery", String.class); Method oneQuery = TestQueryReplace.class.getMethod("oneQuery", String.class);
String query = factory(TestQueryReplace.class).createRequest(oneQuery, new Object[] { "robot" }).getEndpoint() String query = factory(TestQueryReplace.class).createRequest(oneQuery, new Object[] { "robot" }).getEndpoint()
.getQuery(); .getQuery();
assertEquals(query, "x-amz-copy-source=/robot"); assertEquals(query, "x-amz-copy-source=/robot");
} }
@ -1278,16 +1297,16 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest {
public void testBuildTwoQuerys() throws SecurityException, NoSuchMethodException, UnsupportedEncodingException { public void testBuildTwoQuerys() throws SecurityException, NoSuchMethodException, UnsupportedEncodingException {
Method twoQuerys = TestQueryReplace.class.getMethod("twoQuerys", String.class, String.class); Method twoQuerys = TestQueryReplace.class.getMethod("twoQuerys", String.class, String.class);
String query = factory(TestQueryReplace.class).createRequest(twoQuerys, new Object[] { "robot", "eggs" }) String query = factory(TestQueryReplace.class).createRequest(twoQuerys, new Object[] { "robot", "eggs" })
.getEndpoint().getQuery(); .getEndpoint().getQuery();
assertEquals(query, "x-amz-copy-source=/robot/eggs"); assertEquals(query, "x-amz-copy-source=/robot/eggs");
} }
@Test @Test
public void testBuildTwoQuerysOutOfOrder() throws SecurityException, NoSuchMethodException, public void testBuildTwoQuerysOutOfOrder() throws SecurityException, NoSuchMethodException,
UnsupportedEncodingException { UnsupportedEncodingException {
Method twoQuerysOutOfOrder = TestQueryReplace.class.getMethod("twoQuerysOutOfOrder", String.class, String.class); Method twoQuerysOutOfOrder = TestQueryReplace.class.getMethod("twoQuerysOutOfOrder", String.class, String.class);
String query = factory(TestQueryReplace.class).createRequest(twoQuerysOutOfOrder, String query = factory(TestQueryReplace.class).createRequest(twoQuerysOutOfOrder,
new Object[] { "robot", "eggs" }).getEndpoint().getQuery(); new Object[] { "robot", "eggs" }).getEndpoint().getQuery();
assertEquals(query, "x-amz-copy-source=/eggs/robot"); assertEquals(query, "x-amz-copy-source=/eggs/robot");
} }
@ -1300,9 +1319,9 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest {
@Test @Test
public void testMatrixInOptions() throws SecurityException, NoSuchMethodException, UnsupportedEncodingException { public void testMatrixInOptions() throws SecurityException, NoSuchMethodException, UnsupportedEncodingException {
Method oneMatrix = TestMatrixReplace.class.getMethod("matrixInOptions", String.class, Method oneMatrix = TestMatrixReplace.class.getMethod("matrixInOptions", String.class,
TestReplaceMatrixOptions.class); TestReplaceMatrixOptions.class);
String path = factory(TestMatrixReplace.class).createRequest(oneMatrix, String path = factory(TestMatrixReplace.class).createRequest(oneMatrix,
new Object[] { "robot", new TestReplaceMatrixOptions() }).getEndpoint().getPath(); new Object[] { "robot", new TestReplaceMatrixOptions() }).getEndpoint().getPath();
assertEquals(path, "/;x-amz-copy-source=/robot"); assertEquals(path, "/;x-amz-copy-source=/robot");
} }
@ -1338,7 +1357,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest {
public void testBuildTwoMatrix() throws SecurityException, NoSuchMethodException, UnsupportedEncodingException { public void testBuildTwoMatrix() throws SecurityException, NoSuchMethodException, UnsupportedEncodingException {
Method oneMatrix = TestMatrixReplace.class.getMethod("twoMatrix", String.class); Method oneMatrix = TestMatrixReplace.class.getMethod("twoMatrix", String.class);
String path = factory(TestMatrixReplace.class).createRequest(oneMatrix, new Object[] { "robot" }).getEndpoint() String path = factory(TestMatrixReplace.class).createRequest(oneMatrix, new Object[] { "robot" }).getEndpoint()
.getPath(); .getPath();
assertEquals(path, "/;slash=/robot;hyphen=-robot"); assertEquals(path, "/;slash=/robot;hyphen=-robot");
} }
@ -1354,7 +1373,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest {
public void testBuildOneClassMatrix() throws SecurityException, NoSuchMethodException, UnsupportedEncodingException { public void testBuildOneClassMatrix() throws SecurityException, NoSuchMethodException, UnsupportedEncodingException {
Method oneMatrix = TestClassMatrix.class.getMethod("oneMatrix", String.class); Method oneMatrix = TestClassMatrix.class.getMethod("oneMatrix", String.class);
String path = factory(TestClassMatrix.class).createRequest(oneMatrix, new Object[] { "robot" }).getEndpoint() String path = factory(TestClassMatrix.class).createRequest(oneMatrix, new Object[] { "robot" }).getEndpoint()
.getPath(); .getPath();
assertEquals(path, "/;x-amz-copy-source=/robot"); assertEquals(path, "/;x-amz-copy-source=/robot");
} }
@ -1362,7 +1381,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest {
public void testBuildOneMatrix() throws SecurityException, NoSuchMethodException, UnsupportedEncodingException { public void testBuildOneMatrix() throws SecurityException, NoSuchMethodException, UnsupportedEncodingException {
Method oneMatrix = TestMatrixReplace.class.getMethod("oneMatrix", String.class); Method oneMatrix = TestMatrixReplace.class.getMethod("oneMatrix", String.class);
String path = factory(TestMatrixReplace.class).createRequest(oneMatrix, new Object[] { "robot" }).getEndpoint() String path = factory(TestMatrixReplace.class).createRequest(oneMatrix, new Object[] { "robot" }).getEndpoint()
.getPath(); .getPath();
assertEquals(path, "/;x-amz-copy-source=/robot"); assertEquals(path, "/;x-amz-copy-source=/robot");
} }
@ -1370,17 +1389,17 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest {
public void testBuildTwoMatrixs() throws SecurityException, NoSuchMethodException, UnsupportedEncodingException { public void testBuildTwoMatrixs() throws SecurityException, NoSuchMethodException, UnsupportedEncodingException {
Method twoMatrixs = TestMatrixReplace.class.getMethod("twoMatrixs", String.class, String.class); Method twoMatrixs = TestMatrixReplace.class.getMethod("twoMatrixs", String.class, String.class);
String path = factory(TestMatrixReplace.class).createRequest(twoMatrixs, new Object[] { "robot", "eggs" }) String path = factory(TestMatrixReplace.class).createRequest(twoMatrixs, new Object[] { "robot", "eggs" })
.getEndpoint().getPath(); .getEndpoint().getPath();
assertEquals(path, "/;x-amz-copy-source=/robot/eggs"); assertEquals(path, "/;x-amz-copy-source=/robot/eggs");
} }
@Test @Test
public void testBuildTwoMatrixsOutOfOrder() throws SecurityException, NoSuchMethodException, public void testBuildTwoMatrixsOutOfOrder() throws SecurityException, NoSuchMethodException,
UnsupportedEncodingException { UnsupportedEncodingException {
Method twoMatrixsOutOfOrder = TestMatrixReplace.class.getMethod("twoMatrixsOutOfOrder", String.class, Method twoMatrixsOutOfOrder = TestMatrixReplace.class.getMethod("twoMatrixsOutOfOrder", String.class,
String.class); String.class);
String path = factory(TestMatrixReplace.class).createRequest(twoMatrixsOutOfOrder, String path = factory(TestMatrixReplace.class).createRequest(twoMatrixsOutOfOrder,
new Object[] { "robot", "eggs" }).getEndpoint().getPath(); new Object[] { "robot", "eggs" }).getEndpoint().getPath();
assertEquals(path, "/;x-amz-copy-source=/eggs/robot"); assertEquals(path, "/;x-amz-copy-source=/eggs/robot");
} }
@ -1422,7 +1441,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest {
public void testPutPayloadEnclosing() throws SecurityException, NoSuchMethodException, IOException { public void testPutPayloadEnclosing() throws SecurityException, NoSuchMethodException, IOException {
Method method = TestTransformers.class.getMethod("put", PayloadEnclosing.class); Method method = TestTransformers.class.getMethod("put", PayloadEnclosing.class);
HttpRequest request = factory(TestQuery.class).createRequest(method, HttpRequest request = factory(TestQuery.class).createRequest(method,
new PayloadEnclosingImpl(newStringPayload("whoops"))); new PayloadEnclosingImpl(newStringPayload("whoops")));
assertRequestLineEquals(request, "PUT http://localhost:9999?x-ms-version=2009-07-17 HTTP/1.1"); assertRequestLineEquals(request, "PUT http://localhost:9999?x-ms-version=2009-07-17 HTTP/1.1");
assertNonPayloadHeadersEqual(request, ""); assertNonPayloadHeadersEqual(request, "");
assertPayloadEquals(request, "whoops", "application/unknown", false); assertPayloadEquals(request, "whoops", "application/unknown", false);
@ -1440,7 +1459,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest {
} }
public void testPutInputStreamPayloadEnclosingGenerateMD5() throws SecurityException, NoSuchMethodException, public void testPutInputStreamPayloadEnclosingGenerateMD5() throws SecurityException, NoSuchMethodException,
IOException { IOException {
Method method = TestTransformers.class.getMethod("put", PayloadEnclosing.class); Method method = TestTransformers.class.getMethod("put", PayloadEnclosing.class);
PayloadEnclosing payloadEnclosing = new PayloadEnclosingImpl(newInputStreamPayload(toInputStream("whoops"))); PayloadEnclosing payloadEnclosing = new PayloadEnclosingImpl(newInputStreamPayload(toInputStream("whoops")));
@ -1469,7 +1488,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest {
} }
public void testPutPayloadWithGeneratedMD5AndNoContentType() throws SecurityException, NoSuchMethodException, public void testPutPayloadWithGeneratedMD5AndNoContentType() throws SecurityException, NoSuchMethodException,
IOException { IOException {
Payload payload = newStringPayload("whoops"); Payload payload = newStringPayload("whoops");
calculateMD5(payload, crypto.md5()); calculateMD5(payload, crypto.md5());
Method method = TestTransformers.class.getMethod("put", Payload.class); Method method = TestTransformers.class.getMethod("put", Payload.class);
@ -1490,7 +1509,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest {
} }
public void testPutInputStreamPayloadWithMD5() throws NoSuchAlgorithmException, IOException, SecurityException, public void testPutInputStreamPayloadWithMD5() throws NoSuchAlgorithmException, IOException, SecurityException,
NoSuchMethodException { NoSuchMethodException {
Payload payload = newStringPayload("whoops"); Payload payload = newStringPayload("whoops");
payload.setContentLength((long) "whoops".length()); payload.setContentLength((long) "whoops".length());
calculateMD5(payload, crypto.md5()); calculateMD5(payload, crypto.md5());
@ -1515,9 +1534,9 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public static <T> Class<? extends Function<HttpResponse, ?>> unwrap(RestAnnotationProcessor<T> processor, public static <T> Class<? extends Function<HttpResponse, ?>> unwrap(RestAnnotationProcessor<T> processor,
Method method) { Method method) {
return (Class<? extends Function<HttpResponse, ?>>) RestAnnotationProcessor.getParserOrThrowException(method) return (Class<? extends Function<HttpResponse, ?>>) RestAnnotationProcessor.getParserOrThrowException(method)
.getTypeLiteral().getRawType(); .getTypeLiteral().getRawType();
} }
public void testURI() throws SecurityException, NoSuchMethodException { public void testURI() throws SecurityException, NoSuchMethodException {
@ -1554,7 +1573,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest {
RestAnnotationProcessor<TestTransformers> processor = factory(TestTransformers.class); RestAnnotationProcessor<TestTransformers> processor = factory(TestTransformers.class);
Method method = TestTransformers.class.getMethod("oneTransformerWithContext"); Method method = TestTransformers.class.getMethod("oneTransformerWithContext");
GeneratedHttpRequest<TestTransformers> request = new GeneratedHttpRequest<TestTransformers>("GET", URI GeneratedHttpRequest<TestTransformers> request = new GeneratedHttpRequest<TestTransformers>("GET", URI
.create("http://localhost"), TestTransformers.class, method); .create("http://localhost"), TestTransformers.class, method);
Function<HttpResponse, ?> transformer = processor.createResponseParser(method, request); Function<HttpResponse, ?> transformer = processor.createResponseParser(method, request);
assertEquals(transformer.getClass(), ReturnStringIf200Context.class); assertEquals(transformer.getClass(), ReturnStringIf200Context.class);
assertEquals(((ReturnStringIf200Context) transformer).request, request); assertEquals(((ReturnStringIf200Context) transformer).request, request);
@ -1595,7 +1614,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest {
@PUT @PUT
@Path("/{id}") @Path("/{id}")
ListenableFuture<String> put(@PathParam("id") @ParamParser(FirstCharacter.class) String id, ListenableFuture<String> put(@PathParam("id") @ParamParser(FirstCharacter.class) String id,
@BinderParam(BindToStringPayload.class) String payload); @BinderParam(BindToStringPayload.class) String payload);
@PUT @PUT
@Path("/{id}") @Path("/{id}")
@ -1607,7 +1626,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest {
@Headers(keys = "foo", values = "--{id}--") @Headers(keys = "foo", values = "--{id}--")
@ResponseParser(ReturnTrueIf2xx.class) @ResponseParser(ReturnTrueIf2xx.class)
ListenableFuture<String> putHeader(@PathParam("id") String id, ListenableFuture<String> putHeader(@PathParam("id") String id,
@BinderParam(BindToStringPayload.class) String payload); @BinderParam(BindToStringPayload.class) String payload);
} }
public void testCreateGetVarArgOptionsThatProducesHeaders() throws SecurityException, NoSuchMethodException { public void testCreateGetVarArgOptionsThatProducesHeaders() throws SecurityException, NoSuchMethodException {
@ -1622,7 +1641,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest {
assertEquals(request.getHeaders().size(), 2); assertEquals(request.getHeaders().size(), 2);
assertEquals(request.getHeaders().get(HttpHeaders.HOST), Collections.singletonList("localhost")); assertEquals(request.getHeaders().get(HttpHeaders.HOST), Collections.singletonList("localhost"));
assertEquals(request.getHeaders().get(HttpHeaders.IF_MODIFIED_SINCE), Collections.singletonList(dateService assertEquals(request.getHeaders().get(HttpHeaders.IF_MODIFIED_SINCE), Collections.singletonList(dateService
.rfc822DateFormat(date))); .rfc822DateFormat(date)));
} }
public void testCreateGetOptionsThatProducesHeaders() throws SecurityException, NoSuchMethodException { public void testCreateGetOptionsThatProducesHeaders() throws SecurityException, NoSuchMethodException {
@ -1636,7 +1655,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest {
assertEquals(request.getHeaders().size(), 2); assertEquals(request.getHeaders().size(), 2);
assertEquals(request.getHeaders().get(HttpHeaders.HOST), Collections.singletonList("localhost")); assertEquals(request.getHeaders().get(HttpHeaders.HOST), Collections.singletonList("localhost"));
assertEquals(request.getHeaders().get(HttpHeaders.IF_MODIFIED_SINCE), Collections.singletonList(dateService assertEquals(request.getHeaders().get(HttpHeaders.IF_MODIFIED_SINCE), Collections.singletonList(dateService
.rfc822DateFormat(date))); .rfc822DateFormat(date)));
} }
public class PrefixOptions extends BaseHttpRequestOptions { public class PrefixOptions extends BaseHttpRequestOptions {
@ -1699,7 +1718,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest {
@Test(dataProvider = "strings") @Test(dataProvider = "strings")
public void testCreateGetRequest(String key) throws SecurityException, NoSuchMethodException, public void testCreateGetRequest(String key) throws SecurityException, NoSuchMethodException,
UnsupportedEncodingException { UnsupportedEncodingException {
Method method = TestRequest.class.getMethod("get", String.class, String.class); Method method = TestRequest.class.getMethod("get", String.class, String.class);
HttpRequest request = factory(TestRequest.class).createRequest(method, new Object[] { key, "localhost" }); HttpRequest request = factory(TestRequest.class).createRequest(method, new Object[] { key, "localhost" });
assertEquals(request.getEndpoint().getHost(), "localhost"); assertEquals(request.getEndpoint().getHost(), "localhost");
@ -1742,7 +1761,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest {
public void testVirtualHostMethod() throws SecurityException, NoSuchMethodException { public void testVirtualHostMethod() throws SecurityException, NoSuchMethodException {
Method method = TestVirtualHostMethod.class.getMethod("get", String.class, String.class); Method method = TestVirtualHostMethod.class.getMethod("get", String.class, String.class);
HttpRequest request = factory(TestVirtualHostMethod.class).createRequest(method, HttpRequest request = factory(TestVirtualHostMethod.class).createRequest(method,
new Object[] { "1", "localhost" }); new Object[] { "1", "localhost" });
assertEquals(request.getEndpoint().getHost(), "localhost"); assertEquals(request.getEndpoint().getHost(), "localhost");
assertEquals(request.getEndpoint().getPath(), "/1"); assertEquals(request.getEndpoint().getPath(), "/1");
assertEquals(request.getMethod(), HttpMethod.GET); assertEquals(request.getMethod(), HttpMethod.GET);
@ -1807,7 +1826,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest {
public void testOneHeader() throws SecurityException, NoSuchMethodException { public void testOneHeader() throws SecurityException, NoSuchMethodException {
Method method = TestHeaders.class.getMethod("oneHeader", String.class); Method method = TestHeaders.class.getMethod("oneHeader", String.class);
Multimap<String, String> headers = factory(TestHeaders.class).buildHeaders( Multimap<String, String> headers = factory(TestHeaders.class).buildHeaders(
ImmutableMultimap.<String, String> of().entries(), method, "robot"); ImmutableMultimap.<String, String> of().entries(), method, "robot");
assertEquals(headers.size(), 1); assertEquals(headers.size(), 1);
assertEquals(headers.get("header"), Collections.singletonList("robot")); assertEquals(headers.get("header"), Collections.singletonList("robot"));
} }
@ -1816,7 +1835,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest {
public void testOneIntHeader() throws SecurityException, NoSuchMethodException { public void testOneIntHeader() throws SecurityException, NoSuchMethodException {
Method method = TestHeaders.class.getMethod("oneIntHeader", int.class); Method method = TestHeaders.class.getMethod("oneIntHeader", int.class);
Multimap<String, String> headers = factory(TestHeaders.class).buildHeaders( Multimap<String, String> headers = factory(TestHeaders.class).buildHeaders(
ImmutableMultimap.<String, String> of().entries(), method, 1); ImmutableMultimap.<String, String> of().entries(), method, 1);
assertEquals(headers.size(), 1); assertEquals(headers.size(), 1);
assertEquals(headers.get("header"), Collections.singletonList("1")); assertEquals(headers.get("header"), Collections.singletonList("1"));
} }
@ -1825,7 +1844,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest {
public void testTwoDifferentHeaders() throws SecurityException, NoSuchMethodException { public void testTwoDifferentHeaders() throws SecurityException, NoSuchMethodException {
Method method = TestHeaders.class.getMethod("twoDifferentHeaders", String.class, String.class); Method method = TestHeaders.class.getMethod("twoDifferentHeaders", String.class, String.class);
Multimap<String, String> headers = factory(TestHeaders.class).buildHeaders( Multimap<String, String> headers = factory(TestHeaders.class).buildHeaders(
ImmutableMultimap.<String, String> of().entries(), method, "robot", "egg"); ImmutableMultimap.<String, String> of().entries(), method, "robot", "egg");
assertEquals(headers.size(), 2); assertEquals(headers.size(), 2);
assertEquals(headers.get("header1"), Collections.singletonList("robot")); assertEquals(headers.get("header1"), Collections.singletonList("robot"));
assertEquals(headers.get("header2"), Collections.singletonList("egg")); assertEquals(headers.get("header2"), Collections.singletonList("egg"));
@ -1835,7 +1854,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest {
public void testTwoSameHeaders() throws SecurityException, NoSuchMethodException { public void testTwoSameHeaders() throws SecurityException, NoSuchMethodException {
Method method = TestHeaders.class.getMethod("twoSameHeaders", String.class, String.class); Method method = TestHeaders.class.getMethod("twoSameHeaders", String.class, String.class);
Multimap<String, String> headers = factory(TestHeaders.class).buildHeaders( Multimap<String, String> headers = factory(TestHeaders.class).buildHeaders(
ImmutableMultimap.<String, String> of().entries(), method, "robot", "egg"); ImmutableMultimap.<String, String> of().entries(), method, "robot", "egg");
assertEquals(headers.size(), 2); assertEquals(headers.size(), 2);
Collection<String> values = headers.get("header"); Collection<String> values = headers.get("header");
assert values.contains("robot"); assert values.contains("robot");
@ -1858,7 +1877,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest {
@GET @GET
void twoEndpointParams(@EndpointParam(parser = ConvertTwoToURI.class) String EndpointParam1, void twoEndpointParams(@EndpointParam(parser = ConvertTwoToURI.class) String EndpointParam1,
@EndpointParam(parser = ConvertTwoToURI.class) String EndpointParam2); @EndpointParam(parser = ConvertTwoToURI.class) String EndpointParam2);
@Singleton @Singleton
public static class ConvertTwoToURI implements Function<Object, URI> { public static class ConvertTwoToURI implements Function<Object, URI> {
@ -1878,7 +1897,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest {
public void testOneEndpointParam() throws SecurityException, NoSuchMethodException { public void testOneEndpointParam() throws SecurityException, NoSuchMethodException {
Method method = TestEndpointParams.class.getMethod("oneEndpointParam", String.class); Method method = TestEndpointParams.class.getMethod("oneEndpointParam", String.class);
URI uri = factory(TestEndpointParams.class).getEndpointInParametersOrNull(method, new Object[] { "robot" }, URI uri = factory(TestEndpointParams.class).getEndpointInParametersOrNull(method, new Object[] { "robot" },
injector); injector);
assertEquals(uri, URI.create("robot")); assertEquals(uri, URI.create("robot"));
} }
@ -1888,7 +1907,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest {
public void testTwoDifferentEndpointParams() throws SecurityException, NoSuchMethodException { public void testTwoDifferentEndpointParams() throws SecurityException, NoSuchMethodException {
Method method = TestEndpointParams.class.getMethod("twoEndpointParams", String.class, String.class); Method method = TestEndpointParams.class.getMethod("twoEndpointParams", String.class, String.class);
URI uri = factory(TestEndpointParams.class).getEndpointInParametersOrNull(method, URI uri = factory(TestEndpointParams.class).getEndpointInParametersOrNull(method,
new Object[] { "robot", "egg" }, injector); new Object[] { "robot", "egg" }, injector);
assertEquals(uri, URI.create("robot/egg")); assertEquals(uri, URI.create("robot/egg"));
} }
@ -1899,11 +1918,11 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest {
@PUT @PUT
@Path("{foo}") @Path("{foo}")
public ListenableFuture<Void> putWithPath(@PathParam("foo") String path, public ListenableFuture<Void> putWithPath(@PathParam("foo") String path,
@BinderParam(BindToStringPayload.class) String content); @BinderParam(BindToStringPayload.class) String content);
@PUT @PUT
public void twoEntities(@BinderParam(BindToStringPayload.class) String payload1, public void twoEntities(@BinderParam(BindToStringPayload.class) String payload1,
@BinderParam(BindToStringPayload.class) String payload2); @BinderParam(BindToStringPayload.class) String payload2);
} }
@Test @Test
@ -1995,23 +2014,23 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest {
public void testBuildTwoForms() throws SecurityException, NoSuchMethodException, UnsupportedEncodingException { public void testBuildTwoForms() throws SecurityException, NoSuchMethodException, UnsupportedEncodingException {
Method twoForms = TestFormReplace.class.getMethod("twoForms", String.class, String.class); Method twoForms = TestFormReplace.class.getMethod("twoForms", String.class, String.class);
Object form = factory(TestFormReplace.class).createRequest(twoForms, "robot", "eggs").getPayload() Object form = factory(TestFormReplace.class).createRequest(twoForms, "robot", "eggs").getPayload()
.getRawContent(); .getRawContent();
assertEquals(form, "x-amz-copy-source=/robot/eggs"); assertEquals(form, "x-amz-copy-source=/robot/eggs");
} }
@Test @Test
public void testBuildTwoFormsOutOfOrder() throws SecurityException, NoSuchMethodException, public void testBuildTwoFormsOutOfOrder() throws SecurityException, NoSuchMethodException,
UnsupportedEncodingException { UnsupportedEncodingException {
Method twoFormsOutOfOrder = TestFormReplace.class.getMethod("twoFormsOutOfOrder", String.class, String.class); Method twoFormsOutOfOrder = TestFormReplace.class.getMethod("twoFormsOutOfOrder", String.class, String.class);
Object form = factory(TestFormReplace.class).createRequest(twoFormsOutOfOrder, "robot", "eggs").getPayload() Object form = factory(TestFormReplace.class).createRequest(twoFormsOutOfOrder, "robot", "eggs").getPayload()
.getRawContent(); .getRawContent();
assertEquals(form, "x-amz-copy-source=/eggs/robot"); assertEquals(form, "x-amz-copy-source=/eggs/robot");
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
private <T> RestAnnotationProcessor<T> factory(Class<T> clazz) { private <T> RestAnnotationProcessor<T> factory(Class<T> clazz) {
return ((RestAnnotationProcessor<T>) injector.getInstance(Key.get(newParameterizedType( return ((RestAnnotationProcessor<T>) injector.getInstance(Key.get(newParameterizedType(
RestAnnotationProcessor.class, clazz)))); RestAnnotationProcessor.class, clazz))));
} }
DateService dateService = new SimpleDateFormatDateService(); DateService dateService = new SimpleDateFormatDateService();
@ -2019,15 +2038,16 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest {
@BeforeClass @BeforeClass
void setupFactory() { void setupFactory() {
ContextSpec<String, Integer> contextSpec = contextSpec("test", "http://localhost:9999", "1", "userfoo", null, ContextSpec<String, Integer> contextSpec = contextSpec("test", "http://localhost:9999", "1", "userfoo", null,
String.class, Integer.class, ImmutableSet.<Module> of(new MockModule(), new NullLoggingModule(), String.class, Integer.class, ImmutableSet.<Module> of(new MockModule(), new NullLoggingModule(),
new AbstractModule() { new AbstractModule() {
@Override @Override
protected void configure() { protected void configure() {
bind(URI.class).annotatedWith(Localhost2.class).toInstance(URI.create("http://localhost:1111")); bind(URI.class).annotatedWith(Localhost2.class).toInstance(
} URI.create("http://localhost:1111"));
}
})); }));
injector = createContextBuilder(contextSpec).buildInjector(); injector = createContextBuilder(contextSpec).buildInjector();
parserFactory = injector.getInstance(ParseSax.Factory.class); parserFactory = injector.getInstance(ParseSax.Factory.class);

View File

@ -32,10 +32,12 @@ import javax.ws.rs.core.HttpHeaders;
import org.apache.http.HttpEntity; import org.apache.http.HttpEntity;
import org.apache.http.HttpEntityEnclosingRequest; import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.client.methods.HttpDelete; import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpHead; import org.apache.http.client.methods.HttpHead;
import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut; import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.ByteArrayEntity; import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.FileEntity; import org.apache.http.entity.FileEntity;
@ -73,7 +75,26 @@ public class ApacheHCUtils {
} else if (request.getMethod().equals(HttpMethod.POST)) { } else if (request.getMethod().equals(HttpMethod.POST)) {
apacheRequest = new HttpPost(request.getEndpoint()); apacheRequest = new HttpPost(request.getEndpoint());
} else { } else {
throw new UnsupportedOperationException(request.getMethod()); final String method = request.getMethod();
if (request.getPayload() != null)
apacheRequest = new HttpEntityEnclosingRequestBase() {
@Override
public String getMethod() {
return method;
}
};
else
apacheRequest = new HttpRequestBase() {
@Override
public String getMethod() {
return method;
}
};
HttpRequestBase.class.cast(apacheRequest).setURI(request.getEndpoint());
} }
Payload payload = request.getPayload(); Payload payload = request.getPayload();

View File

@ -68,7 +68,7 @@ public class AsyncGaeHttpCommandExecutorServiceIntegrationTest extends BaseHttpC
@Test(enabled = false) @Test(enabled = false)
public void testPerformanceVsNothing() { public void testPerformanceVsNothing() {
setupApiProxy(); setupApiProxy();
int count = 50; int count = 5;
final URI fetch = URI.create("http://www.google.com"); final URI fetch = URI.create("http://www.google.com");
final URLFetchService service = URLFetchServiceFactory.getURLFetchService(); final URLFetchService service = URLFetchServiceFactory.getURLFetchService();
@ -172,7 +172,7 @@ public class AsyncGaeHttpCommandExecutorServiceIntegrationTest extends BaseHttpC
} }
@Override @Override
@Test(enabled = true, invocationCount = 50, timeOut = 3000) @Test(enabled = true, invocationCount = 5, timeOut = 3000)
public void testKillRobotSlowly() throws MalformedURLException, ExecutionException, InterruptedException, public void testKillRobotSlowly() throws MalformedURLException, ExecutionException, InterruptedException,
TimeoutException { TimeoutException {
setupApiProxy(); setupApiProxy();
@ -180,7 +180,7 @@ public class AsyncGaeHttpCommandExecutorServiceIntegrationTest extends BaseHttpC
} }
@Override @Override
@Test(enabled = true, invocationCount = 50, timeOut = 3000) @Test(enabled = true, invocationCount = 5, timeOut = 3000)
public void testPostAsInputStream() throws MalformedURLException, ExecutionException, InterruptedException, public void testPostAsInputStream() throws MalformedURLException, ExecutionException, InterruptedException,
TimeoutException { TimeoutException {
setupApiProxy(); setupApiProxy();
@ -196,7 +196,7 @@ public class AsyncGaeHttpCommandExecutorServiceIntegrationTest extends BaseHttpC
} }
@Override @Override
@Test(enabled = true, invocationCount = 50, timeOut = 3000) @Test(enabled = true, invocationCount = 5, timeOut = 3000)
public void testPostBinder() throws MalformedURLException, ExecutionException, InterruptedException, public void testPostBinder() throws MalformedURLException, ExecutionException, InterruptedException,
TimeoutException { TimeoutException {
setupApiProxy(); setupApiProxy();
@ -209,7 +209,7 @@ public class AsyncGaeHttpCommandExecutorServiceIntegrationTest extends BaseHttpC
} }
@Override @Override
@Test(enabled = true, invocationCount = 50, timeOut = 3000) @Test(enabled = true, invocationCount = 5, timeOut = 3000)
public void testGetAndParseSax() throws MalformedURLException, ExecutionException, InterruptedException, public void testGetAndParseSax() throws MalformedURLException, ExecutionException, InterruptedException,
TimeoutException { TimeoutException {
setupApiProxy(); setupApiProxy();
@ -217,14 +217,14 @@ public class AsyncGaeHttpCommandExecutorServiceIntegrationTest extends BaseHttpC
} }
@Override @Override
@Test(enabled = true, invocationCount = 50, timeOut = 3000) @Test(enabled = true, invocationCount = 5, timeOut = 3000)
public void testGetString() throws MalformedURLException, ExecutionException, InterruptedException, TimeoutException { public void testGetString() throws MalformedURLException, ExecutionException, InterruptedException, TimeoutException {
setupApiProxy(); setupApiProxy();
super.testGetString(); super.testGetString();
} }
@Override @Override
@Test(enabled = true, invocationCount = 50, timeOut = 3000, dataProvider = "gets") @Test(enabled = true, invocationCount = 5, timeOut = 3000, dataProvider = "gets")
public void testGetStringSynch(String path) throws MalformedURLException, ExecutionException, InterruptedException, public void testGetStringSynch(String path) throws MalformedURLException, ExecutionException, InterruptedException,
TimeoutException { TimeoutException {
setupApiProxy(); setupApiProxy();
@ -232,7 +232,7 @@ public class AsyncGaeHttpCommandExecutorServiceIntegrationTest extends BaseHttpC
} }
@Override @Override
@Test(enabled = true, invocationCount = 50, timeOut = 3000) @Test(enabled = true, invocationCount = 5, timeOut = 3000)
public void testGetStringRedirect() throws MalformedURLException, ExecutionException, InterruptedException, public void testGetStringRedirect() throws MalformedURLException, ExecutionException, InterruptedException,
TimeoutException { TimeoutException {
setupApiProxy(); setupApiProxy();
@ -240,7 +240,7 @@ public class AsyncGaeHttpCommandExecutorServiceIntegrationTest extends BaseHttpC
} }
@Override @Override
@Test(enabled = true, invocationCount = 50, timeOut = 3000) @Test(enabled = true, invocationCount = 5, timeOut = 3000)
public void testGetException() throws MalformedURLException, ExecutionException, InterruptedException, public void testGetException() throws MalformedURLException, ExecutionException, InterruptedException,
TimeoutException { TimeoutException {
setupApiProxy(); setupApiProxy();
@ -248,7 +248,7 @@ public class AsyncGaeHttpCommandExecutorServiceIntegrationTest extends BaseHttpC
} }
@Override @Override
@Test(enabled = true, invocationCount = 50, timeOut = 3000) @Test(enabled = true, invocationCount = 5, timeOut = 3000)
public void testGetStringPermanentRedirect() throws MalformedURLException, ExecutionException, InterruptedException, public void testGetStringPermanentRedirect() throws MalformedURLException, ExecutionException, InterruptedException,
TimeoutException { TimeoutException {
setupApiProxy(); setupApiProxy();
@ -256,7 +256,7 @@ public class AsyncGaeHttpCommandExecutorServiceIntegrationTest extends BaseHttpC
} }
@Override @Override
@Test(enabled = true, invocationCount = 50, timeOut = 3000) @Test(enabled = true, invocationCount = 5, timeOut = 3000)
public void testGetSynchException() throws MalformedURLException, ExecutionException, InterruptedException, public void testGetSynchException() throws MalformedURLException, ExecutionException, InterruptedException,
TimeoutException { TimeoutException {
setupApiProxy(); setupApiProxy();
@ -264,21 +264,21 @@ public class AsyncGaeHttpCommandExecutorServiceIntegrationTest extends BaseHttpC
} }
@Override @Override
@Test(enabled = true, invocationCount = 50, timeOut = 3000) @Test(enabled = true, invocationCount = 5, timeOut = 3000)
public void testPost() throws MalformedURLException, ExecutionException, InterruptedException, TimeoutException { public void testPost() throws MalformedURLException, ExecutionException, InterruptedException, TimeoutException {
setupApiProxy(); setupApiProxy();
super.testPost(); super.testPost();
} }
@Override @Override
@Test(enabled = true, invocationCount = 50, timeOut = 3000) @Test(enabled = true, invocationCount = 5, timeOut = 3000)
public void testPut() throws MalformedURLException, ExecutionException, InterruptedException, TimeoutException { public void testPut() throws MalformedURLException, ExecutionException, InterruptedException, TimeoutException {
setupApiProxy(); setupApiProxy();
super.testPut(); super.testPut();
} }
@Override @Override
@Test(enabled = true, invocationCount = 50, timeOut = 3000) @Test(enabled = true, invocationCount = 5, timeOut = 3000)
public void testPutRedirect() throws MalformedURLException, ExecutionException, InterruptedException, public void testPutRedirect() throws MalformedURLException, ExecutionException, InterruptedException,
TimeoutException { TimeoutException {
setupApiProxy(); setupApiProxy();
@ -286,7 +286,7 @@ public class AsyncGaeHttpCommandExecutorServiceIntegrationTest extends BaseHttpC
} }
@Override @Override
@Test(enabled = true, invocationCount = 50, timeOut = 3000) @Test(enabled = true, invocationCount = 5, timeOut = 3000)
public void testGetStringWithHeader() throws MalformedURLException, ExecutionException, InterruptedException, public void testGetStringWithHeader() throws MalformedURLException, ExecutionException, InterruptedException,
TimeoutException { TimeoutException {
setupApiProxy(); setupApiProxy();
@ -294,14 +294,14 @@ public class AsyncGaeHttpCommandExecutorServiceIntegrationTest extends BaseHttpC
} }
@Override @Override
@Test(enabled = true, invocationCount = 50, timeOut = 3000) @Test(enabled = true, invocationCount = 5, timeOut = 3000)
public void testHead() throws MalformedURLException, ExecutionException, InterruptedException, TimeoutException { public void testHead() throws MalformedURLException, ExecutionException, InterruptedException, TimeoutException {
setupApiProxy(); setupApiProxy();
super.testHead(); super.testHead();
} }
@Override @Override
@Test(enabled = true, invocationCount = 50, timeOut = 3000) @Test(enabled = true, invocationCount = 5, timeOut = 3000)
public void testRequestFilter() throws MalformedURLException, ExecutionException, InterruptedException, public void testRequestFilter() throws MalformedURLException, ExecutionException, InterruptedException,
TimeoutException { TimeoutException {
setupApiProxy(); setupApiProxy();
@ -344,4 +344,13 @@ public class AsyncGaeHttpCommandExecutorServiceIntegrationTest extends BaseHttpC
// disabled since test data is too big // disabled since test data is too big
} }
// http://code.google.com/p/googleappengine/issues/detail?id=3599
@Override
@Test(enabled = true, expectedExceptions = IllegalArgumentException.class)
public void testAlternateMethod() throws MalformedURLException, ExecutionException, InterruptedException,
TimeoutException {
setupApiProxy();
super.testAlternateMethod();
}
} }