fixed content-disposition tests

This commit is contained in:
Adrian Cole 2010-09-18 18:43:33 -07:00
parent de5ec94344
commit a8852e54f9
8 changed files with 291 additions and 278 deletions

View File

@ -28,7 +28,6 @@ import static com.google.common.io.Closeables.closeQuietly;
import java.io.ByteArrayInputStream; 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.lang.reflect.Field; import java.lang.reflect.Field;
import java.net.Authenticator; import java.net.Authenticator;
import java.net.HttpURLConnection; import java.net.HttpURLConnection;
@ -85,11 +84,11 @@ public class JavaUrlHttpCommandExecutorService extends BaseHttpCommandExecutorSe
@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, @Named("untrusted") HostnameVerifier verifier, DelegatingErrorHandler errorHandler, HttpWire wire, @Named("untrusted") HostnameVerifier verifier,
@Named("untrusted") Supplier<SSLContext> untrustedSSLContextProvider) throws SecurityException, @Named("untrusted") Supplier<SSLContext> untrustedSSLContextProvider) throws SecurityException,
NoSuchFieldException { 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()));
@ -198,26 +197,25 @@ public class JavaUrlHttpCommandExecutorService extends BaseHttpCommandExecutorSe
connection.setRequestProperty(HttpHeaders.USER_AGENT, USER_AGENT); connection.setRequestProperty(HttpHeaders.USER_AGENT, USER_AGENT);
if (request.getPayload() != null) { if (request.getPayload() != null) {
OutputStream out = null; if (request.getPayload().getContentMD5() != null)
connection.setRequestProperty("Content-MD5", CryptoStreams.base64(request.getPayload().getContentMD5()));
if (request.getPayload().getContentType() != null)
connection.setRequestProperty(HttpHeaders.CONTENT_TYPE, request.getPayload().getContentType());
if (request.getPayload().getContentDisposition() != null)
connection.setRequestProperty("Content-Disposition", request.getPayload().getContentDisposition());
if (chunked) {
connection.setChunkedStreamingMode(8196);
} else {
Long length = checkNotNull(request.getPayload().getContentLength(), "payload.getContentLength");
connection.setRequestProperty(HttpHeaders.CONTENT_LENGTH, length.toString());
connection.setFixedLengthStreamingMode(length.intValue());
}
// writeTo will close the output stream
try { try {
if (request.getPayload().getContentMD5() != null) request.getPayload().writeTo(connection.getOutputStream());
connection.setRequestProperty("Content-MD5", CryptoStreams.base64(request.getPayload().getContentMD5())); } catch (IOException e){
if (request.getPayload().getContentType() != null) e.printStackTrace();
connection.setRequestProperty(HttpHeaders.CONTENT_TYPE, request.getPayload().getContentType()); throw e;
if (request.getPayload().getContentDisposition() != null)
connection.setRequestProperty("Content-Disposition", request.getPayload().getContentDisposition());
if (chunked) {
connection.setChunkedStreamingMode(8196);
} else {
Long length = checkNotNull(request.getPayload().getContentLength(), "payload.getContentLength");
connection.setRequestProperty(HttpHeaders.CONTENT_LENGTH, length.toString());
connection.setFixedLengthStreamingMode(length.intValue());
}
out = connection.getOutputStream();
request.getPayload().writeTo(out);
out.flush();
} finally {
closeQuietly(out);
} }
} else { } else {
connection.setRequestProperty(HttpHeaders.CONTENT_LENGTH, "0"); connection.setRequestProperty(HttpHeaders.CONTENT_LENGTH, "0");
@ -227,7 +225,8 @@ public class JavaUrlHttpCommandExecutorService extends BaseHttpCommandExecutorSe
} }
/** /**
* Only disconnect if there is no content, as disconnecting will throw away unconsumed content. * Only disconnect if there is no content, as disconnecting will throw away
* unconsumed content.
*/ */
@Override @Override
protected void cleanup(HttpURLConnection connection) { protected void cleanup(HttpURLConnection connection) {

View File

@ -180,6 +180,7 @@ public abstract class BasePayload<V> implements Payload {
InputStream in = getInput(); InputStream in = getInput();
try { try {
copy(in, outstream); copy(in, outstream);
outstream.flush();
} finally { } finally {
closeQuietly(in); closeQuietly(in);
} }

View File

@ -31,7 +31,7 @@ import java.io.OutputStream;
import java.net.MalformedURLException; import java.net.MalformedURLException;
import java.net.URI; import java.net.URI;
import java.security.MessageDigest; import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException; import java.util.Collections;
import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException; import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
@ -39,17 +39,21 @@ import java.util.concurrent.atomic.AtomicInteger;
import org.jclouds.crypto.CryptoStreams; import org.jclouds.crypto.CryptoStreams;
import org.jclouds.http.options.GetOptions; import org.jclouds.http.options.GetOptions;
import org.jclouds.io.InputSuppliers; import org.jclouds.io.InputSuppliers;
import org.jclouds.io.Payload;
import org.jclouds.io.Payloads;
import org.jclouds.util.Utils; import org.jclouds.util.Utils;
import org.testng.annotations.BeforeTest; import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider; import org.testng.annotations.DataProvider;
import org.testng.annotations.Test; import org.testng.annotations.Test;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Multimap;
import com.google.common.io.Closeables; import com.google.common.io.Closeables;
/** /**
* Tests for functionality all HttpCommandExecutorServices must express. These tests will operate * Tests for functionality all HttpCommandExecutorServices must express. These
* against an in-memory http engine, so as to ensure end-to-end functionality works. * tests will operate against an in-memory http engine, so as to ensure
* end-to-end functionality works.
* *
* @author Adrian Cole * @author Adrian Cole
*/ */
@ -58,7 +62,7 @@ public abstract class BaseHttpCommandExecutorServiceIntegrationTest extends Base
@Test(invocationCount = 25, timeOut = 5000) @Test(invocationCount = 25, timeOut = 5000)
public void testRequestFilter() throws MalformedURLException, ExecutionException, InterruptedException, public void testRequestFilter() throws MalformedURLException, ExecutionException, InterruptedException,
TimeoutException { TimeoutException {
assertEquals(client.downloadFilter("", "filterme").trim(), "test"); assertEquals(client.downloadFilter("", "filterme").trim(), "test");
} }
@ -66,13 +70,13 @@ public abstract class BaseHttpCommandExecutorServiceIntegrationTest extends Base
@Test(invocationCount = 5, 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 = 1, timeOut = 5000) @Test(invocationCount = 1, timeOut = 5000)
public void testAlternateMethod() throws MalformedURLException, ExecutionException, InterruptedException, public void testAlternateMethod() throws MalformedURLException, ExecutionException, InterruptedException,
TimeoutException { TimeoutException {
assertEquals(client.rowdy("").trim(), XML); assertEquals(client.rowdy("").trim(), XML);
} }
@ -88,26 +92,26 @@ public abstract class BaseHttpCommandExecutorServiceIntegrationTest extends Base
@Test(invocationCount = 5, 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 = 5, 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 = 5, 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 = 5, 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);
} }
@ -118,8 +122,10 @@ public abstract class BaseHttpCommandExecutorServiceIntegrationTest extends Base
assertEquals(CryptoStreams.md5Base64(InputSuppliers.of(input)), md5); assertEquals(CryptoStreams.md5Base64(InputSuppliers.of(input)), md5);
} catch (RuntimeException e) { } catch (RuntimeException e) {
Closeables.closeQuietly(input); Closeables.closeQuietly(input);
// since we are parsing client side, and not through a response handler, the user // since we are parsing client side, and not through a response
// must retry directly. In this case, we are assuming lightning doesn't strike // handler, the user
// must retry directly. In this case, we are assuming lightning doesn't
// strike
// twice in the same spot. // twice in the same spot.
if (Utils.getFirstThrowableOfType(e, IOException.class) != null) { if (Utils.getFirstThrowableOfType(e, IOException.class) != null) {
input = getConsitution(); input = getConsitution();
@ -130,13 +136,13 @@ public abstract class BaseHttpCommandExecutorServiceIntegrationTest extends Base
private InputStream getConsitution() { private InputStream getConsitution() {
InputStream input = context.utils().http().get( InputStream input = context.utils().http().get(
URI.create(String.format("http://localhost:%d/%s", testPort, "101constitutions"))); URI.create(String.format("http://localhost:%d/%s", testPort, "101constitutions")));
return input; return input;
} }
@Test(enabled = false, invocationCount = 5, 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");
// assert get != null; // assert get != null;
// client.submit(get); // client.submit(get);
@ -152,7 +158,7 @@ public abstract class BaseHttpCommandExecutorServiceIntegrationTest extends Base
@Test(invocationCount = 5, 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 {
assertEquals(client.postAsInputStream("", "foo").trim(), "fooPOST"); assertEquals(client.postAsInputStream("", "foo").trim(), "fooPOST");
} catch (Exception e) { } catch (Exception e) {
@ -161,8 +167,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 * Tests sending a big file to the server. Note: this is a heavy test, takes
* finish. * several minutes to finish.
* *
* @throws java.io.IOException * @throws java.io.IOException
*/ */
@ -177,17 +183,12 @@ public abstract class BaseHttpCommandExecutorServiceIntegrationTest extends Base
f.deleteOnExit(); f.deleteOnExit();
long length = (long) (Runtime.getRuntime().freeMemory() * 1.1); long length = (long) (Runtime.getRuntime().freeMemory() * 1.1);
os = new BufferedOutputStream(new FileOutputStream(f.getAbsolutePath())); os = new BufferedOutputStream(new FileOutputStream(f.getAbsolutePath()));
MessageDigest eTag; MessageDigest digester = context.utils().crypto().md5();
try {
eTag = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("Could not find the MD5 algorithm", e);
}
ByteArrayOutputStream out = new ByteArrayOutputStream(); ByteArrayOutputStream out = new ByteArrayOutputStream();
try { try {
for (long i = 0; i < length; i++) { for (long i = 0; i < length; i++) {
eTag.update((byte) 'a'); digester.update((byte) 'a');
os.write((byte) 'a'); os.write((byte) 'a');
} }
os.flush(); os.flush();
@ -197,9 +198,13 @@ public abstract class BaseHttpCommandExecutorServiceIntegrationTest extends Base
Closeables.closeQuietly(out); Closeables.closeQuietly(out);
} }
// upload and verify the response Payload payload = Payloads.newFilePayload(f);
assertEquals(client.postWithMd5("fileso", CryptoStreams.base64Encode(InputSuppliers.of(eTag.digest())), f) byte[] digest = digester.digest();
.trim(), "created"); payload.setContentMD5(digest);
Multimap<String, String> headers = client.postPayloadAndReturnHeaders("", payload);
assertEquals(headers.get("x-Content-MD5"), Collections.singleton(CryptoStreams.base64Encode(InputSuppliers
.of(digest))));
payload.release();
} finally { } finally {
if (os != null) if (os != null)
os.close(); os.close();
@ -223,14 +228,18 @@ public abstract class BaseHttpCommandExecutorServiceIntegrationTest extends Base
@Test(invocationCount = 5, 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 = 5, timeOut = 5000) @Test(invocationCount = 5, timeOut = 5000)
public void testPostContentDisposition() throws MalformedURLException, ExecutionException, InterruptedException, public void testPostContentDisposition() throws ExecutionException, InterruptedException, TimeoutException,
TimeoutException { IOException {
assertEquals(client.postWithContentDisposition("", "attachment; filename=photo.jpg", "foo").trim(), "content-disposition:photo.jpg"); Payload payload = Payloads.newStringPayload("foo");
payload.setContentDisposition("attachment; filename=photo.jpg");
Multimap<String, String> headers = client.postPayloadAndReturnHeaders("", payload);
assertEquals(headers.get("x-Content-Disposition"), Collections.singleton("attachment; filename=photo.jpg"));
payload.release();
} }
@Test(invocationCount = 5, timeOut = 5000) @Test(invocationCount = 5, timeOut = 5000)
@ -240,13 +249,13 @@ public abstract class BaseHttpCommandExecutorServiceIntegrationTest extends Base
@Test(invocationCount = 5, 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 = 5, 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}");
} }
@ -257,7 +266,7 @@ public abstract class BaseHttpCommandExecutorServiceIntegrationTest extends Base
@Test(invocationCount = 5, 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

@ -25,6 +25,7 @@ import static com.google.common.io.ByteStreams.copy;
import static com.google.common.io.ByteStreams.join; import static com.google.common.io.ByteStreams.join;
import static com.google.common.io.ByteStreams.newInputStreamSupplier; import static com.google.common.io.ByteStreams.newInputStreamSupplier;
import static com.google.common.io.ByteStreams.toByteArray; import static com.google.common.io.ByteStreams.toByteArray;
import static com.google.common.io.Closeables.closeQuietly;
import static javax.ws.rs.core.HttpHeaders.CONTENT_LENGTH; import static javax.ws.rs.core.HttpHeaders.CONTENT_LENGTH;
import static org.jclouds.rest.RestContextFactory.contextSpec; import static org.jclouds.rest.RestContextFactory.contextSpec;
import static org.jclouds.rest.RestContextFactory.createContextBuilder; import static org.jclouds.rest.RestContextFactory.createContextBuilder;
@ -43,6 +44,7 @@ import java.util.zip.GZIPInputStream;
import javax.servlet.ServletException; import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.core.HttpHeaders;
import org.jclouds.Constants; import org.jclouds.Constants;
import org.jclouds.crypto.CryptoStreams; import org.jclouds.crypto.CryptoStreams;
@ -92,7 +94,7 @@ public abstract class BaseJettyTest {
Handler server1Handler = new AbstractHandler() { Handler server1Handler = new AbstractHandler() {
public void handle(String target, HttpServletRequest request, HttpServletResponse response, int dispatch) public void handle(String target, HttpServletRequest request, HttpServletResponse response, int dispatch)
throws IOException, ServletException { throws IOException, ServletException {
if (failIfNoContentLength(request, response)) { if (failIfNoContentLength(request, response)) {
return; return;
} else if (target.indexOf("sleep") > 0) { } else if (target.indexOf("sleep") > 0) {
@ -118,33 +120,13 @@ public abstract class BaseJettyTest {
response.sendError(500, "no content"); response.sendError(500, "no content");
} }
} else if (request.getMethod().equals("POST")) { } else if (request.getMethod().equals("POST")) {
if (redirectEveryTwentyRequests(request, response)) // don't redirect large objects
if (request.getContentLength() < 10240 && redirectEveryTwentyRequests(request, response))
return; return;
if (failEveryTenRequests(request, response)) if (failEveryTenRequests(request, response))
return; return;
if (request.getContentLength() > 0) { if (request.getContentLength() > 0) {
if (request.getHeader("Content-MD5") != null) { handlePost(request, response);
String expectedMd5 = request.getHeader("Content-MD5");
String realMd5FromRequest = CryptoStreams.md5Base64(InputSuppliers.of(request.getInputStream()));
boolean matched = expectedMd5.equals(realMd5FromRequest);
if (matched) {
response.setContentType("text/xml");
response.setStatus(HttpServletResponse.SC_OK);
response.getWriter().println("created");
}
//TODO: insert here additional header detection
} else if (request.getHeader("Content-Disposition") != null) {
//get the filename
String content = request.getHeader("Content-Disposition");
int pos = content.lastIndexOf("=");
String fileName = pos > 0 ? content.substring(pos + 1) : "";
response.setContentType("text/xml");
response.setStatus(HttpServletResponse.SC_OK);
response.getWriter().println("content-disposition:" + fileName);
} else {
response.setStatus(HttpServletResponse.SC_OK);
response.getWriter().println(toStringAndClose(request.getInputStream()) + "POST");
}
} else { } else {
handleAction(request, response); handleAction(request, response);
} }
@ -156,7 +138,8 @@ public abstract class BaseJettyTest {
response.getWriter().println("test"); response.getWriter().println("test");
} else if (request.getMethod().equals("HEAD")) { } 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.setContentType("text/xml");
response.setStatus(HttpServletResponse.SC_OK); response.setStatus(HttpServletResponse.SC_OK);
@ -187,10 +170,43 @@ public abstract class BaseJettyTest {
assert client.newStringBuffer() != null; assert client.newStringBuffer() != null;
} }
private static void handlePost(HttpServletRequest request, HttpServletResponse response) throws IOException {
try {
if (request.getHeader("Content-MD5") != null) {
String expectedMd5 = request.getHeader("Content-MD5");
String realMd5FromRequest;
realMd5FromRequest = CryptoStreams.md5Base64(InputSuppliers.of(request.getInputStream()));
boolean matched = expectedMd5.equals(realMd5FromRequest);
if (matched) {
response.setStatus(HttpServletResponse.SC_OK);
response.addHeader("x-Content-MD5", realMd5FromRequest);
} else {
response.sendError(500, "didn't match");
}
} else {
for (String header : new String[] { "Content-Disposition", HttpHeaders.CONTENT_LANGUAGE,
HttpHeaders.CONTENT_ENCODING })
if (request.getHeader(header) != null) {
response.addHeader("x-" + header, request.getHeader(header));
}
response.setStatus(HttpServletResponse.SC_OK);
String responseString = "POST";
if (request.getContentLength() < 10240) {
responseString = toStringAndClose(request.getInputStream()) + "POST";
} else {
closeQuietly(request.getInputStream());
}
response.getWriter().println(responseString);
}
} catch (IOException e) {
response.sendError(500, e.toString());
}
}
protected void setupAndStartSSLServer(final int testPort) throws Exception { protected void setupAndStartSSLServer(final int testPort) throws Exception {
Handler server2Handler = new AbstractHandler() { Handler server2Handler = new AbstractHandler() {
public void handle(String target, HttpServletRequest request, HttpServletResponse response, int dispatch) public void handle(String target, HttpServletRequest request, HttpServletResponse response, int dispatch)
throws IOException, ServletException { throws IOException, ServletException {
if (request.getMethod().equals("PUT")) { if (request.getMethod().equals("PUT")) {
if (request.getContentLength() > 0) { if (request.getContentLength() > 0) {
response.setStatus(HttpServletResponse.SC_OK); response.setStatus(HttpServletResponse.SC_OK);
@ -198,26 +214,14 @@ public abstract class BaseJettyTest {
} }
} else if (request.getMethod().equals("POST")) { } else if (request.getMethod().equals("POST")) {
if (request.getContentLength() > 0) { if (request.getContentLength() > 0) {
if (request.getHeader("Content-MD5") != null) { handlePost(request, response);
String expectedMd5 = request.getHeader("Content-MD5");
String realMd5FromRequest;
realMd5FromRequest = CryptoStreams.md5Base64(InputSuppliers.of(request.getInputStream()));
boolean matched = expectedMd5.equals(realMd5FromRequest);
if (matched) {
response.setContentType("text/xml");
response.setStatus(HttpServletResponse.SC_OK);
response.getWriter().println("created");
}
} else {
response.setStatus(HttpServletResponse.SC_OK);
response.getWriter().println(toStringAndClose(request.getInputStream()) + "POST");
}
} else { } else {
handleAction(request, response); handleAction(request, response);
} }
} else if (request.getMethod().equals("HEAD")) { } 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.setContentType("text/xml");
response.setStatus(HttpServletResponse.SC_OK); response.setStatus(HttpServletResponse.SC_OK);
@ -257,12 +261,12 @@ public abstract class BaseJettyTest {
} }
public static RestContextBuilder<IntegrationTestClient, IntegrationTestAsyncClient> newBuilder(int testPort, public static RestContextBuilder<IntegrationTestClient, IntegrationTestAsyncClient> newBuilder(int testPort,
Properties properties, Module... connectionModules) { Properties properties, Module... connectionModules) {
properties.setProperty(Constants.PROPERTY_TRUST_ALL_CERTS, "true"); properties.setProperty(Constants.PROPERTY_TRUST_ALL_CERTS, "true");
properties.setProperty(Constants.PROPERTY_RELAX_HOSTNAME, "true"); properties.setProperty(Constants.PROPERTY_RELAX_HOSTNAME, "true");
ContextSpec<IntegrationTestClient, IntegrationTestAsyncClient> contextSpec = contextSpec("test", ContextSpec<IntegrationTestClient, IntegrationTestAsyncClient> contextSpec = contextSpec("test",
"http://localhost:" + testPort, "1", "identity", null, IntegrationTestClient.class, "http://localhost:" + testPort, "1", "identity", null, IntegrationTestClient.class,
IntegrationTestAsyncClient.class, ImmutableSet.<Module> copyOf(connectionModules)); IntegrationTestAsyncClient.class, ImmutableSet.<Module> copyOf(connectionModules));
return createContextBuilder(contextSpec, properties); return createContextBuilder(contextSpec, properties);
} }
@ -296,7 +300,7 @@ public abstract class BaseJettyTest {
} }
protected boolean redirectEveryTwentyRequests(HttpServletRequest request, HttpServletResponse response) protected boolean redirectEveryTwentyRequests(HttpServletRequest request, HttpServletResponse response)
throws IOException { throws IOException {
if (cycle.incrementAndGet() % 20 == 0) { if (cycle.incrementAndGet() % 20 == 0) {
response.sendRedirect("http://localhost:" + (testPort + 1) + "/"); response.sendRedirect("http://localhost:" + (testPort + 1) + "/");
((Request) request).setHandled(true); ((Request) request).setHandled(true);

View File

@ -19,13 +19,13 @@
package org.jclouds.http; package org.jclouds.http;
import java.io.File;
import java.lang.annotation.ElementType; import java.lang.annotation.ElementType;
import java.lang.annotation.Retention; import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy; import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target; import java.lang.annotation.Target;
import java.util.Map; import java.util.Map;
import javax.inject.Singleton;
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;
@ -37,12 +37,13 @@ import javax.ws.rs.PathParam;
import org.jclouds.http.functions.ParseSax; import org.jclouds.http.functions.ParseSax;
import org.jclouds.http.options.HttpRequestOptions; import org.jclouds.http.options.HttpRequestOptions;
import org.jclouds.rest.Binder; import org.jclouds.io.Payload;
import org.jclouds.rest.annotations.BinderParam; import org.jclouds.rest.annotations.BinderParam;
import org.jclouds.rest.annotations.ExceptionParser; import org.jclouds.rest.annotations.ExceptionParser;
import org.jclouds.rest.annotations.MapBinder; import org.jclouds.rest.annotations.MapBinder;
import org.jclouds.rest.annotations.MapPayloadParam; import org.jclouds.rest.annotations.MapPayloadParam;
import org.jclouds.rest.annotations.RequestFilters; import org.jclouds.rest.annotations.RequestFilters;
import org.jclouds.rest.annotations.ResponseParser;
import org.jclouds.rest.annotations.XMLResponseParser; import org.jclouds.rest.annotations.XMLResponseParser;
import org.jclouds.rest.binders.BindMapToMatrixParams; import org.jclouds.rest.binders.BindMapToMatrixParams;
import org.jclouds.rest.binders.BindToJsonPayload; import org.jclouds.rest.binders.BindToJsonPayload;
@ -50,6 +51,7 @@ import org.jclouds.rest.binders.BindToStringPayload;
import org.jclouds.util.Utils; import org.jclouds.util.Utils;
import com.google.common.base.Function; import com.google.common.base.Function;
import com.google.common.collect.Multimap;
import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.ListenableFuture;
/** /**
@ -109,7 +111,7 @@ public interface IntegrationTestAsyncClient {
@POST @POST
@Path("/objects/{id}") @Path("/objects/{id}")
ListenableFuture<String> postAsInputStream(@PathParam("id") String id, ListenableFuture<String> postAsInputStream(@PathParam("id") String id,
@BinderParam(BindToInputStreamPayload.class) String toPut); @BinderParam(BindToInputStreamPayload.class) String toPut);
static class BindToInputStreamPayload extends BindToStringPayload { static class BindToInputStreamPayload extends BindToStringPayload {
@Override @Override
@ -120,23 +122,20 @@ public interface IntegrationTestAsyncClient {
} }
} }
@POST @Singleton
@Path("/objects/{id}") static class ResponsePayload implements Function<HttpResponse, Multimap<String, String>> {
ListenableFuture<String> postWithMd5(@PathParam("id") String id, @HeaderParam("Content-MD5") String base64MD5,
@BinderParam(BindToFilePayload.class) File file);
static class BindToFilePayload implements Binder { public Multimap<String, String> apply(HttpResponse from) {
@Override return from.getHeaders();
public void bindToRequest(HttpRequest request, Object payload) {
File f = (File) payload;
request.setPayload(f);
} }
} }
@POST @POST
@Path("/objects/{id}") @Path("/objects/{id}")
String postWithContentDisposition(@PathParam("id") String id, @HeaderParam("Content-Disposition") String contentDisposition, @ResponseParser(ResponsePayload.class)
@BinderParam(BindToStringPayload.class) String toPut); ListenableFuture<Multimap<String, String>> postPayloadAndReturnHeaders(@PathParam("id") String id,
Payload payload);
@POST @POST
@Path("/objects/{id}") @Path("/objects/{id}")
@ -146,7 +145,7 @@ public interface IntegrationTestAsyncClient {
@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);
@GET @GET
@Path("/objects/{id}") @Path("/objects/{id}")

View File

@ -19,12 +19,14 @@
package org.jclouds.http; package org.jclouds.http;
import java.io.File;
import java.util.Map; import java.util.Map;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import org.jclouds.concurrent.Timeout; import org.jclouds.concurrent.Timeout;
import org.jclouds.http.options.HttpRequestOptions; import org.jclouds.http.options.HttpRequestOptions;
import org.jclouds.io.Payload;
import com.google.common.collect.Multimap;
/** /**
* Sample test for the behaviour of our Integration Test jetty server. * Sample test for the behaviour of our Integration Test jetty server.
@ -33,37 +35,35 @@ 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); String rowdy(String path);
boolean exists(String path); boolean exists(String path);
String synch(String id); String synch(String id);
String download(String id); String download(String id);
String downloadException(String id, HttpRequestOptions options); String downloadException(String id, HttpRequestOptions options);
String synchException(String id, String header); String synchException(String id, String header);
String upload(String id, String toPut); String upload(String id, String toPut);
String post(String id, String toPut); String post(String id, String toPut);
String postAsInputStream(String id, String toPut); String postAsInputStream(String id, String toPut);
String postWithMd5(String id, String base64MD5, File file); Multimap<String, String> postPayloadAndReturnHeaders(String id, Payload payload);
String postWithContentDisposition(String id, String contentDisposition, String toPut); String postJson(String id, String toPut);
String postJson(String id, String toPut); String action(String id, String action, Map<String, String> options);
String action(String id, String action, Map<String, String> options); String downloadFilter(String id, String header);
String downloadFilter(String id, String header); String download(String id, String header);
String download(String id, String header); String downloadAndParse(String id);
String downloadAndParse(String id); StringBuffer newStringBuffer();
StringBuffer newStringBuffer();
} }

View File

@ -72,8 +72,10 @@ public abstract class BaseRestClientTest {
bind(TransformingHttpCommandExecutorService.class).toInstance(mock); bind(TransformingHttpCommandExecutorService.class).toInstance(mock);
} }
} }
protected void assertPayloadEquals(HttpRequest request, String toMatch, String contentType, boolean contentMD5) { protected void assertPayloadEquals(HttpRequest request, String toMatch, String contentType, boolean contentMD5) {
assertPayloadEquals(request, toMatch, contentType, null, contentMD5);
}
protected void assertPayloadEquals(HttpRequest request, String toMatch, String contentType, String contentDispositon, boolean contentMD5) {
if (request.getPayload() == null) { if (request.getPayload() == null) {
assertNull(toMatch); assertNull(toMatch);
} else { } else {
@ -86,7 +88,7 @@ public abstract class BaseRestClientTest {
assertEquals(payload, toMatch); assertEquals(payload, toMatch);
Long length = new Long(payload.getBytes().length); Long length = new Long(payload.getBytes().length);
try { try {
assertContentHeadersEqual(request, contentType, length, contentMD5 ? CryptoStreams assertContentHeadersEqual(request, contentType, contentDispositon, length, contentMD5 ? CryptoStreams
.md5(request.getPayload()) : null); .md5(request.getPayload()) : null);
} catch (IOException e) { } catch (IOException e) {
propagate(e); propagate(e);
@ -94,7 +96,7 @@ public abstract class BaseRestClientTest {
} }
} }
protected void assertContentHeadersEqual(HttpRequest request, String contentType, Long length, byte[] contentMD5) { protected void assertContentHeadersEqual(HttpRequest request, String contentType, String contentDispositon, Long length, byte[] contentMD5) {
if (request.getFirstHeaderOrNull(TRANSFER_ENCODING) == null) { if (request.getFirstHeaderOrNull(TRANSFER_ENCODING) == null) {
assertEquals(request.getPayload().getContentLength(), length); assertEquals(request.getPayload().getContentLength(), length);
} else { } else {
@ -103,8 +105,8 @@ public abstract class BaseRestClientTest {
|| request.getPayload().getContentLength().equals(length); || request.getPayload().getContentLength().equals(length);
} }
assertEquals(request.getPayload().getContentType(), contentType); assertEquals(request.getPayload().getContentType(), contentType);
assertEquals(request.getPayload().getContentDisposition(), contentDispositon);
assertEquals(request.getPayload().getContentMD5(), contentMD5); assertEquals(request.getPayload().getContentMD5(), contentMD5);
} }
//FIXME Shouldn't be assertPayloadHeadersEqual? //FIXME Shouldn't be assertPayloadHeadersEqual?

View File

@ -208,7 +208,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);
@ -223,7 +223,7 @@ 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/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().onePath("foo"); caller.getCallee().onePath("foo");
@ -252,7 +252,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);
@ -267,7 +267,7 @@ 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/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().onePath("foo"); caller.getCallee().onePath("foo");
@ -279,8 +279,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();
@ -330,10 +330,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);
} }
@ -383,7 +383,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);
} }
@ -480,7 +480,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(), "");
@ -588,45 +588,45 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest {
@POST @POST
@Path("") @Path("")
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
@Path("") @Path("")
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 {
@ -636,38 +636,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 {
@ -677,20 +677,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 {
@ -804,7 +804,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");
@ -819,10 +819,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"));
} }
@ -835,10 +835,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"));
} }
@ -851,10 +851,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"));
} }
@ -867,7 +867,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");
@ -882,7 +882,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");
@ -897,10 +897,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")
@ -912,10 +912,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 {
@ -1002,7 +1002,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);
@ -1139,7 +1139,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"));
@ -1157,7 +1157,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"));
} }
@ -1166,7 +1166,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"));
} }
@ -1175,17 +1175,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"));
} }
@ -1200,7 +1200,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");
} }
@ -1208,13 +1208,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);
} }
@ -1256,7 +1256,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");
} }
@ -1272,7 +1272,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");
} }
@ -1280,7 +1280,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");
} }
@ -1288,16 +1288,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");
} }
@ -1310,9 +1310,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");
} }
@ -1353,7 +1353,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");
} }
@ -1370,7 +1370,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");
} }
@ -1378,7 +1378,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");
} }
@ -1386,17 +1386,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");
} }
@ -1448,7 +1448,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);
@ -1466,7 +1466,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")));
@ -1500,12 +1500,12 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest {
payload.setContentDisposition("attachment; filename=photo.jpg"); payload.setContentDisposition("attachment; filename=photo.jpg");
HttpRequest request = factory(TestQuery.class).createRequest(method, payload); HttpRequest request = factory(TestQuery.class).createRequest(method, payload);
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, "Content-Disposition: attachment; filename=photo.jpg"); assertNonPayloadHeadersEqual(request, "");
assertPayloadEquals(request, "whoops", "application/unknown", false); assertPayloadEquals(request, "whoops", "application/unknown", "attachment; filename=photo.jpg", false);
} }
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);
@ -1526,7 +1526,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());
@ -1551,9 +1551,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 {
@ -1590,7 +1590,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);
@ -1631,7 +1631,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}")
@ -1643,7 +1643,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 {
@ -1658,7 +1658,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 {
@ -1672,7 +1672,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 {
@ -1735,7 +1735,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");
@ -1778,7 +1778,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);
@ -1843,7 +1843,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"));
} }
@ -1852,7 +1852,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"));
} }
@ -1861,7 +1861,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"));
@ -1871,7 +1871,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");
@ -1894,7 +1894,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> {
@ -1914,7 +1914,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"));
} }
@ -1924,7 +1924,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"));
} }
@ -1936,12 +1936,12 @@ 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
@Path("") @Path("")
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
@ -2039,23 +2039,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();
@ -2063,16 +2063,15 @@ 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( bind(URI.class).annotatedWith(Localhost2.class).toInstance(URI.create("http://localhost:1111"));
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);