updated nested parser so that it can return empty collections

This commit is contained in:
Adrian Cole 2011-02-13 00:06:26 +01:00
parent db6b3375d0
commit 096b25509d
2 changed files with 179 additions and 159 deletions

View File

@ -19,7 +19,9 @@
package org.jclouds.http.functions; package org.jclouds.http.functions;
import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set;
import javax.inject.Inject; import javax.inject.Inject;
import javax.inject.Singleton; import javax.inject.Singleton;
@ -27,7 +29,11 @@ import javax.inject.Singleton;
import org.jclouds.http.HttpResponse; import org.jclouds.http.HttpResponse;
import com.google.common.base.Function; import com.google.common.base.Function;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables; import com.google.common.collect.Iterables;
import com.google.inject.TypeLiteral;
/** /**
* @author Adrian Cole * @author Adrian Cole
@ -36,20 +42,30 @@ import com.google.common.collect.Iterables;
public class UnwrapOnlyNestedJsonValue<T> implements Function<HttpResponse, T> { public class UnwrapOnlyNestedJsonValue<T> implements Function<HttpResponse, T> {
private final ParseJson<Map<String, Map<String, T>>> json; private final ParseJson<Map<String, Map<String, T>>> json;
private final TypeLiteral<T> type;
@Inject @Inject
UnwrapOnlyNestedJsonValue(ParseJson<Map<String, Map<String, T>>> json) { UnwrapOnlyNestedJsonValue(ParseJson<Map<String, Map<String, T>>> json, TypeLiteral<T> type) {
this.json = json; this.json = json;
this.type = type;
} }
@SuppressWarnings("unchecked")
@Override @Override
public T apply(HttpResponse arg0) { public T apply(HttpResponse arg0) {
Map<String, Map<String, T>> map = json.apply(arg0); Map<String, Map<String, T>> map = json.apply(arg0);
if (map == null || map.size() == 0) if (map == null || map.size() == 0)
return null; return null;
Map<String, T> map1 = Iterables.getOnlyElement(map.values()); Map<String, T> map1 = Iterables.getOnlyElement(map.values());
if (map1 == null || map1.size() == 0) if (map1 == null || map1.size() == 0) {
if (type.getRawType().isAssignableFrom(Set.class))
return (T) ImmutableSet.of();
else if (type.getRawType().isAssignableFrom(List.class))
return (T) ImmutableList.of();
else if (type.getRawType().isAssignableFrom(Map.class))
return (T) ImmutableMap.of();
return null; return null;
}
return Iterables.getOnlyElement(map1.values()); return Iterables.getOnlyElement(map1.values());
} }
} }

View File

@ -283,8 +283,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();
@ -850,8 +850,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"));
} }
@ -866,8 +866,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"));
} }
@ -882,8 +882,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"));
} }
@ -960,6 +960,9 @@ 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.<String> of());
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@ -989,6 +992,8 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest {
.createResponseParser(parserFactory, injector, method, request); .createResponseParser(parserFactory, injector, method, request);
assertEquals(parser.apply(new HttpResponse(200, "ok", newStringPayload("{\"runit\":{\"runit\":[]}}"))), null); assertEquals(parser.apply(new HttpResponse(200, "ok", newStringPayload("{\"runit\":{\"runit\":[]}}"))), null);
assertEquals(parser.apply(new HttpResponse(200, "ok", newStringPayload("{\"runit\":{}}"))), null);
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@ -1054,8 +1059,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);
@ -1300,8 +1305,8 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest {
@Test @Test
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)
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");
} }
@ -1397,8 +1402,8 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest {
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)
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");
} }
@ -1412,8 +1417,8 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest {
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)
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");
} }
@ -1496,8 +1501,8 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest {
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)
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");
} }
@ -1559,8 +1564,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);
@ -1702,8 +1707,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);
@ -1770,8 +1775,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")); 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),
.rfc822DateFormat(date))); Collections.singletonList(dateService.rfc822DateFormat(date)));
} }
public void testCreateGetOptionsThatProducesHeaders() throws SecurityException, NoSuchMethodException { public void testCreateGetOptionsThatProducesHeaders() throws SecurityException, NoSuchMethodException {
@ -1784,8 +1789,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")); 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),
.rfc822DateFormat(date))); Collections.singletonList(dateService.rfc822DateFormat(date)));
} }
public class PrefixOptions extends BaseHttpRequestOptions { public class PrefixOptions extends BaseHttpRequestOptions {
@ -2174,13 +2179,12 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest {
@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() {
bind(URI.class).annotatedWith(Localhost2.class).toInstance( bind(URI.class).annotatedWith(Localhost2.class).toInstance(URI.create("http://localhost:1111"));
URI.create("http://localhost:1111"));
} }
})); }));