formatting

This commit is contained in:
Adrian Cole 2011-10-29 00:00:49 +02:00
parent e5478cdd84
commit 71ac2b89e1
8 changed files with 449 additions and 495 deletions

View File

@ -40,20 +40,20 @@ import com.google.common.base.Function;
import com.google.inject.TypeLiteral; import com.google.inject.TypeLiteral;
/** /**
* This object will parse the body of an HttpResponse and return the result of type <T> back to the * This object will parse the body of an HttpResponse and return the result of
* caller. * type <T> back to the caller.
* <p> * <p>
* {@link JAXBContext} works with {@link Class} objects instead of {@link Type}. This could be a * {@link JAXBContext} works with {@link Class} objects instead of {@link Type}.
* limitation if we are trying to parse typed collections of objects. However, when using JAXB we * This could be a limitation if we are trying to parse typed collections of
* expect to have well formed XML documents with one single root element, so the objects to parse * objects. However, when using JAXB we expect to have well formed XML documents
* should not be collections but objects that wrap collections of elements, and that should work * with one single root element, so the objects to parse should not be
* fine. * collections but objects that wrap collections of elements, and that should
* work fine.
* *
* @author Ignasi Barrera * @author Ignasi Barrera
*/ */
@Singleton @Singleton
public class ParseXMLWithJAXB<T> implements Function<HttpResponse, T> public class ParseXMLWithJAXB<T> implements Function<HttpResponse, T> {
{
@Resource @Resource
protected Logger logger = Logger.NULL; protected Logger logger = Logger.NULL;
@ -62,49 +62,36 @@ public class ParseXMLWithJAXB<T> implements Function<HttpResponse, T>
protected final TypeLiteral<T> type; protected final TypeLiteral<T> type;
@Inject @Inject
public ParseXMLWithJAXB(final XMLParser xml, final TypeLiteral<T> type) public ParseXMLWithJAXB(final XMLParser xml, final TypeLiteral<T> type) {
{
this.xml = xml; this.xml = xml;
this.type = type; this.type = type;
} }
@Override @Override
public T apply(final HttpResponse from) public T apply(final HttpResponse from) {
{
InputStream xml = from.getPayload().getInput(); InputStream xml = from.getPayload().getInput();
try try {
{
return apply(xml); return apply(xml);
} } catch (Exception e) {
catch (Exception e)
{
StringBuffer message = new StringBuffer(); StringBuffer message = new StringBuffer();
message.append("Error parsing input"); message.append("Error parsing input");
logger.error(e, message.toString()); logger.error(e, message.toString());
throw new HttpResponseException(message.toString() + "\n" + from, null, from, e); throw new HttpResponseException(message.toString() + "\n" + from, null, from, e);
} } finally {
finally
{
releasePayload(from); releasePayload(from);
} }
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public T apply(final InputStream stream) throws IOException public T apply(final InputStream stream) throws IOException {
{
return (T) apply(stream, type.getRawType()); return (T) apply(stream, type.getRawType());
} }
public <V> V apply(final InputStream stream, final Class<V> type) throws IOException public <V> V apply(final InputStream stream, final Class<V> type) throws IOException {
{ try {
try
{
return xml.fromXML(Strings2.toStringAndClose(stream), type); return xml.fromXML(Strings2.toStringAndClose(stream), type);
} } finally {
finally if (stream != null) {
{
if (stream != null)
{
stream.close(); stream.close();
} }
} }

View File

@ -27,14 +27,13 @@ import java.lang.annotation.Target;
import org.jclouds.http.functions.ParseXMLWithJAXB; import org.jclouds.http.functions.ParseXMLWithJAXB;
/** /**
* Shows the transformer type used to parse XML with the {@link ParseXMLWithJAXB} parser in a * Shows the transformer type used to parse XML with the
* HttpResponse. * {@link ParseXMLWithJAXB} parser in a HttpResponse.
* *
* @author Ignasi Barrera * @author Ignasi Barrera
*/ */
@Target(METHOD) @Target(METHOD)
@Retention(RUNTIME) @Retention(RUNTIME)
public @interface JAXBResponseParser public @interface JAXBResponseParser {
{
} }

View File

@ -26,45 +26,38 @@ import org.jclouds.http.HttpRequest;
* *
* @author Ignasi Barrera * @author Ignasi Barrera
*/ */
public class BindException extends RuntimeException public class BindException extends RuntimeException {
{
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
private HttpRequest request; private HttpRequest request;
public BindException(final HttpRequest request) public BindException(final HttpRequest request) {
{
super(); super();
this.request = request; this.request = request;
} }
public BindException(final HttpRequest request, final String message) public BindException(final HttpRequest request, final String message) {
{
super(message); super(message);
this.request = request; this.request = request;
} }
public BindException(final HttpRequest request, final Throwable cause) public BindException(final HttpRequest request, final Throwable cause) {
{
super(cause.getMessage(), cause); super(cause.getMessage(), cause);
this.request = request; this.request = request;
} }
public BindException(final HttpRequest request, final String message, final Throwable cause) public BindException(final HttpRequest request, final String message, final Throwable cause) {
{
super(message, cause); super(message, cause);
this.request = request; this.request = request;
} }
@Override @Override
public String getMessage() public String getMessage() {
{
String msg = "Could not bind object to request" + request + ": "; String msg = "Could not bind object to request" + request + ": ";
return msg + super.getMessage(); return msg + super.getMessage();
} }
public HttpRequest getRequest() public HttpRequest getRequest() {
{
return request; return request;
} }

View File

@ -40,38 +40,30 @@ import com.google.common.base.Strings;
* @author Ignasi Barrera * @author Ignasi Barrera
*/ */
@Singleton @Singleton
public class BindToXMLPayload implements Binder public class BindToXMLPayload implements Binder {
{
protected final XMLParser xmlParser; protected final XMLParser xmlParser;
@Inject @Inject
public BindToXMLPayload(final XMLParser xmlParser) public BindToXMLPayload(final XMLParser xmlParser) {
{
this.xmlParser = checkNotNull(xmlParser, "xmlParser"); this.xmlParser = checkNotNull(xmlParser, "xmlParser");
} }
@Override @Override
public <R extends HttpRequest> R bindToRequest(final R request, final Object input) public <R extends HttpRequest> R bindToRequest(final R request, final Object input) {
{ try {
try
{
String xml = xmlParser.toXML(checkNotNull(input, "input")); String xml = xmlParser.toXML(checkNotNull(input, "input"));
request.setPayload(xml); request.setPayload(xml);
MutableContentMetadata metadata = request.getPayload().getContentMetadata(); MutableContentMetadata metadata = request.getPayload().getContentMetadata();
if (contentTypeMustBeAdded(metadata)) if (contentTypeMustBeAdded(metadata)) {
{
metadata.setContentType(MediaType.APPLICATION_XML); metadata.setContentType(MediaType.APPLICATION_XML);
} }
return request; return request;
} } catch (IOException ex) {
catch (IOException ex)
{
throw new BindException(request, ex); throw new BindException(request, ex);
} }
} }
private static boolean contentTypeMustBeAdded(final MutableContentMetadata metadata) private static boolean contentTypeMustBeAdded(final MutableContentMetadata metadata) {
{
return Strings.isNullOrEmpty(metadata.getContentType()) return Strings.isNullOrEmpty(metadata.getContentType())
|| metadata.getContentType().equals("application/unknown"); || metadata.getContentType().equals("application/unknown");
} }

View File

@ -31,26 +31,22 @@ import com.google.inject.ImplementedBy;
* @author Ignasi Barrera * @author Ignasi Barrera
*/ */
@ImplementedBy(JAXBParser.class) @ImplementedBy(JAXBParser.class)
public interface XMLParser public interface XMLParser {
{
/** The default xml header. */ /** The default xml header. */
public static final String DEFAULT_XML_HEADER = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>"; public static final String DEFAULT_XML_HEADER = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>";
/** /**
* Serialize the object into xml. If the object is a generic type, use * Serialize the object into xml.
* {@link #toXML(Object, Type)}
*/ */
public String toXML(Object src) throws IOException; public String toXML(Object src) throws IOException;
/** /**
* Serialize the generic object into xml. If the object is not a generic, use * Serialize the object into xml, as the declared type.
* {@link #toXML(Object, Type)}
*/ */
public <T> String toXML(Object src, Class<T> type) throws IOException; public <T> String toXML(Object src, Class<T> type) throws IOException;
/** /**
* Deserialize the generic object from xml. If the object is not a generic type, use * Deserialize the object from xml.
* {@link #fromXML(Object, Class)}
*/ */
public <T> T fromXML(String xml, Class<T> type) throws IOException; public <T> T fromXML(String xml, Class<T> type) throws IOException;

View File

@ -39,44 +39,34 @@ import org.jclouds.xml.XMLParser;
* @see ParseXMLWithJAXB * @see ParseXMLWithJAXB
*/ */
@Singleton @Singleton
public class JAXBParser implements XMLParser public class JAXBParser implements XMLParser {
{
@Override @Override
public String toXML(final Object src) throws IOException public String toXML(final Object src) throws IOException {
{
return toXML(src, src.getClass()); return toXML(src, src.getClass());
} }
@Override @Override
public <T> String toXML(final Object src, final Class<T> type) throws IOException public <T> String toXML(final Object src, final Class<T> type) throws IOException {
{ try {
try
{
JAXBContext context = JAXBContext.newInstance(type); JAXBContext context = JAXBContext.newInstance(type);
Marshaller marshaller = context.createMarshaller(); Marshaller marshaller = context.createMarshaller();
StringWriter writer = new StringWriter(); StringWriter writer = new StringWriter();
marshaller.marshal(src, writer); marshaller.marshal(src, writer);
return writer.toString(); return writer.toString();
} } catch (JAXBException ex) {
catch (JAXBException ex)
{
throw new IOException("Could not marshall object", ex); throw new IOException("Could not marshall object", ex);
} }
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@Override @Override
public <T> T fromXML(final String xml, final Class<T> type) throws IOException public <T> T fromXML(final String xml, final Class<T> type) throws IOException {
{ try {
try
{
StringReader reader = new StringReader(xml); StringReader reader = new StringReader(xml);
JAXBContext context = JAXBContext.newInstance(type); JAXBContext context = JAXBContext.newInstance(type);
Unmarshaller unmarshaller = context.createUnmarshaller(); Unmarshaller unmarshaller = context.createUnmarshaller();
return (T) unmarshaller.unmarshal(reader); return (T) unmarshaller.unmarshal(reader);
} } catch (Exception ex) {
catch (Exception ex)
{
throw new IOException("Could not unmarshall document", ex); throw new IOException("Could not unmarshall document", ex);
} }
} }

View File

@ -39,13 +39,11 @@ import com.google.common.collect.Multimap;
* @author Ignasi Barrera * @author Ignasi Barrera
*/ */
@Test(groups = "unit", testName = "BindToXMLPayloadTest") @Test(groups = "unit", testName = "BindToXMLPayloadTest")
public class BindToXMLPayloadTest public class BindToXMLPayloadTest {
{
XMLParser xml = new JAXBParser(); XMLParser xml = new JAXBParser();
@Test @Test
public void testBindJAXBObject() throws SecurityException, NoSuchMethodException public void testBindJAXBObject() throws SecurityException, NoSuchMethodException {
{
BindToXMLPayload binder = new BindToXMLPayload(xml); BindToXMLPayload binder = new BindToXMLPayload(xml);
// Build the object to bind // Build the object to bind
@ -54,38 +52,39 @@ public class BindToXMLPayloadTest
HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://momma")).build(); HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://momma")).build();
request = binder.bindToRequest(request, obj); request = binder.bindToRequest(request, obj);
assertEquals(request.getPayload().getRawContent(), XMLParser.DEFAULT_XML_HEADER + "<test><elem>Hello World</elem></test>"); assertEquals(request.getPayload().getRawContent(), XMLParser.DEFAULT_XML_HEADER
+ "<test><elem>Hello World</elem></test>");
assertEquals(request.getPayload().getContentMetadata().getContentType(), MediaType.APPLICATION_XML); assertEquals(request.getPayload().getContentMetadata().getContentType(), MediaType.APPLICATION_XML);
} }
@Test @Test
public void testHeaderIsChangedIfNeeded() throws SecurityException, NoSuchMethodException public void testHeaderIsChangedIfNeeded() throws SecurityException, NoSuchMethodException {
{
BindToXMLPayload binder = new BindToXMLPayload(xml); BindToXMLPayload binder = new BindToXMLPayload(xml);
// Build the object to bind // Build the object to bind
TestJAXBDomain obj = new TestJAXBDomain(); TestJAXBDomain obj = new TestJAXBDomain();
obj.setElem("Hello World"); obj.setElem("Hello World");
// Add teh unknown content-type header to verify it is changed by the binder // Add teh unknown content-type header to verify it is changed by the
// binder
Multimap<String, String> headers = ImmutableMultimap.<String, String> of("Content-type", "application/unknown"); Multimap<String, String> headers = ImmutableMultimap.<String, String> of("Content-type", "application/unknown");
HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://momma")).headers(headers).build(); HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://momma")).headers(headers)
.build();
request = binder.bindToRequest(request, obj); request = binder.bindToRequest(request, obj);
assertEquals(request.getPayload().getRawContent(), XMLParser.DEFAULT_XML_HEADER + "<test><elem>Hello World</elem></test>"); assertEquals(request.getPayload().getRawContent(), XMLParser.DEFAULT_XML_HEADER
+ "<test><elem>Hello World</elem></test>");
assertEquals(request.getPayload().getContentMetadata().getContentType(), MediaType.APPLICATION_XML); assertEquals(request.getPayload().getContentMetadata().getContentType(), MediaType.APPLICATION_XML);
} }
@Test(expectedExceptions = NullPointerException.class) @Test(expectedExceptions = NullPointerException.class)
public void testNullIsBad() public void testNullIsBad() {
{
BindToXMLPayload binder = new BindToXMLPayload(xml); BindToXMLPayload binder = new BindToXMLPayload(xml);
binder.bindToRequest(HttpRequest.builder().method("GET").endpoint(URI.create("http://momma")).build(), null); binder.bindToRequest(HttpRequest.builder().method("GET").endpoint(URI.create("http://momma")).build(), null);
} }
@Test(expectedExceptions = BindException.class) @Test(expectedExceptions = BindException.class)
public void testInvalidObjectBinding() public void testInvalidObjectBinding() {
{
BindToXMLPayload binder = new BindToXMLPayload(xml); BindToXMLPayload binder = new BindToXMLPayload(xml);
HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://momma")).build(); HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://momma")).build();
request = binder.bindToRequest(request, new Object()); request = binder.bindToRequest(request, new Object());

View File

@ -175,7 +175,8 @@ import com.sun.jersey.api.uri.UriBuilderImpl;
* *
* @author Adrian Cole * @author Adrian Cole
*/ */
// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire // NOTE:without testName, this will not call @Before* and fail w/NPE during
// surefire
@Test(groups = "unit", testName = "RestAnnotationProcessorTest") @Test(groups = "unit", testName = "RestAnnotationProcessorTest")
public class RestAnnotationProcessorTest extends BaseRestClientTest { public class RestAnnotationProcessorTest extends BaseRestClientTest {
@ -326,8 +327,8 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest {
private Injector injectorForClient() { private Injector injectorForClient() {
RestContextSpec<Caller, AsyncCaller> contextSpec = contextSpec("test", "http://localhost:9999", "1", "", RestContextSpec<Caller, AsyncCaller> contextSpec = contextSpec("test", "http://localhost:9999", "1", "",
"userfoo", null, Caller.class, AsyncCaller.class, ImmutableSet.<Module> of(new MockModule(), "userfoo", null, Caller.class, AsyncCaller.class,
new NullLoggingModule(), new CallerCalleeModule())); ImmutableSet.<Module> of(new MockModule(), new NullLoggingModule(), new CallerCalleeModule()));
return createContextBuilder(contextSpec).buildInjector(); return createContextBuilder(contextSpec).buildInjector();
@ -342,7 +343,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest {
}; };
@Target( { ElementType.METHOD }) @Target({ ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME) @Retention(RetentionPolicy.RUNTIME)
@javax.ws.rs.HttpMethod("FOO") @javax.ws.rs.HttpMethod("FOO")
public @interface FOO { public @interface FOO {
@ -615,9 +616,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest {
Method method = TestPost.class.getMethod("postNonnull", String.class); Method method = TestPost.class.getMethod("postNonnull", String.class);
try { try {
HttpRequest request = factory(TestPost.class).createRequest(method); HttpRequest request = factory(TestPost.class).createRequest(method);
Assert Assert.fail("call should have failed with illegal null parameter, not permitted " + request + " to be created");
.fail("call should have failed with illegal null parameter, not permitted " + request
+ " to be created");
} catch (NullPointerException e) { } catch (NullPointerException e) {
Assert.assertTrue(e.toString().indexOf("postNonnull parameter 1") >= 0, Assert.assertTrue(e.toString().indexOf("postNonnull parameter 1") >= 0,
"Error message should have referred to 'parameter 1': " + e); "Error message should have referred to 'parameter 1': " + e);
@ -628,9 +627,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest {
Method method = TestPost.class.getMethod("postNonnull", String.class); Method method = TestPost.class.getMethod("postNonnull", String.class);
try { try {
HttpRequest request = factory(TestPost.class).createRequest(method, (String) null); HttpRequest request = factory(TestPost.class).createRequest(method, (String) null);
Assert Assert.fail("call should have failed with illegal null parameter, not permitted " + request + " to be created");
.fail("call should have failed with illegal null parameter, not permitted " + request
+ " to be created");
} catch (NullPointerException e) { } catch (NullPointerException e) {
Assert.assertTrue(e.toString().indexOf("postNonnull parameter 1") >= 0, Assert.assertTrue(e.toString().indexOf("postNonnull parameter 1") >= 0,
"Error message should have referred to parameter 'parameter 1': " + e); "Error message should have referred to parameter 'parameter 1': " + e);
@ -729,10 +726,12 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest {
Method method = TestMultipartForm.class.getMethod("withStringPart", String.class); Method method = TestMultipartForm.class.getMethod("withStringPart", String.class);
try { try {
GeneratedHttpRequest<TestMultipartForm> httpRequest = factory(TestMultipartForm.class).createRequest(method, GeneratedHttpRequest<TestMultipartForm> httpRequest = factory(TestMultipartForm.class).createRequest(method,
(String)null); (String) null);
Assert.fail("call should have failed with illegal null parameter, not permitted "+httpRequest+" to be created"); Assert.fail("call should have failed with illegal null parameter, not permitted " + httpRequest
+ " to be created");
} catch (NullPointerException e) { } catch (NullPointerException e) {
Assert.assertTrue(e.toString().indexOf("fooble")>=0, "Error message should have referred to parameter 'fooble': "+e); Assert.assertTrue(e.toString().indexOf("fooble") >= 0,
"Error message should have referred to parameter 'fooble': " + e);
} }
} }
@ -759,9 +758,11 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest {
try { try {
GeneratedHttpRequest<TestMultipartForm> httpRequest = factory(TestMultipartForm.class).createRequest(method, GeneratedHttpRequest<TestMultipartForm> httpRequest = factory(TestMultipartForm.class).createRequest(method,
null, "foobledata"); null, "foobledata");
Assert.fail("call should have failed with illegal null parameter, not permitted "+httpRequest+" to be created"); Assert.fail("call should have failed with illegal null parameter, not permitted " + httpRequest
+ " to be created");
} catch (NullPointerException e) { } catch (NullPointerException e) {
Assert.assertTrue(e.toString().indexOf("name")>=0, "Error message should have referred to parameter 'name': "+e); Assert.assertTrue(e.toString().indexOf("name") >= 0,
"Error message should have referred to parameter 'name': " + e);
} }
} }
@ -931,7 +932,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest {
@Consumes(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON)
ListenableFuture<String> testUnwrapDepth3(); ListenableFuture<String> testUnwrapDepth3();
@Target( { ElementType.METHOD }) @Target({ ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME) @Retention(RetentionPolicy.RUNTIME)
@HttpMethod("ROWDY") @HttpMethod("ROWDY")
public @interface ROWDY { public @interface ROWDY {
@ -1016,8 +1017,8 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest {
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\"}"))),
"foo", "bar")); ImmutableMap.of("foo", "bar"));
} }
@ -1032,8 +1033,8 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest {
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\"}"))),
"foo", "bar")); ImmutableMap.of("foo", "bar"));
} }
@ -1048,8 +1049,8 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest {
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\"}"))),
"foo", "bar")); ImmutableMap.of("foo", "bar"));
} }
@ -1068,7 +1069,6 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest {
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public void testUnwrapValueNamed() throws SecurityException, NoSuchMethodException, IOException { public void testUnwrapValueNamed() throws SecurityException, NoSuchMethodException, IOException {
Method method = TestPut.class.getMethod("testUnwrapValueNamed"); Method method = TestPut.class.getMethod("testUnwrapValueNamed");
@ -1083,6 +1083,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest {
assertEquals(parser.apply(new HttpResponse(200, "ok", newStringPayload("{ foo:\"bar\"}"))), "bar"); assertEquals(parser.apply(new HttpResponse(200, "ok", newStringPayload("{ foo:\"bar\"}"))), "bar");
} }
public void testWrapWith() throws SecurityException, NoSuchMethodException, IOException { public void testWrapWith() throws SecurityException, NoSuchMethodException, IOException {
Method method = TestPut.class.getMethod("testWrapWith", String.class); Method method = TestPut.class.getMethod("testWrapWith", String.class);
HttpRequest request = factory(TestPut.class).createRequest(method, "bar"); HttpRequest request = factory(TestPut.class).createRequest(method, "bar");
@ -1148,8 +1149,8 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest {
assertEquals(parser.apply(new HttpResponse(200, "ok", assertEquals(parser.apply(new HttpResponse(200, "ok",
newStringPayload("{\"runit\":{\"runit\":[\"0.7.0\",\"0.7.1\"]}}"))), ImmutableSet.of("0.7.0", "0.7.1")); newStringPayload("{\"runit\":{\"runit\":[\"0.7.0\",\"0.7.1\"]}}"))), ImmutableSet.of("0.7.0", "0.7.1"));
assertEquals(parser.apply(new HttpResponse(200, "ok", newStringPayload("{\"runit\":{}}"))), ImmutableSet assertEquals(parser.apply(new HttpResponse(200, "ok", newStringPayload("{\"runit\":{}}"))),
.<String> of()); ImmutableSet.<String> of());
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@ -1168,7 +1169,6 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest {
assertEquals(parser.apply(new HttpResponse(200, "ok", newStringPayload("{\"runit\":[]}"))), null); assertEquals(parser.apply(new HttpResponse(200, "ok", newStringPayload("{\"runit\":[]}"))), null);
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public void testSelectOnlyElement() throws SecurityException, NoSuchMethodException, IOException { public void testSelectOnlyElement() throws SecurityException, NoSuchMethodException, IOException {
Method method = TestPut.class.getMethod("selectOnlyElement"); Method method = TestPut.class.getMethod("selectOnlyElement");
@ -1306,8 +1306,8 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest {
Method method = TestRequestFilter.class.getMethod("getOverride", HttpRequest.class); Method method = TestRequestFilter.class.getMethod("getOverride", HttpRequest.class);
HttpRequest request = factory(TestRequestFilter.class).createRequest( HttpRequest request = factory(TestRequestFilter.class).createRequest(
method, method,
HttpRequest.builder().method("GET").endpoint(URI.create("http://localhost")).headers( HttpRequest.builder().method("GET").endpoint(URI.create("http://localhost"))
ImmutableMultimap.of("foo", "bar")).build()); .headers(ImmutableMultimap.of("foo", "bar")).build());
assertEquals(request.getFilters().size(), 1); assertEquals(request.getFilters().size(), 1);
assertEquals(request.getHeaders().size(), 1); assertEquals(request.getHeaders().size(), 1);
assertEquals(request.getFilters().get(0).getClass(), TestRequestFilter2.class); assertEquals(request.getFilters().get(0).getClass(), TestRequestFilter2.class);
@ -1551,8 +1551,8 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest {
@Test @Test
public void testQueryInOptions() throws SecurityException, NoSuchMethodException { public void testQueryInOptions() throws SecurityException, NoSuchMethodException {
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)
new Object[] { "robot", new TestReplaceQueryOptions() }).getEndpoint().getQuery(); .createRequest(oneQuery, new Object[] { "robot", new TestReplaceQueryOptions() }).getEndpoint().getQuery();
assertEquals(query, "x-amz-copy-source=/robot"); assertEquals(query, "x-amz-copy-source=/robot");
} }
@ -1647,8 +1647,8 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest {
@Test @Test
public void testBuildTwoQuerysOutOfOrder() throws SecurityException, NoSuchMethodException { public void testBuildTwoQuerysOutOfOrder() throws SecurityException, NoSuchMethodException {
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)
new Object[] { "robot", "eggs" }).getEndpoint().getQuery(); .createRequest(twoQuerysOutOfOrder, new Object[] { "robot", "eggs" }).getEndpoint().getQuery();
assertEquals(query, "x-amz-copy-source=/eggs/robot"); assertEquals(query, "x-amz-copy-source=/eggs/robot");
} }
@ -1662,8 +1662,8 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest {
public void testMatrixInOptions() throws SecurityException, NoSuchMethodException { public void testMatrixInOptions() throws SecurityException, NoSuchMethodException {
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)
new Object[] { "robot", new TestReplaceMatrixOptions() }).getEndpoint().getPath(); .createRequest(oneMatrix, new Object[] { "robot", new TestReplaceMatrixOptions() }).getEndpoint().getPath();
assertEquals(path, "/;x-amz-copy-source=/robot"); assertEquals(path, "/;x-amz-copy-source=/robot");
} }
@ -1745,8 +1745,8 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest {
public void testBuildTwoMatrixsOutOfOrder() throws SecurityException, NoSuchMethodException { public void testBuildTwoMatrixsOutOfOrder() throws SecurityException, NoSuchMethodException {
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)
new Object[] { "robot", "eggs" }).getEndpoint().getPath(); .createRequest(twoMatrixsOutOfOrder, new Object[] { "robot", "eggs" }).getEndpoint().getPath();
assertEquals(path, "/;x-amz-copy-source=/eggs/robot"); assertEquals(path, "/;x-amz-copy-source=/eggs/robot");
} }
@ -1808,8 +1808,8 @@ 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(Strings2 PayloadEnclosing payloadEnclosing = new PayloadEnclosingImpl(
.toInputStream("whoops"))); newInputStreamPayload(Strings2.toInputStream("whoops")));
calculateMD5(payloadEnclosing, crypto.md5()); calculateMD5(payloadEnclosing, crypto.md5());
HttpRequest request = factory(TestQuery.class).createRequest(method, payloadEnclosing); HttpRequest request = factory(TestQuery.class).createRequest(method, payloadEnclosing);
@ -1951,8 +1951,8 @@ 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 = GeneratedHttpRequest.<TestTransformers> builder().method("GET") GeneratedHttpRequest<TestTransformers> request = GeneratedHttpRequest.<TestTransformers> builder().method("GET")
.endpoint(URI.create("http://localhost")).declaring(TestTransformers.class).javaMethod(method).args( .endpoint(URI.create("http://localhost")).declaring(TestTransformers.class).javaMethod(method)
new Object[] {}).build(); .args(new Object[] {}).build();
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);
@ -1992,7 +1992,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest {
@GET @GET
@Path("/{id}") @Path("/{id}")
@QueryParams(keys = "acl", values="") @QueryParams(keys = "acl", values = "")
ListenableFuture<String> getQueryEmpty(@PathParam("id") String id); ListenableFuture<String> getQueryEmpty(@PathParam("id") String id);
@PUT @PUT
@ -2024,8 +2024,8 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest {
assertEquals(request.getMethod(), HttpMethod.GET); assertEquals(request.getMethod(), HttpMethod.GET);
assertEquals(request.getHeaders().size(), 2); assertEquals(request.getHeaders().size(), 2);
assertEquals(request.getHeaders().get(HttpHeaders.HOST), Collections.singletonList("localhost:9999")); assertEquals(request.getHeaders().get(HttpHeaders.HOST), Collections.singletonList("localhost:9999"));
assertEquals(request.getHeaders().get(HttpHeaders.IF_MODIFIED_SINCE), Collections.singletonList(dateService assertEquals(request.getHeaders().get(HttpHeaders.IF_MODIFIED_SINCE),
.rfc822DateFormat(date))); Collections.singletonList(dateService.rfc822DateFormat(date)));
} }
public void testCreateGetOptionsThatProducesHeaders() throws SecurityException, NoSuchMethodException { public void testCreateGetOptionsThatProducesHeaders() throws SecurityException, NoSuchMethodException {
@ -2038,8 +2038,8 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest {
assertEquals(request.getMethod(), HttpMethod.GET); assertEquals(request.getMethod(), HttpMethod.GET);
assertEquals(request.getHeaders().size(), 2); assertEquals(request.getHeaders().size(), 2);
assertEquals(request.getHeaders().get(HttpHeaders.HOST), Collections.singletonList("localhost:9999")); assertEquals(request.getHeaders().get(HttpHeaders.HOST), Collections.singletonList("localhost:9999"));
assertEquals(request.getHeaders().get(HttpHeaders.IF_MODIFIED_SINCE), Collections.singletonList(dateService assertEquals(request.getHeaders().get(HttpHeaders.IF_MODIFIED_SINCE),
.rfc822DateFormat(date))); Collections.singletonList(dateService.rfc822DateFormat(date)));
} }
public class PrefixOptions extends BaseHttpRequestOptions { public class PrefixOptions extends BaseHttpRequestOptions {
@ -2419,8 +2419,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest {
} }
@Test(expectedExceptions = AuthorizationException.class) @Test(expectedExceptions = AuthorizationException.class)
public void testProvidesWithGenericQualifiedAuthorizationException() throws SecurityException, public void testProvidesWithGenericQualifiedAuthorizationException() throws SecurityException, NoSuchMethodException {
NoSuchMethodException {
injector.getInstance(AsyncClientFactory.class).create(TestClassForm.class).exception(); injector.getInstance(AsyncClientFactory.class).create(TestClassForm.class).exception();
} }
@ -2473,6 +2472,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest {
public String getElem() { public String getElem() {
return elem; return elem;
} }
public void setElem(String elem) { public void setElem(String elem) {
this.elem = elem; this.elem = elem;
} }
@ -2482,9 +2482,9 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest {
public void testCreateJAXBResponseParserWithAnnotation() throws SecurityException, NoSuchMethodException { public void testCreateJAXBResponseParserWithAnnotation() throws SecurityException, NoSuchMethodException {
RestAnnotationProcessor<TestJAXBResponseParser> processor = factory(TestJAXBResponseParser.class); RestAnnotationProcessor<TestJAXBResponseParser> processor = factory(TestJAXBResponseParser.class);
Method method = TestJAXBResponseParser.class.getMethod("jaxbGetWithAnnotation"); Method method = TestJAXBResponseParser.class.getMethod("jaxbGetWithAnnotation");
GeneratedHttpRequest<TestJAXBResponseParser> request = GeneratedHttpRequest.<TestJAXBResponseParser> builder().method("GET") GeneratedHttpRequest<TestJAXBResponseParser> request = GeneratedHttpRequest.<TestJAXBResponseParser> builder()
.endpoint(URI.create("http://localhost")).declaring(TestJAXBResponseParser.class).javaMethod(method).args( .method("GET").endpoint(URI.create("http://localhost")).declaring(TestJAXBResponseParser.class)
new Object[] {}).build(); .javaMethod(method).args(new Object[] {}).build();
Function<HttpResponse, ?> transformer = processor.createResponseParser(method, request); Function<HttpResponse, ?> transformer = processor.createResponseParser(method, request);
assertEquals(transformer.getClass(), ParseXMLWithJAXB.class); assertEquals(transformer.getClass(), ParseXMLWithJAXB.class);
} }
@ -2493,9 +2493,9 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest {
public void testCreateJAXBResponseParserWithAcceptHeader() throws SecurityException, NoSuchMethodException { public void testCreateJAXBResponseParserWithAcceptHeader() throws SecurityException, NoSuchMethodException {
RestAnnotationProcessor<TestJAXBResponseParser> processor = factory(TestJAXBResponseParser.class); RestAnnotationProcessor<TestJAXBResponseParser> processor = factory(TestJAXBResponseParser.class);
Method method = TestJAXBResponseParser.class.getMethod("jaxbGetWithAcceptHeader"); Method method = TestJAXBResponseParser.class.getMethod("jaxbGetWithAcceptHeader");
GeneratedHttpRequest<TestJAXBResponseParser> request = GeneratedHttpRequest.<TestJAXBResponseParser> builder().method("GET") GeneratedHttpRequest<TestJAXBResponseParser> request = GeneratedHttpRequest.<TestJAXBResponseParser> builder()
.endpoint(URI.create("http://localhost")).declaring(TestJAXBResponseParser.class).javaMethod(method).args( .method("GET").endpoint(URI.create("http://localhost")).declaring(TestJAXBResponseParser.class)
new Object[] {}).build(); .javaMethod(method).args(new Object[] {}).build();
Function<HttpResponse, ?> transformer = processor.createResponseParser(method, request); Function<HttpResponse, ?> transformer = processor.createResponseParser(method, request);
assertEquals(transformer.getClass(), ParseXMLWithJAXB.class); assertEquals(transformer.getClass(), ParseXMLWithJAXB.class);
} }
@ -2536,14 +2536,13 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest {
assertEquals(domain.getElem(), "Hello World"); assertEquals(domain.getElem(), "Hello World");
} }
DateService dateService = new SimpleDateFormatDateService(); DateService dateService = new SimpleDateFormatDateService();
@BeforeClass @BeforeClass
void setupFactory() { void setupFactory() {
RestContextSpec<String, Integer> contextSpec = contextSpec("test", "http://localhost:9999", "1", "", "userfoo", RestContextSpec<String, Integer> contextSpec = contextSpec("test", "http://localhost:9999", "1", "", "userfoo",
null, String.class, Integer.class, ImmutableSet.<Module> of(new MockModule(), new NullLoggingModule(), null, String.class, Integer.class,
new AbstractModule() { ImmutableSet.<Module> of(new MockModule(), new NullLoggingModule(), new AbstractModule() {
@Override @Override
protected void configure() { protected void configure() {
@ -2551,8 +2550,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest {
}).toInstance(ImmutableSet.of("foo")); }).toInstance(ImmutableSet.of("foo"));
bind(new TypeLiteral<Set<String>>() { bind(new TypeLiteral<Set<String>>() {
}).annotatedWith(Names.named("bar")).toInstance(ImmutableSet.of("bar")); }).annotatedWith(Names.named("bar")).toInstance(ImmutableSet.of("bar"));
bind(URI.class).annotatedWith(Localhost2.class).toInstance( bind(URI.class).annotatedWith(Localhost2.class).toInstance(URI.create("http://localhost:1111"));
URI.create("http://localhost:1111"));
} }
@SuppressWarnings("unused") @SuppressWarnings("unused")