instance_id
stringlengths
17
39
repo
stringclasses
8 values
issue_id
stringlengths
14
34
pr_id
stringlengths
14
34
linking_methods
sequencelengths
1
3
base_commit
stringlengths
40
40
merge_commit
stringlengths
0
40
hints_text
sequencelengths
0
106
resolved_comments
sequencelengths
0
119
created_at
unknown
labeled_as
sequencelengths
0
7
problem_title
stringlengths
7
174
problem_statement
stringlengths
0
55.4k
gold_files
sequencelengths
0
10
gold_files_postpatch
sequencelengths
1
10
test_files
sequencelengths
0
60
gold_patch
stringlengths
220
5.83M
test_patch
stringlengths
386
194k
split_random
stringclasses
3 values
split_time
stringclasses
3 values
issue_start_time
unknown
issue_created_at
unknown
issue_by_user
stringlengths
3
21
split_repo
stringclasses
3 values
square/retrofit/63_66
square/retrofit
square/retrofit/63
square/retrofit/66
[ "timestamp(timedelta=611.0, similarity=0.9184791542342733)" ]
e997c7218efa52faf9b91022a8f9ad46091aa05c
292340be8ce436aad6b50fb7706bc0ae86d02704
[ "`Fetcher` removed.\n" ]
[ "`1f *` is way cuter than (float) . . . fun.\n\nNit: it isn't 'percent' anymore, it's 'fraction'\n", "Say `Guarded by 'this'` rather than `Synchronized on 'this'.` ?\n" ]
"2012-10-17T06:28:33"
[]
Change Fetcher API To Report Progress as Float
From @swankjesse on #62: > It would be more conventional for the progress listener to just take a float between 0 and 1. It's sort of weird that a UI decision (progress update granularity) is being decided here. > > In slow transfers (say 1MiB over 3G) using percent is lame because multiple reads may yield the same percentage of progress. (10KiB and 19 KiB are both reported as 1% done).
[ "http/src/main/java/retrofit/http/Fetcher.java", "http/src/main/java/retrofit/http/ProgressListener.java" ]
[ "http/src/main/java/retrofit/http/Fetcher.java", "http/src/main/java/retrofit/http/ProgressListener.java" ]
[ "http/src/test/java/retrofit/http/FetcherTest.java" ]
diff --git a/http/src/main/java/retrofit/http/Fetcher.java b/http/src/main/java/retrofit/http/Fetcher.java index 8f4d1f66e8..37cc0df1c3 100644 --- a/http/src/main/java/retrofit/http/Fetcher.java +++ b/http/src/main/java/retrofit/http/Fetcher.java @@ -71,9 +71,6 @@ public void run() { } static class DownloadHandler extends CallbackResponseHandler<Void> { - /** Throttles how often we send progress updates. Specified in %. */ - private static final int PROGRESS_GRANULARITY = 5; - private final ByteSink.Factory destination; private final ProgressListener progressListener; private final MainThread mainThread; @@ -93,8 +90,8 @@ static class DownloadHandler extends CallbackResponseHandler<Void> { InputStream in = entity.getContent(); try { ByteSink out = destination.newSink(); - final int total = (int) entity.getContentLength(); - int totalRead = 0; + final long total = entity.getContentLength(); + long totalRead = 0; try { byte[] buffer = new byte[4096]; int read; @@ -102,10 +99,12 @@ static class DownloadHandler extends CallbackResponseHandler<Void> { out.write(buffer, read); if (progressListener != null) { totalRead += read; - int percent = totalRead * 100 / total; - if (percent - progressUpdate.percent > PROGRESS_GRANULARITY) { - progressUpdate.percent = percent; - mainThread.execute(progressUpdate); + progressUpdate.percent = 1f * totalRead / total; + synchronized (progressUpdate) { + if (progressUpdate.run) { + progressUpdate.run = false; + mainThread.execute(progressUpdate); + } } } } @@ -123,9 +122,17 @@ static class DownloadHandler extends CallbackResponseHandler<Void> { /** Invokes ProgressListener in UI thread. */ private class ProgressUpdate implements Runnable { - private volatile int percent; + /** Amount to report when run. */ + volatile float percent; + + /** Whether or not this update has been run. Synchronized on 'this'. */ + boolean run = true; + public void run() { progressListener.hearProgress(percent); + synchronized (this) { + run = true; + } } } } diff --git a/http/src/main/java/retrofit/http/ProgressListener.java b/http/src/main/java/retrofit/http/ProgressListener.java index 7427ca45b2..2e485c8b2c 100644 --- a/http/src/main/java/retrofit/http/ProgressListener.java +++ b/http/src/main/java/retrofit/http/ProgressListener.java @@ -1,4 +1,4 @@ -// Copyright 2010 Square, Inc. +// Copyright 2012 Square, Inc. package retrofit.http; /** @@ -11,7 +11,7 @@ public interface ProgressListener { /** * Hears a progress update. * - * @param percent 0-100 + * @param percent Float bounded by (0..1]. */ - void hearProgress(int percent); + void hearProgress(float percent); }
diff --git a/http/src/test/java/retrofit/http/FetcherTest.java b/http/src/test/java/retrofit/http/FetcherTest.java index cbddcff439..589ccc9b84 100644 --- a/http/src/test/java/retrofit/http/FetcherTest.java +++ b/http/src/test/java/retrofit/http/FetcherTest.java @@ -17,7 +17,7 @@ import java.util.Arrays; import java.util.concurrent.Executor; -import static org.easymock.EasyMock.anyInt; +import static org.easymock.EasyMock.anyFloat; import static org.easymock.EasyMock.createMock; import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.expectLastCall; @@ -40,8 +40,7 @@ public class FetcherTest { private HttpResponse response = createMock(HttpResponse.class); @SuppressWarnings("unchecked") private Callback<Void> callback = createMock(Callback.class); - private ProgressListener progressListener - = createMock(ProgressListener.class); + private ProgressListener progressListener = createMock(ProgressListener.class); @Test public void testSuccessfulFetch() throws Exception { DummyInputStream in = new DummyInputStream(); @@ -56,7 +55,8 @@ public class FetcherTest { expect(entity.getContentLength()).andReturn(3L); expect(entity.getContent()).andReturn(in); expect(sinkFactory.newSink()).andReturn(sink); - progressListener.hearProgress(anyInt()); expectLastCall().atLeastOnce(); + progressListener.hearProgress(anyFloat()); + expectLastCall().atLeastOnce(); callback.call(null); replayAll();
test
train
"2012-10-17T08:07:13"
"2012-10-16T00:06:09"
JakeWharton
val
square/retrofit/105_106
square/retrofit
square/retrofit/105
square/retrofit/106
[ "timestamp(timedelta=83.0, similarity=0.8480295100306232)" ]
05db64dbebe4873cc36099e14a6eb7bd4858dace
3eac5515bfebfafa8a8af3742705e400f85bb248
[]
[]
"2012-11-28T05:57:22"
[]
Change Thread Names Based On Current Request
To make thread dump debugging a lot more clear.
[ "retrofit/src/main/java/retrofit/http/Platform.java", "retrofit/src/main/java/retrofit/http/RestAdapter.java" ]
[ "retrofit/src/main/java/retrofit/http/Platform.java", "retrofit/src/main/java/retrofit/http/RestAdapter.java" ]
[]
diff --git a/retrofit/src/main/java/retrofit/http/Platform.java b/retrofit/src/main/java/retrofit/http/Platform.java index 377cdcc596..fa72a470c4 100644 --- a/retrofit/src/main/java/retrofit/http/Platform.java +++ b/retrofit/src/main/java/retrofit/http/Platform.java @@ -14,6 +14,7 @@ import static android.os.Process.THREAD_PRIORITY_BACKGROUND; import static retrofit.http.RestAdapter.SynchronousExecutor; +import static retrofit.http.RestAdapter.THREAD_PREFIX; abstract class Platform { private static final Platform PLATFORM = findPlatform(); @@ -58,7 +59,7 @@ private static class Base extends Platform { Thread.currentThread().setPriority(THREAD_PRIORITY_BACKGROUND); r.run(); } - }, "Retrofit-" + threadCounter.getAndIncrement()); + }, THREAD_PREFIX + threadCounter.getAndIncrement()); } }); } @@ -89,7 +90,7 @@ private static class Android extends Platform { Process.setThreadPriority(THREAD_PRIORITY_BACKGROUND); r.run(); } - }, "Retrofit-" + threadCounter.getAndIncrement()); + }, THREAD_PREFIX + threadCounter.getAndIncrement()); } }); } diff --git a/retrofit/src/main/java/retrofit/http/RestAdapter.java b/retrofit/src/main/java/retrofit/http/RestAdapter.java index fd3fa2e5d8..8f605c273b 100644 --- a/retrofit/src/main/java/retrofit/http/RestAdapter.java +++ b/retrofit/src/main/java/retrofit/http/RestAdapter.java @@ -44,6 +44,7 @@ public class RestAdapter { private static final Logger LOGGER = Logger.getLogger(RestAdapter.class.getName()); private static final int LOG_CHUNK_SIZE = 4000; + static final String THREAD_PREFIX = "Retrofit-"; private final Server server; private final Provider<HttpClient> httpClientProvider; @@ -141,6 +142,11 @@ private Object invokeRequest(Method method, Object[] args, boolean isSynchronous .build(); url = request.getURI().toString(); + if (!isSynchronousInvocation) { + // If we are executing asynchronously then update the current thread with a useful name. + Thread.currentThread().setName(THREAD_PREFIX + url); + } + // Determine deserialization type by method return type or generic parameter to Callback argument. Type type = responseTypeCache.get(method); if (type == null) {
null
train
train
"2012-11-28T06:32:02"
"2012-11-28T01:04:31"
JakeWharton
val
square/retrofit/113_115
square/retrofit
square/retrofit/113
square/retrofit/115
[ "timestamp(timedelta=1170.0, similarity=0.850510378883364)" ]
bc304b3093193e79c9c2094b2caecde852888f1e
2adc5af775727d56e6bdbd8417ddad9f1ef7fd4f
[ "See #115 for pull request.\n" ]
[]
"2012-12-10T21:36:25"
[]
If no parameters are present after creating request, do not append ? to URI
I have noticed that the ? is always present at the end of URIs. This is completely valid, I suspect, but it was unexpected when I was making some Robolectric unit tests to check if the thing was sending the information to the correct URI. Perhaps, if the parameters are empty (as in there are no parameters to be appended) don't add the ? query parameters separator.
[ "retrofit/src/main/java/retrofit/http/HttpMethodType.java" ]
[ "retrofit/src/main/java/retrofit/http/HttpMethodType.java" ]
[ "retrofit/src/test/java/retrofit/http/RestAdapterTest.java" ]
diff --git a/retrofit/src/main/java/retrofit/http/HttpMethodType.java b/retrofit/src/main/java/retrofit/http/HttpMethodType.java index d1a58e973a..fc981b49b8 100644 --- a/retrofit/src/main/java/retrofit/http/HttpMethodType.java +++ b/retrofit/src/main/java/retrofit/http/HttpMethodType.java @@ -84,6 +84,9 @@ private static URI getUri(HttpRequestBuilder builder) throws URISyntaxException private static URI getParameterizedUri(HttpRequestBuilder builder) throws URISyntaxException { List<NameValuePair> queryParams = builder.getParamList(false); String queryString = URLEncodedUtils.format(queryParams, HTTP.UTF_8); + if (queryString != null && queryString.length() == 0) { + queryString = null; + } return URIUtils.createURI(builder.getScheme(), builder.getHost(), -1, builder.getRelativePath(), queryString, null); }
diff --git a/retrofit/src/test/java/retrofit/http/RestAdapterTest.java b/retrofit/src/test/java/retrofit/http/RestAdapterTest.java index 87552a85ac..d7ead7d0ad 100644 --- a/retrofit/src/test/java/retrofit/http/RestAdapterTest.java +++ b/retrofit/src/test/java/retrofit/http/RestAdapterTest.java @@ -49,7 +49,8 @@ public class RestAdapterTest { private static final String ENTITY_PATH_PARAM = "entity/{id}"; private static final String BASE_URL = "http://host/api/entity"; private static final String PATH_URL_PREFIX = BASE_URL + "/"; - private static final String GET_DELETE_SIMPLE_URL = BASE_URL + "?"; + private static final String GET_DELETE_SIMPLE_URL = BASE_URL; + private static final String GET_DELETE_SIMPLE_URL_WITH_PARAMS = GET_DELETE_SIMPLE_URL + "?"; private static final Gson GSON = new Gson(); private static final Response RESPONSE = new Response("some text"); private static final ServerError SERVER_ERROR = new ServerError("danger, danger!"); @@ -99,7 +100,7 @@ public class RestAdapterTest { } @Test public void testServiceDeleteParamAsync() throws IOException { - expectAsyncLifecycle(HttpDelete.class, GET_DELETE_SIMPLE_URL + "id=" + ID); + expectAsyncLifecycle(HttpDelete.class, GET_DELETE_SIMPLE_URL_WITH_PARAMS + "id=" + ID); replayAll(); DeleteService service = restAdapter.create(DeleteService.class); @@ -108,7 +109,7 @@ public class RestAdapterTest { } @Test public void testServiceDeleteParamSync() throws IOException { - expectSyncLifecycle(HttpDelete.class, GET_DELETE_SIMPLE_URL + "id=" + ID); + expectSyncLifecycle(HttpDelete.class, GET_DELETE_SIMPLE_URL_WITH_PARAMS + "id=" + ID); replayAll(); DeleteService service = restAdapter.create(DeleteService.class); @@ -118,7 +119,7 @@ public class RestAdapterTest { } @Test public void testServiceDeleteWithFixedParamAsync() throws IOException { - expectAsyncLifecycle(HttpDelete.class, GET_DELETE_SIMPLE_URL + "filter=merchant&id=" + ID); + expectAsyncLifecycle(HttpDelete.class, GET_DELETE_SIMPLE_URL_WITH_PARAMS + "filter=merchant&id=" + ID); replayAll(); DeleteService service = restAdapter.create(DeleteService.class); @@ -127,7 +128,7 @@ public class RestAdapterTest { } @Test public void testServiceDeleteWithFixedParamSync() throws IOException { - expectSyncLifecycle(HttpDelete.class, GET_DELETE_SIMPLE_URL + "filter=merchant&id=" + ID); + expectSyncLifecycle(HttpDelete.class, GET_DELETE_SIMPLE_URL_WITH_PARAMS + "filter=merchant&id=" + ID); replayAll(); DeleteService service = restAdapter.create(DeleteService.class); @@ -137,7 +138,7 @@ public class RestAdapterTest { } @Test public void testServiceDeleteWithMultipleFixedParamAsync() throws IOException { - expectAsyncLifecycle(HttpDelete.class, GET_DELETE_SIMPLE_URL + "filter=merchant&name2=value2&" + "id=" + ID); + expectAsyncLifecycle(HttpDelete.class, GET_DELETE_SIMPLE_URL_WITH_PARAMS + "filter=merchant&name2=value2&" + "id=" + ID); replayAll(); DeleteService service = restAdapter.create(DeleteService.class); @@ -146,7 +147,7 @@ public class RestAdapterTest { } @Test public void testServiceDeleteWithMultipleFixedParamSync() throws IOException { - expectSyncLifecycle(HttpDelete.class, GET_DELETE_SIMPLE_URL + "filter=merchant&name2=value2&" + "id=" + ID); + expectSyncLifecycle(HttpDelete.class, GET_DELETE_SIMPLE_URL_WITH_PARAMS + "filter=merchant&name2=value2&" + "id=" + ID); replayAll(); DeleteService service = restAdapter.create(DeleteService.class); @@ -156,7 +157,7 @@ public class RestAdapterTest { } @Test public void testServiceDeletePathParamAsync() throws IOException { - expectAsyncLifecycle(HttpDelete.class, PATH_URL_PREFIX + ID + "?"); + expectAsyncLifecycle(HttpDelete.class, PATH_URL_PREFIX + ID); replayAll(); DeleteService service = restAdapter.create(DeleteService.class); @@ -165,7 +166,7 @@ public class RestAdapterTest { } @Test public void testServiceDeletePathParamSync() throws IOException { - expectSyncLifecycle(HttpDelete.class, PATH_URL_PREFIX + ID + "?"); + expectSyncLifecycle(HttpDelete.class, PATH_URL_PREFIX + ID); replayAll(); DeleteService service = restAdapter.create(DeleteService.class); @@ -194,7 +195,7 @@ public class RestAdapterTest { } @Test public void testServiceGetParamAsync() throws IOException { - expectAsyncLifecycle(HttpGet.class, GET_DELETE_SIMPLE_URL + "id=" + ID); + expectAsyncLifecycle(HttpGet.class, GET_DELETE_SIMPLE_URL_WITH_PARAMS + "id=" + ID); replayAll(); GetService service = restAdapter.create(GetService.class); @@ -203,7 +204,7 @@ public class RestAdapterTest { } @Test public void testServiceGetParamSync() throws IOException { - expectSyncLifecycle(HttpGet.class, GET_DELETE_SIMPLE_URL + "id=" + ID); + expectSyncLifecycle(HttpGet.class, GET_DELETE_SIMPLE_URL_WITH_PARAMS + "id=" + ID); replayAll(); GetService service = restAdapter.create(GetService.class); @@ -213,7 +214,7 @@ public class RestAdapterTest { } @Test public void testServiceGetWithFixedParamAsync() throws IOException { - expectAsyncLifecycle(HttpGet.class, GET_DELETE_SIMPLE_URL + "filter=merchant&id=" + ID); + expectAsyncLifecycle(HttpGet.class, GET_DELETE_SIMPLE_URL_WITH_PARAMS + "filter=merchant&id=" + ID); replayAll(); GetService service = restAdapter.create(GetService.class); @@ -222,7 +223,7 @@ public class RestAdapterTest { } @Test public void testServiceGetWithFixedParamSync() throws IOException { - expectSyncLifecycle(HttpGet.class, GET_DELETE_SIMPLE_URL + "filter=merchant&id=" + ID); + expectSyncLifecycle(HttpGet.class, GET_DELETE_SIMPLE_URL_WITH_PARAMS + "filter=merchant&id=" + ID); replayAll(); GetService service = restAdapter.create(GetService.class); @@ -232,7 +233,7 @@ public class RestAdapterTest { } @Test public void testServiceGetWithMultipleFixedParamsAsync() throws IOException { - expectAsyncLifecycle(HttpGet.class, GET_DELETE_SIMPLE_URL + "filter=merchant&name2=value2&id=" + ID); + expectAsyncLifecycle(HttpGet.class, GET_DELETE_SIMPLE_URL_WITH_PARAMS + "filter=merchant&name2=value2&id=" + ID); replayAll(); GetService service = restAdapter.create(GetService.class); @@ -241,7 +242,7 @@ public class RestAdapterTest { } @Test public void testServiceGetWithMultipleFixedParamsSync() throws IOException { - expectSyncLifecycle(HttpGet.class, GET_DELETE_SIMPLE_URL + "filter=merchant&name2=value2&id=" + ID); + expectSyncLifecycle(HttpGet.class, GET_DELETE_SIMPLE_URL_WITH_PARAMS + "filter=merchant&name2=value2&id=" + ID); replayAll(); GetService service = restAdapter.create(GetService.class); @@ -251,7 +252,7 @@ public class RestAdapterTest { } @Test public void testServiceGetPathParamAsync() throws IOException { - expectAsyncLifecycle(HttpGet.class, PATH_URL_PREFIX + ID + "?"); + expectAsyncLifecycle(HttpGet.class, PATH_URL_PREFIX + ID); replayAll(); GetService service = restAdapter.create(GetService.class); @@ -260,7 +261,7 @@ public class RestAdapterTest { } @Test public void testServiceGetPathParamSync() throws IOException { - expectSyncLifecycle(HttpGet.class, PATH_URL_PREFIX + ID + "?"); + expectSyncLifecycle(HttpGet.class, PATH_URL_PREFIX + ID); replayAll(); GetService service = restAdapter.create(GetService.class);
val
train
"2012-12-06T05:18:41"
"2012-12-06T23:30:52"
thorinside
val
square/retrofit/112_127
square/retrofit
square/retrofit/112
square/retrofit/127
[ "timestamp(timedelta=62234.0, similarity=0.9450963938144088)" ]
6800bb199a4f23b76c43c543e5bfe83383e8c8e0
dc4fd8cda39016cf9f38441416a4000d50753d72
[ "#127 \n" ]
[ "Rather than doing a loop with two splits, you might be better off with a single regex. Perhaps a case-insensitive pattern like `(?i)\\Wcharset=([^\\s]+)`\n\n(From Guava's tests, content types look like this: `application/atom+xml; a=1; a=2; b=3`)\n", "Guava's tests suggest that charset can be in upper case.\n", "Should pull in tests. I'm slacking.\n", "oooh, and the RFCs:\nhttp://www.ietf.org/rfc/rfc2045.txt\nhttp://www.ietf.org/rfc/rfc2046\n", "Eep, Guava also handles this nastiness:\n text/plain; charset=\"utf-8\"\n text/plain; charset=\"\\u\\tf-\\8\"\n", "IOException ?\n", "nit: something like \\W at the beginning as to not match say `text/plain; notthecharset=ascii`.\n", "dig\n", "test that you can have another parameter after the charset?\n" ]
"2012-12-19T04:09:14"
[]
Force UTF8 everywhere. Blow-up otherwise.
It will please @swankjesse.
[ "retrofit/src/main/java/retrofit/http/GsonConverter.java", "retrofit/src/main/java/retrofit/http/HttpMethodType.java", "retrofit/src/main/java/retrofit/http/RestAdapter.java", "retrofit/src/main/java/retrofit/http/Types.java" ]
[ "retrofit/src/main/java/retrofit/http/GsonConverter.java", "retrofit/src/main/java/retrofit/http/HttpMethodType.java", "retrofit/src/main/java/retrofit/http/RestAdapter.java", "retrofit/src/main/java/retrofit/http/Utils.java" ]
[ "retrofit/src/test/java/retrofit/http/UtilsTest.java" ]
diff --git a/retrofit/src/main/java/retrofit/http/GsonConverter.java b/retrofit/src/main/java/retrofit/http/GsonConverter.java index 01213902b6..6dbb992be9 100644 --- a/retrofit/src/main/java/retrofit/http/GsonConverter.java +++ b/retrofit/src/main/java/retrofit/http/GsonConverter.java @@ -12,13 +12,14 @@ import retrofit.io.MimeType; import retrofit.io.TypedBytes; +import static retrofit.http.RestAdapter.UTF_8; + /** * A {@link Converter} which uses GSON for serialization and deserialization of entities. * * @author Jake Wharton (jw@squareup.com) */ public class GsonConverter implements Converter { - private static final String ENCODING = "UTF-8"; // TODO use actual encoding private static final MimeType JSON = new MimeType("application/json", "json"); private final Gson gson; @@ -29,7 +30,7 @@ public GsonConverter(Gson gson) { @Override public Object to(byte[] body, Type type) throws ConversionException { try { - InputStreamReader isr = new InputStreamReader(new ByteArrayInputStream(body), ENCODING); + InputStreamReader isr = new InputStreamReader(new ByteArrayInputStream(body), UTF_8); return gson.fromJson(isr, type); } catch (IOException e) { throw new ConversionException(e); @@ -47,9 +48,9 @@ private static class JsonTypedBytes implements TypedBytes { JsonTypedBytes(Gson gson, Object object) { try { - jsonBytes = gson.toJson(object).getBytes(ENCODING); + jsonBytes = gson.toJson(object).getBytes(UTF_8); } catch (UnsupportedEncodingException e) { - throw new IllegalArgumentException(ENCODING + " doesn't exist!?"); + throw new IllegalStateException(UTF_8 + " encoding does not exist."); } } diff --git a/retrofit/src/main/java/retrofit/http/HttpMethodType.java b/retrofit/src/main/java/retrofit/http/HttpMethodType.java index 91be554021..79e755c98e 100644 --- a/retrofit/src/main/java/retrofit/http/HttpMethodType.java +++ b/retrofit/src/main/java/retrofit/http/HttpMethodType.java @@ -144,7 +144,6 @@ private static void addParams(HttpEntityEnclosingRequestBase request, request.setEntity(entity); } else { List<NameValuePair> paramList = builder.getParamList(true); - // TODO: Use specified encoding. (See CallbackResponseHandler et al) request.setEntity(new UrlEncodedFormEntity(paramList, HTTP.UTF_8)); } } catch (UnsupportedEncodingException e) { diff --git a/retrofit/src/main/java/retrofit/http/RestAdapter.java b/retrofit/src/main/java/retrofit/http/RestAdapter.java index ba81a910b6..d82e3663c3 100644 --- a/retrofit/src/main/java/retrofit/http/RestAdapter.java +++ b/retrofit/src/main/java/retrofit/http/RestAdapter.java @@ -22,6 +22,7 @@ import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpEntityEnclosingRequestBase; import org.apache.http.client.methods.HttpUriRequest; +import org.apache.http.protocol.HTTP; import org.apache.http.util.EntityUtils; import retrofit.http.HttpProfiler.RequestInformation; @@ -35,6 +36,7 @@ public class RestAdapter { private static final Logger LOGGER = Logger.getLogger(RestAdapter.class.getName()); private static final int LOG_CHUNK_SIZE = 4000; static final String THREAD_PREFIX = "Retrofit-"; + static final String UTF_8 = "UTF-8"; private final Server server; private final Provider<HttpClient> httpClientProvider; @@ -175,7 +177,15 @@ private Object invokeRequest(Method method, Object[] args, boolean isSynchronous headers = new Header[realHeaders.length]; for (int i = 0; i < realHeaders.length; i++) { org.apache.http.Header realHeader = realHeaders[i]; - headers[i] = new Header(realHeader.getName(), realHeader.getValue()); + String headerName = realHeader.getName(); + String headerValue = realHeader.getValue(); + + if (HTTP.CONTENT_TYPE.equalsIgnoreCase(headerName) // + && !UTF_8.equalsIgnoreCase(Utils.parseCharset(headerValue))) { + throw new IOException("Only UTF-8 charset supported."); + } + + headers[i] = new Header(headerName, headerValue); } } @@ -200,7 +210,7 @@ private Object invokeRequest(Method method, Object[] args, boolean isSynchronous private static void logResponseBody(String url, byte[] body, int statusCode, long elapsedTime) throws UnsupportedEncodingException { LOGGER.fine("---- HTTP " + statusCode + " from " + url + " (" + elapsedTime + "ms)"); - String bodyString = new String(body, "UTF-8"); + String bodyString = new String(body, UTF_8); for (int i = 0; i < body.length; i += LOG_CHUNK_SIZE) { int end = Math.min(bodyString.length(), i + LOG_CHUNK_SIZE); LOGGER.fine(bodyString.substring(i, end)); @@ -271,7 +281,7 @@ static Type getResponseObjectType(Method method, boolean isSynchronousInvocation String.format("Last parameter of %s must be a Class or ParameterizedType", method)); } if (Callback.class.isAssignableFrom(callbackClass)) { - callbackType = Types.getGenericSupertype(callbackType, callbackClass, Callback.class); + callbackType = Utils.getGenericSupertype(callbackType, callbackClass, Callback.class); if (callbackType instanceof ParameterizedType) { Type[] types = ((ParameterizedType) callbackType).getActualTypeArguments(); for (int i = 0; i < types.length; i++) { diff --git a/retrofit/src/main/java/retrofit/http/Types.java b/retrofit/src/main/java/retrofit/http/Utils.java similarity index 71% rename from retrofit/src/main/java/retrofit/http/Types.java rename to retrofit/src/main/java/retrofit/http/Utils.java index 548d630153..60cc067931 100644 --- a/retrofit/src/main/java/retrofit/http/Types.java +++ b/retrofit/src/main/java/retrofit/http/Utils.java @@ -1,18 +1,22 @@ -// Copyright 2008 Google, Inc. +// Copyright 2012 Square, Inc. package retrofit.http; import java.lang.reflect.Type; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import static java.util.regex.Pattern.CASE_INSENSITIVE; +import static retrofit.http.RestAdapter.UTF_8; + +final class Utils { + private static final Pattern CHARSET = Pattern.compile("\\Wcharset=([^\\s;]+)", CASE_INSENSITIVE); -/** - * Helper methods for dealing with generic types via reflection copied from Guice's {@code - * MoreTypes} class. - */ -class Types { /** * Returns the generic supertype for {@code supertype}. For example, given a class * {@code IntegerSet}, the result for when supertype is {@code Set.class} is {@code Set<Integer>} * and the result when the supertype is {@code Collection.class} is {@code Collection<Integer>}. */ + // Copied from Guice's {@code MoreTypes} class. Copyright 2006 Google, Inc. static Type getGenericSupertype(Type context, Class<?> rawType, Class<?> toResolve) { if (toResolve == rawType) { return context; @@ -46,4 +50,12 @@ static Type getGenericSupertype(Type context, Class<?> rawType, Class<?> toResol // we can't resolve this further return toResolve; } + + static String parseCharset(String headerValue) { + Matcher match = CHARSET.matcher(headerValue); + if (match.find()) { + return match.group(1).replaceAll("[\"\\\\]", ""); + } + return UTF_8; + } } \ No newline at end of file
diff --git a/retrofit/src/test/java/retrofit/http/UtilsTest.java b/retrofit/src/test/java/retrofit/http/UtilsTest.java new file mode 100644 index 0000000000..e529f7f033 --- /dev/null +++ b/retrofit/src/test/java/retrofit/http/UtilsTest.java @@ -0,0 +1,24 @@ +// Copyright 2012 Square, Inc. +package retrofit.http; + +import org.junit.Test; + +import static org.fest.assertions.api.Assertions.assertThat; +import static retrofit.http.RestAdapter.UTF_8; +import static retrofit.http.Utils.parseCharset; + +public class UtilsTest { + @Test public void testCharsetParsing() { + assertThat(parseCharset("text/plain;charset=utf-8")).isEqualToIgnoringCase(UTF_8); + assertThat(parseCharset("text/plain; charset=utf-8")).isEqualToIgnoringCase(UTF_8); + assertThat(parseCharset("text/plain; charset=utf-8")).isEqualToIgnoringCase(UTF_8); + assertThat(parseCharset("text/plain; \tcharset=utf-8")).isEqualToIgnoringCase(UTF_8); + assertThat(parseCharset("text/plain; \r\n\tcharset=utf-8")).isEqualToIgnoringCase(UTF_8); + assertThat(parseCharset("text/plain; CHARSET=utf-8")).isEqualToIgnoringCase(UTF_8); + assertThat(parseCharset("text/plain; charset=UTF-8")).isEqualToIgnoringCase(UTF_8); + assertThat(parseCharset("text/plain; charset=\"\\u\\tf-\\8\"")).isEqualToIgnoringCase(UTF_8); + assertThat(parseCharset("text/plain; charset=\"utf-8\"")).isEqualToIgnoringCase(UTF_8); + assertThat(parseCharset("text/plain; charset=utf-8; other=thing")).isEqualToIgnoringCase(UTF_8); + assertThat(parseCharset("text/plain; notthecharset=utf-16;")).isEqualToIgnoringCase(UTF_8); + } +}
val
train
"2012-12-19T05:21:53"
"2012-12-06T05:59:59"
JakeWharton
val
square/retrofit/122_129
square/retrofit
square/retrofit/122
square/retrofit/129
[ "keyword_pr_to_issue" ]
5fecbc6381f538658a63e9675449467f27170ea2
9942d8e08ec1c5346863207e77d8885416edca8b
[ "Fixed by #129.\n" ]
[ "not doing this per-request is very good\n", "HashSet --> LinkedHashSet\n", "HashMap --> LinkedHashMap\n", "Would it be better to create all the methods eagerly? I could go either way myself.\n\nNot that I offer any alternatives, but Method.equals() is a painfully slow method. It uses toString(). Sigh.\n", "sucks that these aren't all final. It would probably make it worse, but you could change the code to have a static factory method that does all the parsing and then calls the constructor with all of the ready-to-go values.\n", "nice defensive coding\n", "Does this trigger if I call equals() on a service interface?\n", "Did you rename Types to Utils?\n", "you're calling method.getGenericParameterTypes() here and method.getParameterTypes() below. If you wanna make a small optimization, call only one of these and store the result?\n", "nit: calling `toString()` is a waste of code\n", "Seems like this method duplicates the work in parseResponseType.\n", "LinkedHashSet\n", "make this a static constant? I recall Patterns being expensive to compile\n", "In the other pull request I did.\n", "Yeah they're non-final so that we can load them in the background thread if you're executing things asynchronously. We need to know whether or not the method is a synchronous one or not regardless. Perhaps we just check the synchronous boolean like before and then pass it down so all these values can be computed in the constructor. Will think on it a bit.\n", "`SparseArray` + `hashCode()`?\n", "Ah, nevermind. That's Android-specific. Could pull its sources in. Or just allow boxing and use `Integer` in the map.\n", "What you have here is good for now. If you want, we can profile this later and see if that is indeed a hot spot.\n", "Yep. Filed @ #130\n", "Rather than `Returns whether` say `Returns true if the method is synchronous`. Way less ambiguous.\n", "Perfect\n", "... though the cast could throw a ClassCastException if for whatever reason your last parameter isn't a Class<?>. For example, it'll probably crash if the last parameter is a GenericArrayType like `List<String>[]`. Defend against that by doing\n\n```\n hasCallback = typeToCheck instanceof Class && Callback.class.isAssignableFrom(...);\n```\n", "you're duplicating this work. . . lines 330--339 are very similar to 312-317. Extract a method that returns the callbackType or null?\n", "should this do something cleverer with exceptions? Usually when I call Executor.execute() I don't expect a RuntimeException to bubble up\n", "mmmmm I love mexican food-themed test cases\n", "nice\n", "The only usage of this class is when you want asynchronous HTTP requests with callbacks happening on the background thread rather than some main thread. I'm not even sure if there's a use-case for it, really. Perhaps we should just simplify and remove it.\n", "Ah, if you're on the JVM and don't specify your own executors this is the default asynchronous behavior as well.\n" ]
"2012-12-19T10:04:07"
[]
Lazily Cache Endpoint Metadata
We calculate a lot of metadata on endpoint definitions with every invocation. The heavy hitters should be cached in the anonymous proxy class generated by `RestAdapter` to avoid doing reflection on every API call. Might be useful to abstract everything into a POJO and use a `Map<Method, MethodMetadata>` or something.
[ "retrofit/src/main/java/retrofit/http/HttpRequestBuilder.java", "retrofit/src/main/java/retrofit/http/Platform.java", "retrofit/src/main/java/retrofit/http/RequestLine.java", "retrofit/src/main/java/retrofit/http/RestAdapter.java", "retrofit/src/main/java/retrofit/http/Utils.java" ]
[ "retrofit/src/main/java/retrofit/http/HttpRequestBuilder.java", "retrofit/src/main/java/retrofit/http/Platform.java", "retrofit/src/main/java/retrofit/http/RestAdapter.java", "retrofit/src/main/java/retrofit/http/Utils.java" ]
[ "retrofit/src/test/java/retrofit/http/HttpRequestBuilderTest.java", "retrofit/src/test/java/retrofit/http/RestAdapterTest.java" ]
diff --git a/retrofit/src/main/java/retrofit/http/HttpRequestBuilder.java b/retrofit/src/main/java/retrofit/http/HttpRequestBuilder.java index 37a283e851..4c919f896e 100644 --- a/retrofit/src/main/java/retrofit/http/HttpRequestBuilder.java +++ b/retrofit/src/main/java/retrofit/http/HttpRequestBuilder.java @@ -1,22 +1,21 @@ package retrofit.http; -import org.apache.http.NameValuePair; -import org.apache.http.client.methods.HttpUriRequest; -import org.apache.http.message.BasicNameValuePair; -import retrofit.io.TypedBytes; - -import javax.inject.Named; import java.io.UnsupportedEncodingException; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.net.URISyntaxException; import java.net.URLEncoder; import java.util.ArrayList; -import java.util.HashSet; +import java.util.LinkedHashSet; import java.util.List; import java.util.Set; -import java.util.regex.Matcher; -import java.util.regex.Pattern; +import javax.inject.Named; +import org.apache.http.NameValuePair; +import org.apache.http.client.methods.HttpUriRequest; +import org.apache.http.message.BasicNameValuePair; +import retrofit.io.TypedBytes; + +import static retrofit.http.RestAdapter.MethodDetails; /** * Builds HTTP requests from Java method invocations. Handles "path parameters" in the @@ -31,37 +30,33 @@ final class HttpRequestBuilder { private final Converter converter; - private Method javaMethod; - private boolean isSynchronous; + private MethodDetails methodDetails; private Object[] args; private String apiUrl; private String replacedRelativePath; private Headers headers; private List<NameValuePair> nonPathParams; - private RequestLine requestLine; private TypedBytes singleEntity; HttpRequestBuilder(Converter converter) { this.converter = converter; } - HttpRequestBuilder setMethod(Method method, boolean isSynchronous) { - this.javaMethod = method; - this.isSynchronous = isSynchronous; - requestLine = RequestLine.fromMethod(method); + HttpRequestBuilder setMethod(MethodDetails methodDetails) { + this.methodDetails = methodDetails; return this; } Method getMethod() { - return javaMethod; + return methodDetails.method; } boolean isSynchronous() { - return isSynchronous; + return methodDetails.isSynchronous; } String getRelativePath() { - return replacedRelativePath != null ? replacedRelativePath : requestLine.getRelativePath(); + return replacedRelativePath != null ? replacedRelativePath : methodDetails.path; } HttpRequestBuilder setApiUrl(String apiUrl) { @@ -69,7 +64,6 @@ HttpRequestBuilder setApiUrl(String apiUrl) { return this; } - /** The last argument is assumed to be the Callback and is ignored. */ HttpRequestBuilder setArgs(Object[] args) { this.args = args; return this; @@ -110,46 +104,28 @@ List<NameValuePair> getParamList(boolean includePathParams) { /** Converts all but the last method argument to a list of HTTP request parameters. */ private List<NameValuePair> createParamList() { - Annotation[][] parameterAnnotations = javaMethod.getParameterAnnotations(); - int count = parameterAnnotations.length; - if (!isSynchronous) { - count -= 1; - } - - List<NameValuePair> params = new ArrayList<NameValuePair>(count); + List<NameValuePair> params = new ArrayList<NameValuePair>(); // Add query parameter(s), if specified. - QueryParams queryParams = javaMethod.getAnnotation(QueryParams.class); - if (queryParams != null) { - QueryParam[] annotations = queryParams.value(); - for (QueryParam annotation : annotations) { - params.add(addPair(annotation)); - } - } - - // Also check for a single specified query parameter. - QueryParam queryParam = javaMethod.getAnnotation(QueryParam.class); - if (queryParam != null) { - params.add(addPair(queryParam)); + for (QueryParam annotation : methodDetails.pathQueryParams) { + params.add(new BasicNameValuePair(annotation.name(), annotation.value())); } // Add arguments as parameters. - for (int i = 0; i < count; i++) { + String[] pathNamedParams = methodDetails.pathNamedParams; + int singleEntityArgumentIndex = methodDetails.singleEntityArgumentIndex; + for (int i = 0; i < pathNamedParams.length; i++) { Object arg = args[i]; if (arg == null) continue; - for (Annotation annotation : parameterAnnotations[i]) { - final Class<? extends Annotation> type = annotation.annotationType(); - if (type == Named.class) { - String name = getName(parameterAnnotations[i], javaMethod, i); - params.add(new BasicNameValuePair(name, String.valueOf(arg))); - } else if (type == SingleEntity.class) { - if (arg instanceof TypedBytes) { - // Let the object specify its own entity representation. - singleEntity = (TypedBytes) arg; - } else { - // Just an object: serialize it with supplied converter - singleEntity = converter.from(arg); - } + if (i != singleEntityArgumentIndex) { + params.add(new BasicNameValuePair(pathNamedParams[i], String.valueOf(arg))); + } else { + if (arg instanceof TypedBytes) { + // Let the object specify its own entity representation. + singleEntity = (TypedBytes) arg; + } else { + // Just an object: serialize it with supplied converter. + singleEntity = converter.from(arg); } } } @@ -170,16 +146,12 @@ public String getMimeType() { return singleEntity == null ? null : singleEntity.mimeType().mimeName(); } - private BasicNameValuePair addPair(QueryParam queryParam) { - return new BasicNameValuePair(queryParam.name(), queryParam.value()); - } - HttpUriRequest build() throws URISyntaxException { // Alter parameter list if path parameters are present. - Set<String> pathParams = getPathParameters(requestLine.getRelativePath()); + Set<String> pathParams = new LinkedHashSet<String>(methodDetails.pathParams); List<NameValuePair> paramList = createParamList(); if (!pathParams.isEmpty()) { - String replacedPath = requestLine.getRelativePath(); + String replacedPath = methodDetails.path; for (String pathParam : pathParams) { NameValuePair found = null; @@ -216,7 +188,7 @@ HttpUriRequest build() throws URISyntaxException { } } - return requestLine.getHttpMethod().createFrom(this); + return methodDetails.httpMethod.createFrom(this); } private String doReplace(String replacedPath, String paramName, String newVal) { @@ -224,23 +196,6 @@ private String doReplace(String replacedPath, String paramName, String newVal) { return replacedPath; } - /** - * Gets the set of unique path params used in the given uri. If a param is used twice in the - * uri, it will only show up once in the set. - * - * @param path the path to search through. - * @return set of path params. - */ - static Set<String> getPathParameters(String path) { - Pattern p = Pattern.compile("\\{([a-z_-]*)\\}"); - Matcher m = p.matcher(path); - Set<String> patterns = new HashSet<String>(); - while (m.find()) { - patterns.add(m.group(1)); - } - return patterns; - } - /** Gets the parameter name from the {@link Named} annotation. */ static String getName(Annotation[] annotations, Method method, int parameterIndex) { return findAnnotation(annotations, Named.class, method, parameterIndex).value(); diff --git a/retrofit/src/main/java/retrofit/http/Platform.java b/retrofit/src/main/java/retrofit/http/Platform.java index f8dfd7b03e..0e4ddda90f 100644 --- a/retrofit/src/main/java/retrofit/http/Platform.java +++ b/retrofit/src/main/java/retrofit/http/Platform.java @@ -13,7 +13,7 @@ import retrofit.android.MainThreadExecutor; import static android.os.Process.THREAD_PRIORITY_BACKGROUND; -import static retrofit.http.RestAdapter.SynchronousExecutor; +import static retrofit.http.Utils.SynchronousExecutor; import static retrofit.http.RestAdapter.THREAD_PREFIX; abstract class Platform { diff --git a/retrofit/src/main/java/retrofit/http/RequestLine.java b/retrofit/src/main/java/retrofit/http/RequestLine.java deleted file mode 100644 index 82a9ce2c71..0000000000 --- a/retrofit/src/main/java/retrofit/http/RequestLine.java +++ /dev/null @@ -1,66 +0,0 @@ -package retrofit.http; - -import java.lang.annotation.Annotation; -import java.lang.reflect.Method; - -/** - * Contains the desired {@link HttpMethodType} and relative path specified by a service method. See - * also the factory method {@link #fromMethod(Method)}. - * - * @author Patrick Forhan (patrick@squareup.com) - */ -final class RequestLine { - private final String relativePath; - private final HttpMethodType httpMethod; - - private RequestLine(HttpMethodType methodType, Annotation methodAnnotation) { - relativePath = getValue(methodAnnotation); - httpMethod = methodType; - } - - String getRelativePath() { - return relativePath; - } - - HttpMethodType getHttpMethod() { - return httpMethod; - } - - /** Using reflection, get the value field of the specified annotation. */ - private static String getValue(Annotation annotation) { - try { - final Method valueMethod = annotation.annotationType().getMethod("value"); - return (String) valueMethod.invoke(annotation); - } catch (Exception ex) { - throw new IllegalStateException("Failed to extract URI path", ex); - } - } - - /** - * Looks for exactly one annotation of type {@link DELETE}, {@link GET}, {@link POST}, or - * {@link PUT} and extracts its path data. Throws an {@link IllegalStateException} if none or - * multiple are found. - */ - static RequestLine fromMethod(Method method) { - Annotation[] annotations = method.getAnnotations(); - RequestLine found = null; - for (Annotation annotation : annotations) { - // look for an HttpMethod annotation describing the type: - final retrofit.http.HttpMethod typeAnnotation = - annotation.annotationType().getAnnotation(retrofit.http.HttpMethod.class); - if (typeAnnotation != null) { - if (found != null) { - throw new IllegalStateException( - "Method annotated with multiple HTTP method annotations: " + method.toString()); - } - found = new RequestLine(typeAnnotation.value(), annotation); - } - } - - if (found == null) { - throw new IllegalStateException( - "Method not annotated with GET, POST, PUT, or DELETE: " + method.toString()); - } - return found; - } -} \ No newline at end of file diff --git a/retrofit/src/main/java/retrofit/http/RestAdapter.java b/retrofit/src/main/java/retrofit/http/RestAdapter.java index d82e3663c3..0721eff342 100644 --- a/retrofit/src/main/java/retrofit/http/RestAdapter.java +++ b/retrofit/src/main/java/retrofit/http/RestAdapter.java @@ -3,18 +3,24 @@ import java.io.IOException; import java.io.UnsupportedEncodingException; +import java.lang.annotation.Annotation; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Proxy; import java.lang.reflect.Type; import java.lang.reflect.WildcardType; -import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; import java.util.Map; +import java.util.Set; import java.util.concurrent.Executor; import java.util.concurrent.TimeUnit; import java.util.logging.Level; import java.util.logging.Logger; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import javax.inject.Named; import javax.inject.Provider; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; @@ -26,6 +32,8 @@ import org.apache.http.util.EntityUtils; import retrofit.http.HttpProfiler.RequestInformation; +import static retrofit.http.Utils.SynchronousExecutor; + /** * Converts Java method calls to Rest calls. * @@ -96,23 +104,36 @@ public <T> T create(Class<T> type) { } private class RestHandler implements InvocationHandler { - private final Map<Method, Type> responseTypeCache = new HashMap<Method, Type>(); - - @SuppressWarnings("unchecked") @Override - public Object invoke(Object proxy, final Method method, final Object[] args) { - if (methodWantsSynchronousInvocation(method)) { - return invokeRequest(method, args, true); - } else { - if (httpExecutor == null || callbackExecutor == null) { - throw new IllegalStateException("Asynchronous invocation requires calling setExecutors."); + final Map<Method, MethodDetails> methodDetailsCache = + new LinkedHashMap<Method, MethodDetails>(); + + @SuppressWarnings("unchecked") + @Override public Object invoke(Object proxy, Method method, final Object[] args) { + // Load or create the details cache for the current method. + final MethodDetails methodDetails; + synchronized (methodDetailsCache) { + MethodDetails tempMethodDetails = methodDetailsCache.get(method); + if (tempMethodDetails == null) { + tempMethodDetails = new MethodDetails(method); + methodDetailsCache.put(method, tempMethodDetails); } - httpExecutor.execute(new CallbackRunnable(obtainCallback(args), callbackExecutor) { - @Override public Object obtainResponse() { - return invokeRequest(method, args, false); - } - }); - return null; // Asynchronous methods should have return type of void. + methodDetails = tempMethodDetails; + } + + if (methodDetails.isSynchronous) { + return invokeRequest(methodDetails, args); + } + + if (httpExecutor == null || callbackExecutor == null) { + throw new IllegalStateException("Asynchronous invocation requires calling setExecutors."); } + Callback<?> callback = (Callback<?>) args[args.length - 1]; + httpExecutor.execute(new CallbackRunnable(callback, callbackExecutor) { + @Override public Object obtainResponse() { + return invokeRequest(methodDetails, args); + } + }); + return null; // Asynchronous methods should have return type of void. } /** @@ -121,31 +142,27 @@ public Object invoke(Object proxy, final Method method, final Object[] args) { * @return HTTP response object of specified {@code type}. * @throws RetrofitError Thrown if any error occurs during the HTTP request. */ - private Object invokeRequest(Method method, Object[] args, boolean isSynchronousInvocation) { + private Object invokeRequest(MethodDetails methodDetails, Object[] args) { long start = System.nanoTime(); + + methodDetails.init(); // Ensure all relevant method information has been loaded. + String url = server.apiUrl(); try { // Build the request and headers. final HttpUriRequest request = new HttpRequestBuilder(converter) // - .setMethod(method, isSynchronousInvocation) + .setMethod(methodDetails) .setArgs(args) .setApiUrl(url) .setHeaders(requestHeaders) .build(); url = request.getURI().toString(); - if (!isSynchronousInvocation) { + if (!methodDetails.isSynchronous) { // If we are executing asynchronously then update the current thread with a useful name. Thread.currentThread().setName(THREAD_PREFIX + url); } - // Determine deserialization type by return type or generic parameter to Callback argument. - Type type = responseTypeCache.get(method); - if (type == null) { - type = getResponseObjectType(method, isSynchronousInvocation); - responseTypeCache.put(method, type); - } - Object profilerObject = null; if (profiler != null) { profilerObject = profiler.beforeCall(); @@ -158,7 +175,7 @@ private Object invokeRequest(Method method, Object[] args, boolean isSynchronous long elapsedTime = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start); if (profiler != null) { - RequestInformation requestInfo = getRequestInfo(server, method, request); + RequestInformation requestInfo = getRequestInfo(server, methodDetails, request); profiler.afterCall(requestInfo, elapsedTime, statusCode, profilerObject); } @@ -189,6 +206,7 @@ private Object invokeRequest(Method method, Object[] args, boolean isSynchronous } } + Type type = methodDetails.type; if (statusCode >= 200 && statusCode < 300) { // 2XX == successful request try { return converter.to(body, type); @@ -207,6 +225,181 @@ private Object invokeRequest(Method method, Object[] args, boolean isSynchronous } } + /** Cached details about an interface method. */ + static class MethodDetails { + private static final Pattern PATH_PARAMETERS = Pattern.compile("\\{([a-z_-]*)\\}"); + + final Method method; + final boolean isSynchronous; + + private boolean loaded = false; + + Type type; + HttpMethodType httpMethod; + String path; + Set<String> pathParams; + QueryParam[] pathQueryParams; + String[] pathNamedParams; + int singleEntityArgumentIndex = -1; + + MethodDetails(Method method) { + this.method = method; + isSynchronous = parseResponseType(); + } + + synchronized void init() { + if (loaded) return; + + parseMethodAnnotations(); + parseParameterAnnotations(); + + loaded = true; + } + + /** Loads {@link #httpMethod}, {@link #path}, and {@link #pathQueryParams}. */ + private void parseMethodAnnotations() { + for (Annotation annotation : method.getAnnotations()) { + Class<? extends Annotation> annotationType = annotation.annotationType(); + + // Look for an HttpMethod annotation describing the request type. + if (annotationType == GET.class + || annotationType == POST.class + || annotationType == PUT.class + || annotationType == DELETE.class) { + if (this.httpMethod != null) { + throw new IllegalStateException( + "Method annotated with multiple HTTP method annotations: " + method); + } + this.httpMethod = annotationType.getAnnotation(HttpMethod.class).value(); + try { + path = (String) annotationType.getMethod("value").invoke(annotation); + } catch (Exception e) { + throw new IllegalStateException("Failed to extract URI path.", e); + } + + pathParams = parsePathParameters(path); + } else if (annotationType == QueryParams.class) { + if (this.pathQueryParams != null) { + throw new IllegalStateException( + "QueryParam and QueryParams annotations are mutually exclusive."); + } + this.pathQueryParams = ((QueryParams) annotation).value(); + } else if (annotationType == QueryParam.class) { + if (this.pathQueryParams != null) { + throw new IllegalStateException( + "QueryParam and QueryParams annotations are mutually exclusive."); + } + this.pathQueryParams = new QueryParam[] { (QueryParam) annotation }; + } + } + + if (httpMethod == null) { + throw new IllegalStateException( + "Method not annotated with GET, POST, PUT, or DELETE: " + method); + } + if (pathQueryParams == null) { + pathQueryParams = new QueryParam[0]; + } + } + + /** Loads {@link #type}. Returns true if the method is synchronous. */ + private boolean parseResponseType() { + // Synchronous methods have a non-void return type. + Type returnType = method.getGenericReturnType(); + + // Asynchronous methods should have a Callback type as the last argument. + Type lastArgType = null; + Class<?> lastArgClass = null; + Type[] parameterTypes = method.getGenericParameterTypes(); + if (parameterTypes.length > 0) { + Type typeToCheck = parameterTypes[parameterTypes.length - 1]; + lastArgType = typeToCheck; + if (typeToCheck instanceof ParameterizedType) { + typeToCheck = ((ParameterizedType) typeToCheck).getRawType(); + } + if (typeToCheck instanceof Class) { + lastArgClass = (Class<?>) typeToCheck; + } + } + + boolean hasReturnType = returnType != void.class; + boolean hasCallback = lastArgClass != null && Callback.class.isAssignableFrom(lastArgClass); + + // Check for invalid configurations. + if (hasReturnType && hasCallback) { + throw new IllegalArgumentException( + "Method may only have return type or Callback as last argument, not both."); + } + if (!hasReturnType && !hasCallback) { + throw new IllegalArgumentException( + "Method must have either a return type or Callback as last argument."); + } + + if (hasReturnType) { + type = returnType; + return true; + } + + lastArgType = Utils.getGenericSupertype(lastArgType, lastArgClass, Callback.class); + if (lastArgType instanceof ParameterizedType) { + Type[] types = ((ParameterizedType) lastArgType).getActualTypeArguments(); + for (int i = 0; i < types.length; i++) { + Type type = types[i]; + if (type instanceof WildcardType) { + types[i] = ((WildcardType) type).getUpperBounds()[0]; + } + } + type = types[0]; + return false; + } + throw new IllegalArgumentException( + String.format("Last parameter of %s must be of type Callback<X> or Callback<? super X>.", + method)); + } + + /** Loads {@link #pathNamedParams} and {@link #singleEntityArgumentIndex}. */ + private void parseParameterAnnotations() { + Annotation[][] parameterAnnotations = method.getParameterAnnotations(); + int count = parameterAnnotations.length; + if (!isSynchronous) { + count -= 1; // Callback is last argument when not a synchronous method. + } + + String[] namedParams = new String[count]; + for (int i = 0; i < count; i++) { + for (Annotation parameterAnnotation : parameterAnnotations[i]) { + Class<? extends Annotation> annotationType = parameterAnnotation.annotationType(); + if (annotationType == Named.class) { + namedParams[i] = ((Named) parameterAnnotation).value(); + } else if (annotationType == SingleEntity.class) { + if (singleEntityArgumentIndex != -1) { + throw new IllegalStateException( + "Method annotated with multiple SingleEntity method annotations: " + method); + } + singleEntityArgumentIndex = i; + } else { + throw new IllegalArgumentException( + "Method argument " + i + " not annotated with Named or SingleEntity: " + method); + } + } + } + pathNamedParams = namedParams; + } + + /** + * Gets the set of unique path parameters used in the given URI. If a parameter is used twice in + * the URI, it will only show up once in the set. + */ + static Set<String> parsePathParameters(String path) { + Matcher m = PATH_PARAMETERS.matcher(path); + Set<String> patterns = new LinkedHashSet<String>(); + while (m.find()) { + patterns.add(m.group(1)); + } + return patterns; + } + } + private static void logResponseBody(String url, byte[] body, int statusCode, long elapsedTime) throws UnsupportedEncodingException { LOGGER.fine("---- HTTP " + statusCode + " from " + url + " (" + elapsedTime + "ms)"); @@ -218,14 +411,9 @@ private static void logResponseBody(String url, byte[] body, int statusCode, lon LOGGER.fine("---- END HTTP"); } - private static Callback<?> obtainCallback(Object[] args) { - return (Callback<?>) args[args.length - 1]; - } - - private static HttpProfiler.RequestInformation getRequestInfo(Server server, Method method, - HttpUriRequest request) { - RequestLine requestLine = RequestLine.fromMethod(method); - HttpMethodType httpMethod = requestLine.getHttpMethod(); + private static HttpProfiler.RequestInformation getRequestInfo(Server server, + MethodDetails methodDetails, HttpUriRequest request) { + HttpMethodType httpMethod = methodDetails.httpMethod; HttpProfiler.Method profilerMethod = httpMethod.profilerMethod(); long contentLength = 0; @@ -239,63 +427,8 @@ private static HttpProfiler.RequestInformation getRequestInfo(Server server, Met contentType = entityContentType != null ? entityContentType.getValue() : null; } - return new HttpProfiler.RequestInformation(profilerMethod, server.apiUrl(), - requestLine.getRelativePath(), contentLength, contentType); - } - - /** - * Determine whether or not execution for a method should be done synchronously. - * - * @throws IllegalArgumentException if the supplied {@code method} has both a return type and - * {@link Callback} argument or neither of the two. - */ - static boolean methodWantsSynchronousInvocation(Method method) { - boolean hasReturnType = method.getReturnType() != void.class; - - Class<?>[] parameterTypes = method.getParameterTypes(); - boolean hasCallback = parameterTypes.length > 0 && Callback.class.isAssignableFrom( - parameterTypes[parameterTypes.length - 1]); - - if ((hasReturnType && hasCallback) || (!hasReturnType && !hasCallback)) { - throw new IllegalArgumentException( - "Method must have either a return type or Callback as last argument."); - } - return hasReturnType; - } - - /** Get the callback parameter types. */ - static Type getResponseObjectType(Method method, boolean isSynchronousInvocation) { - if (isSynchronousInvocation) { - return method.getGenericReturnType(); - } - - Type[] parameterTypes = method.getGenericParameterTypes(); - Type callbackType = parameterTypes[parameterTypes.length - 1]; - Class<?> callbackClass; - if (callbackType instanceof Class) { - callbackClass = (Class<?>) callbackType; - } else if (callbackType instanceof ParameterizedType) { - callbackClass = (Class<?>) ((ParameterizedType) callbackType).getRawType(); - } else { - throw new ClassCastException( - String.format("Last parameter of %s must be a Class or ParameterizedType", method)); - } - if (Callback.class.isAssignableFrom(callbackClass)) { - callbackType = Utils.getGenericSupertype(callbackType, callbackClass, Callback.class); - if (callbackType instanceof ParameterizedType) { - Type[] types = ((ParameterizedType) callbackType).getActualTypeArguments(); - for (int i = 0; i < types.length; i++) { - Type type = types[i]; - if (type instanceof WildcardType) { - types[i] = ((WildcardType) type).getUpperBounds()[0]; - } - } - return types[0]; - } - } - throw new IllegalArgumentException(String.format( - "Last parameter of %s must be of type Callback<X,Y,Z> or Callback<? super X,..,..>.", - method)); + return new HttpProfiler.RequestInformation(profilerMethod, server.apiUrl(), methodDetails.path, + contentLength, contentType); } /** @@ -406,10 +539,4 @@ private void ensureSaneDefaults() { } } } - - static class SynchronousExecutor implements Executor { - @Override public void execute(Runnable runnable) { - runnable.run(); - } - } } \ No newline at end of file diff --git a/retrofit/src/main/java/retrofit/http/Utils.java b/retrofit/src/main/java/retrofit/http/Utils.java index 60cc067931..2c01ac816f 100644 --- a/retrofit/src/main/java/retrofit/http/Utils.java +++ b/retrofit/src/main/java/retrofit/http/Utils.java @@ -2,6 +2,7 @@ package retrofit.http; import java.lang.reflect.Type; +import java.util.concurrent.Executor; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -58,4 +59,10 @@ static String parseCharset(String headerValue) { } return UTF_8; } + + static class SynchronousExecutor implements Executor { + @Override public void execute(Runnable runnable) { + runnable.run(); + } + } } \ No newline at end of file
diff --git a/retrofit/src/test/java/retrofit/http/HttpRequestBuilderTest.java b/retrofit/src/test/java/retrofit/http/HttpRequestBuilderTest.java index 59077f472b..b13e752130 100644 --- a/retrofit/src/test/java/retrofit/http/HttpRequestBuilderTest.java +++ b/retrofit/src/test/java/retrofit/http/HttpRequestBuilderTest.java @@ -6,7 +6,6 @@ import java.lang.reflect.Method; import java.net.URISyntaxException; import java.net.URLEncoder; -import java.util.Set; import java.util.UUID; import javax.inject.Named; import org.apache.http.client.methods.HttpGet; @@ -16,32 +15,13 @@ import static org.fest.assertions.api.Assertions.assertThat; import static org.fest.assertions.api.Fail.fail; +import static retrofit.http.RestAdapter.MethodDetails; /** @author Eric Denman (edenman@squareup.com) */ public class HttpRequestBuilderTest { private static final Gson GSON = new Gson(); private static final String API_URL = "http://taqueria.com/lengua/taco"; - @Test public void testRegex() throws Exception { - expectParams(""); - expectParams("foo"); - expectParams("foo/bar"); - expectParams("foo/bar/{taco}", "taco"); - expectParams("foo/bar/{t}", "t"); - expectParams("foo/bar/{taco}/or/{burrito}", "taco", "burrito"); - expectParams("foo/bar/{taco}/or/{taco}", "taco"); - expectParams("foo/bar/{taco-shell}", "taco-shell"); - expectParams("foo/bar/{taco_shell}", "taco_shell"); - } - - private void expectParams(String path, String... expected) { - Set<String> calculated = HttpRequestBuilder.getPathParameters(path); - assertThat(calculated.size()).isEqualTo(expected.length); - for (String val : expected) { - assertThat(calculated).contains(val); - } - } - @Test public void testNormalGet() throws Exception { Method method = getTestMethod("normalGet"); String expectedId = UUID.randomUUID().toString(); @@ -198,8 +178,10 @@ private static Method getTestMethod(String name) { } private HttpUriRequest build(Method method, Object[] args) throws URISyntaxException { + MethodDetails methodDetails = new MethodDetails(method); + methodDetails.init(); return new HttpRequestBuilder(new GsonConverter(GSON)) // - .setMethod(method, false) // + .setMethod(methodDetails) // .setArgs(args) // .setApiUrl(API_URL) // .build(); diff --git a/retrofit/src/test/java/retrofit/http/RestAdapterTest.java b/retrofit/src/test/java/retrofit/http/RestAdapterTest.java index 2b7c86a708..068ec3da3b 100644 --- a/retrofit/src/test/java/retrofit/http/RestAdapterTest.java +++ b/retrofit/src/test/java/retrofit/http/RestAdapterTest.java @@ -3,6 +3,7 @@ import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; +import java.util.Set; import org.apache.http.HttpMessage; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; @@ -38,6 +39,7 @@ import static org.easymock.EasyMock.verify; import static org.fest.assertions.api.Assertions.assertThat; import static org.fest.assertions.api.Assertions.fail; +import static retrofit.http.RestAdapter.MethodDetails; public class RestAdapterTest { private static final String ID = "123"; @@ -75,6 +77,26 @@ public class RestAdapterTest { .build(); } + @Test public void testRegex() throws Exception { + expectParams(""); + expectParams("foo"); + expectParams("foo/bar"); + expectParams("foo/bar/{taco}", "taco"); + expectParams("foo/bar/{t}", "t"); + expectParams("foo/bar/{taco}/or/{burrito}", "taco", "burrito"); + expectParams("foo/bar/{taco}/or/{taco}", "taco"); + expectParams("foo/bar/{taco-shell}", "taco-shell"); + expectParams("foo/bar/{taco_shell}", "taco_shell"); + } + + private void expectParams(String path, String... expected) { + Set<String> calculated = MethodDetails.parsePathParameters(path); + assertThat(calculated.size()).isEqualTo(expected.length); + for (String val : expected) { + assertThat(calculated).contains(val); + } + } + @Test public void testServiceDeleteSimpleAsync() throws IOException { expectAsyncLifecycle(HttpDelete.class, GET_DELETE_SIMPLE_URL); replayAll(); @@ -433,78 +455,94 @@ public class RestAdapterTest { @Test public void testConcreteCallbackTypes() { Type expected = Response.class; - Method method = getTypeTestMethod("a"); - assertThat(RestAdapter.methodWantsSynchronousInvocation(method)).isFalse(); - assertThat(RestAdapter.getResponseObjectType(method, false)).as("a").isEqualTo(expected); + MethodDetails method = new MethodDetails(getTypeTestMethod("a")); + method.init(); + assertThat(method.isSynchronous).isFalse(); + assertThat(method.type).as("a").isEqualTo(expected); } @Test public void testConcreteCallbackTypesWithParams() { Type expected = Response.class; - Method method = getTypeTestMethod("b"); - assertThat(RestAdapter.methodWantsSynchronousInvocation(method)).isFalse(); - assertThat(RestAdapter.getResponseObjectType(method, false)).as("b").isEqualTo(expected); + MethodDetails method = new MethodDetails(getTypeTestMethod("b")); + method.init(); + assertThat(method.isSynchronous).isFalse(); + assertThat(method.type).as("a").isEqualTo(expected); } @Test public void testGenericCallbackTypes() { Type expected = Response.class; - Method method = getTypeTestMethod("c"); - assertThat(RestAdapter.methodWantsSynchronousInvocation(method)).isFalse(); - assertThat(RestAdapter.getResponseObjectType(method, false)).as("c").isEqualTo(expected); + MethodDetails method = new MethodDetails(getTypeTestMethod("c")); + method.init(); + assertThat(method.isSynchronous).isFalse(); + assertThat(method.type).as("a").isEqualTo(expected); } @Test public void testGenericCallbackTypesWithParams() { Type expected = Response.class; - Method method = getTypeTestMethod("d"); - assertThat(RestAdapter.methodWantsSynchronousInvocation(method)).isFalse(); - assertThat(RestAdapter.getResponseObjectType(method, false)).as("d").isEqualTo(expected); + MethodDetails method = new MethodDetails(getTypeTestMethod("d")); + method.init(); + assertThat(method.isSynchronous).isFalse(); + assertThat(method.type).as("a").isEqualTo(expected); } @Test public void testWildcardGenericCallbackTypes() { Type expected = Response.class; - Method method = getTypeTestMethod("e"); - assertThat(RestAdapter.methodWantsSynchronousInvocation(method)).isFalse(); - assertThat(RestAdapter.getResponseObjectType(method, false)).as("e").isEqualTo(expected); + MethodDetails method = new MethodDetails(getTypeTestMethod("e")); + method.init(); + assertThat(method.isSynchronous).isFalse(); + assertThat(method.type).as("a").isEqualTo(expected); } @Test public void testGenericCallbackWithGenericType() { Type expected = new TypeToken<List<String>>() {}.getType(); - Method method = getTypeTestMethod("f"); - assertThat(RestAdapter.methodWantsSynchronousInvocation(method)).isFalse(); - assertThat(RestAdapter.getResponseObjectType(method, false)).as("f").isEqualTo(expected); + MethodDetails method = new MethodDetails(getTypeTestMethod("f")); + method.init(); + assertThat(method.isSynchronous).isFalse(); + assertThat(method.type).as("a").isEqualTo(expected); } @Ignore // TODO support this case! @Test public void testExtendingGenericCallback() { Type expected = Response.class; - Method method = getTypeTestMethod("g"); - assertThat(RestAdapter.methodWantsSynchronousInvocation(method)).isFalse(); - assertThat(RestAdapter.getResponseObjectType(method, false)).as("g").isEqualTo(expected); + MethodDetails method = new MethodDetails(getTypeTestMethod("g")); + method.init(); + assertThat(method.isSynchronous).isFalse(); + assertThat(method.type).as("a").isEqualTo(expected); } @Test(expected = IllegalArgumentException.class) public void testMissingCallbackTypes() { - Method method = getTypeTestMethod("h"); - assertThat(RestAdapter.methodWantsSynchronousInvocation(method)).isFalse(); - RestAdapter.getResponseObjectType(method, false); + MethodDetails method = new MethodDetails(getTypeTestMethod("h")); + assertThat(method.isSynchronous).isFalse(); + method.init(); } @Test public void testSynchronousResponse() { Type expected = Response.class; - Method method = getTypeTestMethod("x"); - assertThat(RestAdapter.methodWantsSynchronousInvocation(method)).isTrue(); - assertThat(RestAdapter.getResponseObjectType(method, true)).as("x").isEqualTo(expected); + MethodDetails method = new MethodDetails(getTypeTestMethod("x")); + method.init(); + assertThat(method.isSynchronous).isTrue(); + assertThat(method.type).as("a").isEqualTo(expected); } @Test public void testSynchronousGenericResponse() { Type expected = new TypeToken<List<String>>() {}.getType(); - Method method = getTypeTestMethod("y"); - assertThat(RestAdapter.methodWantsSynchronousInvocation(method)).isTrue(); - assertThat(RestAdapter.getResponseObjectType(method, true)).as("y").isEqualTo(expected); + MethodDetails method = new MethodDetails(getTypeTestMethod("y")); + method.init(); + assertThat(method.isSynchronous).isTrue(); + assertThat(method.type).as("a").isEqualTo(expected); } @Test(expected = IllegalArgumentException.class) public void testSynchronousWithAsyncCallback() { - RestAdapter.methodWantsSynchronousInvocation(getTypeTestMethod("z")); + MethodDetails method = new MethodDetails(getTypeTestMethod("z")); + method.init(); + } + + @Ignore // TODO Issue #130 + @Test public void testNonEndpointMethodsSucceed() { + TypeTestService service = restAdapter.create(TypeTestService.class); + assertThat(service.equals(new Object())).isFalse(); } private void replayAll() {
test
train
"2012-12-19T22:27:50"
"2012-12-18T07:58:43"
JakeWharton
val
square/retrofit/130_132
square/retrofit
square/retrofit/130
square/retrofit/132
[ "keyword_issue_to_pr", "keyword_pr_to_issue" ]
89fd13bbe7af39573cce9e6d3cfd61d3f5bb7b2d
8e92fdaf54bc1f3293c0de59e4e85ba97c200333
[ "Fixed by #132 .\n" ]
[ "use `Class<?>` here. Otherwise somebody might accidentally pass a parameterized type, and that'll never work in comparison against `getDeclaringClass()`.\n" ]
"2012-12-20T21:25:22"
[]
Calling Non-endpoint Methods Triggers Logic
We need to only proceed trying to make an HTTP request if the method invoked on the `InvocationHandler` is annotated with one of our HTTP verb annotations.
[ "retrofit/src/main/java/retrofit/http/RestAdapter.java" ]
[ "retrofit/src/main/java/retrofit/http/RestAdapter.java" ]
[ "retrofit/src/test/java/retrofit/http/RestAdapterTest.java" ]
diff --git a/retrofit/src/main/java/retrofit/http/RestAdapter.java b/retrofit/src/main/java/retrofit/http/RestAdapter.java index 37c9647df5..4e3fc72464 100644 --- a/retrofit/src/main/java/retrofit/http/RestAdapter.java +++ b/retrofit/src/main/java/retrofit/http/RestAdapter.java @@ -5,6 +5,7 @@ import java.io.UnsupportedEncodingException; import java.lang.annotation.Annotation; import java.lang.reflect.InvocationHandler; +import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Proxy; @@ -100,15 +101,26 @@ private RestAdapter(Server server, Provider<HttpClient> httpClientProvider, Exec @SuppressWarnings("unchecked") public <T> T create(Class<T> type) { return (T) Proxy.newProxyInstance(type.getClassLoader(), new Class<?>[] { type }, - new RestHandler()); + new RestHandler(type)); } private class RestHandler implements InvocationHandler { - final Map<Method, MethodDetails> methodDetailsCache = + private final Class<?> declaringType; + private final Map<Method, MethodDetails> methodDetailsCache = new LinkedHashMap<Method, MethodDetails>(); + RestHandler(Class<?> declaringType) { + this.declaringType = declaringType; + } + @SuppressWarnings("unchecked") - @Override public Object invoke(Object proxy, Method method, final Object[] args) { + @Override public Object invoke(Object proxy, Method method, final Object[] args) + throws InvocationTargetException, IllegalAccessException { + // If the method is not a direct member of the interface then defer to normal invocation. + if (method.getDeclaringClass() != declaringType) { + return method.invoke(this, args); + } + // Load or create the details cache for the current method. final MethodDetails methodDetails; synchronized (methodDetailsCache) {
diff --git a/retrofit/src/test/java/retrofit/http/RestAdapterTest.java b/retrofit/src/test/java/retrofit/http/RestAdapterTest.java index 068ec3da3b..9b3a6f03ae 100644 --- a/retrofit/src/test/java/retrofit/http/RestAdapterTest.java +++ b/retrofit/src/test/java/retrofit/http/RestAdapterTest.java @@ -539,7 +539,6 @@ public void testSynchronousWithAsyncCallback() { method.init(); } - @Ignore // TODO Issue #130 @Test public void testNonEndpointMethodsSucceed() { TypeTestService service = restAdapter.create(TypeTestService.class); assertThat(service.equals(new Object())).isFalse();
train
train
"2012-12-20T22:06:40"
"2012-12-19T23:51:45"
JakeWharton
val
square/retrofit/154_158
square/retrofit
square/retrofit/154
square/retrofit/158
[ "timestamp(timedelta=6.0, similarity=0.8424064248324534)" ]
a7755edc83d3907204093840a7c15d954120c926
ab81d9058ef899ecd91f81e4d195b920c157e6ff
[ "I was going to take a stab at this, but according to http://stackoverflow.com/questions/4669692/valid-characters-for-directory-part-of-a-url-for-short-links and the referenced RFCs, this appears to be appropriate behavior for a URL path. Maybe there is something I'm missing, but it appears that { and } require percent escaping.\n", "The percent escaping is insignificant for the { character. But it is important that we get the behavior we want for the `?`, `&` and `#` characters, which have very different semantics depending on whether they're escaped or not.\n", "I wrote some failing test cases and results [here](https://gist.github.com/campnic/5024459). \n\nIt appears that the path parameters are being escaped correctly but that query parameters are not. If I could get confirmation on that, I'll get a patch pulled together.\n" ]
[ "You can just `return` here and drop the first and last line.\n", "All the changes in this file need to be two-space indentation instead of four.\n", "Sorry, do you guys have a format template for eclipse? I'm fighting my own\ntemplate to try to keep things styled like the rest of the project.\nOn Feb 24, 2013 4:31 PM, \"Jake Wharton\" notifications@github.com wrote:\n\n> In retrofit/src/test/java/retrofit/http/RequestBuilderTest.java:\n> \n> > @@ -76,6 +76,48 @@\n> > assertThat(request.getUrl()).isEqualTo(\"http://example.com/foo/bar/pong/?kit=kat&riff=raff\");\n> > assertThat(request.getBody()).isNull();\n> > }\n> > +\n> > - @Test public void getWithPathAndQueryQuestionMarkParam() throws Exception {\n> > - Request request = new Helper() //\n> \n> Needs to be two-space indentation instead of four.\n> \n> —\n> Reply to this email directly or view it on GitHubhttps://github.com/square/retrofit/pull/158/files#r3129647.\n", "No, sorry. None of us use Eclipse. I realize it can be a challenge since there are wildly different styles. I can fix it after merging, if you'd like.\n", "Naw, I'll fix it. Better to have it be correct so i am reminded in the future.\n" ]
"2013-02-24T18:40:10"
[]
Path Params Are Incorrectly Encoded As Query Params
``` java @GET("/foo/{bar}/") Response a(@Name("bar") String bar) ``` ``` java a("{baz}"); ``` is incorrectly encoded to `/foo/%7Bpbaz%7D/` instead of `/foo/{baz}/`.
[ "retrofit/src/main/java/retrofit/http/RequestBuilder.java" ]
[ "retrofit/src/main/java/retrofit/http/RequestBuilder.java" ]
[ "retrofit/src/test/java/retrofit/http/RequestBuilderTest.java" ]
diff --git a/retrofit/src/main/java/retrofit/http/RequestBuilder.java b/retrofit/src/main/java/retrofit/http/RequestBuilder.java index 2fe5394137..d73adcdd8b 100644 --- a/retrofit/src/main/java/retrofit/http/RequestBuilder.java +++ b/retrofit/src/main/java/retrofit/http/RequestBuilder.java @@ -88,12 +88,7 @@ Request build() { } } if (found != null) { - String value; - try { - value = URLEncoder.encode(String.valueOf(found.getValue()), UTF_8); - } catch (UnsupportedEncodingException e) { - throw new AssertionError(e); - } + String value = getUrlEncodedValue(found); replacedPath = replacedPath.replace("{" + found.getName() + "}", value); paramList.remove(found); } else { @@ -127,7 +122,8 @@ Request build() { for (int i = 0, count = paramList.size(); i < count; i++) { url.append((i == 0) ? '?' : '&'); Parameter nonPathParam = paramList.get(i); - url.append(nonPathParam.getName()).append("=").append(nonPathParam.getValue()); + String value = getUrlEncodedValue(nonPathParam); + url.append(nonPathParam.getName()).append("=").append(value); } } else if (!paramList.isEmpty()) { if (methodInfo.isMultipart) { @@ -157,4 +153,12 @@ Request build() { return new Request(methodInfo.restMethod.value(), url.toString(), headers, body); } + + private static String getUrlEncodedValue(Parameter found) { + try { + return URLEncoder.encode(String.valueOf(found.getValue()), UTF_8); + } catch (UnsupportedEncodingException e) { + throw new AssertionError(e); + } + } } \ No newline at end of file
diff --git a/retrofit/src/test/java/retrofit/http/RequestBuilderTest.java b/retrofit/src/test/java/retrofit/http/RequestBuilderTest.java index 7615893a2d..7de05d4f12 100644 --- a/retrofit/src/test/java/retrofit/http/RequestBuilderTest.java +++ b/retrofit/src/test/java/retrofit/http/RequestBuilderTest.java @@ -76,6 +76,48 @@ public class RequestBuilderTest { assertThat(request.getUrl()).isEqualTo("http://example.com/foo/bar/pong/?kit=kat&riff=raff"); assertThat(request.getBody()).isNull(); } + + @Test public void getWithPathAndQueryQuestionMarkParam() throws Exception { + Request request = new Helper() // + .setMethod("GET") // + .setUrl("http://example.com") // + .setPath("/foo/bar/{ping}/") // + .addNamedParam("ping", "pong?") // + .addNamedParam("kit", "kat?") // + .build(); + assertThat(request.getMethod()).isEqualTo("GET"); + assertThat(request.getHeaders()).isEmpty(); + assertThat(request.getUrl()).isEqualTo("http://example.com/foo/bar/pong%3F/?kit=kat%3F"); + assertThat(request.getBody()).isNull(); + } + + @Test public void getWithPathAndQueryAmpersandParam() throws Exception { + Request request = new Helper() // + .setMethod("GET") // + .setUrl("http://example.com") // + .setPath("/foo/bar/{ping}/") // + .addNamedParam("ping", "pong&") // + .addNamedParam("kit", "kat&") // + .build(); + assertThat(request.getMethod()).isEqualTo("GET"); + assertThat(request.getHeaders()).isEmpty(); + assertThat(request.getUrl()).isEqualTo("http://example.com/foo/bar/pong%26/?kit=kat%26"); + assertThat(request.getBody()).isNull(); + } + + @Test public void getWithPathAndQueryHashParam() throws Exception { + Request request = new Helper() // + .setMethod("GET") // + .setUrl("http://example.com") // + .setPath("/foo/bar/{ping}/") // + .addNamedParam("ping", "pong#") // + .addNamedParam("kit", "kat#") // + .build(); + assertThat(request.getMethod()).isEqualTo("GET"); + assertThat(request.getHeaders()).isEmpty(); + assertThat(request.getUrl()).isEqualTo("http://example.com/foo/bar/pong%23/?kit=kat%23"); + assertThat(request.getBody()).isNull(); + } @Test public void getWithPathAndQueryParamAsync() throws Exception { Request request = new Helper() //
val
train
"2013-02-22T16:32:06"
"2013-02-20T07:53:09"
JakeWharton
val
square/retrofit/163_164
square/retrofit
square/retrofit/163
square/retrofit/164
[ "timestamp(timedelta=2.0, similarity=0.8664043957630777)" ]
db20a59b2819fbe4fe7e9a8478b726b592dc3971
258e289385c75d2f3104d487eba98731358a28ae
[ "We force the implementations of `Client` to parse the \"Content-Type\" header in order to create a `TypedInput` for the response. This `TypedInput` is handed directly to the response converter which is responsible for decoding the bytes in accordance to the MIME type and encoding. Having the iteration here is not only redundant, but unnecessary.\n\nIt should be the responsibility of the converter to determine whether or not a MIME type is invalid. We probably shouldn't be enforcing this by default since we don't live in a perfect world of well-behaved servers. Theoretically you could deal with a server that sends down ASCII text documents and your converter turns them into `String`s which should be a perfectly valid use-case.\n", "@brh could you report this as a bug against Rotton Tomatoes? We're never going to get out of this charset hell until everyone goes to UTF-8.\n", "HA! There are a few defects or requests I have saw on their page that are several years old and they have not gotten any reply at all. Will look into it though.\n" ]
[]
"2013-03-07T17:15:20"
[]
Relax UTF-8 requirements or make configurable
In RestAdapter.invokeRequest(RestMethodInfo methodDetails, Object[] args) this check (line ~186) ``` java for (Header header : headers) { if (HTTP.CONTENT_TYPE.equalsIgnoreCase(header.getName()) // && !UTF_8.equalsIgnoreCase(Utils.parseCharset(header.getValue()))) { throw new IOException("Only UTF-8 charset supported."); } } ``` Naturally, bombs out on sites that don't "behave properly", like rottentomatoes api. Can this check be made more flexible or removed altogether?
[ "retrofit/src/main/java/retrofit/http/GsonConverter.java", "retrofit/src/main/java/retrofit/http/RequestBuilder.java", "retrofit/src/main/java/retrofit/http/RestAdapter.java", "retrofit/src/main/java/retrofit/http/Utils.java" ]
[ "retrofit/src/main/java/retrofit/http/GsonConverter.java", "retrofit/src/main/java/retrofit/http/RequestBuilder.java", "retrofit/src/main/java/retrofit/http/RestAdapter.java", "retrofit/src/main/java/retrofit/http/Utils.java" ]
[ "retrofit/src/test/java/retrofit/http/UtilsTest.java" ]
diff --git a/retrofit/src/main/java/retrofit/http/GsonConverter.java b/retrofit/src/main/java/retrofit/http/GsonConverter.java index ae032b3e68..a2372291bb 100644 --- a/retrofit/src/main/java/retrofit/http/GsonConverter.java +++ b/retrofit/src/main/java/retrofit/http/GsonConverter.java @@ -11,8 +11,6 @@ import retrofit.http.mime.TypedInput; import retrofit.http.mime.TypedOutput; -import static retrofit.http.RestAdapter.UTF_8; - /** * A {@link Converter} which uses GSON for serialization and deserialization of entities. * @@ -26,9 +24,10 @@ public GsonConverter(Gson gson) { } @Override public Object fromBody(TypedInput body, Type type) throws ConversionException { + String charset = Utils.parseCharset(body.mimeType()); InputStreamReader isr = null; try { - isr = new InputStreamReader(body.in(), UTF_8); + isr = new InputStreamReader(body.in(), charset); return gson.fromJson(isr, type); } catch (IOException e) { throw new ConversionException(e); @@ -46,7 +45,7 @@ public GsonConverter(Gson gson) { @Override public TypedOutput toBody(Object object) { try { - return new JsonTypedOutput(gson.toJson(object).getBytes(UTF_8)); + return new JsonTypedOutput(gson.toJson(object).getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { throw new AssertionError(e); } diff --git a/retrofit/src/main/java/retrofit/http/RequestBuilder.java b/retrofit/src/main/java/retrofit/http/RequestBuilder.java index d73adcdd8b..a7b8495690 100644 --- a/retrofit/src/main/java/retrofit/http/RequestBuilder.java +++ b/retrofit/src/main/java/retrofit/http/RequestBuilder.java @@ -11,7 +11,6 @@ import retrofit.http.mime.TypedOutput; import retrofit.http.mime.TypedString; -import static retrofit.http.RestAdapter.UTF_8; import static retrofit.http.RestMethodInfo.NO_SINGLE_ENTITY; /** @@ -156,7 +155,7 @@ Request build() { private static String getUrlEncodedValue(Parameter found) { try { - return URLEncoder.encode(String.valueOf(found.getValue()), UTF_8); + return URLEncoder.encode(String.valueOf(found.getValue()), "UTF-8"); } catch (UnsupportedEncodingException e) { throw new AssertionError(e); } diff --git a/retrofit/src/main/java/retrofit/http/RestAdapter.java b/retrofit/src/main/java/retrofit/http/RestAdapter.java index 3a0503674e..fd10dff55b 100644 --- a/retrofit/src/main/java/retrofit/http/RestAdapter.java +++ b/retrofit/src/main/java/retrofit/http/RestAdapter.java @@ -8,7 +8,6 @@ import java.lang.reflect.Proxy; import java.lang.reflect.Type; import java.util.LinkedHashMap; -import java.util.List; import java.util.Map; import java.util.concurrent.Executor; import java.util.concurrent.TimeUnit; @@ -34,7 +33,6 @@ public class RestAdapter { private static final Logger LOGGER = Logger.getLogger(RestAdapter.class.getName()); private static final int LOG_CHUNK_SIZE = 4000; static final String THREAD_PREFIX = "Retrofit-"; - static final String UTF_8 = "UTF-8"; private final Server server; private final Client.Provider clientProvider; @@ -183,14 +181,6 @@ private Object invokeRequest(RestMethodInfo methodDetails, Object[] args) { body = logResponse(url, response.getStatus(), body, elapsedTime); } - List<Header> headers = response.getHeaders(); - for (Header header : headers) { - if ("Content-Type".equalsIgnoreCase(header.getName()) // - && !UTF_8.equalsIgnoreCase(Utils.parseCharset(header.getValue()))) { - throw new IOException("Only UTF-8 charset supported."); - } - } - Type type = methodDetails.type; if (statusCode >= 200 && statusCode < 300) { // 2XX == successful request if (type.equals(Response.class)) { @@ -230,7 +220,8 @@ private static TypedInput logResponse(String url, int statusCode, TypedInput bod LOGGER.fine("<--- HTTP " + statusCode + " " + url + " (" + elapsedTime + "ms)"); byte[] bodyBytes = Utils.streamToBytes(body.in()); - String bodyString = new String(bodyBytes, UTF_8); + String bodyCharset = Utils.parseCharset(body.mimeType()); + String bodyString = new String(bodyBytes, bodyCharset); for (int i = 0; i < bodyString.length(); i += LOG_CHUNK_SIZE) { int end = Math.min(bodyString.length(), i + LOG_CHUNK_SIZE); LOGGER.fine(bodyString.substring(i, end)); diff --git a/retrofit/src/main/java/retrofit/http/Utils.java b/retrofit/src/main/java/retrofit/http/Utils.java index c5d89a6494..7e4789f6c2 100644 --- a/retrofit/src/main/java/retrofit/http/Utils.java +++ b/retrofit/src/main/java/retrofit/http/Utils.java @@ -11,9 +11,8 @@ import java.util.regex.Pattern; import static java.util.regex.Pattern.CASE_INSENSITIVE; -import static retrofit.http.RestAdapter.UTF_8; -final class Utils { +public final class Utils { private static final Pattern CHARSET = Pattern.compile("\\Wcharset=([^\\s;]+)", CASE_INSENSITIVE); private static final int BUFFER_SIZE = 0x1000; @@ -75,12 +74,12 @@ static Type getGenericSupertype(Type context, Class<?> rawType, Class<?> toResol return toResolve; } - static String parseCharset(String mimeType) { + public static String parseCharset(String mimeType) { Matcher match = CHARSET.matcher(mimeType); if (match.find()) { return match.group(1).replaceAll("[\"\\\\]", ""); } - return UTF_8; + return "UTF-8"; } static class SynchronousExecutor implements Executor { @@ -88,4 +87,8 @@ static class SynchronousExecutor implements Executor { runnable.run(); } } + + public Utils() { + // No instances. + } } \ No newline at end of file
diff --git a/retrofit/src/test/java/retrofit/http/UtilsTest.java b/retrofit/src/test/java/retrofit/http/UtilsTest.java index a81347f377..5176f02309 100644 --- a/retrofit/src/test/java/retrofit/http/UtilsTest.java +++ b/retrofit/src/test/java/retrofit/http/UtilsTest.java @@ -4,21 +4,20 @@ import org.junit.Test; import static org.fest.assertions.api.Assertions.assertThat; -import static retrofit.http.RestAdapter.UTF_8; import static retrofit.http.Utils.parseCharset; public class UtilsTest { @Test public void charsetParsing() { - assertThat(parseCharset("text/plain;charset=utf-8")).isEqualToIgnoringCase(UTF_8); - assertThat(parseCharset("text/plain; charset=utf-8")).isEqualToIgnoringCase(UTF_8); - assertThat(parseCharset("text/plain; charset=utf-8")).isEqualToIgnoringCase(UTF_8); - assertThat(parseCharset("text/plain; \tcharset=utf-8")).isEqualToIgnoringCase(UTF_8); - assertThat(parseCharset("text/plain; \r\n\tcharset=utf-8")).isEqualToIgnoringCase(UTF_8); - assertThat(parseCharset("text/plain; CHARSET=utf-8")).isEqualToIgnoringCase(UTF_8); - assertThat(parseCharset("text/plain; charset=UTF-8")).isEqualToIgnoringCase(UTF_8); - assertThat(parseCharset("text/plain; charset=\"\\u\\tf-\\8\"")).isEqualToIgnoringCase(UTF_8); - assertThat(parseCharset("text/plain; charset=\"utf-8\"")).isEqualToIgnoringCase(UTF_8); - assertThat(parseCharset("text/plain; charset=utf-8; other=thing")).isEqualToIgnoringCase(UTF_8); - assertThat(parseCharset("text/plain; notthecharset=utf-16;")).isEqualToIgnoringCase(UTF_8); + assertThat(parseCharset("text/plain;charset=utf-8")).isEqualToIgnoringCase("UTF-8"); + assertThat(parseCharset("text/plain; charset=utf-8")).isEqualToIgnoringCase("UTF-8"); + assertThat(parseCharset("text/plain; charset=utf-8")).isEqualToIgnoringCase("UTF-8"); + assertThat(parseCharset("text/plain; \tcharset=utf-8")).isEqualToIgnoringCase("UTF-8"); + assertThat(parseCharset("text/plain; \r\n\tcharset=utf-8")).isEqualToIgnoringCase("UTF-8"); + assertThat(parseCharset("text/plain; CHARSET=utf-8")).isEqualToIgnoringCase("UTF-8"); + assertThat(parseCharset("text/plain; charset=UTF-8")).isEqualToIgnoringCase("UTF-8"); + assertThat(parseCharset("text/plain; charset=\"\\u\\tf-\\8\"")).isEqualToIgnoringCase("UTF-8"); + assertThat(parseCharset("text/plain; charset=\"utf-8\"")).isEqualToIgnoringCase("UTF-8"); + assertThat(parseCharset("text/plain;charset=utf-8;other=thing")).isEqualToIgnoringCase("UTF-8"); + assertThat(parseCharset("text/plain; notthecharset=utf-16;")).isEqualToIgnoringCase("UTF-8"); } }
train
train
"2013-03-07T10:09:00"
"2013-03-07T15:59:55"
brh
val
square/retrofit/142_180
square/retrofit
square/retrofit/142
square/retrofit/180
[ "timestamp(timedelta=2.0, similarity=0.9750595156461359)" ]
2fcabb79e66d572725c72950e4a73dab1e328985
ee8bca47f9ba7cc2c5dd83b665b8f0d642209d8d
[ "Sadly this doesn't save as much work as you'd hope. The `Object...` means that the arguments get boxed into an array, after any primitive arguments get boxed into their wrapper types. Worst of all, values that need to be computed still need to be computed:\n\n```\n Log.debug(\"The result is %s\", someExpensiveOperation());\n```\n", "``` java\nlogger.log(new LogCallback() {\n @Override public String log() {\n return \"The result is \" + someExpensiveOperation();\n }\n});\n```\n\nOnly kidding...\n", "Should we add a `debug(boolean)` toggle onto `RestAdapter` like we do with that yet-unreleased internal library? If we guard every log statement with\n\n``` java\nif (debug) {\n log(\"%s/%s + %s ^ %s # %s\", foos, bar, baz, bind, balj, sd, sf, sg, wg);\n}\n```\n\nthe boxing and allocations aren't incurred unless you want them.\n\nI'll take the verbosity for conciseness of the actual logging code.\n", "Yeah, if we guard the logs then it's fine.\n", "(I'm mostly offended by performance bugs caused by log messages that get filtered out)\n" ]
[ "What's with the ugly arrow?\n", "Include request duration? length?\n", "Indicated direction of data. Without they look very similar in the logs flying by.\n" ]
"2013-04-12T04:24:31"
[]
Abstract Logging API
Easier control over sending the logs. And deferring string replacements using something like: ``` java public void log(String message, Object... args); ```
[ "retrofit/src/main/java/retrofit/http/Platform.java", "retrofit/src/main/java/retrofit/http/RestAdapter.java" ]
[ "retrofit/src/main/java/retrofit/http/Platform.java", "retrofit/src/main/java/retrofit/http/RestAdapter.java" ]
[]
diff --git a/retrofit/src/main/java/retrofit/http/Platform.java b/retrofit/src/main/java/retrofit/http/Platform.java index 28ad856133..da9bfc7fee 100644 --- a/retrofit/src/main/java/retrofit/http/Platform.java +++ b/retrofit/src/main/java/retrofit/http/Platform.java @@ -2,6 +2,7 @@ import android.os.Build; import android.os.Process; +import android.util.Log; import com.google.gson.Gson; import java.util.concurrent.Executor; import java.util.concurrent.Executors; @@ -39,6 +40,7 @@ Converter defaultConverter() { abstract Client.Provider defaultClient(); abstract Executor defaultHttpExecutor(); abstract Executor defaultCallbackExecutor(); + abstract RestAdapter.Log defaultLog(); /** Provides sane defaults for operation on the JVM. */ private static class Base extends Platform { @@ -69,6 +71,14 @@ private static class Base extends Platform { @Override Executor defaultCallbackExecutor() { return new SynchronousExecutor(); } + + @Override RestAdapter.Log defaultLog() { + return new RestAdapter.Log() { + @Override public void log(String message) { + System.out.println(message); + } + }; + } } /** Provides sane defaults for operation on Android. */ @@ -105,5 +115,13 @@ private static class Android extends Platform { @Override Executor defaultCallbackExecutor() { return new MainThreadExecutor(); } + + @Override RestAdapter.Log defaultLog() { + return new RestAdapter.Log() { + @Override public void log(String message) { + Log.d("Retrofit", message); + } + }; + } } } diff --git a/retrofit/src/main/java/retrofit/http/RestAdapter.java b/retrofit/src/main/java/retrofit/http/RestAdapter.java index 4bff10d1e8..e77f412197 100644 --- a/retrofit/src/main/java/retrofit/http/RestAdapter.java +++ b/retrofit/src/main/java/retrofit/http/RestAdapter.java @@ -1,6 +1,7 @@ // Copyright 2012 Square, Inc. package retrofit.http; +import java.io.ByteArrayOutputStream; import java.io.IOException; import java.lang.reflect.InvocationHandler; import java.lang.reflect.InvocationTargetException; @@ -11,8 +12,6 @@ import java.util.Map; import java.util.concurrent.Executor; import java.util.concurrent.TimeUnit; -import java.util.logging.Level; -import java.util.logging.Logger; import retrofit.http.Profiler.RequestInformation; import retrofit.http.client.Client; import retrofit.http.client.Request; @@ -30,10 +29,15 @@ * @author Jake Wharton (jw@squareup.com) */ public class RestAdapter { - private static final Logger LOGGER = Logger.getLogger(RestAdapter.class.getName()); private static final int LOG_CHUNK_SIZE = 4000; static final String THREAD_PREFIX = "Retrofit-"; + /** Simple logging abstraction for debug messages. */ + public interface Log { + /** Log a debug message to the appropriate console. */ + void log(String message); + } + private final Server server; private final Client.Provider clientProvider; private final Executor httpExecutor; @@ -41,9 +45,12 @@ public class RestAdapter { private final Headers headers; private final Converter converter; private final Profiler profiler; + private final Log log; + private volatile boolean debug; private RestAdapter(Server server, Client.Provider clientProvider, Executor httpExecutor, - Executor callbackExecutor, Headers headers, Converter converter, Profiler profiler) { + Executor callbackExecutor, Headers headers, Converter converter, Profiler profiler, Log log, + boolean debug) { this.server = server; this.clientProvider = clientProvider; this.httpExecutor = httpExecutor; @@ -51,6 +58,13 @@ private RestAdapter(Server server, Client.Provider clientProvider, Executor http this.headers = headers; this.converter = converter; this.profiler = profiler; + this.log = log; + this.debug = debug; + } + + /** Toggle debug logging on and off. */ + public void setDebug(boolean debug) { + this.debug = debug; } /** @@ -141,10 +155,11 @@ private class RestHandler implements InvocationHandler { private Object invokeRequest(RestMethodInfo methodDetails, Object[] args) { methodDetails.init(); // Ensure all relevant method information has been loaded. - String url = server.getUrl(); + String serverUrl = server.getUrl(); + String url = serverUrl; // Keep some url in case RequestBuilder throws an exception. try { Request request = new RequestBuilder(converter) // - .setApiUrl(server.getUrl()) + .setApiUrl(serverUrl) .setArgs(args) .setHeaders(headers.get()) .setMethodInfo(methodDetails) @@ -153,11 +168,11 @@ private Object invokeRequest(RestMethodInfo methodDetails, Object[] args) { if (!methodDetails.isSynchronous) { // If we are executing asynchronously then update the current thread with a useful name. - Thread.currentThread().setName(THREAD_PREFIX + url); + Thread.currentThread().setName(THREAD_PREFIX + url.substring(serverUrl.length())); } - if (LOGGER.isLoggable(Level.FINE)) { - logRequest(request); + if (debug) { + request = logAndReplaceRequest(request); } Object profilerObject = null; @@ -171,14 +186,12 @@ private Object invokeRequest(RestMethodInfo methodDetails, Object[] args) { int statusCode = response.getStatus(); if (profiler != null) { - RequestInformation requestInfo = getRequestInfo(server, methodDetails, request); + RequestInformation requestInfo = getRequestInfo(serverUrl, methodDetails, request); profiler.afterCall(requestInfo, elapsedTime, statusCode, profilerObject); } - TypedInput body = response.getBody(); - if (LOGGER.isLoggable(Level.FINE)) { - // Replace the response since the logger needs to consume the entire input stream. - body = logResponse(url, response.getStatus(), body, elapsedTime); + if (debug) { + response = logAndReplaceResponse(url, response, elapsedTime); } Type type = methodDetails.type; @@ -189,6 +202,7 @@ private Object invokeRequest(RestMethodInfo methodDetails, Object[] args) { } return new ResponseWrapper(response, response); } + TypedInput body = response.getBody(); if (body == null) { return new ResponseWrapper(response, null); } @@ -213,34 +227,77 @@ private Object invokeRequest(RestMethodInfo methodDetails, Object[] args) { } } - private static void logRequest(Request request) { - LOGGER.fine("---> HTTP " + request.getMethod() + " " + request.getUrl()); + /** Log request headers and body. Consumes request body and returns identical replacement. */ + private Request logAndReplaceRequest(Request request) throws IOException { + log.log(String.format("---> HTTP %s %s", request.getMethod(), request.getUrl())); + for (Header header : request.getHeaders()) { - LOGGER.fine(header.getName() + ": " + header.getValue()); + log.log(header.getName() + ": " + header.getValue()); } - LOGGER.fine("---> END HTTP"); + + TypedOutput body = request.getBody(); + int bodySize = 0; + if (body != null) { + if (!request.getHeaders().isEmpty()) { + log.log(""); + } + + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + body.writeTo(baos); + byte[] bodyBytes = baos.toByteArray(); + bodySize = bodyBytes.length; + String bodyMime = body.mimeType(); + String bodyString = new String(bodyBytes, Utils.parseCharset(bodyMime)); + for (int i = 0; i < bodyString.length(); i += LOG_CHUNK_SIZE) { + int end = Math.min(bodyString.length(), i + LOG_CHUNK_SIZE); + log.log(bodyString.substring(i, end)); + } + + body = new TypedByteArray(bodyMime, bodyBytes); + } + + log.log(String.format("---> END HTTP (%s-byte body)", bodySize)); + + // Since we consumed the original request, return a new, identical one from its bytes. + return new Request(request.getMethod(), request.getUrl(), request.getHeaders(), body); } - /** Log response data. Returns replacement {@link TypedInput}. */ - private static TypedInput logResponse(String url, int statusCode, TypedInput body, - long elapsedTime) throws IOException { - LOGGER.fine("<--- HTTP " + statusCode + " " + url + " (" + elapsedTime + "ms)"); - - byte[] bodyBytes = Utils.streamToBytes(body.in()); - String bodyCharset = Utils.parseCharset(body.mimeType()); - String bodyString = new String(bodyBytes, bodyCharset); - for (int i = 0; i < bodyString.length(); i += LOG_CHUNK_SIZE) { - int end = Math.min(bodyString.length(), i + LOG_CHUNK_SIZE); - LOGGER.fine(bodyString.substring(i, end)); + /** Log response headers and body. Consumes response body and returns identical replacement. */ + private Response logAndReplaceResponse(String url, Response response, long elapsedTime) + throws IOException { + log.log(String.format("<--- HTTP %s %s (%sms)", response.getStatus(), url, elapsedTime)); + + for (Header header : response.getHeaders()) { + log.log(header.getName() + ": " + header.getValue()); + } + + TypedInput body = response.getBody(); + int bodySize = 0; + if (body != null) { + if (!response.getHeaders().isEmpty()) { + log.log(""); + } + + byte[] bodyBytes = Utils.streamToBytes(body.in()); + bodySize = bodyBytes.length; + String bodyMime = body.mimeType(); + String bodyCharset = Utils.parseCharset(bodyMime); + String bodyString = new String(bodyBytes, bodyCharset); + for (int i = 0; i < bodyString.length(); i += LOG_CHUNK_SIZE) { + int end = Math.min(bodyString.length(), i + LOG_CHUNK_SIZE); + log.log(bodyString.substring(i, end)); + } + + body = new TypedByteArray(bodyMime, bodyBytes); } - LOGGER.fine("<--- END HTTP"); + log.log(String.format("---> END HTTP (%s-byte body)", bodySize)); - // Since we consumed the entire input stream, return a new, identical one from its bytes. - return new TypedByteArray(body.mimeType(), bodyBytes); + // Since we consumed the original response, return a new, identical one from its bytes. + return new Response(response.getStatus(), response.getReason(), response.getHeaders(), body); } - private static Profiler.RequestInformation getRequestInfo(Server server, + private static Profiler.RequestInformation getRequestInfo(String serverUrl, RestMethodInfo methodDetails, Request request) { long contentLength = 0; String contentType = null; @@ -251,7 +308,7 @@ private static Profiler.RequestInformation getRequestInfo(Server server, contentType = body.mimeType(); } - return new Profiler.RequestInformation(methodDetails.restMethod.value(), server.getUrl(), + return new Profiler.RequestInformation(methodDetails.restMethod.value(), serverUrl, methodDetails.path, contentLength, contentType); } @@ -279,6 +336,8 @@ public static class Builder { private Headers headers; private Converter converter; private Profiler profiler; + private Log log; + private boolean debug; public Builder setServer(String endpoint) { if (endpoint == null) throw new NullPointerException("endpoint"); @@ -340,13 +399,24 @@ public Builder setProfiler(Profiler profiler) { return this; } + public Builder setLog(Log log) { + if (log == null) throw new NullPointerException("log"); + this.log = log; + return this; + } + + public Builder setDebug(boolean debug) { + this.debug = debug; + return this; + } + public RestAdapter build() { if (server == null) { throw new IllegalArgumentException("Server may not be null."); } ensureSaneDefaults(); - return new RestAdapter(server, clientProvider, httpExecutor, callbackExecutor, - headers, converter, profiler); + return new RestAdapter(server, clientProvider, httpExecutor, callbackExecutor, headers, + converter, profiler, log, debug); } private void ensureSaneDefaults() { @@ -362,6 +432,9 @@ private void ensureSaneDefaults() { if (callbackExecutor == null) { callbackExecutor = Platform.get().defaultCallbackExecutor(); } + if (log == null) { + log = Platform.get().defaultLog(); + } if (headers == null) { headers = Headers.NONE; }
null
train
train
"2013-03-30T00:50:17"
"2013-02-12T05:28:47"
JakeWharton
val
square/retrofit/188_190
square/retrofit
square/retrofit/188
square/retrofit/190
[ "timestamp(timedelta=1.0, similarity=0.9123221038546971)" ]
1af9c9595077a7cfc0c30c3669208cc5bd047407
1c5b74c8ed760755195ca6082c6d9890296eae38
[]
[]
"2013-05-04T03:06:18"
[]
Clear Thread Name When Idle
Reset the thread name to "Retrofit-Idle" when the background operations complete.
[ "retrofit/src/main/java/retrofit/http/Platform.java", "retrofit/src/main/java/retrofit/http/RestAdapter.java" ]
[ "retrofit/src/main/java/retrofit/http/Platform.java", "retrofit/src/main/java/retrofit/http/RestAdapter.java" ]
[]
diff --git a/retrofit/src/main/java/retrofit/http/Platform.java b/retrofit/src/main/java/retrofit/http/Platform.java index da9bfc7fee..1a8de06d21 100644 --- a/retrofit/src/main/java/retrofit/http/Platform.java +++ b/retrofit/src/main/java/retrofit/http/Platform.java @@ -7,7 +7,6 @@ import java.util.concurrent.Executor; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; -import java.util.concurrent.atomic.AtomicInteger; import retrofit.http.android.AndroidApacheClient; import retrofit.http.android.MainThreadExecutor; import retrofit.http.client.Client; @@ -15,7 +14,7 @@ import static android.os.Process.THREAD_PRIORITY_BACKGROUND; import static java.lang.Thread.MIN_PRIORITY; -import static retrofit.http.RestAdapter.THREAD_PREFIX; +import static retrofit.http.RestAdapter.IDLE_THREAD_NAME; import static retrofit.http.Utils.SynchronousExecutor; abstract class Platform { @@ -55,15 +54,13 @@ private static class Base extends Platform { @Override Executor defaultHttpExecutor() { return Executors.newCachedThreadPool(new ThreadFactory() { - private final AtomicInteger threadCounter = new AtomicInteger(); - @Override public Thread newThread(final Runnable r) { return new Thread(new Runnable() { @Override public void run() { Thread.currentThread().setPriority(MIN_PRIORITY); r.run(); } - }, THREAD_PREFIX + threadCounter.getAndIncrement()); + }, IDLE_THREAD_NAME); } }); } @@ -99,15 +96,13 @@ private static class Android extends Platform { @Override Executor defaultHttpExecutor() { return Executors.newCachedThreadPool(new ThreadFactory() { - private final AtomicInteger threadCounter = new AtomicInteger(); - @Override public Thread newThread(final Runnable r) { return new Thread(new Runnable() { @Override public void run() { Process.setThreadPriority(THREAD_PRIORITY_BACKGROUND); r.run(); } - }, THREAD_PREFIX + threadCounter.getAndIncrement()); + }, IDLE_THREAD_NAME); } }); } diff --git a/retrofit/src/main/java/retrofit/http/RestAdapter.java b/retrofit/src/main/java/retrofit/http/RestAdapter.java index 1e209138a5..7c67c2d524 100644 --- a/retrofit/src/main/java/retrofit/http/RestAdapter.java +++ b/retrofit/src/main/java/retrofit/http/RestAdapter.java @@ -31,6 +31,7 @@ public class RestAdapter { private static final int LOG_CHUNK_SIZE = 4000; static final String THREAD_PREFIX = "Retrofit-"; + static final String IDLE_THREAD_NAME = THREAD_PREFIX + "Idle"; /** Simple logging abstraction for debug messages. */ public interface Log { @@ -234,6 +235,10 @@ private Object invokeRequest(RestMethodInfo methodDetails, Object[] args) { throw RetrofitError.networkError(url, e); } catch (Throwable t) { throw RetrofitError.unexpectedError(url, t); + } finally { + if (!methodDetails.isSynchronous) { + Thread.currentThread().setName(IDLE_THREAD_NAME); + } } } }
null
train
train
"2013-05-04T04:01:42"
"2013-05-02T18:20:14"
JakeWharton
val
square/retrofit/199_201
square/retrofit
square/retrofit/199
square/retrofit/201
[ "timestamp(timedelta=1.0, similarity=0.889659614331013)" ]
6ce88d01a3264cbbbb5bc94ff3fce0976075f08f
bca23bc0e8e8302945f19c29fb2c2feb95e8adc5
[ "Ah so it looks like the regular expression that matches path params does not accept digits -- `private static final Pattern PATH_PARAMETERS = Pattern.compile(\"\\\\{([a-z_-]+)\\\\}\");` at https://github.com/square/retrofit/blob/master/retrofit/src/main/java/retrofit/http/RestMethodInfo.java#L18.\n\nWas it intentional that path params such as `/foo/{bar1}` not be allowed?\n" ]
[]
"2013-05-09T09:12:18"
[]
Named path params ending with digits should be valid
The following test should pass: https://github.com/matthewmichihara/retrofit/commit/abfade69c7ab213fd07dbcc2604f5942c3324114
[ "retrofit/src/main/java/retrofit/http/RestMethodInfo.java" ]
[ "retrofit/src/main/java/retrofit/http/RestMethodInfo.java" ]
[ "retrofit/src/test/java/retrofit/http/RestMethodInfoTest.java" ]
diff --git a/retrofit/src/main/java/retrofit/http/RestMethodInfo.java b/retrofit/src/main/java/retrofit/http/RestMethodInfo.java index e7ac42b56e..8591265de1 100644 --- a/retrofit/src/main/java/retrofit/http/RestMethodInfo.java +++ b/retrofit/src/main/java/retrofit/http/RestMethodInfo.java @@ -15,7 +15,10 @@ /** Cached details about an interface method. */ final class RestMethodInfo { static final int NO_SINGLE_ENTITY = -1; - private static final Pattern PATH_PARAMETERS = Pattern.compile("\\{([a-z_-]+)\\}"); + + // Matches strings containing lowercase characters, digits, underscores, or hyphens that start + // with a lowercase character in between '{' and '}'. + private static final Pattern PATH_PARAMETERS = Pattern.compile("\\{([a-z][a-z0-9_-]*)\\}"); final Method method; final boolean isSynchronous;
diff --git a/retrofit/src/test/java/retrofit/http/RestMethodInfoTest.java b/retrofit/src/test/java/retrofit/http/RestMethodInfoTest.java index 80255d253c..7591ecfd38 100644 --- a/retrofit/src/test/java/retrofit/http/RestMethodInfoTest.java +++ b/retrofit/src/test/java/retrofit/http/RestMethodInfoTest.java @@ -31,6 +31,8 @@ public class RestMethodInfoTest { expectParams("foo/bar/{taco}/or/{taco}", "taco"); expectParams("foo/bar/{taco-shell}", "taco-shell"); expectParams("foo/bar/{taco_shell}", "taco_shell"); + expectParams("foo/bar/{sha256}", "sha256"); + expectParams("foo/bar/{1}"); // Invalid parameter, name cannot start with digit. } private static void expectParams(String path, String... expected) {
test
train
"2013-05-09T03:24:11"
"2013-05-09T01:44:40"
matthewmichihara
val
square/retrofit/193_223
square/retrofit
square/retrofit/193
square/retrofit/223
[ "keyword_issue_to_pr" ]
b1dc27cb52903b298af02324f1df6468dac37945
7f081c863751bd6b1f9c845d0038d959b74c8946
[ "Is there a standard for object to XML mapping? GSON and Jackson are the canonical JSON mappers, protocol buffers are protocol buffers, etc.\n", "Most common is jaxb. It it is a wreck for generic types. Ex. it forces you to make classes like `Things` as `List<Thing>` isn't possible at top-level. Jackson 2+ has [limited XML support](http://www.cowtowncoder.com/blog/archives/2012/03/entry_467.html).\n\nPersonally, I tend to bite the bullet and write SAX often enough as the shape of XML is often far from ideal forms of java objects, but usually not terribly nested. I concede being weird here.\n", "Once issues #225 and #223 are merged, I'll write an example S3 api.\n", "I think I'll go ahead and work on this now, as it should help make things I've failed to explain earlier more concrete.\n", "closing this PR, as I don't want to distract important change for the sake of optional change.\n" ]
[ "probably need addQueryParam, unless addPathParam implies this. (ex. many signatures are query parameters)\n", "I'm ok leaving this out, but affecting the body of the request often comes up in crappier apis (like SOAP). If we leave this out, I'd need to do it in a custom http impl I think.\n", "I had query in my initial proposal for this. Left it out since it seemed like a strange thing. I don't mind having it for consistency.\n", "Yes, please!\n", "Thanks, @JakeWharton. The use case is temporarily signed Urls have a query\nparam designating the signature.\n\nFor example: \nGET /photos/puppy.jpg?AWSAccessKeyId=AKIAIOSFODNN7EXAMPLE&\n Signature=NpgCjnDzrM%2BWFzoENXmpNDUsSn8%3D&\n Expires=1175139620\n", "What is the signature in that case? Does it require having access to the non-query URL or request body?\n", "Depends oauth, s3, etc have different signing practices. Many need to read\nthe entire request. Some include an md5 header of the body.\n", "For example, s3 needs to read the request method (PUT and GET are very\nimportant to differentiate from a signature pov)\n", "This definitely isn't designed with signing in mind since we provide no access to the underlying request. It's something to consider moving forward, though.\n" ]
"2013-05-25T03:03:41"
[]
XML api sample
Would be nice to be able to easily use retrofit for XML apis like AWS. I'll volunteer to make a sample, if you don't mind giving me pointers as to what might be needed in abstract.
[ "CHANGELOG.md", "pom.xml", "retrofit-samples/github-client/pom.xml", "retrofit-samples/pom.xml", "retrofit/pom.xml", "retrofit/src/main/java/retrofit/RequestBuilder.java", "retrofit/src/main/java/retrofit/RequestHeaders.java", "retrofit/src/main/java/retrofit/RestAdapter.java", "retrofit/src/main/java/retrofit/RestMethodInfo.java" ]
[ "CHANGELOG.md", "pom.xml", "retrofit-samples/github-client/pom.xml", "retrofit-samples/pom.xml", "retrofit/pom.xml", "retrofit/src/main/java/retrofit/RequestBuilder.java", "retrofit/src/main/java/retrofit/RequestInterceptor.java", "retrofit/src/main/java/retrofit/RestAdapter.java", "retrofit/src/main/java/retrofit/RestMethodInfo.java" ]
[ "retrofit/src/test/java/retrofit/RequestBuilderTest.java", "retrofit/src/test/java/retrofit/RestAdapterTest.java", "retrofit/src/test/java/retrofit/RestMethodInfoTest.java" ]
diff --git a/CHANGELOG.md b/CHANGELOG.md index 4ea6cde500..91e269fb94 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,14 @@ Change Log ========== +Version 1.1.0 *(In Development)* +-------------------------------- + + * Introduce `RequestInterceptor` to replace `RequestHeaders`. An interceptor provided to the + `RestAdapter.Builder` will be called for every request and allow setting both headers and + additional path parameter replacements. + + Version 1.0.2 *(2013-05-23)* ---------------------------- diff --git a/pom.xml b/pom.xml index 1ac4386273..19dc9a93db 100644 --- a/pom.xml +++ b/pom.xml @@ -25,7 +25,7 @@ <groupId>com.squareup.retrofit</groupId> <artifactId>parent</artifactId> - <version>1.0.3-SNAPSHOT</version> + <version>1.1.0-SNAPSHOT</version> <packaging>pom</packaging> <name>Retrofit (Parent)</name> diff --git a/retrofit-samples/github-client/pom.xml b/retrofit-samples/github-client/pom.xml index e3653123b3..1ba5ee2d6a 100644 --- a/retrofit-samples/github-client/pom.xml +++ b/retrofit-samples/github-client/pom.xml @@ -6,7 +6,7 @@ <parent> <groupId>com.squareup.retrofit.samples</groupId> <artifactId>parent</artifactId> - <version>1.0.3-SNAPSHOT</version> + <version>1.1.0-SNAPSHOT</version> <relativePath>../pom.xml</relativePath> </parent> diff --git a/retrofit-samples/pom.xml b/retrofit-samples/pom.xml index 682ce75183..622b520634 100644 --- a/retrofit-samples/pom.xml +++ b/retrofit-samples/pom.xml @@ -6,7 +6,7 @@ <parent> <groupId>com.squareup.retrofit</groupId> <artifactId>parent</artifactId> - <version>1.0.3-SNAPSHOT</version> + <version>1.1.0-SNAPSHOT</version> <relativePath>../pom.xml</relativePath> </parent> diff --git a/retrofit/pom.xml b/retrofit/pom.xml index c7bfc0c9c0..8abc2eb4cf 100644 --- a/retrofit/pom.xml +++ b/retrofit/pom.xml @@ -6,7 +6,7 @@ <parent> <groupId>com.squareup.retrofit</groupId> <artifactId>parent</artifactId> - <version>1.0.3-SNAPSHOT</version> + <version>1.1.0-SNAPSHOT</version> <relativePath>../pom.xml</relativePath> </parent> diff --git a/retrofit/src/main/java/retrofit/RequestBuilder.java b/retrofit/src/main/java/retrofit/RequestBuilder.java index dd69c9add0..8847422379 100644 --- a/retrofit/src/main/java/retrofit/RequestBuilder.java +++ b/retrofit/src/main/java/retrofit/RequestBuilder.java @@ -26,180 +26,185 @@ import retrofit.mime.MultipartTypedOutput; import retrofit.mime.TypedOutput; -/** Builds HTTP requests from Java method invocations. */ -final class RequestBuilder { +final class RequestBuilder implements RequestInterceptor.RequestFacade { private final Converter converter; - - private RestMethodInfo methodInfo; - private Object[] args; + private final List<Header> headers; + private final StringBuilder queryParams; + private final String[] paramNames; + private final RestMethodInfo.ParamUsage[] paramUsages; + private final String requestMethod; + private final boolean isSynchronous; + + private final FormUrlEncodedTypedOutput formBody; + private final MultipartTypedOutput multipartBody; + private TypedOutput body; + + private String relativeUrl; private String apiUrl; - private List<retrofit.client.Header> headers; - RequestBuilder(Converter converter) { + RequestBuilder(Converter converter, RestMethodInfo methodInfo) { this.converter = converter; - } - /** Supply cached method metadata info. */ - RequestBuilder methodInfo(RestMethodInfo methodDetails) { - this.methodInfo = methodDetails; - return this; - } + paramNames = methodInfo.requestParamNames; + paramUsages = methodInfo.requestParamUsage; + requestMethod = methodInfo.requestMethod; + isSynchronous = methodInfo.isSynchronous; - /** Base API url. */ - RequestBuilder apiUrl(String apiUrl) { - this.apiUrl = apiUrl; - return this; - } - - /** Arguments from method invocation. */ - RequestBuilder args(Object[] args) { - this.args = args; - return this; - } + headers = new ArrayList<Header>(); + queryParams = new StringBuilder(); - /** A list of custom headers. */ - RequestBuilder headers(List<retrofit.client.Header> headers) { - this.headers = headers; - return this; - } + relativeUrl = methodInfo.requestUrl; - /** - * Construct a {@link Request} from the supplied information. You <strong>must</strong> call - * {@link #methodInfo}, {@link #apiUrl}, {@link #args}, and {@link #headers} before invoking this - * method. - */ - Request build() throws UnsupportedEncodingException { - String apiUrl = this.apiUrl; + String requestQuery = methodInfo.requestQuery; + if (requestQuery != null) { + queryParams.append('?').append(requestQuery); + } - StringBuilder url = new StringBuilder(apiUrl); - if (apiUrl.endsWith("/")) { - // We require relative paths to start with '/'. Prevent a double-slash. - url.deleteCharAt(url.length() - 1); + switch (methodInfo.requestType) { + case FORM_URL_ENCODED: + formBody = new FormUrlEncodedTypedOutput(); + multipartBody = null; + body = formBody; + break; + case MULTIPART: + formBody = null; + multipartBody = new MultipartTypedOutput(); + body = multipartBody; + break; + case SIMPLE: + formBody = null; + multipartBody = null; + // If present, 'body' will be set in 'setArguments' call. + break; + default: + throw new IllegalArgumentException("Unknown request type: " + methodInfo.requestType); } + } - // Append the method relative URL. - url.append(buildRelativeUrl()); + void setApiUrl(String apiUrl) { + this.apiUrl = apiUrl; + } - // Append query parameters, if needed. - if (methodInfo.hasQueryParams) { - boolean first = true; - String requestQuery = methodInfo.requestQuery; - if (requestQuery != null) { - url.append('?').append(requestQuery); - first = false; - } - String[] requestQueryName = methodInfo.requestQueryName; - for (int i = 0; i < requestQueryName.length; i++) { - String query = requestQueryName[i]; - if (query != null) { - Object arg = args[i]; - if (arg != null) { // Null values are skipped. - String value = URLEncoder.encode(String.valueOf(arg), "UTF-8"); - url.append(first ? '?' : '&').append(query).append('=').append(value); - first = false; - } - } - } + @Override public void addHeader(String name, String value) { + if (name == null) { + throw new IllegalArgumentException("Header name must not be null."); } + headers.add(new Header(name, value)); + } - List<retrofit.client.Header> headers = new ArrayList<retrofit.client.Header>(); - if (this.headers != null) { - headers.addAll(this.headers); + @Override public void addPathParam(String name, String value) { + if (name == null) { + throw new IllegalArgumentException("Path replacement name must not be null."); } - List<Header> methodHeaders = methodInfo.headers; - if (methodHeaders != null) { - headers.addAll(methodHeaders); + if (value == null) { + throw new IllegalArgumentException( + "Path replacement \"" + name + "\" value must not be null."); } - // RFC 2616: Header names are case-insensitive. - String[] requestParamHeader = methodInfo.requestParamHeader; - if (requestParamHeader != null) { - for (int i = 0; i < requestParamHeader.length; i++) { - String name = requestParamHeader[i]; - if (name == null) continue; - Object arg = args[i]; - if (arg != null) { - headers.add(new retrofit.client.Header(name, String.valueOf(arg))); - } - } + try { + String encodedValue = URLEncoder.encode(String.valueOf(value), "UTF-8"); + relativeUrl = relativeUrl.replace("{" + name + "}", encodedValue); + } catch (UnsupportedEncodingException e) { + throw new RuntimeException( + "Unable to convert path parameter \"" + name + "\" value to UTF-8:" + value, e); } + } - return new Request(methodInfo.requestMethod, url.toString(), headers, buildBody()); + private void addQueryParam(String name, String value) { + if (name == null) { + throw new IllegalArgumentException("Query param name must not be null."); + } + if (value == null) { + throw new IllegalArgumentException("Query param \"" + name + "\" value must not be null."); + } + try { + value = URLEncoder.encode(String.valueOf(value), "UTF-8"); + StringBuilder queryParams = this.queryParams; + queryParams.append(queryParams.length() > 0 ? '&' : '?'); + queryParams.append(name).append('=').append(value); + } catch (UnsupportedEncodingException e) { + throw new RuntimeException( + "Unable to convert query parameter \"" + name + "\" value to UTF-8: " + value, e); + } } - /** Create the final relative URL by performing parameter replacement. */ - private String buildRelativeUrl() throws UnsupportedEncodingException { - String replacedPath = methodInfo.requestUrl; - String[] requestUrlParam = methodInfo.requestUrlParam; - for (int i = 0; i < requestUrlParam.length; i++) { - String param = requestUrlParam[i]; - if (param != null) { - Object arg = args[i]; - if (arg == null) { - throw new IllegalArgumentException("Path parameters must not be null: " + param + "."); - } - String value = URLEncoder.encode(String.valueOf(arg), "UTF-8"); - replacedPath = replacedPath.replace("{" + param + "}", value); + void setArguments(Object[] args) { + if (args == null) { + return; + } + int count = args.length; + if (!isSynchronous) { + count -= 1; + } + for (int i = 0; i < count; i++) { + String name = paramNames[i]; + Object value = args[i]; + RestMethodInfo.ParamUsage paramUsage = paramUsages[i]; + switch (paramUsage) { + case PATH: + if (value == null) { + throw new IllegalArgumentException( + "Path parameter \"" + name + "\" value must not be null."); + } + addPathParam(name, value.toString()); + break; + case QUERY: + if (value != null) { // Skip null values. + addQueryParam(name, value.toString()); + } + break; + case HEADER: + if (value != null) { // Skip null values. + addHeader(name, value.toString()); + } + break; + case FIELD: + if (value != null) { // Skip null values. + formBody.addField(name, value.toString()); + } + break; + case PART: + if (value == null) { + throw new IllegalArgumentException( + "Multipart part \"" + name + "\" value must not be null."); + } + if (value instanceof TypedOutput) { + multipartBody.addPart(name, (TypedOutput) value); + } else { + multipartBody.addPart(name, converter.toBody(value)); + } + break; + case BODY: + if (value == null) { + throw new IllegalArgumentException("Body parameter value must not be null."); + } + if (value instanceof TypedOutput) { + body = (TypedOutput) value; + } else { + body = converter.toBody(value); + } + break; + default: + throw new IllegalArgumentException("Unknown parameter usage: " + paramUsage); } } - return replacedPath; } - /** Create the request body using the method info and invocation arguments. */ - private TypedOutput buildBody() { - switch (methodInfo.requestType) { - case SIMPLE: { - int bodyIndex = methodInfo.bodyIndex; - if (bodyIndex == RestMethodInfo.NO_BODY) { - return null; - } - Object body = args[bodyIndex]; - if (body == null) { - throw new IllegalArgumentException("Body must not be null."); - } - if (body instanceof TypedOutput) { - return (TypedOutput) body; - } else { - return converter.toBody(body); - } - } + Request build() throws UnsupportedEncodingException { + String apiUrl = this.apiUrl; - case FORM_URL_ENCODED: { - FormUrlEncodedTypedOutput body = new FormUrlEncodedTypedOutput(); - String[] requestFormFields = methodInfo.requestFormFields; - for (int i = 0; i < requestFormFields.length; i++) { - String name = requestFormFields[i]; - if (name != null) { - Object value = args[i]; - if (value != null) { // Null values are skipped. - body.addField(name, String.valueOf(value)); - } - } - } - return body; - } + StringBuilder url = new StringBuilder(apiUrl); + if (apiUrl.endsWith("/")) { + // We require relative paths to start with '/'. Prevent a double-slash. + url.deleteCharAt(url.length() - 1); + } - case MULTIPART: { - MultipartTypedOutput body = new MultipartTypedOutput(); - String[] requestMultipartPart = methodInfo.requestMultipartPart; - for (int i = 0; i < requestMultipartPart.length; i++) { - String name = requestMultipartPart[i]; - if (name != null) { - Object value = args[i]; - if (value == null) { - throw new IllegalArgumentException("Multipart part must not be null: " + name + "."); - } - if (value instanceof TypedOutput) { - body.addPart(name, (TypedOutput) value); - } else { - body.addPart(name, converter.toBody(value)); - } - } - } - return body; - } + url.append(relativeUrl); - default: - throw new IllegalArgumentException("Unknown request type " + methodInfo.requestType); + StringBuilder queryParams = this.queryParams; + if (queryParams.length() > 0) { + url.append(queryParams); } + + return new Request(requestMethod, url.toString(), headers, body); } } diff --git a/retrofit/src/main/java/retrofit/RequestHeaders.java b/retrofit/src/main/java/retrofit/RequestHeaders.java deleted file mode 100644 index c1bef05d5e..0000000000 --- a/retrofit/src/main/java/retrofit/RequestHeaders.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright (C) 2013 Square, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package retrofit; - -import java.util.Collections; -import java.util.List; -import retrofit.client.Header; - -/** Manages headers for each request. */ -public interface RequestHeaders { - /** - * Get a list of headers for a request. This method will be called once for each request allowing - * you to change the list as the state of your application changes. - */ - List<Header> get(); - - /** Empty header list. */ - RequestHeaders NONE = new RequestHeaders() { - @Override public List<Header> get() { - return Collections.emptyList(); - } - }; -} diff --git a/retrofit/src/main/java/retrofit/RequestInterceptor.java b/retrofit/src/main/java/retrofit/RequestInterceptor.java new file mode 100644 index 0000000000..d5b1d09538 --- /dev/null +++ b/retrofit/src/main/java/retrofit/RequestInterceptor.java @@ -0,0 +1,25 @@ +package retrofit; + +/** Intercept every request before it is executed in order to add additional data. */ +public interface RequestInterceptor { + /** Called for every request. Add data using methods on the supplied {@link RequestFacade}. */ + void intercept(RequestFacade request); + + interface RequestFacade { + /** Add a header to the request. This will not replace any existing headers. */ + void addHeader(String name, String value); + + /** + * Add a path parameter replacement. This works exactly like a {@link retrofit.http.Part + * &#64;Part}-annotated method argument. + */ + void addPathParam(String name, String value); + } + + /** A {@link RequestInterceptor} which does no modification of requests. */ + RequestInterceptor NONE = new RequestInterceptor() { + @Override public void intercept(RequestFacade request) { + // Do nothing. + } + }; +} diff --git a/retrofit/src/main/java/retrofit/RestAdapter.java b/retrofit/src/main/java/retrofit/RestAdapter.java index 8b549fc760..a447a0fc22 100644 --- a/retrofit/src/main/java/retrofit/RestAdapter.java +++ b/retrofit/src/main/java/retrofit/RestAdapter.java @@ -117,7 +117,7 @@ public interface Log { private final Client.Provider clientProvider; private final Executor httpExecutor; private final Executor callbackExecutor; - private final RequestHeaders requestHeaders; + private final RequestInterceptor requestInterceptor; private final Converter converter; private final Profiler profiler; private final ErrorHandler errorHandler; @@ -125,13 +125,13 @@ public interface Log { private volatile boolean debug; private RestAdapter(Server server, Client.Provider clientProvider, Executor httpExecutor, - Executor callbackExecutor, RequestHeaders requestHeaders, Converter converter, + Executor callbackExecutor, RequestInterceptor requestInterceptor, Converter converter, Profiler profiler, ErrorHandler errorHandler, Log log, boolean debug) { this.server = server; this.clientProvider = clientProvider; this.httpExecutor = httpExecutor; this.callbackExecutor = callbackExecutor; - this.requestHeaders = requestHeaders; + this.requestInterceptor = requestInterceptor; this.converter = converter; this.profiler = profiler; this.errorHandler = errorHandler; @@ -214,12 +214,13 @@ private Object invokeRequest(RestMethodInfo methodDetails, Object[] args) { String serverUrl = server.getUrl(); String url = serverUrl; // Keep some url in case RequestBuilder throws an exception. try { - Request request = new RequestBuilder(converter) // - .apiUrl(serverUrl) // - .args(args) // - .headers(requestHeaders.get()) // - .methodInfo(methodDetails) // - .build(); + RequestBuilder requestBuilder = new RequestBuilder(converter, methodDetails); + requestBuilder.setApiUrl(serverUrl); + requestBuilder.setArguments(args); + + requestInterceptor.intercept(requestBuilder); + + Request request = requestBuilder.build(); url = request.getUrl(); if (!methodDetails.isSynchronous) { @@ -408,7 +409,7 @@ public static class Builder { private Client.Provider clientProvider; private Executor httpExecutor; private Executor callbackExecutor; - private RequestHeaders requestHeaders; + private RequestInterceptor requestInterceptor; private Converter converter; private Profiler profiler; private ErrorHandler errorHandler; @@ -473,12 +474,12 @@ public Builder setExecutors(Executor httpExecutor, Executor callbackExecutor) { return this; } - /** */ - public Builder setRequestHeaders(RequestHeaders requestHeaders) { - if (requestHeaders == null) { - throw new NullPointerException("Request headers may not be null."); + /** A request interceptor for adding data to every request. */ + public Builder setRequestInterceptor(RequestInterceptor requestInterceptor) { + if (requestInterceptor == null) { + throw new NullPointerException("Request interceptor may not be null."); } - this.requestHeaders = requestHeaders; + this.requestInterceptor = requestInterceptor; return this; } @@ -533,8 +534,8 @@ public RestAdapter build() { throw new IllegalArgumentException("Server may not be null."); } ensureSaneDefaults(); - return new RestAdapter(server, clientProvider, httpExecutor, callbackExecutor, requestHeaders, - converter, profiler, errorHandler, log, debug); + return new RestAdapter(server, clientProvider, httpExecutor, callbackExecutor, + requestInterceptor, converter, profiler, errorHandler, log, debug); } private void ensureSaneDefaults() { @@ -556,8 +557,8 @@ private void ensureSaneDefaults() { if (log == null) { log = Platform.get().defaultLog(); } - if (requestHeaders == null) { - requestHeaders = RequestHeaders.NONE; + if (requestInterceptor == null) { + requestInterceptor = RequestInterceptor.NONE; } } } diff --git a/retrofit/src/main/java/retrofit/RestMethodInfo.java b/retrofit/src/main/java/retrofit/RestMethodInfo.java index dfdeffd210..809f6aac44 100644 --- a/retrofit/src/main/java/retrofit/RestMethodInfo.java +++ b/retrofit/src/main/java/retrofit/RestMethodInfo.java @@ -39,13 +39,15 @@ /** Request metadata about a service interface declaration. */ final class RestMethodInfo { - static final int NO_BODY = -1; - // Upper and lower characters, digits, underscores, and hyphens, starting with a character. private static final String PARAM = "[a-zA-Z][a-zA-Z0-9_-]*"; private static final Pattern PARAM_NAME_REGEX = Pattern.compile(PARAM); private static final Pattern PARAM_URL_REGEX = Pattern.compile("\\{(" + PARAM + ")\\}"); + enum ParamUsage { + PATH, QUERY, FIELD, PART, BODY, HEADER + } + enum RequestType { /** No content-specific logic required. */ SIMPLE, @@ -71,13 +73,8 @@ enum RequestType { List<retrofit.client.Header> headers; // Parameter-level details - String[] requestUrlParam; - String[] requestQueryName; - boolean hasQueryParams = false; - String[] requestFormFields; - String[] requestMultipartPart; - String[] requestParamHeader; - int bodyIndex = NO_BODY; + String[] requestParamNames; + ParamUsage[] requestParamUsage; RestMethodInfo(Method method) { this.method = method; @@ -189,7 +186,6 @@ private void parsePath(String path) { if (question != -1 && question < path.length() - 1) { url = path.substring(0, question); query = path.substring(question + 1); - hasQueryParams = true; // Ensure the query string does not have any named parameters. Matcher queryParamMatcher = PARAM_URL_REGEX.matcher(query); @@ -282,8 +278,7 @@ private boolean parseResponseType() { } /** - * Loads {@link #requestUrlParam}, {@link #requestQueryName}, {@link #requestFormFields}, - * {@link #requestMultipartPart}, and {@link #requestParamHeader}. Must be called after + * Loads {@link #requestParamNames} and {@link #requestParamUsage}. Must be called after * {@link #parseMethodAnnotations()}. */ private void parseParameters() { @@ -295,17 +290,16 @@ private void parseParameters() { count -= 1; // Callback is last argument when not a synchronous method. } - String[] urlParam = new String[count]; - String[] queryName = new String[count]; - String[] formValue = new String[count]; - String[] multipartPart = new String[count]; - String[] paramHeader = new String[count]; + String[] paramNames = new String[count]; + requestParamNames = paramNames; + ParamUsage[] paramUsage = new ParamUsage[count]; + requestParamUsage = paramUsage; + boolean gotField = false; boolean gotPart = false; + boolean gotBody = false; for (int i = 0; i < count; i++) { - boolean hasRetrofitAnnotation = false; - Class<?> parameterType = parameterTypes[i]; Annotation[] parameterAnnotations = parameterAnnotationArrays[i]; if (parameterAnnotations != null) { @@ -313,7 +307,6 @@ private void parseParameters() { Class<? extends Annotation> annotationType = parameterAnnotation.annotationType(); if (annotationType == Path.class) { - hasRetrofitAnnotation = true; String name = ((Path) parameterAnnotation).value(); if (!PARAM_NAME_REGEX.matcher(name).matches()) { @@ -328,21 +321,21 @@ private void parseParameters() { "Method URL \"" + requestUrl + "\" does not contain {" + name + "}."); } - urlParam[i] = name; + paramNames[i] = name; + paramUsage[i] = ParamUsage.PATH; } else if (annotationType == Query.class) { - hasRetrofitAnnotation = true; - hasQueryParams = true; String name = ((Query) parameterAnnotation).value(); - queryName[i] = name; + paramNames[i] = name; + paramUsage[i] = ParamUsage.QUERY; } else if (annotationType == Header.class) { String name = ((Header) parameterAnnotation).value(); if (parameterType != String.class) { throw new IllegalStateException("@Header parameter type must be String: " + name); } - hasRetrofitAnnotation = true; - paramHeader[i] = name; + paramNames[i] = name; + paramUsage[i] = ParamUsage.HEADER; } else if (annotationType == Field.class) { if (requestType != RequestType.FORM_URL_ENCODED) { throw new IllegalStateException( @@ -352,8 +345,8 @@ private void parseParameters() { String name = ((Field) parameterAnnotation).value(); gotField = true; - hasRetrofitAnnotation = true; - formValue[i] = name; + paramNames[i] = name; + paramUsage[i] = ParamUsage.FIELD; } else if (annotationType == Part.class) { if (requestType != RequestType.MULTIPART) { throw new IllegalStateException( @@ -363,31 +356,31 @@ private void parseParameters() { String name = ((Part) parameterAnnotation).value(); gotPart = true; - hasRetrofitAnnotation = true; - multipartPart[i] = name; + paramNames[i] = name; + paramUsage[i] = ParamUsage.PART; } else if (annotationType == Body.class) { if (requestType != RequestType.SIMPLE) { throw new IllegalStateException( "@Body parameters cannot be used with form or multi-part encoding."); } - if (bodyIndex != NO_BODY) { + if (gotBody) { throw new IllegalStateException( "Method annotated with multiple Body method annotations: " + method); } - hasRetrofitAnnotation = true; - bodyIndex = i; + gotBody = true; + paramUsage[i] = ParamUsage.BODY; } } } - if (!hasRetrofitAnnotation) { + if (paramUsage[i] == null) { throw new IllegalStateException( - "No annotations found on parameter " + (i + 1) + " of " + method.getName()); + "No Retrofit annotation found on parameter " + (i + 1) + " of " + method.getName()); } } - if (requestType == RequestType.SIMPLE && !requestHasBody && bodyIndex != NO_BODY) { + if (requestType == RequestType.SIMPLE && !requestHasBody && gotBody) { throw new IllegalStateException("Non-body HTTP method cannot contain @Body or @TypedOutput."); } if (requestType == RequestType.FORM_URL_ENCODED && !gotField) { @@ -396,12 +389,6 @@ private void parseParameters() { if (requestType == RequestType.MULTIPART && !gotPart) { throw new IllegalStateException("Multipart method must contain at least one @Part."); } - - requestUrlParam = urlParam; - requestQueryName = queryName; - requestFormFields = formValue; - requestMultipartPart = multipartPart; - requestParamHeader = paramHeader; } /**
diff --git a/retrofit/src/test/java/retrofit/RequestBuilderTest.java b/retrofit/src/test/java/retrofit/RequestBuilderTest.java index 0f0b207569..11fe09615d 100644 --- a/retrofit/src/test/java/retrofit/RequestBuilderTest.java +++ b/retrofit/src/test/java/retrofit/RequestBuilderTest.java @@ -21,7 +21,13 @@ import static org.fest.assertions.api.Assertions.assertThat; import static org.fest.assertions.api.Assertions.fail; -import static retrofit.RestMethodInfo.NO_BODY; +import static retrofit.RestMethodInfo.ParamUsage; +import static retrofit.RestMethodInfo.ParamUsage.BODY; +import static retrofit.RestMethodInfo.ParamUsage.FIELD; +import static retrofit.RestMethodInfo.ParamUsage.HEADER; +import static retrofit.RestMethodInfo.ParamUsage.PART; +import static retrofit.RestMethodInfo.ParamUsage.PATH; +import static retrofit.RestMethodInfo.ParamUsage.QUERY; import static retrofit.RestMethodInfo.RequestType; public class RequestBuilderTest { @@ -60,7 +66,7 @@ public class RequestBuilderTest { .build(); fail("Null path parameters not allowed."); } catch (IllegalArgumentException e) { - assertThat(e.getMessage()).isEqualTo("Path parameters must not be null: ping."); + assertThat(e.getMessage()).isEqualTo("Path parameter \"ping\" value must not be null."); } } @@ -78,12 +84,12 @@ public class RequestBuilderTest { } @Test public void queryParamOptional() throws Exception { - Request request1 = new Helper() // - .setMethod("GET") // - .setUrl("http://example.com") // - .setPath("/foo/bar/") // - .addQueryParam("ping", null) // - .build(); + Request request1 = new Helper() // + .setMethod("GET") // + .setUrl("http://example.com") // + .setPath("/foo/bar/") // + .addQueryParam("ping", null) // + .build(); assertThat(request1.getUrl()).isEqualTo("http://example.com/foo/bar/"); Request request2 = new Helper() // @@ -233,7 +239,7 @@ public class RequestBuilderTest { .build(); fail("Null body not allowed."); } catch (IllegalArgumentException e) { - assertThat(e.getMessage()).isEqualTo("Body must not be null."); + assertThat(e.getMessage()).isEqualTo("Body parameter value must not be null."); } } @@ -292,7 +298,7 @@ public class RequestBuilderTest { .build(); fail("Null multipart part is not allowed."); } catch (IllegalArgumentException e) { - assertThat(e.getMessage()).isEqualTo("Multipart part must not be null: ping."); + assertThat(e.getMessage()).isEqualTo("Multipart part \"ping\" value must not be null."); } } @@ -318,7 +324,7 @@ public class RequestBuilderTest { .setFormEncoded() // .addField("foo", "bar") // .addField("ping", null) // - .addField("kit", "kat") + .addField("kit", "kat") // .build(); assertTypedBytes(request.getBody(), "foo=bar&kit=kat"); } @@ -390,17 +396,12 @@ private static class Helper { private RequestType requestType = RequestType.SIMPLE; private String method; private boolean hasBody = false; - private boolean hasQueryParams = false; private String path; private String query; - private final List<String> pathParams = new ArrayList<String>(); - private final List<String> queryParams = new ArrayList<String>(); - private final List<String> fieldParams = new ArrayList<String>(); - private final List<String> partParams = new ArrayList<String>(); - private final List<String> headerParams = new ArrayList<String>(); + private final List<String> paramNames = new ArrayList<String>(); + private final List<ParamUsage> paramUsages = new ArrayList<ParamUsage>(); private final List<Object> args = new ArrayList<Object>(); private final List<Header> headers = new ArrayList<Header>(); - private int bodyIndex = NO_BODY; private String url; Helper setMethod(String method) { @@ -425,49 +426,48 @@ Helper setPath(String path) { Helper setQuery(String query) { this.query = query; - hasQueryParams = true; return this; } - private void addParam(String path, String query, String field, String part, String header, - Object value) { - pathParams.add(path); - queryParams.add(query); - fieldParams.add(field); - partParams.add(part); - headerParams.add(header); - args.add(value); - } - Helper addPathParam(String name, Object value) { - addParam(name, null, null, null, null, value); + paramNames.add(name); + paramUsages.add(PATH); + args.add(value); return this; } Helper addQueryParam(String name, String value) { - addParam(null, name, null, null, null, value); - hasQueryParams = true; + paramNames.add(name); + paramUsages.add(QUERY); + args.add(value); return this; } Helper addField(String name, String value) { - addParam(null, null, name, null, null, value); + paramNames.add(name); + paramUsages.add(FIELD); + args.add(value); return this; } Helper addPart(String name, Object value) { - addParam(null, null, null, name, null, value); + paramNames.add(name); + paramUsages.add(PART); + args.add(value); return this; } Helper setBody(Object value) { - addParam(null, null, null, null, null, value); - bodyIndex = args.size() - 1; + paramNames.add(null); + paramUsages.add(BODY); + args.add(value); return this; } Helper addHeaderParam(String name, Object value) { - addParam(null, null, null, null, name, value); + paramNames.add(name); + paramUsages.add(HEADER); + args.add(value); return this; } @@ -503,21 +503,20 @@ Request build() throws Exception { methodInfo.requestUrl = path; methodInfo.requestUrlParamNames = RestMethodInfo.parsePathParameters(path); methodInfo.requestQuery = query; - methodInfo.hasQueryParams = hasQueryParams; - methodInfo.requestUrlParam = pathParams.toArray(new String[pathParams.size()]); - methodInfo.requestQueryName = queryParams.toArray(new String[queryParams.size()]); - methodInfo.requestFormFields = fieldParams.toArray(new String[fieldParams.size()]); - methodInfo.requestMultipartPart = partParams.toArray(new String[partParams.size()]); - methodInfo.requestParamHeader = headerParams.toArray(new String[headerParams.size()]); - methodInfo.bodyIndex = bodyIndex; + methodInfo.requestParamNames = paramNames.toArray(new String[paramNames.size()]); + methodInfo.requestParamUsage = paramUsages.toArray(new ParamUsage[paramUsages.size()]); methodInfo.loaded = true; - return new RequestBuilder(GSON) // - .apiUrl(url) - .headers(headers) - .args(args.toArray(new Object[args.size()])) - .methodInfo(methodInfo) - .build(); + RequestBuilder requestBuilder = new RequestBuilder(GSON, methodInfo); + + for (Header header : headers) { + requestBuilder.addHeader(header.getName(), header.getValue()); + } + + requestBuilder.setApiUrl(url); + requestBuilder.setArguments(args.toArray(new Object[args.size()])); + + return requestBuilder.build(); } @SuppressWarnings("UnusedDeclaration") // Accessed via reflection. diff --git a/retrofit/src/test/java/retrofit/RestAdapterTest.java b/retrofit/src/test/java/retrofit/RestAdapterTest.java index e880cca809..bf6d603f0b 100644 --- a/retrofit/src/test/java/retrofit/RestAdapterTest.java +++ b/retrofit/src/test/java/retrofit/RestAdapterTest.java @@ -209,8 +209,7 @@ public void log(String message) { @Test public void asynchronousUsesExecutors() throws Exception { Response response = new Response(200, "OK", NO_HEADERS, new TypedString("{}")); - when(mockClient.execute(any(Request.class))) // - .thenReturn(response); + when(mockClient.execute(any(Request.class))).thenReturn(response); Callback<Object> callback = mock(Callback.class); example.something(callback); diff --git a/retrofit/src/test/java/retrofit/RestMethodInfoTest.java b/retrofit/src/test/java/retrofit/RestMethodInfoTest.java index 3659165b54..064c450d97 100644 --- a/retrofit/src/test/java/retrofit/RestMethodInfoTest.java +++ b/retrofit/src/test/java/retrofit/RestMethodInfoTest.java @@ -32,7 +32,10 @@ import static java.lang.annotation.RetentionPolicy.RUNTIME; import static org.fest.assertions.api.Assertions.assertThat; import static org.junit.Assert.fail; -import static retrofit.RestMethodInfo.NO_BODY; +import static retrofit.RestMethodInfo.ParamUsage.BODY; +import static retrofit.RestMethodInfo.ParamUsage.HEADER; +import static retrofit.RestMethodInfo.ParamUsage.PATH; +import static retrofit.RestMethodInfo.ParamUsage.QUERY; import static retrofit.RestMethodInfo.RequestType.MULTIPART; import static retrofit.RestMethodInfo.RequestType.SIMPLE; @@ -356,7 +359,7 @@ class Example { assertThat(methodInfo.requestUrl).isEqualTo("/foo"); } - @Test public void singleQueryParam() { + @Test public void singlePathQueryParam() { class Example { @GET("/foo?a=b") Response a() { @@ -383,15 +386,12 @@ class Example { RestMethodInfo methodInfo = new RestMethodInfo(method); methodInfo.init(); - assertThat(methodInfo.requestUrlParam).isEmpty(); - assertThat(methodInfo.requestQueryName).isEmpty(); - assertThat(methodInfo.requestFormFields).isEmpty(); - assertThat(methodInfo.requestMultipartPart).isEmpty(); - assertThat(methodInfo.bodyIndex).isEqualTo(NO_BODY); + assertThat(methodInfo.requestParamNames).isEmpty(); + assertThat(methodInfo.requestParamUsage).isEmpty(); assertThat(methodInfo.requestType).isEqualTo(SIMPLE); } - @Test public void singleParam() { + @Test public void singleQueryParam() { class Example { @GET("/") Response a(@Query("a") String a) { return null; @@ -402,12 +402,12 @@ class Example { RestMethodInfo methodInfo = new RestMethodInfo(method); methodInfo.init(); - assertThat(methodInfo.requestQueryName).hasSize(1).containsSequence("a"); - assertThat(methodInfo.bodyIndex).isEqualTo(NO_BODY); + assertThat(methodInfo.requestParamNames).hasSize(1).containsExactly("a"); + assertThat(methodInfo.requestParamUsage).hasSize(1).containsExactly(QUERY); assertThat(methodInfo.requestType).isEqualTo(SIMPLE); } - @Test public void multipleParams() { + @Test public void multipleQueryParams() { class Example { @GET("/") Response a(@Query("a") String a, @Query("b") String b, @Query("c") String c) { return null; @@ -418,8 +418,8 @@ class Example { RestMethodInfo methodInfo = new RestMethodInfo(method); methodInfo.init(); - assertThat(methodInfo.requestQueryName).hasSize(3).containsSequence("a", "b", "c"); - assertThat(methodInfo.bodyIndex).isEqualTo(NO_BODY); + assertThat(methodInfo.requestParamNames).hasSize(3).containsExactly("a", "b", "c"); + assertThat(methodInfo.requestParamUsage).hasSize(3).containsExactly(QUERY, QUERY, QUERY); assertThat(methodInfo.requestType).isEqualTo(SIMPLE); } @@ -434,11 +434,8 @@ class Example { RestMethodInfo methodInfo = new RestMethodInfo(method); methodInfo.init(); - assertThat(methodInfo.requestUrlParam).containsOnly(new String[] { null }); - assertThat(methodInfo.requestQueryName).containsOnly(new String[] { null }); - assertThat(methodInfo.requestFormFields).containsOnly(new String[] { null }); - assertThat(methodInfo.requestMultipartPart).containsOnly(new String[] { null }); - assertThat(methodInfo.bodyIndex).isEqualTo(0); + assertThat(methodInfo.requestParamNames).hasSize(1).containsExactly(new String[] { null }); + assertThat(methodInfo.requestParamUsage).hasSize(1).containsExactly(BODY); assertThat(methodInfo.requestType).isEqualTo(SIMPLE); } @@ -453,11 +450,8 @@ class Example { RestMethodInfo methodInfo = new RestMethodInfo(method); methodInfo.init(); - assertThat(methodInfo.requestUrlParam).containsOnly(new String[] { null }); - assertThat(methodInfo.requestQueryName).containsOnly(new String[] { null }); - assertThat(methodInfo.requestFormFields).containsOnly(new String[] { null }); - assertThat(methodInfo.requestMultipartPart).containsOnly(new String[] { null }); - assertThat(methodInfo.bodyIndex).isEqualTo(0); + assertThat(methodInfo.requestParamNames).hasSize(1).containsExactly(new String[] { null }); + assertThat(methodInfo.requestParamUsage).hasSize(1).containsExactly(BODY); assertThat(methodInfo.requestType).isEqualTo(SIMPLE); } @@ -484,11 +478,8 @@ class Example { RestMethodInfo methodInfo = new RestMethodInfo(method); methodInfo.init(); - assertThat(methodInfo.requestUrlParam).containsExactly("a", null, "c"); - assertThat(methodInfo.requestQueryName).containsExactly(null, null, null); - assertThat(methodInfo.requestFormFields).containsExactly(null, null, null); - assertThat(methodInfo.requestMultipartPart).containsExactly(null, null, null); - assertThat(methodInfo.bodyIndex).isEqualTo(1); + assertThat(methodInfo.requestParamNames).containsExactly("a", null, "c"); + assertThat(methodInfo.requestParamUsage).containsExactly(PATH, BODY, PATH); assertThat(methodInfo.requestType).isEqualTo(SIMPLE); } @@ -712,8 +703,8 @@ Response a(@Header("a") String a, @Header("b") String b) { RestMethodInfo methodInfo = new RestMethodInfo(method); methodInfo.init(); - assertThat(Arrays.asList(methodInfo.requestParamHeader)) - .isEqualTo(Arrays.asList("a", "b")); + assertThat(methodInfo.requestParamNames).containsExactly("a", "b"); + assertThat(methodInfo.requestParamUsage).containsExactly(HEADER, HEADER); } @Test(expected = IllegalStateException.class)
train
train
"2013-06-03T08:52:03"
"2013-05-07T19:05:14"
codefromthecrypt
val
square/retrofit/221_246
square/retrofit
square/retrofit/221
square/retrofit/246
[ "timestamp(timedelta=0.0, similarity=0.8643421939391179)", "keyword_pr_to_issue" ]
c7484864352c6367300a5ae398880450d6b843ff
738e41c113c0429d6ae51d68d5f55c79d5988c15
[ "Yep. Good catch!\n", "Is there any method allowing custom timeout value in retrofit?\n", "@uKL No. It's an HTTP client configuration and thus should be configured there. We will provide defaults for use with the default HTTP clients, though.\n", "Roger that. So I'll have to implement _Client_ interface and create my own Http client. Do you think it's a good idea to extend _UrlConnectionClient_ and just deal with protected _HttpURLConnection openConnection(Request request)_ method?\n", "Yes. That's a good strategy for `HttpUrlConnection`. If you're using OkHttp or Apache HttpClient you can configure the client and just pass it to the client constructor.\n\n``` java\nOkHttpClient ok = new OkHttpClient();\n// TODO configure timeouts and such\n\nRestAdapter ra = new RestAdapter.Builder()\n .client(new OkClient(ok))\n .build();\n```\n", "Thanks. Anyway, personally I think that the `Client` interface should implement some common stuff like timeouts. After digging in the source code, it'd be useful if I'd be able to use default implementation of `Platform.defaultClient()` and still be able to set most commonly used values.\n", "Hi, I having the same request. I try to configure the timeout by myself as @JakeWharton indicates in the previous comment, but I cannot set the HttpParams to OkHttpClient.\n\nI tried something like:\n\nHttpParams httpParams = new BasicHttpParams();\n HttpConnectionParams.setConnectionTimeout(httpParams, CONNECTION_TIMEOUT);\n DefaultHttpClient client = new DefaultHttpClient(httpParams);\n\nBut then I cannot set the client to RestAdapter. Any ideas?\n\nThx!\n", "``` java\nRestAdapter r = new RestAdapter.Builder()\n .setSever(...)\n .setClient(new ApacheClient(client))\n .build();\n```\n", "How can I configure an `OkHttpClient` to use custom timeouts? Should I extend the `OkClient` from retrofit to set the timeouts for each `HttpURLConnection` created via `UrlConnectionClient.openConnection(Request)` ?\n", "You don't need to extend.\n\n``` java\nOkHttpClient client = new OkHttpClient();\nclient.setBlahTimeout(1234);\n\nRestAdapter r = new RestAdapter.Builder()\n .setServer(..)\n .setClient(new OkClient(client))\n .build();\n```\n", "I lied. You need to subclass!\n", "Thx, I got it.\n" ]
[]
"2013-06-24T23:05:26"
[]
UrlConnectionClient default timeouts behavior
I think that the connection and read timeout in `UrlConnectionClient.java` should be set to specific values other than the defaults. With OkHttp the default are 0 for both of them. The [documentation](http://developer.android.com/reference/java/net/URLConnection.html#setReadTimeout%28int%29) for ReadTimeout says: > Sets the maximum time to wait for an input stream read to complete before giving up. Reading will fail with a SocketTimeoutException if the timeout elapses before data becomes available. The default value of 0 disables read timeouts; read attempts will block indefinitely. This might not be what we want as a default behavior. Maybe this apply to Picasso also..
[ "retrofit/src/main/java/retrofit/client/ApacheClient.java", "retrofit/src/main/java/retrofit/client/OkClient.java", "retrofit/src/main/java/retrofit/client/UrlConnectionClient.java" ]
[ "retrofit/src/main/java/retrofit/client/ApacheClient.java", "retrofit/src/main/java/retrofit/client/Defaults.java", "retrofit/src/main/java/retrofit/client/OkClient.java", "retrofit/src/main/java/retrofit/client/UrlConnectionClient.java" ]
[]
diff --git a/retrofit/src/main/java/retrofit/client/ApacheClient.java b/retrofit/src/main/java/retrofit/client/ApacheClient.java index 1b75da3d19..480f1cd14c 100644 --- a/retrofit/src/main/java/retrofit/client/ApacheClient.java +++ b/retrofit/src/main/java/retrofit/client/ApacheClient.java @@ -32,17 +32,27 @@ import org.apache.http.entity.AbstractHttpEntity; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicHeader; +import org.apache.http.params.BasicHttpParams; +import org.apache.http.params.HttpConnectionParams; +import org.apache.http.params.HttpParams; import org.apache.http.util.EntityUtils; import retrofit.mime.TypedByteArray; import retrofit.mime.TypedOutput; /** A {@link Client} which uses an implementation of Apache's {@link HttpClient}. */ public class ApacheClient implements Client { + private static HttpClient createDefaultClient() { + HttpParams params = new BasicHttpParams(); + HttpConnectionParams.setConnectionTimeout(params, Defaults.CONNECT_TIMEOUT); + HttpConnectionParams.setSoTimeout(params, Defaults.READ_TIMEOUT); + return new DefaultHttpClient(params); + } + private final HttpClient client; /** Creates an instance backed by {@link DefaultHttpClient}. */ public ApacheClient() { - this(new DefaultHttpClient()); + this(createDefaultClient()); } public ApacheClient(HttpClient client) { diff --git a/retrofit/src/main/java/retrofit/client/Defaults.java b/retrofit/src/main/java/retrofit/client/Defaults.java new file mode 100644 index 0000000000..95de30500e --- /dev/null +++ b/retrofit/src/main/java/retrofit/client/Defaults.java @@ -0,0 +1,6 @@ +package retrofit.client; + +class Defaults { + static final int CONNECT_TIMEOUT = 15 * 1000; // 15s + static final int READ_TIMEOUT = 20 * 1000; // 20s +} diff --git a/retrofit/src/main/java/retrofit/client/OkClient.java b/retrofit/src/main/java/retrofit/client/OkClient.java index 122fb55edb..6286cdd6c3 100644 --- a/retrofit/src/main/java/retrofit/client/OkClient.java +++ b/retrofit/src/main/java/retrofit/client/OkClient.java @@ -33,6 +33,9 @@ public OkClient(OkHttpClient client) { } @Override protected HttpURLConnection openConnection(Request request) throws IOException { - return client.open(new URL(request.getUrl())); + HttpURLConnection connection = client.open(new URL(request.getUrl())); + connection.setConnectTimeout(Defaults.CONNECT_TIMEOUT); + connection.setReadTimeout(Defaults.READ_TIMEOUT); + return connection; } } diff --git a/retrofit/src/main/java/retrofit/client/UrlConnectionClient.java b/retrofit/src/main/java/retrofit/client/UrlConnectionClient.java index fcca8c4846..d7375d8b29 100644 --- a/retrofit/src/main/java/retrofit/client/UrlConnectionClient.java +++ b/retrofit/src/main/java/retrofit/client/UrlConnectionClient.java @@ -34,7 +34,11 @@ public class UrlConnectionClient implements Client { } protected HttpURLConnection openConnection(Request request) throws IOException { - return (HttpURLConnection) new URL(request.getUrl()).openConnection(); + HttpURLConnection connection = + (HttpURLConnection) new URL(request.getUrl()).openConnection(); + connection.setConnectTimeout(Defaults.CONNECT_TIMEOUT); + connection.setReadTimeout(Defaults.READ_TIMEOUT); + return connection; } void prepareRequest(HttpURLConnection connection, Request request) throws IOException {
null
test
train
"2013-06-20T21:40:55"
"2013-05-21T21:52:03"
niqo01
val
square/retrofit/250_251
square/retrofit
square/retrofit/250
square/retrofit/251
[ "timestamp(timedelta=0.0, similarity=0.8664596156238292)" ]
37b2290403a2840147c8c70f07c4cde111f5f9ed
25f9145e018c871b5bbcfd3cd82213e4325ff676
[]
[]
"2013-06-25T20:21:07"
[]
Allow to pass null for @Part
[ "retrofit/src/main/java/retrofit/RequestBuilder.java", "retrofit/src/main/java/retrofit/mime/MultipartTypedOutput.java" ]
[ "retrofit/src/main/java/retrofit/RequestBuilder.java", "retrofit/src/main/java/retrofit/mime/MultipartTypedOutput.java" ]
[ "retrofit/src/test/java/retrofit/RequestBuilderTest.java" ]
diff --git a/retrofit/src/main/java/retrofit/RequestBuilder.java b/retrofit/src/main/java/retrofit/RequestBuilder.java index 5023b2e428..0b85c4369e 100644 --- a/retrofit/src/main/java/retrofit/RequestBuilder.java +++ b/retrofit/src/main/java/retrofit/RequestBuilder.java @@ -167,14 +167,12 @@ void setArguments(Object[] args) { } break; case PART: - if (value == null) { - throw new IllegalArgumentException( - "Multipart part \"" + name + "\" value must not be null."); - } - if (value instanceof TypedOutput) { - multipartBody.addPart(name, (TypedOutput) value); - } else { - multipartBody.addPart(name, converter.toBody(value)); + if (value != null) { // Skip null values. + if (value instanceof TypedOutput) { + multipartBody.addPart(name, (TypedOutput) value); + } else { + multipartBody.addPart(name, converter.toBody(value)); + } } break; case BODY: @@ -209,6 +207,10 @@ Request build() throws UnsupportedEncodingException { url.append(queryParams); } + if (multipartBody != null && multipartBody.getPartCount() == 0) { + throw new IllegalStateException("Multipart requests must contain at least one part."); + } + return new Request(requestMethod, url.toString(), headers, body); } } diff --git a/retrofit/src/main/java/retrofit/mime/MultipartTypedOutput.java b/retrofit/src/main/java/retrofit/mime/MultipartTypedOutput.java index 62fd0abd8e..90ab62396d 100644 --- a/retrofit/src/main/java/retrofit/mime/MultipartTypedOutput.java +++ b/retrofit/src/main/java/retrofit/mime/MultipartTypedOutput.java @@ -51,6 +51,10 @@ public void addPart(String name, TypedOutput body) { length += part.length; } + public int getPartCount() { + return parts.size(); + } + @Override public String fileName() { return null; }
diff --git a/retrofit/src/test/java/retrofit/RequestBuilderTest.java b/retrofit/src/test/java/retrofit/RequestBuilderTest.java index 8d916123f5..0266007289 100644 --- a/retrofit/src/test/java/retrofit/RequestBuilderTest.java +++ b/retrofit/src/test/java/retrofit/RequestBuilderTest.java @@ -315,6 +315,30 @@ public class RequestBuilderTest { assertThat(two).contains("kit").contains("kat"); } + @Test public void multipartNullRemovesPart() throws Exception { + Request request = new Helper() // + .setMethod("POST") // + .setHasBody() // + .setUrl("http://example.com") // + .setPath("/foo/bar/") // + .setMultipart() // + .addPart("ping", "pong") // + .addPart("fizz", null) // + .build(); + assertThat(request.getMethod()).isEqualTo("POST"); + assertThat(request.getHeaders()).isEmpty(); + assertThat(request.getUrl()).isEqualTo("http://example.com/foo/bar/"); + + MultipartTypedOutput body = (MultipartTypedOutput) request.getBody(); + List<byte[]> bodyParts = MimeHelper.getParts(body); + assertThat(bodyParts).hasSize(1); + + Iterator<byte[]> iterator = bodyParts.iterator(); + + String one = new String(iterator.next(), "UTF-8"); + assertThat(one).contains("ping").contains("pong"); + } + @Test public void multipartPartOptional() throws Exception { try { new Helper() // @@ -325,9 +349,9 @@ public class RequestBuilderTest { .setMultipart() // .addPart("ping", null) // .build(); - fail("Null multipart part is not allowed."); - } catch (IllegalArgumentException e) { - assertThat(e.getMessage()).isEqualTo("Multipart part \"ping\" value must not be null."); + fail("Empty multipart request is not allowed."); + } catch (IllegalStateException e) { + assertThat(e.getMessage()).isEqualTo("Multipart requests must contain at least one part."); } }
train
train
"2013-06-25T20:20:12"
"2013-06-25T20:00:10"
dnkoutso
val

Mozzarella-0.3.1

Motivation

  • Mozzarella is a dataset matching issues (= problem statements) and corresponding pull requests (PRs = problem solutions) of a selection of well maintained Java GitHub repositories. The original purpose was to serve as training and evaluation data for ML models concerned with fault localization and automated program repair of complex code bases. However, there might be more use cases that could benefit from this data.
  • Inspired by SWEBench paper (https://arxiv.org/abs/2310.06770) which collected similar data (however on file level only) for Python code bases.

Author

  • Feedback2Code Bachelors Project at Hasso Plattner Institute, Potsdam in cooperation with SAP.

Composition

  • Each instance is called a task and resembles a matching of a GitHub issue and the corresponding fix. Each tasks contains information about the issue/pr (ids, comments...), the problem statement and the solution that was applied by a human developer, including relevant files, relevant methods and the actual changed code.
  • The dataset currently contains 2734 tasks from 8 repositories. For a repository to be included in the dataset it has to be written mostly in Java, have a large amount of issues and pull requests in English, have good test coverage and be published under a permissive license.
  • Included in the dataset are three different train/validate/test splits:
    • Random split: The tasks are randomly split with the proportions 60/20/20
    • Repository split: Instead of splitting the individual tasks, the repositories are allocated to train/validate/test in 60/20/20 proportions and the tasks recieve the same split as the belonging repository
    • Time split: All tasks in the test split were created earlier than tasks in the validation split. All tasks in the train split were created earlier than tasks in the test split. In respect to the belonging repository.

Repositories

  • mockito/mockito (MIT)
  • square/retrofit (Apache 2.0)
  • iluwatar/java-design-patterns (MIT)
  • netty/netty (Apache 2.0)
  • pinpoint-apm/pinpoint (Apache 2.0)
  • kestra-io/kestra (Apache 2.0)
  • provectus/kafka-ui (Apache 2.0)
  • bazelbuild/bazel (Apache 2.0)

Which columns exist?

  • instance_id: (str) - unique identifier for this task/instance. Format: username__reponame-issueid
  • repo: (str) - The repository owner/name identifier from GitHub.
  • issue_id: (str) - A formatted identifier for an issue/problem, usually as repo_owner/repo_name/issue-number.
  • pr_id: (str) - A formatted instance identifier for the corresponding PR/solution, usually as repo_owner/repo_name/PR-number.
  • linking_methods: (list str) - The method used to create this task (eg. timestamp, keyword...). See details below.
  • base_commit: (str) - The commit hash representing the HEAD of the repository before the solution PR is applied.
  • merge_commit: (str) - The commit hash representing the HEAD of the repository after the PR is merged.
  • hints_text: (str) - Comments made on the issue
  • resolved_comments: (str) - Comments made on the PR
  • created_at: (str) - The creation date of the pull request.
  • labeled_as: (list str) - List of labels applied to the issue
  • problem_statement: (str) - The issue title and body.
  • gold_files: (list str) - List of paths to the files not containing tests that were changed in the PR (at the point of the base commit)
  • test_files: (list str) - List of paths to the files containing tests that were changed in the PR (at the point of the base commit)
  • gold_patch: (str) - The gold patch, the patch generated by the PR (minus test-related code), that resolved the issue. As diff.
  • test_patch: (str) - A test-file patch that was contributed by the solution PR. As diff.
  • split_random: (str) - The random split this tasks belongs to ('train'/'test'/'val'). See details above.
  • split_repo: (str) - The repository split this tasks belongs to ('train'/'test'/'val'). See details above.
  • split_time: (str) - The time split this tasks belongs to ('train'/'test'/'val'). See details above.

Collection Process

  • All data is taken from publicly accesible GitHub repositories under MIT or Apache-2.0 licenses.
  • The data is collected by gathering issue and PR information from the GitHub API. To create a task instance, we attempt for each PR to find the issues that were solved by that PR using all of the following linking methods:
    • connected: GitHub offers a feature to assign to a PR the issues that the PR adresses. These preexisting links are used as link in our dataset.
    • keyword: Each PR is scanned for mentions of issues and each issue is scanned for mentions of PRs. Then the proximity of those matches is checked for certains keywords indicating a solution relationship.
    • timestamp: Possible matches are determined by looking at issues and PR that were closed around the same time. Then their titles and descriptions are checked for semantic similarity using OpenAI embeddings.

Preprocessing

  • From the dataset removed were tasks that modify more than ten files (because we deem them overly complex for our purposes) and tasks that modify no files or only test files.
  • To improve the accuracy of timestamp linking, tasks linked by exclusively timestamp are removed if there are keyword/connection tasks that suggest a different matching or if there are other exclusively timestamp tasks with a higher similarity.

Uses

  • The dataset is currently being used to train and validate models for fault localization at file and method level.
  • The dataset will be used to train and validate models for automatic code generation / bug fixing.
  • Other uses could be possible, however are not yet explored by our project.

Maintenance

  • More repsitories will most likely be added fairly soon. All fields are subject to change depending on what we deem sensible.
  • This is the newest version of the dataset as of 18/07/2024

License

Copyright 2024 Feedback2Code

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Downloads last month
0
Edit dataset card