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
timestamp[ns] | 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:33Z" | [] | 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:09Z" | 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:22Z" | [] | 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:31Z" | 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:25Z" | [] | 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:52Z" | 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:14Z" | [] | 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 ([email protected])
*/
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:59Z" | 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:07Z" | [] | 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 ([email protected])
- */
-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 ([email protected]) */
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:43Z" | 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:22Z" | [] | 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:45Z" | 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\" [email protected] 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:10Z" | [] | 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:09Z" | 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:20Z" | [] | 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:55Z" | 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:31Z" | [] | 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 ([email protected])
*/
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:47Z" | 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:18Z" | [] | 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:14Z" | 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:18Z" | [] | 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:40Z" | 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:41Z" | [] | 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
+ * @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:14Z" | 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:26Z" | [] | 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:03Z" | 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:07Z" | [] | 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:10Z" | dnkoutso | val |
|
square/retrofit/239_255 | square/retrofit | square/retrofit/239 | square/retrofit/255 | [
"timestamp(timedelta=0.0, similarity=0.8659461484328028)"
] | 5d4e4c41b6ec01028c914a0c1038b91f5ad6a97f | 4f1546b005e8f458af3b952bc6d19f98cf45ddf4 | [
"A way to leave out the POST body would be great too. I'd like to see request logs, but not the personal data being sent.\n"
] | [] | "2013-07-09T00:39:52Z" | [] | Add a less verbose logging level | Currently from what I can see there's no logging and debug logging. A level that would log the request without the response would be extremely useful.
| [
"CHANGELOG.md",
"retrofit/src/main/java/retrofit/RestAdapter.java"
] | [
"CHANGELOG.md",
"retrofit/src/main/java/retrofit/RestAdapter.java"
] | [
"retrofit/src/test/java/retrofit/RestAdapterTest.java"
] | diff --git a/CHANGELOG.md b/CHANGELOG.md
index 7974b9f27e..b68962b302 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,6 +1,14 @@
Change Log
==========
+Version 1.2.0 *(In Development)*
+--------------------------------
+
+ * Change `setDebug` to `setLogLevel` on `RestAdapter` and `RestAdapter.Builder` and provide
+ two levels of logging via `LogLevel`.
+ * Query parameters can now be added in a request interceptor.
+
+
Version 1.1.1 *(2013-06-25)*
----------------------------
diff --git a/retrofit/src/main/java/retrofit/RestAdapter.java b/retrofit/src/main/java/retrofit/RestAdapter.java
index a447a0fc22..c318a3d8c0 100644
--- a/retrofit/src/main/java/retrofit/RestAdapter.java
+++ b/retrofit/src/main/java/retrofit/RestAdapter.java
@@ -113,6 +113,16 @@ public interface Log {
void log(String message);
}
+ /** Controls the level of logging. */
+ public enum LogLevel {
+ /** No logging. */
+ NONE,
+ /** Log only the request method and URL and the response status code and execution time. */
+ BASIC,
+ /** Log the headers, body, and metadata for both requests and responses. */
+ FULL
+ }
+
private final Server server;
private final Client.Provider clientProvider;
private final Executor httpExecutor;
@@ -122,11 +132,11 @@ public interface Log {
private final Profiler profiler;
private final ErrorHandler errorHandler;
private final Log log;
- private volatile boolean debug;
+ private volatile LogLevel logLevel;
private RestAdapter(Server server, Client.Provider clientProvider, Executor httpExecutor,
Executor callbackExecutor, RequestInterceptor requestInterceptor, Converter converter,
- Profiler profiler, ErrorHandler errorHandler, Log log, boolean debug) {
+ Profiler profiler, ErrorHandler errorHandler, Log log, LogLevel logLevel) {
this.server = server;
this.clientProvider = clientProvider;
this.httpExecutor = httpExecutor;
@@ -136,12 +146,15 @@ private RestAdapter(Server server, Client.Provider clientProvider, Executor http
this.profiler = profiler;
this.errorHandler = errorHandler;
this.log = log;
- this.debug = debug;
+ this.logLevel = logLevel;
}
- /** Toggle debug logging on or off. */
- public void setDebug(boolean debug) {
- this.debug = debug;
+ /** Change the level of logging. */
+ public void setLogLevel(LogLevel loglevel) {
+ if (logLevel == null) {
+ throw new NullPointerException("Log level may not be null.");
+ }
+ this.logLevel = loglevel;
}
/** Create an implementation of the API defined by the specified {@code service} interface. */
@@ -228,8 +241,10 @@ private Object invokeRequest(RestMethodInfo methodDetails, Object[] args) {
Thread.currentThread().setName(THREAD_PREFIX + url.substring(serverUrl.length()));
}
- if (debug) {
+ if (logLevel == LogLevel.FULL) {
request = logAndReplaceRequest(request);
+ } else if (logLevel == LogLevel.BASIC) {
+ logRequestLine(request);
}
Object profilerObject = null;
@@ -248,8 +263,10 @@ private Object invokeRequest(RestMethodInfo methodDetails, Object[] args) {
profiler.afterCall(requestInfo, elapsedTime, statusCode, profilerObject);
}
- if (debug) {
+ if (logLevel == LogLevel.FULL) {
response = logAndReplaceResponse(url, response, elapsedTime);
+ } else if (logLevel == LogLevel.BASIC) {
+ logResponseLine(url, response, elapsedTime);
}
Type type = methodDetails.responseObjectType;
@@ -300,9 +317,17 @@ private Object invokeRequest(RestMethodInfo methodDetails, Object[] args) {
}
}
+ private void logRequestLine(Request request) {
+ log.log(String.format("---> HTTP %s %s", request.getMethod(), request.getUrl()));
+ }
+
+ private void logResponseLine(String url, Response response, long elapsedTime) {
+ log.log(String.format("<--- HTTP %s %s (%sms)", response.getStatus(), url, elapsedTime));
+ }
+
/** 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()));
+ logRequestLine(request);
for (Header header : request.getHeaders()) {
log.log(header.getName() + ": " + header.getValue());
@@ -338,7 +363,7 @@ private Request logAndReplaceRequest(Request request) throws IOException {
/** 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));
+ logResponseLine(url, response, elapsedTime);
for (Header header : response.getHeaders()) {
log.log(header.getName() + ": " + header.getValue());
@@ -414,7 +439,7 @@ public static class Builder {
private Profiler profiler;
private ErrorHandler errorHandler;
private Log log;
- private boolean debug;
+ private LogLevel logLevel = LogLevel.NONE;
/** API server base URL. */
public Builder setServer(String endpoint) {
@@ -522,9 +547,12 @@ public Builder setLog(Log log) {
return this;
}
- /** Enable debug logging. */
- public Builder setDebug(boolean debug) {
- this.debug = debug;
+ /** Change the level of logging. */
+ public Builder setLogLevel(LogLevel logLevel) {
+ if (logLevel == null) {
+ throw new NullPointerException("Log level may not be null.");
+ }
+ this.logLevel = logLevel;
return this;
}
@@ -535,7 +563,7 @@ public RestAdapter build() {
}
ensureSaneDefaults();
return new RestAdapter(server, clientProvider, httpExecutor, callbackExecutor,
- requestInterceptor, converter, profiler, errorHandler, log, debug);
+ requestInterceptor, converter, profiler, errorHandler, log, logLevel);
}
private void ensureSaneDefaults() {
| diff --git a/retrofit/src/test/java/retrofit/RestAdapterTest.java b/retrofit/src/test/java/retrofit/RestAdapterTest.java
index bf6d603f0b..1b5b13cdcf 100644
--- a/retrofit/src/test/java/retrofit/RestAdapterTest.java
+++ b/retrofit/src/test/java/retrofit/RestAdapterTest.java
@@ -10,12 +10,12 @@
import java.util.concurrent.Executor;
import org.junit.Before;
import org.junit.Test;
-import retrofit.converter.ConversionException;
-import retrofit.http.GET;
import retrofit.client.Client;
import retrofit.client.Header;
import retrofit.client.Request;
import retrofit.client.Response;
+import retrofit.converter.ConversionException;
+import retrofit.http.GET;
import retrofit.mime.TypedInput;
import retrofit.mime.TypedString;
@@ -32,10 +32,27 @@
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;
import static retrofit.Profiler.RequestInformation;
+import static retrofit.RestAdapter.LogLevel.BASIC;
+import static retrofit.RestAdapter.LogLevel.FULL;
import static retrofit.Utils.SynchronousExecutor;
public class RestAdapterTest {
- private static List<Header> NO_HEADERS = Collections.emptyList();
+ private static final List<Header> NO_HEADERS = Collections.emptyList();
+
+ /** Not all servers play nice and add content-type headers to responses. */
+ private static final TypedInput NO_MIME_BODY = new TypedInput() {
+ @Override public String mimeType() {
+ return null;
+ }
+
+ @Override public long length() {
+ return 2;
+ }
+
+ @Override public InputStream in() throws IOException {
+ return new ByteArrayInputStream("{}".getBytes("UTF-8"));
+ }
+ };
private interface Example {
@GET("/") Object something();
@@ -85,7 +102,34 @@ private interface Example {
verify(mockProfiler).afterCall(any(RequestInformation.class), anyInt(), eq(200), same(data));
}
- @Test public void logSuccessfulRequestResponseOnDebugWhenResponseBodyPresent() throws Exception {
+ @Test public void logRequestResponseBasic() throws Exception {
+ final List<String> logMessages = new ArrayList<String>();
+ RestAdapter.Log log = new RestAdapter.Log() {
+ public void log(String message) {
+ logMessages.add(message);
+ }
+ };
+
+ Example example = new RestAdapter.Builder() //
+ .setClient(mockClient)
+ .setExecutors(mockRequestExecutor, mockCallbackExecutor)
+ .setServer("http://example.com")
+ .setProfiler(mockProfiler)
+ .setLog(log)
+ .setLogLevel(BASIC)
+ .build()
+ .create(Example.class);
+
+ when(mockClient.execute(any(Request.class))) //
+ .thenReturn(new Response(200, "OK", NO_HEADERS, new TypedString("{}")));
+
+ example.something();
+ assertThat(logMessages).hasSize(2);
+ assertThat(logMessages.get(0)).isEqualTo("---> HTTP GET http://example.com/");
+ assertThat(logMessages.get(1)).matches("<--- HTTP 200 http://example.com/ \\([0-9]+ms\\)");
+ }
+
+ @Test public void logSuccessfulRequestResponseFullWhenResponseBodyPresent() throws Exception {
final List<String> logMessages = new ArrayList<String>();
RestAdapter.Log log = new RestAdapter.Log() {
public void log(String message) {
@@ -99,7 +143,7 @@ public void log(String message) {
.setServer("http://example.com")
.setProfiler(mockProfiler)
.setLog(log)
- .setDebug(true)
+ .setLogLevel(FULL)
.build()
.create(Example.class);
@@ -115,7 +159,7 @@ public void log(String message) {
assertThat(logMessages.get(4)).isEqualTo("<--- END HTTP (2-byte body)");
}
- @Test public void logSuccessfulRequestResponseOnDebugWhenResponseBodyAbsent() throws Exception {
+ @Test public void logSuccessfulRequestResponseFullWhenResponseBodyAbsent() throws Exception {
final List<String> logMessages = new ArrayList<String>();
RestAdapter.Log log = new RestAdapter.Log() {
public void log(String message) {
@@ -129,7 +173,7 @@ public void log(String message) {
.setServer("http://example.com")
.setProfiler(mockProfiler)
.setLog(log)
- .setDebug(true)
+ .setLogLevel(FULL)
.build()
.create(Example.class);
@@ -144,30 +188,14 @@ public void log(String message) {
assertThat(logMessages.get(3)).isEqualTo("<--- END HTTP (0-byte body)");
}
- /** Not all servers play nice and add content-type headers to responses. */
- TypedInput inputMissingMimeType = new TypedInput() {
-
- @Override public String mimeType() {
- return null;
- }
-
- @Override public long length() {
- return 2;
- }
-
- @Override public InputStream in() throws IOException {
- return new ByteArrayInputStream("{}".getBytes());
- }
- };
-
@Test public void successfulRequestResponseWhenMimeTypeMissing() throws Exception {
when(mockClient.execute(any(Request.class))) //
- .thenReturn(new Response(200, "OK", NO_HEADERS, inputMissingMimeType));
+ .thenReturn(new Response(200, "OK", NO_HEADERS, NO_MIME_BODY));
example.something();
}
- @Test public void logSuccessfulRequestResponseOnDebugWhenMimeTypeMissing() throws Exception {
+ @Test public void logSuccessfulRequestResponseFullWhenMimeTypeMissing() throws Exception {
final List<String> logMessages = new ArrayList<String>();
RestAdapter.Log log = new RestAdapter.Log() {
public void log(String message) {
@@ -181,12 +209,12 @@ public void log(String message) {
.setServer("http://example.com")
.setProfiler(mockProfiler)
.setLog(log)
- .setDebug(true)
+ .setLogLevel(FULL)
.build()
.create(Example.class);
when(mockClient.execute(any(Request.class))) //
- .thenReturn(new Response(200, "OK", NO_HEADERS, inputMissingMimeType));
+ .thenReturn(new Response(200, "OK", NO_HEADERS, NO_MIME_BODY));
example.something();
assertThat(logMessages).hasSize(5);
@@ -245,7 +273,7 @@ public void log(String message) {
}
}
- @Test public void logErrorRequestResponseOnDebugWhenMimeTypeMissing() throws Exception {
+ @Test public void logErrorRequestResponseFullWhenMimeTypeMissing() throws Exception {
final List<String> logMessages = new ArrayList<String>();
RestAdapter.Log log = new RestAdapter.Log() {
public void log(String message) {
@@ -259,12 +287,12 @@ public void log(String message) {
.setServer("http://example.com")
.setProfiler(mockProfiler)
.setLog(log)
- .setDebug(true)
+ .setLogLevel(FULL)
.build()
.create(Example.class);
Response responseMissingMimeType = //
- new Response(403, "Forbidden", NO_HEADERS, inputMissingMimeType);
+ new Response(403, "Forbidden", NO_HEADERS, NO_MIME_BODY);
when(mockClient.execute(any(Request.class))).thenReturn(responseMissingMimeType);
@@ -283,7 +311,7 @@ public void log(String message) {
assertThat(logMessages.get(4)).isEqualTo("<--- END HTTP (2-byte body)");
}
- @Test public void logErrorRequestResponseOnDebugWhenResponseBodyAbsent() throws Exception {
+ @Test public void logErrorRequestResponseFullWhenResponseBodyAbsent() throws Exception {
final List<String> logMessages = new ArrayList<String>();
RestAdapter.Log log = new RestAdapter.Log() {
public void log(String message) {
@@ -297,7 +325,7 @@ public void log(String message) {
.setServer("http://example.com")
.setProfiler(mockProfiler)
.setLog(log)
- .setDebug(true)
+ .setLogLevel(FULL)
.build()
.create(Example.class);
| train | train | 2013-07-09T01:46:51 | "2013-06-10T12:20:18Z" | hamidp | val |
square/retrofit/244_259 | square/retrofit | square/retrofit/244 | square/retrofit/259 | [
"timestamp(timedelta=0.0, similarity=0.8956541909589226)"
] | a9dd5b77ea3d414d077372c547cf4753d86a6ac1 | 1c7466739f907bf8b1fbb6b716cf7248f7d5bd02 | [] | [] | "2013-07-09T23:15:16Z" | [
"Website"
] | Missing RestAdapter Documentation | The primary documentation for Retrofit appears to be http://square.github.io/retrofit/. However, that page is missing how to actually instantiate the `RestAdapter` (only documented on [the blog post announcing Retrofit](http://corner.squareup.com/2013/05/retrofit-one-dot-oh.html)). Basically, the page just starts talking about `restAdapter` with no indication of where it came from.
| [
"website/index.html"
] | [
"website/index.html"
] | [] | diff --git a/website/index.html b/website/index.html
index 2b46e883fc..326933e8b0 100644
--- a/website/index.html
+++ b/website/index.html
@@ -49,7 +49,11 @@ <h3 id="introduction">Introduction</h3>
List<Repo> listRepos(@Path("user") String user);
}</pre>
<p>The <code>RestAdapter</code> class generates an implementation of the <code>GitHubService</code> interface.</p>
- <pre class="prettyprint">GitHubService service = restAdapter.create(GitHubService.class);</pre>
+ <pre class="prettyprint">RestAdapter restAdapter = new RestAdapter.Builder()
+ .setServer("https://api.github.com")
+ .build();
+
+GitHubService service = restAdapter.create(GitHubService.class);</pre>
<p>Each call on the generated <code>GitHubService</code> makes an HTTP request to the remote webserver.</p>
<pre class="prettyprint">List<Repo> repos = service.listRepos("octocat");</pre>
<p>Use annotations to describe the HTTP request:</p>
| null | train | train | 2013-07-09T03:39:29 | "2013-06-18T13:59:35Z" | commonsguy | val |
square/retrofit/228_260 | square/retrofit | square/retrofit/228 | square/retrofit/260 | [
"timestamp(timedelta=0.0, similarity=0.8658240195075431)"
] | a9dd5b77ea3d414d077372c547cf4753d86a6ac1 | 0e10cbc83f6def3e487230c99434225d64fb8599 | [
"This will always happen with the current detection method because the platform jar will be on the classpath. I didn't know of anything better at the time. Maybe a system property or something could be used.\n"
] | [] | "2013-07-10T00:08:04Z" | [] | When developing in Android Studio, Android Platform is detected | I'm using Android Studio for developing retrofit. When running unit tests, `Platform.Android` is used as `android.os.Build` is in my classpath incidentally. Is there an alternate way to tell if we are running inside Android? Or could we expose Platform so that folks can use different means to detect the platform without c&p what's in retrofit?
| [
"retrofit/src/main/java/retrofit/Platform.java"
] | [
"retrofit/src/main/java/retrofit/Platform.java"
] | [] | diff --git a/retrofit/src/main/java/retrofit/Platform.java b/retrofit/src/main/java/retrofit/Platform.java
index 8721a097df..aeead9acee 100644
--- a/retrofit/src/main/java/retrofit/Platform.java
+++ b/retrofit/src/main/java/retrofit/Platform.java
@@ -43,10 +43,12 @@ static Platform get() {
private static Platform findPlatform() {
try {
Class.forName("android.os.Build");
- return new Android();
- } catch (ClassNotFoundException e) {
- return new Base();
+ if (Build.VERSION.SDK_INT != 0) {
+ return new Android();
+ }
+ } catch (ClassNotFoundException ignored) {
}
+ return new Base();
}
abstract Converter defaultConverter();
| null | train | train | 2013-07-09T03:39:29 | "2013-05-27T14:46:04Z" | codefromthecrypt | val |
square/retrofit/284_289 | square/retrofit | square/retrofit/284 | square/retrofit/289 | [
"timestamp(timedelta=19.0, similarity=0.8588720248976324)"
] | 613e85c7a3b7a813abbc645fa5550f5608ca4627 | c4719c5979da5ff85e35b4b71b419e9602555eb9 | [
"Grabbing a response body out of an error is also a pain. Some APIs return error status codes and include an error message body. In this case you need to grab the response body out of `RetrofitError`. There was even a pull request to try and take care of the ugly object casting code necessary to accomplish this: https://github.com/square/retrofit/pull/243\n",
"That's what `getBodyAs(Type)` is for. If you want to convert the body to a string then just read the body's input stream to a string.\n",
"Discussion at #297.\n",
"When I try to make a POST request with Retrofit in Android application, I face this error:\n\nfailure : retrofit.RetrofitError: 307 Temporary Redirect\n\nPlease help me to resolve this error\n"
] | [] | "2013-07-28T11:51:51Z" | [] | RetrofitError is a nightmare to work with. | How do you know if it was a conversion error, network error, random error inside Retrofit? Yuck. This API interaction needs rethought.
| [
"retrofit/src/main/java/retrofit/RetrofitError.java"
] | [
"retrofit/src/main/java/retrofit/RetrofitConversionError.java",
"retrofit/src/main/java/retrofit/RetrofitError.java",
"retrofit/src/main/java/retrofit/RetrofitHttpError.java",
"retrofit/src/main/java/retrofit/RetrofitNetworkError.java",
"retrofit/src/main/java/retrofit/RetrofitResponseError.java",
"retrofit/src/main/java/retrofit/UnexpectedRetrofitError.java"
] | [
"retrofit/src/test/java/retrofit/RetrofitErrorTest.java"
] | diff --git a/retrofit/src/main/java/retrofit/RetrofitConversionError.java b/retrofit/src/main/java/retrofit/RetrofitConversionError.java
new file mode 100644
index 0000000000..97155a6b8e
--- /dev/null
+++ b/retrofit/src/main/java/retrofit/RetrofitConversionError.java
@@ -0,0 +1,13 @@
+package retrofit;
+
+import retrofit.client.Response;
+import retrofit.converter.Converter;
+
+import java.lang.reflect.Type;
+
+public class RetrofitConversionError extends RetrofitResponseError {
+ protected RetrofitConversionError(String url, Response response, Converter converter,
+ Type successType, Throwable exception) {
+ super(url, response, converter, successType, exception);
+ }
+}
diff --git a/retrofit/src/main/java/retrofit/RetrofitError.java b/retrofit/src/main/java/retrofit/RetrofitError.java
index 4a8b2cff0d..d867406fdc 100644
--- a/retrofit/src/main/java/retrofit/RetrofitError.java
+++ b/retrofit/src/main/java/retrofit/RetrofitError.java
@@ -15,89 +15,87 @@
*/
package retrofit;
-import java.io.IOException;
-import java.lang.reflect.Type;
import retrofit.client.Response;
import retrofit.converter.ConversionException;
import retrofit.converter.Converter;
-import retrofit.mime.TypedInput;
-public class RetrofitError extends RuntimeException {
- public static RetrofitError networkError(String url, IOException exception) {
- return new RetrofitError(url, null, null, null, true, exception);
+import java.io.IOException;
+import java.lang.reflect.Type;
+
+public abstract class RetrofitError extends RuntimeException {
+ public static RetrofitNetworkError networkError(String url, IOException exception) {
+ return new RetrofitNetworkError(url, exception);
}
- public static RetrofitError conversionError(String url, Response response, Converter converter,
- Type successType, ConversionException exception) {
- return new RetrofitError(url, response, converter, successType, false, exception);
+ public static RetrofitConversionError conversionError(String url, Response response,
+ Converter converter, Type successType,
+ ConversionException exception) {
+ return new RetrofitConversionError(url, response, converter, successType, exception);
}
- public static RetrofitError httpError(String url, Response response, Converter converter,
- Type successType) {
- return new RetrofitError(url, response, converter, successType, false, null);
+ public static RetrofitHttpError httpError(String url, Response response, Converter converter,
+ Type successType) {
+ return new RetrofitHttpError(url, response, converter, successType);
}
- public static RetrofitError unexpectedError(String url, Throwable exception) {
- return new RetrofitError(url, null, null, null, false, exception);
+ public static UnexpectedRetrofitError unexpectedError(String url, Throwable exception) {
+ return new UnexpectedRetrofitError(url, exception);
}
private final String url;
- private final Response response;
- private final Converter converter;
- private final Type successType;
- private final boolean networkError;
- private RetrofitError(String url, Response response, Converter converter, Type successType,
- boolean networkError, Throwable exception) {
+ protected RetrofitError(String message, String url) {
+ super(message);
+ this.url = url;
+ }
+
+ protected RetrofitError(String url, Throwable exception) {
super(exception);
this.url = url;
- this.response = response;
- this.converter = converter;
- this.successType = successType;
- this.networkError = networkError;
}
- /** The request URL which produced the error. */
+ protected RetrofitError(String message, String url, Throwable exception) {
+ super(message, exception);
+ this.url = url;
+ }
+
+ /**
+ * The request URL which produced the error.
+ */
public String getUrl() {
return url;
}
- /** Response object containing status code, headers, body, etc. */
- public Response getResponse() {
- return response;
- }
+ /**
+ * Response object containing status code, headers, body, etc. if present, null otherwise.
+ *
+ * @deprecated Will be moved to {@link RetrofitResponseError}.
+ */
+ @Deprecated
+ public abstract Response getResponse();
- /** Whether or not this error was the result of a network error. */
- public boolean isNetworkError() {
- return networkError;
- }
+ /**
+ * Whether or not this error was the result of a network error.
+ *
+ * @deprecated Use the instanceof operator instead and test for a {@link RetrofitNetworkError}.
+ */
+ @Deprecated
+ public abstract boolean isNetworkError();
/**
* HTTP response body converted to the type declared by either the interface method return type or
- * the generic type of the supplied {@link Callback} parameter.
+ * the generic type of the supplied {@link Callback} parameter. Null if no body is present.
+ *
+ * @deprecated Will be moved to {@link RetrofitResponseError}.
*/
- public Object getBody() {
- TypedInput body = response.getBody();
- if (body == null) {
- return null;
- }
- try {
- return converter.fromBody(body, successType);
- } catch (ConversionException e) {
- throw new RuntimeException(e);
- }
- }
+ @Deprecated
+ public abstract Object getBody();
- /** HTTP response body converted to specified {@code type}. */
- public Object getBodyAs(Type type) {
- TypedInput body = response.getBody();
- if (body == null) {
- return null;
- }
- try {
- return converter.fromBody(body, type);
- } catch (ConversionException e) {
- throw new RuntimeException(e);
- }
- }
+ /**
+ * HTTP response body converted to specified {@code type}. Null if no body is present.
+ *
+ * @deprecated Will be moved to {@link RetrofitResponseError}.
+ */
+ @Deprecated
+ public abstract Object getBodyAs(Type type);
}
diff --git a/retrofit/src/main/java/retrofit/RetrofitHttpError.java b/retrofit/src/main/java/retrofit/RetrofitHttpError.java
new file mode 100644
index 0000000000..2bd80334c4
--- /dev/null
+++ b/retrofit/src/main/java/retrofit/RetrofitHttpError.java
@@ -0,0 +1,13 @@
+package retrofit;
+
+import retrofit.client.Response;
+import retrofit.converter.Converter;
+
+import java.lang.reflect.Type;
+
+public class RetrofitHttpError extends RetrofitResponseError {
+ protected RetrofitHttpError(String url, Response response, Converter converter,
+ Type successType) {
+ super(url, response, converter, successType);
+ }
+}
diff --git a/retrofit/src/main/java/retrofit/RetrofitNetworkError.java b/retrofit/src/main/java/retrofit/RetrofitNetworkError.java
new file mode 100644
index 0000000000..2b94d3d451
--- /dev/null
+++ b/retrofit/src/main/java/retrofit/RetrofitNetworkError.java
@@ -0,0 +1,36 @@
+package retrofit;
+
+import retrofit.client.Response;
+
+import java.lang.reflect.Type;
+
+public class RetrofitNetworkError extends RetrofitError {
+
+ protected RetrofitNetworkError(String url, Throwable exception) {
+ super("Request to " + url + " failed.", url, exception);
+ }
+
+ @Override
+ @Deprecated
+ public Response getResponse() {
+ return null;
+ }
+
+ @Override
+ @Deprecated
+ public boolean isNetworkError() {
+ return true;
+ }
+
+ @Override
+ @Deprecated
+ public Object getBody() {
+ return null;
+ }
+
+ @Override
+ @Deprecated
+ public Object getBodyAs(Type type) {
+ return null;
+ }
+}
diff --git a/retrofit/src/main/java/retrofit/RetrofitResponseError.java b/retrofit/src/main/java/retrofit/RetrofitResponseError.java
new file mode 100644
index 0000000000..a56286db12
--- /dev/null
+++ b/retrofit/src/main/java/retrofit/RetrofitResponseError.java
@@ -0,0 +1,90 @@
+package retrofit;
+
+import retrofit.client.Response;
+import retrofit.converter.ConversionException;
+import retrofit.converter.Converter;
+import retrofit.mime.TypedInput;
+
+import java.lang.reflect.Type;
+
+public abstract class RetrofitResponseError extends RetrofitError {
+
+ protected Response response;
+ protected Converter converter;
+ protected Type successType;
+
+ protected RetrofitResponseError(String url, Response response, Converter converter,
+ Type successType, Throwable exception) {
+ super("Request to " + url + " failed; response code is "
+ + ((response == null) ? "unknown" : response.getStatus() + " " + response.getReason())
+ + ".", url, exception);
+ this.response = response;
+ this.converter = converter;
+ this.successType = successType;
+ }
+
+ protected RetrofitResponseError(String url, Response response, Converter converter,
+ Type successType) {
+ super("Request to " + url + " failed; response code is "
+ + ((response == null) ? "unknown" : response.getStatus() + " " + response.getReason())
+ + ".", url);
+ this.response = response;
+ this.converter = converter;
+ this.successType = successType;
+ }
+
+ @Override
+ @Deprecated
+ public boolean isNetworkError() {
+ return false;
+ }
+
+ @Override
+ public Response getResponse() {
+ return response;
+ }
+
+ @Override
+ public Object getBody() {
+ if (response == null) {
+ return null;
+ }
+
+ TypedInput body = response.getBody();
+ if (body == null) {
+ return null;
+ }
+
+ if (converter == null) {
+ throw new RuntimeException("Cannot convert body, supplied converter is null.");
+ }
+
+ try {
+ return converter.fromBody(body, successType);
+ } catch (ConversionException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ @Override
+ public Object getBodyAs(Type type) {
+ if (response == null) {
+ return null;
+ }
+
+ TypedInput body = response.getBody();
+ if (body == null) {
+ return null;
+ }
+
+ if (converter == null) {
+ throw new RuntimeException("Cannot convert body, supplied converter is null.");
+ }
+
+ try {
+ return converter.fromBody(body, type);
+ } catch (ConversionException e) {
+ throw new RuntimeException(e);
+ }
+ }
+}
diff --git a/retrofit/src/main/java/retrofit/UnexpectedRetrofitError.java b/retrofit/src/main/java/retrofit/UnexpectedRetrofitError.java
new file mode 100644
index 0000000000..eb46806487
--- /dev/null
+++ b/retrofit/src/main/java/retrofit/UnexpectedRetrofitError.java
@@ -0,0 +1,35 @@
+package retrofit;
+
+import retrofit.client.Response;
+
+import java.lang.reflect.Type;
+
+public class UnexpectedRetrofitError extends RetrofitError {
+ protected UnexpectedRetrofitError(String url, Throwable exception) {
+ super("Request to " + url + " failed.", url, exception);
+ }
+
+ @Override
+ @Deprecated
+ public Response getResponse() {
+ return null;
+ }
+
+ @Override
+ @Deprecated
+ public boolean isNetworkError() {
+ return false;
+ }
+
+ @Override
+ @Deprecated
+ public Object getBody() {
+ return null;
+ }
+
+ @Override
+ @Deprecated
+ public Object getBodyAs(Type type) {
+ return null;
+ }
+}
| diff --git a/retrofit/src/test/java/retrofit/RetrofitErrorTest.java b/retrofit/src/test/java/retrofit/RetrofitErrorTest.java
new file mode 100644
index 0000000000..9fe0e2c8f7
--- /dev/null
+++ b/retrofit/src/test/java/retrofit/RetrofitErrorTest.java
@@ -0,0 +1,213 @@
+package retrofit;
+
+import com.google.gson.Gson;
+import org.junit.Test;
+import retrofit.client.Header;
+import retrofit.client.Response;
+import retrofit.converter.ConversionException;
+import retrofit.converter.Converter;
+import retrofit.converter.GsonConverter;
+import retrofit.mime.TypedInput;
+import retrofit.mime.TypedString;
+
+import java.io.IOException;
+import java.lang.reflect.Type;
+import java.util.ArrayList;
+
+import static org.fest.assertions.api.Assertions.assertThat;
+import static org.fest.assertions.api.Assertions.fail;
+import static org.mockito.Matchers.any;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+@SuppressWarnings("ThrowableResultOfMethodCallIgnored")
+public class RetrofitErrorTest {
+
+ @Test
+ public void everyRetrofitErrorHasAMessage() throws Exception {
+ String url = "http://example.com/";
+ Response response = new Response(200, "OK", new ArrayList<Header>(),
+ new TypedString("\"foo\""));
+ Converter conv = new GsonConverter(new Gson());
+
+ assertThat(RetrofitError.networkError(url, new IOException()).getMessage())
+ .isNotNull()
+ .isNotEmpty()
+ .contains(url);
+
+ assertThat(RetrofitError.conversionError(url, response, conv, String.class, null).getMessage())
+ .isNotNull()
+ .isNotEmpty()
+ .contains(url)
+ .contains("200 OK");
+
+ assertThat(RetrofitError.httpError(url, response, conv, String.class).getMessage())
+ .isNotNull()
+ .isNotEmpty()
+ .contains(url)
+ .contains("200 OK");
+
+ assertThat(RetrofitError.unexpectedError(url, new IOException()).getMessage())
+ .isNotNull()
+ .isNotEmpty()
+ .contains(url);
+ }
+
+ @Test
+ public void isNetworkErrorIsOnlyTrueForNetworkErrors() throws Exception {
+ assertThat(RetrofitError.networkError(null, null).isNetworkError()).isTrue();
+ assertThat(RetrofitError.conversionError(null, null, null, null, null).isNetworkError())
+ .isFalse();
+ assertThat(RetrofitError.httpError(null, null, null, null).isNetworkError()).isFalse();
+ assertThat(RetrofitError.unexpectedError(null, null).isNetworkError()).isFalse();
+ }
+
+ @Test
+ public void getBodyReturnsNullIfResponseIsNull() throws Exception {
+ assertThat(RetrofitError.networkError(null, null).getBody()).isNull();
+ assertThat(RetrofitError.conversionError(null, null, null, null, null).getBody()).isNull();
+ assertThat(RetrofitError.httpError(null, null, null, null).getBody()).isNull();
+ assertThat(RetrofitError.unexpectedError(null, null).getBody()).isNull();
+ }
+
+ @Test
+ public void getBodyReturnsNullIfResponseBodyIsNull() throws Exception {
+ Response dummyResponse = new Response(204, "No Content", new ArrayList<Header>(), null);
+ assertThat(RetrofitError.conversionError(null, dummyResponse, null, null, null).getBody())
+ .isNull();
+ assertThat(RetrofitError.httpError(null, dummyResponse, null, null).getBody()).isNull();
+ }
+
+ @Test
+ public void getBodyThrowsRuntimeExceptionIfBodyIsPresentButConverterIsNot() throws Exception {
+ Response dummyResponse = new Response(200, "OK", new ArrayList<Header>(),
+ new TypedString("\"foo\""));
+
+ try {
+ RetrofitError.conversionError(null, dummyResponse, null, null, null).getBody();
+ fail("A RuntimeException should have been thrown.");
+ } catch (RuntimeException e) {
+ // ok
+ }
+
+ try {
+ RetrofitError.httpError(null, dummyResponse, null, null).getBody();
+ fail("A RuntimeException should have been thrown.");
+ } catch (RuntimeException e) {
+ // ok
+ }
+ }
+
+ @Test
+ public void getBodyReturnsConvertedBody() throws Exception {
+ Response dummyResponse = new Response(200, "OK", new ArrayList<Header>(),
+ new TypedString("\"foo\""));
+ Converter converter = new GsonConverter(new Gson());
+
+ assertThat((String) RetrofitError.conversionError(null, dummyResponse, converter,
+ String.class, null).getBody())
+ .isEqualTo("foo");
+
+ assertThat((String) RetrofitError.httpError(null, dummyResponse, converter, String.class)
+ .getBody()).isEqualTo("foo");
+ }
+
+ @Test
+ public void getBodyThrowsRuntimeExceptionIfConversionExceptionWasThrown() throws Exception {
+ Response dummyResponse = new Response(200, "OK", new ArrayList<Header>(),
+ new TypedString("\"foo\""));
+
+ Converter converter = mock(Converter.class);
+ when(converter.fromBody(any(TypedInput.class), any(Type.class)))
+ .thenThrow(new ConversionException("Expected."));
+
+ try {
+ RetrofitError.conversionError(null, dummyResponse, converter, String.class, null).getBody();
+ fail("A RuntimeException should have been thrown.");
+ } catch (RuntimeException e) {
+ // ok
+ }
+
+ try {
+ RetrofitError.httpError(null, dummyResponse, converter, String.class).getBody();
+ fail("A RuntimeException should have been thrown.");
+ } catch (RuntimeException e) {
+ // ok
+ }
+ }
+
+ @Test
+ public void getBodyAsReturnsNullIfResponseIsNull() throws Exception {
+ assertThat(RetrofitError.networkError(null, null).getBodyAs(String.class)).isNull();
+ assertThat(RetrofitError.conversionError(null, null, null, null, null).getBodyAs(String.class))
+ .isNull();
+ assertThat(RetrofitError.httpError(null, null, null, null).getBodyAs(String.class)).isNull();
+ assertThat(RetrofitError.unexpectedError(null, null).getBodyAs(String.class)).isNull();
+ }
+
+ @Test
+ public void getBodyAsReturnsNullIfResponseBodyIsNull() throws Exception {
+ Response dummyResponse = new Response(204, "No Content", new ArrayList<Header>(), null);
+ assertThat(RetrofitError.conversionError(null, dummyResponse, null, null, null)
+ .getBodyAs(String.class)).isNull();
+ assertThat(RetrofitError.httpError(null, dummyResponse, null, null).getBodyAs(String.class)).isNull();
+ }
+
+ @Test
+ public void getBodyAsThrowsRuntimeExceptionIfBodyIsPresentButConverterIsNot() throws Exception {
+ Response dummyResponse = new Response(204, "No Content", new ArrayList<Header>(),
+ new TypedString("\"foo\""));
+
+ try {
+ RetrofitError.conversionError(null, dummyResponse, null, null, null).getBodyAs(String.class);
+ fail("A RuntimeException should have been thrown.");
+ } catch (RuntimeException e) {
+ // ok
+ }
+
+ try {
+ RetrofitError.httpError(null, dummyResponse, null, null).getBodyAs(String.class);
+ fail("A RuntimeException should have been thrown.");
+ } catch (RuntimeException e) {
+ // ok
+ }
+ }
+
+ @Test
+ public void getBodyAsReturnsConvertedBody() throws Exception {
+ Response response = new Response(200, "OK", new ArrayList<Header>(),
+ new TypedString("\"foo\""));
+ Converter converter = new GsonConverter(new Gson());
+
+ assertThat((String) RetrofitError.conversionError(null, response, converter, String.class, null)
+ .getBodyAs(String.class)).isEqualTo("foo");
+
+ assertThat((String) RetrofitError.httpError(null, response, converter, String.class)
+ .getBodyAs(String.class)).isEqualTo("foo");
+ }
+
+ @Test
+ public void getBodyAsThrowsRuntimeExceptionIfConversionExceptionWasThrown() throws Exception {
+ Response dummyResponse = new Response(200, "OK", new ArrayList<Header>(),
+ new TypedString("\"foo\""));
+
+ Converter converter = mock(Converter.class);
+ when(converter.fromBody(any(TypedInput.class), any(Type.class)))
+ .thenThrow(new ConversionException("Expected."));
+
+ try {
+ RetrofitError.conversionError(null, dummyResponse, converter, String.class, null)
+ .getBodyAs(String.class);
+ fail("A RuntimeException should have been thrown.");
+ } catch (RuntimeException e) {
+ // ok
+ }
+
+ try {
+ RetrofitError.httpError(null, dummyResponse, converter, String.class).getBodyAs(String.class);
+ fail("A RuntimeException should have been thrown.");
+ } catch (RuntimeException e) {
+ // ok
+ }
+ }
+}
| train | train | 2013-07-25T08:21:08 | "2013-07-25T01:08:19Z" | JakeWharton | val |
square/retrofit/282_294 | square/retrofit | square/retrofit/282 | square/retrofit/294 | [
"keyword_pr_to_issue"
] | 613e85c7a3b7a813abbc645fa5550f5608ca4627 | e20a05223e32b1addeb19fbb9c2d5d926bf4c31b | [
"one of the challenges of PATCH is idiomatically handling it.\n\nthe json-patch rfc is pretty good though sadly no gson impl exists for it.\n there's a jackson LGPL project though https://github.com/fge/json-patch\n\nOn Wed, Jul 24, 2013 at 10:33 AM, Marijn van der Werf <\[email protected]> wrote:\n\n> The PATCH method can be used to only edit some properties of a resource,\n> instead of overwriting it as PUT does. Unfortunately, Retrofit doesn't\n> offer support for PATCH requests. Are there any plans of adding this\n> request method?\n> \n> —\n> Reply to this email directly or view it on GitHubhttps://github.com/square/retrofit/issues/282\n> .\n",
"You can also add a custom HTTP method annotation yourself.\n\n``` java\n@RestMethod(\"PATCH\")\n@Target(METHOD) @Retention(RUNTIME)\nprivate @interface PATCH {\n String value();\n}\n```\n",
"I already tried that, by replicating the PUT annotation (with `@RestMethod(value = \"PATCH\", hasBody = true)`). Unfortunately this causes a `retrofit.RetrofitError`: `java.net.ProtocolException: Unknown method 'PATCH'; must be one of [OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE]`.\n\nIs there a way to add a `X-HTTP-Method-Override: PUT` only to specific interface methods?\n\nAs for a parseable response: I was planning to return a full object, but I understand that using a json-patch instead would possibly make things quite complicated.\n",
"That's a bug then! A custom annotation is the right way to do this. We can't feasibly support every HTTP method on the planet (since you can make arbitrary ones) and like @adriancole PATCH has certain semantics which we can't know.\n",
"Can you paste the full stack trace?\n",
"Will this suffice?\n\n```\nretrofit.RetrofitError: java.net.ProtocolException: Unknown method 'PATCH'; must be one of [OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE]\n at retrofit.RestAdapter$RestHandler.invokeRequest(RestAdapter.java:292)\n at retrofit.RestAdapter$RestHandler.access$400(RestAdapter.java:157)\n at retrofit.RestAdapter$RestHandler$1.obtainResponse(RestAdapter.java:199)\n at retrofit.CallbackRunnable.run(CallbackRunnable.java:38)\n at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)\n at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)\n at retrofit.Platform$Android$2$1.run(Platform.java:132)\n at java.lang.Thread.run(Thread.java:841)\nCaused by: java.net.ProtocolException: Unknown method 'PATCH'; must be one of [OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE]\n at java.net.HttpURLConnection.setRequestMethod(HttpURLConnection.java:677)\n at retrofit.client.UrlConnectionClient.prepareRequest(UrlConnectionClient.java:41)\n at retrofit.client.UrlConnectionClient.execute(UrlConnectionClient.java:32)\n at retrofit.RestAdapter$RestHandler.invokeRequest(RestAdapter.java:241)\n at retrofit.RestAdapter$RestHandler.access$400(RestAdapter.java:157)\n at retrofit.RestAdapter$RestHandler$1.obtainResponse(RestAdapter.java:199)\n at retrofit.CallbackRunnable.run(CallbackRunnable.java:38)\n at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)\n at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)\n at retrofit.Platform$Android$2$1.run(Platform.java:132)\n at java.lang.Thread.run(Thread.java:841)\n```\n",
"Yep. I just needed to see which client this was happening in so I can easily reproduce.\n",
"take a look at #294 \n",
"I am attempting to use @PATCH. The retrofit logs say \"PATCH\", but my server says it is receiving a POST. I have tried both OkClient and UrlConnectionClient.\n",
"@alecplumb can you use okhttp's MockWebServer to confirm this in a test case?\n",
"I ran into this issue (v1.6.1) as well, was wondering if `PATCH` is supported. I am new to Android/Retrofit so not sure if this has been addressed.\n\n```\nD/Retrofit﹕ java.net.ProtocolException: Unknown method 'PATCH'; must be one of [OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE]\n at java.net.HttpURLConnection.setRequestMethod(HttpURLConnection.java:677)\n at retrofit.client.UrlConnectionClient.prepareRequest(UrlConnectionClient.java:50)\n at retrofit.client.UrlConnectionClient.execute(UrlConnectionClient.java:37)\n at retrofit.RestAdapter$RestHandler.invokeRequest(RestAdapter.java:321)\n at retrofit.RestAdapter$RestHandler.access$100(RestAdapter.java:220)\n at retrofit.RestAdapter$RestHandler$2.obtainResponse(RestAdapter.java:278)\n at retrofit.CallbackRunnable.run(CallbackRunnable.java:42)\n at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)\n at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)\n at retrofit.Platform$Android$2$1.run(Platform.java:142)\n at java.lang.Thread.run(Thread.java:841)\n```\n",
"That's a limitation of the built-in HttpUrlConnection. You need to use\nOkHttp or Apache HttpClient instead.\nOn Jul 20, 2014 2:49 PM, \"Kapil\" [email protected] wrote:\n\n> I ran into this issue (v1.6.1) as well, was wondering if PATCH is\n> supported. I am new to Android/Retrofit so not sure if this has been\n> addressed.\n> \n> D/Retrofit﹕ java.net.ProtocolException: Unknown method 'PATCH'; must be one of [OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE]\n> at java.net.HttpURLConnection.setRequestMethod(HttpURLConnection.java:677)\n> at retrofit.client.UrlConnectionClient.prepareRequest(UrlConnectionClient.java:50)\n> at retrofit.client.UrlConnectionClient.execute(UrlConnectionClient.java:37)\n> at retrofit.RestAdapter$RestHandler.invokeRequest(RestAdapter.java:321)\n> at retrofit.RestAdapter$RestHandler.access$100(RestAdapter.java:220)\n> at retrofit.RestAdapter$RestHandler$2.obtainResponse(RestAdapter.java:278)\n> at retrofit.CallbackRunnable.run(CallbackRunnable.java:42)\n> at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)\n> at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)\n> at retrofit.Platform$Android$2$1.run(Platform.java:142)\n> at java.lang.Thread.run(Thread.java:841)\n> \n> —\n> Reply to this email directly or view it on GitHub\n> https://github.com/square/retrofit/issues/282#issuecomment-49560672.\n",
"Thanks. How can I get the latest `okhttp` build, I am getting this error -\n\nI downloaded `v2.0.0` from here - http://square.github.io/okhttp/\n\n```\nE/AndroidRuntime﹕ FATAL EXCEPTION: main\n java.lang.RuntimeException: Retrofit detected an unsupported OkHttp on the classpath.\n To use OkHttp with this version of Retrofit, you'll need:\n 1. com.squareup.okhttp:okhttp:1.6.0 (or newer)\n 2. com.squareup.okhttp:okhttp-urlconnection:1.6.0 (or newer)\n Note that OkHttp 2.0.0+ is supported!\n at retrofit.Platform.hasOkHttpOnClasspath(Platform.java:186)\n```\n",
"You need both the okhttp jar and the okhttp-urlconnection jar. Downloads are here: http://search.maven.org/#search%7Cga%7C1%7Cg%3Acom.squareup.okhttp\n",
"Now I get this error -\n\n```\nRetrofit﹕ java.lang.NoClassDefFoundError: com.squareup.okhttp.internal.http.RetryableSink\n at com.squareup.okhttp.internal.Util.<clinit>(Util.java:231)\n at com.squareup.okhttp.ConnectionPool.<init>(ConnectionPool.java:82)\n at com.squareup.okhttp.ConnectionPool.<clinit>(ConnectionPool.java:71)\n at com.squareup.okhttp.OkHttpClient.copyWithDefaults(OkHttpClient.java:477)\n at com.squareup.okhttp.OkUrlFactory.open(OkUrlFactory.java:66)\n at com.squareup.okhttp.OkUrlFactory.open(OkUrlFactory.java:61)\n at retrofit.client.OkClient.openConnection(OkClient.java:45)\n at retrofit.client.UrlConnectionClient.execute(UrlConnectionClient.java:36)\n at retrofit.RestAdapter$RestHandler.invokeRequest(RestAdapter.java:321)\n at retrofit.RestAdapter$RestHandler.access$100(RestAdapter.java:220)\n at retrofit.RestAdapter$RestHandler$2.obtainResponse(RestAdapter.java:278)\n at retrofit.CallbackRunnable.run(CallbackRunnable.java:42)\n at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)\n at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)\n at retrofit.Platform$Android$2$1.run(Platform.java:142)\n at java.lang.Thread.run(Thread.java:841)\n```\n\nI am using Android Studio and have added both the jars to Gradle dependency -\n\n```\ndependencies {\n compile files('libs/retrofit-1.6.1.jar')\n compile files('libs/gson-2.2.4.jar')\n compile files('libs/okhttp-2.0.0.jar')\n compile files('libs/okhttp-urlconnection-2.0.0.jar')\n}\n```\n",
"If you are using Gradle you can stop ferrying jars around. Try:\n\n``` groovy\ndependencies {\n compile 'com.squareup.retrofit:retrofit:1.6.1'\n compile 'com.squareup.okhttp:okhttp:2.0.0'\n compile 'com.squareup.okhttp:okhttp-urlconnection:2.0.0'\n}\n```\n",
"Thanks yea that worked :thumbsup: \n",
"Hey @kapso, do you mind to share how to get PATCH to work in Android Studio? I am new to retrofit, so any help will be highly appreciated.\n\nThanks!\n",
"@pdichone You just need to add the gradle the following dependences:\n\n```\ncompile 'com.squareup.retrofit:retrofit:1.9.0'\ncompile 'com.squareup.okhttp:okhttp:2.0.0'\ncompile 'com.squareup.okhttp:okhttp-urlconnection:2.0.0'\n```\n\nAnd the patch will start working.\n",
"As of March 2016, with Retrofit `2.0.0-beta4` I am using PATCH successfully without any further libraries inclusion as mentioned in the comments here.\n",
"Could someone give an example of using a PATCH request? I am sending data to server but I am receiving 400 error in response. The server is seeing some weird characters as input and not decipherable data.\n",
"Client Interface in Android is here\n\n`@PATCH(\"employeeJobs/{id}\")\n Call<EmployeeJob> UpdateEmpJob(@Body HashMap empJob, @Path(\"id\") int id);`\n\nWhere my `empJob` HashMap has as many properties of empJob entity as I want.\n\nCorresponding .Net WebApi generic controller which is inherited by all other controllers has this `PATCH` method.\n\n```\n [Route(\"{id:int}\")]\n [HttpPatch]\n public IHttpActionResult Patch(int id, Delta<T> ent)\n {\n if (!ModelState.IsValid) return BadRequest(ModelState);\n\n T origEnt = dbSet.Single(p => p.Id == id);\n\n if (origEnt == null) return NotFound();\n\n try\n {\n ent.Patch(origEnt);\n db.SaveChanges();\n\n return Ok(origEnt);\n }\n catch (Exception e)\n {\n while (e.InnerException != null) e = e.InnerException;\n return BadRequest(e.Message);\n }\n }\n```\n\n`\n"
] | [
":-o\n\nHow did this pass checkstyle?\n",
"And why did idea insist on doing that :p NP will fix when I get back online.\n\nOn Monday, August 5, 2013, Jake Wharton wrote:\n\n> In retrofit/src/test/java/retrofit/RestMethodInfoTest.java:\n> \n> > -import retrofit.http.Body;\n> > -import retrofit.http.DELETE;\n> > -import retrofit.http.Field;\n> > -import retrofit.http.FormUrlEncoded;\n> > -import retrofit.http.GET;\n> > -import retrofit.http.HEAD;\n> > -import retrofit.http.Header;\n> > -import retrofit.http.Headers;\n> > -import retrofit.http.Multipart;\n> > -import retrofit.http.POST;\n> > -import retrofit.http.PUT;\n> > -import retrofit.http.Part;\n> > -import retrofit.http.Path;\n> > -import retrofit.http.Query;\n> > -import retrofit.http.RestMethod;\n> > +import retrofit.http.*;\n> \n> :-o\n> \n> How did this pass checkstyle?\n> \n> —\n> Reply to this email directly or view it on GitHubhttps://github.com/square/retrofit/pull/294/files#r5587198\n> .\n",
"UGH! That's awful.\n",
"Hmm tests don't seem to be run through checkstyle. Not sure how I feel about that.\n",
"Kinda stupid that `setRequestMethod` uses strings for a fixed set of valid values. Great that you found a way to bypass that though!\n"
] | "2013-08-05T18:25:59Z" | [] | PATCH method support | The `PATCH` method can be used to only edit some properties of a resource, instead of overwriting it as `PUT` does. Unfortunately, Retrofit doesn't offer support for `PATCH` requests. Are there any plans of adding this request method?
| [
"retrofit/src/main/java/retrofit/client/UrlConnectionClient.java"
] | [
"retrofit/src/main/java/retrofit/client/UrlConnectionClient.java",
"retrofit/src/main/java/retrofit/http/PATCH.java"
] | [
"retrofit/src/test/java/retrofit/RestMethodInfoTest.java",
"retrofit/src/test/java/retrofit/client/UrlConnectionClientTest.java"
] | diff --git a/retrofit/src/main/java/retrofit/client/UrlConnectionClient.java b/retrofit/src/main/java/retrofit/client/UrlConnectionClient.java
index d7375d8b29..861ad3615d 100644
--- a/retrofit/src/main/java/retrofit/client/UrlConnectionClient.java
+++ b/retrofit/src/main/java/retrofit/client/UrlConnectionClient.java
@@ -17,16 +17,31 @@
import java.io.IOException;
import java.io.InputStream;
+import java.lang.reflect.Field;
import java.net.HttpURLConnection;
+import java.net.ProtocolException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
+
+import retrofit.RetrofitError;
import retrofit.mime.TypedInput;
import retrofit.mime.TypedOutput;
/** Retrofit client that uses {@link HttpURLConnection} for communication. */
public class UrlConnectionClient implements Client {
+ private final Field methodField;
+
+ public UrlConnectionClient() {
+ try {
+ this.methodField = HttpURLConnection.class.getDeclaredField("method");
+ this.methodField.setAccessible(true);
+ } catch (NoSuchFieldException e) {
+ throw RetrofitError.unexpectedError(null, e);
+ }
+ }
+
@Override public Response execute(Request request) throws IOException {
HttpURLConnection connection = openConnection(request);
prepareRequest(connection, request);
@@ -42,7 +57,17 @@ protected HttpURLConnection openConnection(Request request) throws IOException {
}
void prepareRequest(HttpURLConnection connection, Request request) throws IOException {
- connection.setRequestMethod(request.getMethod());
+ // HttpURLConnection artificially restricts request method
+ try {
+ connection.setRequestMethod(request.getMethod());
+ } catch (ProtocolException e) {
+ try {
+ methodField.set(connection, request.getMethod());
+ } catch (IllegalAccessException e1) {
+ throw RetrofitError.unexpectedError(request.getUrl(), e1);
+ }
+ }
+
connection.setDoInput(true);
for (Header header : request.getHeaders()) {
diff --git a/retrofit/src/main/java/retrofit/http/PATCH.java b/retrofit/src/main/java/retrofit/http/PATCH.java
new file mode 100644
index 0000000000..57f1739152
--- /dev/null
+++ b/retrofit/src/main/java/retrofit/http/PATCH.java
@@ -0,0 +1,30 @@
+/*
+ * 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.http;
+
+import java.lang.annotation.Retention;
+import java.lang.annotation.Target;
+
+import static java.lang.annotation.ElementType.METHOD;
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+
+/** Make a PATCH request to a REST path relative to base URL. */
+@Target(METHOD)
+@Retention(RUNTIME)
+@RestMethod(value = "PATCH", hasBody = true)
+public @interface PATCH {
+ String value();
+}
| diff --git a/retrofit/src/test/java/retrofit/RestMethodInfoTest.java b/retrofit/src/test/java/retrofit/RestMethodInfoTest.java
index 064c450d97..7d86636612 100644
--- a/retrofit/src/test/java/retrofit/RestMethodInfoTest.java
+++ b/retrofit/src/test/java/retrofit/RestMethodInfoTest.java
@@ -20,6 +20,7 @@
import retrofit.http.Header;
import retrofit.http.Headers;
import retrofit.http.Multipart;
+import retrofit.http.PATCH;
import retrofit.http.POST;
import retrofit.http.PUT;
import retrofit.http.Part;
@@ -315,6 +316,22 @@ class Example {
assertThat(methodInfo.requestUrl).isEqualTo("/foo");
}
+ @Test public void patchMethod() {
+ class Example {
+ @PATCH("/foo") Response a() {
+ return null;
+ }
+ }
+
+ Method method = TestingUtils.getMethod(Example.class, "a");
+ RestMethodInfo methodInfo = new RestMethodInfo(method);
+ methodInfo.init();
+
+ assertThat(methodInfo.requestMethod).isEqualTo("PATCH");
+ assertThat(methodInfo.requestHasBody).isTrue();
+ assertThat(methodInfo.requestUrl).isEqualTo("/foo");
+ }
+
@RestMethod("CUSTOM1")
@Target(METHOD) @Retention(RUNTIME)
private @interface CUSTOM1 {
diff --git a/retrofit/src/test/java/retrofit/client/UrlConnectionClientTest.java b/retrofit/src/test/java/retrofit/client/UrlConnectionClientTest.java
index 68fef779d9..e00f321ce9 100644
--- a/retrofit/src/test/java/retrofit/client/UrlConnectionClientTest.java
+++ b/retrofit/src/test/java/retrofit/client/UrlConnectionClientTest.java
@@ -37,6 +37,22 @@ public class UrlConnectionClientTest {
assertThat(connection.getHeaderFields()).isEmpty();
}
+ @Test public void patch() throws Exception {
+ TypedString body = new TypedString("hi");
+ Request request = new Request("PATCH", HOST + "/foo/bar/", null, body);
+
+ DummyHttpUrlConnection connection = (DummyHttpUrlConnection) client.openConnection(request);
+ client.prepareRequest(connection, request);
+
+ assertThat(connection.getRequestMethod()).isEqualTo("PATCH");
+ assertThat(connection.getURL().toString()).isEqualTo(HOST + "/foo/bar/");
+ assertThat(connection.getRequestProperties()).hasSize(2);
+ assertThat(connection.getRequestProperty("Content-Type")) //
+ .isEqualTo("text/plain; charset=UTF-8");
+ assertThat(connection.getRequestProperty("Content-Length")).isEqualTo("2");
+ assertBytes(connection.getOutputStream().toByteArray(), "hi");
+ }
+
@Test public void post() throws Exception {
TypedString body = new TypedString("hi");
Request request = new Request("POST", HOST + "/foo/bar/", null, body);
| test | train | 2013-07-25T08:21:08 | "2013-07-24T17:33:11Z" | marijnvdwerf | val |
square/retrofit/320_383 | square/retrofit | square/retrofit/320 | square/retrofit/383 | [
"timestamp(timedelta=9.0, similarity=0.8545729481843294)"
] | 9750f0045670fbd7494de43fdda1139349b84156 | ce5f5ae2921960d5c8f5e11757f527261ba144df | [
"Dupe #232. The server URL is a bit easier to include, however.\n"
] | [] | "2014-01-20T09:20:33Z" | [] | Add URL to callback responses. | It would be a good idea to add the URL that was was in the server object to the callback responses.
For instance if a changeable server is used and changed during asynchronous request before the callback is triggered it would be great to know what URL the response came from.
| [
"retrofit-mock/src/main/java/retrofit/MockHttpException.java",
"retrofit/src/main/java/retrofit/Utils.java",
"retrofit/src/main/java/retrofit/client/ApacheClient.java",
"retrofit/src/main/java/retrofit/client/Response.java",
"retrofit/src/main/java/retrofit/client/UrlConnectionClient.java"
] | [
"retrofit-mock/src/main/java/retrofit/MockHttpException.java",
"retrofit/src/main/java/retrofit/Utils.java",
"retrofit/src/main/java/retrofit/client/ApacheClient.java",
"retrofit/src/main/java/retrofit/client/Response.java",
"retrofit/src/main/java/retrofit/client/UrlConnectionClient.java"
] | [
"retrofit/src/test/java/retrofit/ErrorHandlerTest.java",
"retrofit/src/test/java/retrofit/RestAdapterTest.java",
"retrofit/src/test/java/retrofit/client/ApacheClientTest.java",
"retrofit/src/test/java/retrofit/client/UrlConnectionClientTest.java"
] | diff --git a/retrofit-mock/src/main/java/retrofit/MockHttpException.java b/retrofit-mock/src/main/java/retrofit/MockHttpException.java
index 87d18b3bf8..908cd562d3 100644
--- a/retrofit-mock/src/main/java/retrofit/MockHttpException.java
+++ b/retrofit-mock/src/main/java/retrofit/MockHttpException.java
@@ -102,6 +102,6 @@ public MockHttpException withHeader(String name, String value) {
}
Response toResponse(Converter converter) {
- return new Response(code, reason, headers, new MockTypedInput(converter, responseBody));
+ return new Response("", code, reason, headers, new MockTypedInput(converter, responseBody));
}
}
diff --git a/retrofit/src/main/java/retrofit/Utils.java b/retrofit/src/main/java/retrofit/Utils.java
index 4fbe02039a..49c0cbe755 100644
--- a/retrofit/src/main/java/retrofit/Utils.java
+++ b/retrofit/src/main/java/retrofit/Utils.java
@@ -93,7 +93,8 @@ static Response readBodyToBytesIfNecessary(Response response) throws IOException
}
static Response replaceResponseBody(Response response, TypedInput body) {
- return new Response(response.getStatus(), response.getReason(), response.getHeaders(), body);
+ return new Response(response.getUrl(), response.getStatus(), response.getReason(),
+ response.getHeaders(), body);
}
static <T> void validateServiceClass(Class<T> service) {
diff --git a/retrofit/src/main/java/retrofit/client/ApacheClient.java b/retrofit/src/main/java/retrofit/client/ApacheClient.java
index e65ff060ad..236e7005ec 100644
--- a/retrofit/src/main/java/retrofit/client/ApacheClient.java
+++ b/retrofit/src/main/java/retrofit/client/ApacheClient.java
@@ -62,7 +62,7 @@ public ApacheClient(HttpClient client) {
@Override public Response execute(Request request) throws IOException {
HttpUriRequest apacheRequest = createRequest(request);
HttpResponse apacheResponse = execute(client, apacheRequest);
- return parseResponse(apacheResponse);
+ return parseResponse(request.getUrl(), apacheResponse);
}
/** Execute the specified {@code request} using the provided {@code client}. */
@@ -74,7 +74,7 @@ static HttpUriRequest createRequest(Request request) {
return new GenericHttpRequest(request);
}
- static Response parseResponse(HttpResponse response) throws IOException {
+ static Response parseResponse(String url, HttpResponse response) throws IOException {
StatusLine statusLine = response.getStatusLine();
int status = statusLine.getStatusCode();
String reason = statusLine.getReasonPhrase();
@@ -97,7 +97,7 @@ static Response parseResponse(HttpResponse response) throws IOException {
body = new TypedByteArray(contentType, bytes);
}
- return new Response(status, reason, headers, body);
+ return new Response(url, status, reason, headers, body);
}
private static class GenericHttpRequest extends HttpEntityEnclosingRequestBase {
diff --git a/retrofit/src/main/java/retrofit/client/Response.java b/retrofit/src/main/java/retrofit/client/Response.java
index 44c1406b9a..9c605f232d 100644
--- a/retrofit/src/main/java/retrofit/client/Response.java
+++ b/retrofit/src/main/java/retrofit/client/Response.java
@@ -22,11 +22,34 @@
/** An HTTP response. */
public final class Response {
+ private final String url;
private final int status;
private final String reason;
private final List<Header> headers;
private final TypedInput body;
+ public Response(String url, int status, String reason, List<Header> headers, TypedInput body) {
+ if (url == null) {
+ throw new IllegalArgumentException("url == null");
+ }
+ if (status < 200) {
+ throw new IllegalArgumentException("Invalid status code: " + status);
+ }
+ if (reason == null) {
+ throw new IllegalArgumentException("reason == null");
+ }
+ if (headers == null) {
+ throw new IllegalArgumentException("headers == null");
+ }
+
+ this.url = url;
+ this.status = status;
+ this.reason = reason;
+ this.headers = Collections.unmodifiableList(new ArrayList<Header>(headers));
+ this.body = body;
+ }
+
+ @Deprecated
public Response(int status, String reason, List<Header> headers, TypedInput body) {
if (status < 200) {
throw new IllegalArgumentException("Invalid status code: " + status);
@@ -38,12 +61,18 @@ public Response(int status, String reason, List<Header> headers, TypedInput body
throw new IllegalArgumentException("headers == null");
}
+ this.url = null;
this.status = status;
this.reason = reason;
this.headers = Collections.unmodifiableList(new ArrayList<Header>(headers));
this.body = body;
}
+ /** Request URL. */
+ public String getUrl() {
+ return url;
+ }
+
/** Status line code. */
public int getStatus() {
return status;
diff --git a/retrofit/src/main/java/retrofit/client/UrlConnectionClient.java b/retrofit/src/main/java/retrofit/client/UrlConnectionClient.java
index 10eaf37238..97fbbceff2 100644
--- a/retrofit/src/main/java/retrofit/client/UrlConnectionClient.java
+++ b/retrofit/src/main/java/retrofit/client/UrlConnectionClient.java
@@ -111,7 +111,7 @@ Response readResponse(HttpURLConnection connection) throws IOException {
stream = connection.getInputStream();
}
TypedInput responseBody = new TypedInputStream(mimeType, length, stream);
- return new Response(status, reason, headers, responseBody);
+ return new Response(connection.getURL().toString(), status, reason, headers, responseBody);
}
private static class TypedInputStream implements TypedInput {
| diff --git a/retrofit/src/test/java/retrofit/ErrorHandlerTest.java b/retrofit/src/test/java/retrofit/ErrorHandlerTest.java
index 981b3b05b1..4230d5b96a 100644
--- a/retrofit/src/test/java/retrofit/ErrorHandlerTest.java
+++ b/retrofit/src/test/java/retrofit/ErrorHandlerTest.java
@@ -30,7 +30,7 @@ static class TestException extends Exception {
/* An HTTP client which always returns a 400 response */
static class MockInvalidResponseClient implements Client {
@Override public Response execute(Request request) throws IOException {
- return new Response(400, "invalid request", Collections.<Header>emptyList(), null);
+ return new Response("", 400, "invalid request", Collections.<Header>emptyList(), null);
}
}
diff --git a/retrofit/src/test/java/retrofit/RestAdapterTest.java b/retrofit/src/test/java/retrofit/RestAdapterTest.java
index 67fa3cf1fb..4239c693cc 100644
--- a/retrofit/src/test/java/retrofit/RestAdapterTest.java
+++ b/retrofit/src/test/java/retrofit/RestAdapterTest.java
@@ -127,7 +127,7 @@ private interface InvalidExample extends Example {
Object data = new Object();
when(mockProfiler.beforeCall()).thenReturn(data);
when(mockClient.execute(any(Request.class))) //
- .thenReturn(new Response(200, "OK", NO_HEADERS, null));
+ .thenReturn(new Response("http://example.com/", 200, "OK", NO_HEADERS, null));
example.something();
@@ -155,7 +155,7 @@ public void log(String message) {
.create(Example.class);
when(mockClient.execute(any(Request.class))) //
- .thenReturn(new Response(200, "OK", TWO_HEADERS, new TypedString("{}")));
+ .thenReturn(new Response("http://example.com/", 200, "OK", TWO_HEADERS, new TypedString("{}")));
example.something();
assertThat(logMessages).hasSize(2);
@@ -182,7 +182,7 @@ public void log(String message) {
.create(Example.class);
when(mockClient.execute(any(Request.class))) //
- .thenReturn(new Response(200, "OK", TWO_HEADERS, new TypedString("{}")));
+ .thenReturn(new Response("http://example.com/", 200, "OK", TWO_HEADERS, new TypedString("{}")));
example.something();
assertThat(logMessages).hasSize(7);
@@ -214,7 +214,7 @@ public void log(String message) {
.create(Example.class);
when(mockClient.execute(any(Request.class))) //
- .thenReturn(new Response(200, "OK", TWO_HEADERS, new TypedString("{}")));
+ .thenReturn(new Response("http://example.com/", 200, "OK", TWO_HEADERS, new TypedString("{}")));
example.something(new TypedString("Hi"));
assertThat(logMessages).hasSize(13);
@@ -252,7 +252,7 @@ public void log(String message) {
.create(Example.class);
when(mockClient.execute(any(Request.class))) //
- .thenReturn(new Response(200, "OK", TWO_HEADERS, null));
+ .thenReturn(new Response("http://example.com/", 200, "OK", TWO_HEADERS, null));
example.something();
assertThat(logMessages).hasSize(7);
@@ -267,7 +267,7 @@ public void log(String message) {
@Test public void successfulRequestResponseWhenMimeTypeMissing() throws Exception {
when(mockClient.execute(any(Request.class))) //
- .thenReturn(new Response(200, "OK", NO_HEADERS, NO_MIME_BODY));
+ .thenReturn(new Response("http://example.com/", 200, "OK", NO_HEADERS, NO_MIME_BODY));
example.something();
}
@@ -291,7 +291,7 @@ public void log(String message) {
.create(Example.class);
when(mockClient.execute(any(Request.class))) //
- .thenReturn(new Response(200, "OK", TWO_HEADERS, NO_MIME_BODY));
+ .thenReturn(new Response("http://example.com/", 200, "OK", TWO_HEADERS, NO_MIME_BODY));
example.something();
assertThat(logMessages).hasSize(9);
@@ -308,7 +308,7 @@ public void log(String message) {
@Test public void synchronousDoesNotUseExecutors() throws Exception {
when(mockClient.execute(any(Request.class))) //
- .thenReturn(new Response(200, "OK", NO_HEADERS, null));
+ .thenReturn(new Response("http://example.com/", 200, "OK", NO_HEADERS, null));
example.something();
@@ -317,7 +317,7 @@ public void log(String message) {
}
@Test public void asynchronousUsesExecutors() throws Exception {
- Response response = new Response(200, "OK", NO_HEADERS, new TypedString("{}"));
+ Response response = new Response("http://example.com/", 200, "OK", NO_HEADERS, new TypedString("{}"));
when(mockClient.execute(any(Request.class))).thenReturn(response);
Callback<Object> callback = mock(Callback.class);
@@ -330,7 +330,7 @@ public void log(String message) {
@Test public void malformedResponseThrowsConversionException() throws Exception {
when(mockClient.execute(any(Request.class))) //
- .thenReturn(new Response(200, "OK", NO_HEADERS, new TypedString("{")));
+ .thenReturn(new Response("http://example.com/", 200, "OK", NO_HEADERS, new TypedString("{")));
try {
example.something();
@@ -344,7 +344,7 @@ public void log(String message) {
@Test public void errorResponseThrowsHttpError() throws Exception {
when(mockClient.execute(any(Request.class))) //
- .thenReturn(new Response(500, "Internal Server Error", NO_HEADERS, null));
+ .thenReturn(new Response("http://example.com/", 500, "Internal Server Error", NO_HEADERS, null));
try {
example.something();
@@ -373,7 +373,7 @@ public void log(String message) {
.create(Example.class);
Response responseMissingMimeType = //
- new Response(403, "Forbidden", TWO_HEADERS, NO_MIME_BODY);
+ new Response("http://example.com/", 403, "Forbidden", TWO_HEADERS, NO_MIME_BODY);
when(mockClient.execute(any(Request.class))).thenReturn(responseMissingMimeType);
@@ -415,7 +415,7 @@ public void log(String message) {
.create(Example.class);
when(mockClient.execute(any(Request.class))) //
- .thenReturn(new Response(500, "Internal Server Error", TWO_HEADERS, null));
+ .thenReturn(new Response("http://example.com/", 500, "Internal Server Error", TWO_HEADERS, null));
try {
example.something();
@@ -456,7 +456,7 @@ public void log(String message) {
doReturn(bodyStream).when(body).in();
when(mockClient.execute(any(Request.class))) //
- .thenReturn(new Response(200, "OK", NO_HEADERS, body));
+ .thenReturn(new Response("http://example.com/", 200, "OK", NO_HEADERS, body));
try {
example.something();
@@ -481,7 +481,7 @@ public void log(String message) {
}
@Test public void getResponseDirectly() throws Exception {
- Response response = new Response(200, "OK", NO_HEADERS, null);
+ Response response = new Response("http://example.com/", 200, "OK", NO_HEADERS, null);
when(mockClient.execute(any(Request.class))) //
.thenReturn(response);
assertThat(example.direct()).isSameAs(response);
@@ -502,7 +502,7 @@ public void log(String message) {
ByteArrayInputStream is = spy(new ByteArrayInputStream("hello".getBytes()));
TypedInput typedInput = mock(TypedInput.class);
when(typedInput.in()).thenReturn(is);
- Response response = new Response(200, "OK", NO_HEADERS, typedInput);
+ Response response = new Response("http://example.com/", 200, "OK", NO_HEADERS, typedInput);
when(mockClient.execute(any(Request.class))) //
.thenReturn(response);
example.something();
@@ -510,7 +510,7 @@ public void log(String message) {
}
@Test public void getResponseDirectlyAsync() throws Exception {
- Response response = new Response(200, "OK", NO_HEADERS, null);
+ Response response = new Response("http://example.com/", 200, "OK", NO_HEADERS, null);
when(mockClient.execute(any(Request.class))) //
.thenReturn(response);
Callback<Response> callback = mock(Callback.class);
@@ -524,7 +524,7 @@ public void log(String message) {
@Test public void observableCallsOnNext() throws Exception {
when(mockClient.execute(any(Request.class))) //
- .thenReturn(new Response(200, "OK", NO_HEADERS, new TypedString("hello")));
+ .thenReturn(new Response("http://example.com/", 200, "OK", NO_HEADERS, new TypedString("hello")));
Action1<String> action = mock(Action1.class);
example.observable("Howdy").subscribe(action);
verify(action).call(eq("hello"));
@@ -532,7 +532,7 @@ public void log(String message) {
@Test public void observableCallsOnError() throws Exception {
when(mockClient.execute(any(Request.class))) //
- .thenReturn(new Response(300, "FAIL", NO_HEADERS, new TypedString("bummer")));
+ .thenReturn(new Response("http://example.com/", 300, "FAIL", NO_HEADERS, new TypedString("bummer")));
Action1<String> onSuccess = mock(Action1.class);
Action1<Throwable> onError = mock(Action1.class);
example.observable("Howdy").subscribe(onSuccess, onError);
@@ -543,7 +543,7 @@ public void log(String message) {
@Test public void observableHandlesParams() throws Exception {
ArgumentCaptor<Request> requestCaptor = ArgumentCaptor.forClass(Request.class);
when(mockClient.execute(requestCaptor.capture())) //
- .thenReturn(new Response(200, "OK", NO_HEADERS, new TypedString("hello")));
+ .thenReturn(new Response("http://example.com/", 200, "OK", NO_HEADERS, new TypedString("hello")));
ArgumentCaptor<Response> responseCaptor = ArgumentCaptor.forClass(Response.class);
Action1<Response> action = mock(Action1.class);
example.observable("X", "Y").subscribe(action);
@@ -557,7 +557,7 @@ public void log(String message) {
}
@Test public void observableUsesHttpExecutor() throws IOException {
- Response response = new Response(200, "OK", NO_HEADERS, new TypedString("hello"));
+ Response response = new Response("http://example.com/", 200, "OK", NO_HEADERS, new TypedString("hello"));
when(mockClient.execute(any(Request.class))).thenReturn(response);
example.observable("Howdy").subscribe(mock(Action1.class));
diff --git a/retrofit/src/test/java/retrofit/client/ApacheClientTest.java b/retrofit/src/test/java/retrofit/client/ApacheClientTest.java
index 82e51fb96d..74cc4c3bb8 100644
--- a/retrofit/src/test/java/retrofit/client/ApacheClientTest.java
+++ b/retrofit/src/test/java/retrofit/client/ApacheClientTest.java
@@ -100,8 +100,9 @@ public class ApacheClientTest {
apacheResponse.addHeader("Content-Type", "text/plain");
apacheResponse.addHeader("foo", "bar");
apacheResponse.addHeader("kit", "kat");
- Response response = ApacheClient.parseResponse(apacheResponse);
+ Response response = ApacheClient.parseResponse(HOST + "/foo/bar/", apacheResponse);
+ assertThat(response.getUrl()).isEqualTo(HOST + "/foo/bar/");
assertThat(response.getStatus()).isEqualTo(200);
assertThat(response.getReason()).isEqualTo("OK");
assertThat(response.getHeaders()).hasSize(3) //
@@ -115,8 +116,9 @@ public class ApacheClientTest {
HttpResponse apacheResponse = new BasicHttpResponse(statusLine);
apacheResponse.addHeader("foo", "bar");
apacheResponse.addHeader("kit", "kat");
- Response response = ApacheClient.parseResponse(apacheResponse);
+ Response response = ApacheClient.parseResponse(HOST + "/foo/bar/", apacheResponse);
+ assertThat(response.getUrl()).isEqualTo(HOST + "/foo/bar/");
assertThat(response.getStatus()).isEqualTo(200);
assertThat(response.getReason()).isEqualTo("OK");
assertThat(response.getHeaders()).hasSize(2) //
diff --git a/retrofit/src/test/java/retrofit/client/UrlConnectionClientTest.java b/retrofit/src/test/java/retrofit/client/UrlConnectionClientTest.java
index e00f321ce9..4adb93fc75 100644
--- a/retrofit/src/test/java/retrofit/client/UrlConnectionClientTest.java
+++ b/retrofit/src/test/java/retrofit/client/UrlConnectionClientTest.java
@@ -113,6 +113,7 @@ public class UrlConnectionClientTest {
connection.setInputStream(new ByteArrayInputStream("hello".getBytes("UTF-8")));
Response response = client.readResponse(connection);
+ assertThat(response.getUrl()).isEqualTo(HOST);
assertThat(response.getStatus()).isEqualTo(200);
assertThat(response.getReason()).isEqualTo("OK");
assertThat(response.getHeaders()).hasSize(3) //
@@ -131,6 +132,7 @@ public class UrlConnectionClientTest {
connection.setInputStream(new ByteArrayInputStream("hello".getBytes("UTF-8")));
Response response = client.readResponse(connection);
+ assertThat(response.getUrl()).isEqualTo(HOST);
assertThat(response.getStatus()).isEqualTo(201);
assertThat(response.getReason()).isEqualTo("OK");
assertThat(response.getHeaders()).hasSize(3) //
@@ -159,6 +161,7 @@ public class UrlConnectionClientTest {
connection.addResponseHeader("kit", "kat");
Response response = client.readResponse(connection);
+ assertThat(response.getUrl()).isEqualTo(HOST);
assertThat(response.getStatus()).isEqualTo(200);
assertThat(response.getReason()).isEqualTo("OK");
assertThat(response.getHeaders()).hasSize(2) //
| val | train | 2014-01-14T22:53:59 | "2013-08-29T22:54:07Z" | jjNford | val |
square/retrofit/338_401 | square/retrofit | square/retrofit/338 | square/retrofit/401 | [
"timestamp(timedelta=0.0, similarity=0.8572497243187753)"
] | 883a7c9b07a158b201e234d54ced9943b84bafb3 | a780256beeafa32bcb1a9554fd624971555816c6 | [
"@mattstep what's the state of the art for testing http binders against app engine?\n",
"Yo, hmm, good question. I've not touched that in a few months. I can respin context when I've got some time, if there isn't a Bart strike this week, wanna meet up for coffee? Might be able to use some of the hooks we added for CapeDwarf...\n",
"@mattstep pretty busy this week and out some of next. eom is pretty open so will follow-up offline\n",
"Sweet, give me a call or hit me on irc.\n"
] | [] | "2014-02-03T07:32:09Z" | [] | Evaluate Better AppEngine support | Reflection is not allowed in our use of `HttpUrlConnection`. Easy solution is to disable on that platform. Harder but arguably better solution is to use their [URL fetch API](https://developers.google.com/appengine/docs/java/javadoc/com/google/appengine/api/urlfetch/package-summary).
| [
"pom.xml",
"retrofit/pom.xml",
"retrofit/src/main/java/retrofit/Platform.java"
] | [
"pom.xml",
"retrofit/pom.xml",
"retrofit/src/main/java/retrofit/Platform.java",
"retrofit/src/main/java/retrofit/appengine/UrlFetchClient.java"
] | [
"retrofit/src/test/java/retrofit/TestingUtils.java",
"retrofit/src/test/java/retrofit/appengine/UrlFetchClientTest.java",
"retrofit/src/test/java/retrofit/client/ApacheClientTest.java"
] | diff --git a/pom.xml b/pom.xml
index e5c02f88d7..2ac4e7298c 100644
--- a/pom.xml
+++ b/pom.xml
@@ -52,6 +52,7 @@
<gson.version>2.2.4</gson.version>
<okhttp.version>1.3.0</okhttp.version>
<rxjava.version>0.16.1</rxjava.version>
+ <appengine.version>1.8.9</appengine.version>
<!-- Converter Dependencies -->
<protobuf.version>2.5.0</protobuf.version>
@@ -111,6 +112,11 @@
<artifactId>rxjava-core</artifactId>
<version>${rxjava.version}</version>
</dependency>
+ <dependency>
+ <groupId>com.google.appengine</groupId>
+ <artifactId>appengine-api-1.0-sdk</artifactId>
+ <version>${appengine.version}</version>
+ </dependency>
<dependency>
<groupId>com.google.protobuf</groupId>
diff --git a/retrofit/pom.xml b/retrofit/pom.xml
index 7cbf095770..c964f9b48f 100644
--- a/retrofit/pom.xml
+++ b/retrofit/pom.xml
@@ -18,6 +18,7 @@
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
</dependency>
+
<dependency>
<groupId>com.google.android</groupId>
<artifactId>android</artifactId>
@@ -33,6 +34,11 @@
<artifactId>rxjava-core</artifactId>
<optional>true</optional>
</dependency>
+ <dependency>
+ <groupId>com.google.appengine</groupId>
+ <artifactId>appengine-api-1.0-sdk</artifactId>
+ <optional>true</optional>
+ </dependency>
<dependency>
<groupId>junit</groupId>
@@ -55,4 +61,17 @@
<scope>test</scope>
</dependency>
</dependencies>
+
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-compiler-plugin</artifactId>
+ <configuration>
+ <!-- The AppEngine dependency has an annotation processor we don't want to run. -->
+ <compilerArgument>-proc:none</compilerArgument>
+ </configuration>
+ </plugin>
+ </plugins>
+ </build>
</project>
diff --git a/retrofit/src/main/java/retrofit/Platform.java b/retrofit/src/main/java/retrofit/Platform.java
index 2276419408..3e76c3dbe4 100644
--- a/retrofit/src/main/java/retrofit/Platform.java
+++ b/retrofit/src/main/java/retrofit/Platform.java
@@ -24,6 +24,7 @@
import retrofit.android.AndroidApacheClient;
import retrofit.android.AndroidLog;
import retrofit.android.MainThreadExecutor;
+import retrofit.appengine.UrlFetchClient;
import retrofit.client.Client;
import retrofit.client.OkClient;
import retrofit.client.UrlConnectionClient;
@@ -50,6 +51,11 @@ private static Platform findPlatform() {
}
} catch (ClassNotFoundException ignored) {
}
+
+ if (System.getProperty("com.google.appengine.runtime.version") != null) {
+ return new AppEngine();
+ }
+
return new Base();
}
@@ -149,6 +155,17 @@ private static class Android extends Platform {
}
}
+ private static class AppEngine extends Base {
+ @Override Client.Provider defaultClient() {
+ final UrlFetchClient client = new UrlFetchClient();
+ return new Client.Provider() {
+ @Override public Client get() {
+ return client;
+ }
+ };
+ }
+ }
+
/** Determine whether or not OkHttp is present on the runtime classpath. */
private static boolean hasOkHttpOnClasspath() {
try {
diff --git a/retrofit/src/main/java/retrofit/appengine/UrlFetchClient.java b/retrofit/src/main/java/retrofit/appengine/UrlFetchClient.java
new file mode 100644
index 0000000000..fd25039c34
--- /dev/null
+++ b/retrofit/src/main/java/retrofit/appengine/UrlFetchClient.java
@@ -0,0 +1,112 @@
+package retrofit.appengine;
+
+import com.google.appengine.api.urlfetch.HTTPHeader;
+import com.google.appengine.api.urlfetch.HTTPMethod;
+import com.google.appengine.api.urlfetch.HTTPRequest;
+import com.google.appengine.api.urlfetch.HTTPResponse;
+import com.google.appengine.api.urlfetch.URLFetchService;
+import com.google.appengine.api.urlfetch.URLFetchServiceFactory;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.net.URL;
+import java.util.ArrayList;
+import java.util.List;
+import retrofit.client.Client;
+import retrofit.client.Header;
+import retrofit.client.Request;
+import retrofit.client.Response;
+import retrofit.mime.TypedByteArray;
+import retrofit.mime.TypedOutput;
+
+/** A {@link Client} for Google AppEngine's which uses its {@link URLFetchService}. */
+public class UrlFetchClient implements Client {
+ private static HTTPMethod getHttpMethod(String method) {
+ if ("GET".equals(method)) {
+ return HTTPMethod.GET;
+ } else if ("POST".equals(method)) {
+ return HTTPMethod.POST;
+ } else if ("PATCH".equals(method)) {
+ return HTTPMethod.PATCH;
+ } else if ("PUT".equals(method)) {
+ return HTTPMethod.PUT;
+ } else if ("DELETE".equals(method)) {
+ return HTTPMethod.DELETE;
+ } else if ("HEAD".equals(method)) {
+ return HTTPMethod.HEAD;
+ } else {
+ throw new IllegalStateException("Illegal HTTP method: " + method);
+ }
+ }
+
+ private final URLFetchService urlFetchService;
+
+ public UrlFetchClient() {
+ this(URLFetchServiceFactory.getURLFetchService());
+ }
+
+ public UrlFetchClient(URLFetchService urlFetchService) {
+ this.urlFetchService = urlFetchService;
+ }
+
+ @Override public Response execute(Request request) throws IOException {
+ HTTPRequest fetchRequest = createRequest(request);
+ HTTPResponse fetchResponse = execute(urlFetchService, fetchRequest);
+ return parseResponse(fetchResponse);
+ }
+
+ /** Execute the specified {@code request} using the provided {@code urlFetchService}. */
+ protected HTTPResponse execute(URLFetchService urlFetchService, HTTPRequest request)
+ throws IOException {
+ return urlFetchService.fetch(request);
+ }
+
+ static HTTPRequest createRequest(Request request) throws IOException {
+ HTTPMethod httpMethod = getHttpMethod(request.getMethod());
+ URL url = new URL(request.getUrl());
+ HTTPRequest fetchRequest = new HTTPRequest(url, httpMethod);
+
+ for (Header header : request.getHeaders()) {
+ fetchRequest.addHeader(new HTTPHeader(header.getName(), header.getValue()));
+ }
+
+ TypedOutput body = request.getBody();
+ if (body != null) {
+ fetchRequest.setHeader(new HTTPHeader("Content-Type", body.mimeType()));
+ long length = body.length();
+ if (length != -1) {
+ fetchRequest.setHeader(new HTTPHeader("Content-Length", String.valueOf(length)));
+ }
+
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ body.writeTo(baos);
+ fetchRequest.setPayload(baos.toByteArray());
+ }
+
+ return fetchRequest;
+ }
+
+ static Response parseResponse(HTTPResponse response) {
+ String url = response.getFinalUrl().toString();
+ int status = response.getResponseCode();
+
+ List<HTTPHeader> fetchHeaders = response.getHeaders();
+ List<Header> headers = new ArrayList<Header>(fetchHeaders.size());
+ String contentType = "application/octet-stream";
+ for (HTTPHeader fetchHeader : fetchHeaders) {
+ String name = fetchHeader.getName();
+ String value = fetchHeader.getValue();
+ if ("Content-Type".equalsIgnoreCase(name)) {
+ contentType = value;
+ }
+ headers.add(new Header(name, value));
+ }
+
+ TypedByteArray body = null;
+ byte[] fetchBody = response.getContent();
+ if (fetchBody != null) {
+ body = new TypedByteArray(contentType, fetchBody);
+ }
+
+ return new Response(url, status, "", headers, body);
+ }
+}
| diff --git a/retrofit/src/test/java/retrofit/TestingUtils.java b/retrofit/src/test/java/retrofit/TestingUtils.java
index 709b1bcb5c..a4a031fe7a 100644
--- a/retrofit/src/test/java/retrofit/TestingUtils.java
+++ b/retrofit/src/test/java/retrofit/TestingUtils.java
@@ -1,6 +1,7 @@
// Copyright 2013 Square, Inc.
package retrofit;
+import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Map;
import retrofit.mime.MultipartTypedOutput;
@@ -26,11 +27,7 @@ public static TypedOutput createMultipart(Map<String, TypedOutput> parts) {
return typedOutput;
}
- public static void assertMultipart(TypedOutput typedOutput) {
- assertThat(typedOutput).isInstanceOf(MultipartTypedOutput.class);
- }
-
- public static void assertBytes(byte[] bytes, String expected) throws Exception {
+ public static void assertBytes(byte[] bytes, String expected) throws IOException {
assertThat(new String(bytes, "UTF-8")).isEqualTo(expected);
}
}
diff --git a/retrofit/src/test/java/retrofit/appengine/UrlFetchClientTest.java b/retrofit/src/test/java/retrofit/appengine/UrlFetchClientTest.java
new file mode 100644
index 0000000000..76b942a248
--- /dev/null
+++ b/retrofit/src/test/java/retrofit/appengine/UrlFetchClientTest.java
@@ -0,0 +1,131 @@
+// Copyright 2014 Square, Inc.
+package retrofit.appengine;
+
+import com.google.appengine.api.urlfetch.HTTPHeader;
+import com.google.appengine.api.urlfetch.HTTPRequest;
+import com.google.appengine.api.urlfetch.HTTPResponse;
+import com.google.common.io.ByteStreams;
+import java.io.IOException;
+import java.net.URL;
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import org.junit.Test;
+import retrofit.TestingUtils;
+import retrofit.client.Header;
+import retrofit.client.Request;
+import retrofit.client.Response;
+import retrofit.mime.TypedOutput;
+import retrofit.mime.TypedString;
+
+import static com.google.appengine.api.urlfetch.HTTPMethod.GET;
+import static com.google.appengine.api.urlfetch.HTTPMethod.POST;
+import static java.util.Arrays.asList;
+import static org.fest.assertions.api.Assertions.assertThat;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+import static retrofit.TestingUtils.assertBytes;
+
+public class UrlFetchClientTest {
+ private static final String HOST = "http://example.com";
+
+ @Test public void get() throws IOException {
+ Request request = new Request("GET", HOST + "/foo/bar/?kit=kat", null, null);
+ HTTPRequest fetchRequest = UrlFetchClient.createRequest(request);
+
+ assertThat(fetchRequest.getMethod()).isEqualTo(GET);
+ assertThat(fetchRequest.getURL().toString()).isEqualTo(HOST + "/foo/bar/?kit=kat");
+ assertThat(fetchRequest.getHeaders()).isEmpty();
+ assertThat(fetchRequest.getPayload()).isNull();
+ }
+
+ @Test public void post() throws IOException {
+ TypedString body = new TypedString("hi");
+ Request request = new Request("POST", HOST + "/foo/bar/", null, body);
+ HTTPRequest fetchRequest = UrlFetchClient.createRequest(request);
+
+ assertThat(fetchRequest.getMethod()).isEqualTo(POST);
+ assertThat(fetchRequest.getURL().toString()).isEqualTo(HOST + "/foo/bar/");
+ List<HTTPHeader> fetchHeaders = fetchRequest.getHeaders();
+ assertThat(fetchHeaders).hasSize(2);
+ assertHeader(fetchHeaders.get(0), "Content-Type", "text/plain; charset=UTF-8");
+ assertHeader(fetchHeaders.get(1), "Content-Length", "2");
+ assertBytes(fetchRequest.getPayload(), "hi");
+ }
+
+ @Test public void multipart() throws IOException {
+ Map<String, TypedOutput> bodyParams = new LinkedHashMap<String, TypedOutput>();
+ bodyParams.put("foo", new TypedString("bar"));
+ bodyParams.put("ping", new TypedString("pong"));
+ TypedOutput body = TestingUtils.createMultipart(bodyParams);
+ Request request = new Request("POST", HOST + "/that/", null, body);
+ HTTPRequest fetchRequest = UrlFetchClient.createRequest(request);
+
+ assertThat(fetchRequest.getMethod()).isEqualTo(POST);
+ assertThat(fetchRequest.getURL().toString()).isEqualTo(HOST + "/that/");
+ List<HTTPHeader> fetchHeaders = fetchRequest.getHeaders();
+ assertThat(fetchHeaders).hasSize(2);
+ HTTPHeader headerZero = fetchHeaders.get(0);
+ assertThat(headerZero.getName()).isEqualTo("Content-Type");
+ assertThat(headerZero.getValue()).startsWith("multipart/form-data; boundary=");
+ assertHeader(fetchHeaders.get(1), "Content-Length", String.valueOf(body.length()));
+ assertThat(fetchRequest.getPayload()).isNotEmpty();
+ }
+
+ @Test public void headers() throws IOException {
+ List<Header> headers = new ArrayList<Header>();
+ headers.add(new Header("kit", "kat"));
+ headers.add(new Header("foo", "bar"));
+ Request request = new Request("GET", HOST + "/this/", headers, null);
+ HTTPRequest fetchRequest = UrlFetchClient.createRequest(request);
+
+ List<HTTPHeader> fetchHeaders = fetchRequest.getHeaders();
+ assertThat(fetchHeaders).hasSize(2);
+ assertHeader(fetchHeaders.get(0), "kit", "kat");
+ assertHeader(fetchHeaders.get(1), "foo", "bar");
+ }
+
+ @Test public void response() throws Exception {
+ HTTPResponse fetchResponse = mock(HTTPResponse.class);
+ when(fetchResponse.getHeaders()).thenReturn(
+ asList(new HTTPHeader("foo", "bar"), new HTTPHeader("kit", "kat"),
+ new HTTPHeader("Content-Type", "text/plain")));
+ when(fetchResponse.getContent()).thenReturn("hello".getBytes("UTF-8"));
+ when(fetchResponse.getFinalUrl()).thenReturn(new URL(HOST + "/foo/bar/"));
+ when(fetchResponse.getResponseCode()).thenReturn(200);
+
+ Response response = UrlFetchClient.parseResponse(fetchResponse);
+
+ assertThat(response.getUrl()).isEqualTo(HOST + "/foo/bar/");
+ assertThat(response.getStatus()).isEqualTo(200);
+ assertThat(response.getReason()).isEqualTo("");
+ assertThat(response.getHeaders()).hasSize(3) //
+ .containsOnly(new Header("foo", "bar"), new Header("kit", "kat"),
+ new Header("Content-Type", "text/plain"));
+ assertBytes(ByteStreams.toByteArray(response.getBody().in()), "hello");
+ }
+
+ @Test public void emptyResponse() throws Exception {
+ HTTPResponse fetchResponse = mock(HTTPResponse.class);
+ when(fetchResponse.getHeaders()).thenReturn(
+ asList(new HTTPHeader("foo", "bar"), new HTTPHeader("kit", "kat")));
+ when(fetchResponse.getContent()).thenReturn(null);
+ when(fetchResponse.getFinalUrl()).thenReturn(new URL(HOST + "/foo/bar/"));
+ when(fetchResponse.getResponseCode()).thenReturn(200);
+
+ Response response = UrlFetchClient.parseResponse(fetchResponse);
+
+ assertThat(response.getUrl()).isEqualTo(HOST + "/foo/bar/");
+ assertThat(response.getStatus()).isEqualTo(200);
+ assertThat(response.getReason()).isEqualTo("");
+ assertThat(response.getHeaders()).hasSize(2) //
+ .containsExactly(new Header("foo", "bar"), new Header("kit", "kat"));
+ assertThat(response.getBody()).isNull();
+ }
+
+ private static void assertHeader(HTTPHeader header, String name, String value) {
+ assertThat(header.getName()).isEqualTo(name);
+ assertThat(header.getValue()).isEqualTo(value);
+ }
+}
diff --git a/retrofit/src/test/java/retrofit/client/ApacheClientTest.java b/retrofit/src/test/java/retrofit/client/ApacheClientTest.java
index 74cc4c3bb8..59dd74a07c 100644
--- a/retrofit/src/test/java/retrofit/client/ApacheClientTest.java
+++ b/retrofit/src/test/java/retrofit/client/ApacheClientTest.java
@@ -2,6 +2,7 @@
package retrofit.client;
import com.google.common.io.ByteStreams;
+import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
@@ -16,12 +17,12 @@
import org.apache.http.message.BasicStatusLine;
import org.junit.Test;
import retrofit.TestingUtils;
+import retrofit.mime.MultipartTypedOutput;
import retrofit.mime.TypedOutput;
import retrofit.mime.TypedString;
import static org.fest.assertions.api.Assertions.assertThat;
import static retrofit.TestingUtils.assertBytes;
-import static retrofit.TestingUtils.assertMultipart;
import static retrofit.client.ApacheClient.TypedOutputEntity;
public class ApacheClientTest {
@@ -41,14 +42,14 @@ public class ApacheClientTest {
}
}
- @Test public void post() throws Exception {
+ @Test public void post() throws IOException {
TypedString body = new TypedString("hi");
Request request = new Request("POST", HOST + "/foo/bar/", null, body);
HttpUriRequest apacheRequest = ApacheClient.createRequest(request);
assertThat(apacheRequest.getMethod()).isEqualTo("POST");
assertThat(apacheRequest.getURI().toString()).isEqualTo(HOST + "/foo/bar/");
- assertThat(apacheRequest.getAllHeaders()).hasSize(0);
+ assertThat(apacheRequest.getAllHeaders()).isEmpty();
assertThat(apacheRequest).isInstanceOf(HttpEntityEnclosingRequest.class);
HttpEntityEnclosingRequest entityRequest = (HttpEntityEnclosingRequest) apacheRequest;
@@ -68,12 +69,12 @@ public class ApacheClientTest {
assertThat(apacheRequest.getMethod()).isEqualTo("POST");
assertThat(apacheRequest.getURI().toString()).isEqualTo(HOST + "/that/");
- assertThat(apacheRequest.getAllHeaders()).hasSize(0);
+ assertThat(apacheRequest.getAllHeaders()).isEmpty();
assertThat(apacheRequest).isInstanceOf(HttpEntityEnclosingRequest.class);
HttpEntityEnclosingRequest entityRequest = (HttpEntityEnclosingRequest) apacheRequest;
TypedOutputEntity entity = (TypedOutputEntity) entityRequest.getEntity();
- assertMultipart(entity.typedOutput);
+ assertThat(entity.typedOutput).isInstanceOf(MultipartTypedOutput.class);
// TODO test more?
}
@@ -93,7 +94,7 @@ public class ApacheClientTest {
assertThat(foo.getValue()).isEqualTo("bar");
}
- @Test public void response() throws Exception {
+ @Test public void response() throws IOException {
StatusLine statusLine = new BasicStatusLine(HttpVersion.HTTP_1_1, 200, "OK");
HttpResponse apacheResponse = new BasicHttpResponse(statusLine);
apacheResponse.setEntity(new TypedOutputEntity(new TypedString("hello")));
@@ -111,7 +112,7 @@ public class ApacheClientTest {
assertBytes(ByteStreams.toByteArray(response.getBody().in()), "hello");
}
- @Test public void emptyResponse() throws Exception {
+ @Test public void emptyResponse() throws IOException {
StatusLine statusLine = new BasicStatusLine(HttpVersion.HTTP_1_1, 200, "OK");
HttpResponse apacheResponse = new BasicHttpResponse(statusLine);
apacheResponse.addHeader("foo", "bar");
| val | train | 2014-02-21T00:45:02 | "2013-10-15T05:16:50Z" | JakeWharton | val |
square/retrofit/434_441 | square/retrofit | square/retrofit/434 | square/retrofit/441 | [
"timestamp(timedelta=0.0, similarity=0.9298023288008835)"
] | 67839e7ad39d01b7c14233c773d67481a336921b | 6bbd9d327d5a1fe5d389e7ac7b3f4e49b53f3eab | [
"I know retrofit uses mimeType of TypedOutput as Content-Type, but sometimes we need to override the Content-Type like PATCH method with Content-Type \"application/json-patch+json\".\n",
"Makes sense. I'll look into it this week.\n"
] | [
"Suggestion: Move this block to a memoized method on RestMethodInfo, so it's cached.\n"
] | "2014-03-19T07:45:34Z" | [] | Override Content-Type Header | ``` java
@Headers({"Content-Type:application/json-patch+json"})
```
But two `Content-Type` heads set :(
The other one is `application/json; charset=UTF-8`
| [
"retrofit/src/main/java/retrofit/RequestBuilder.java",
"retrofit/src/main/java/retrofit/RestAdapter.java",
"retrofit/src/main/java/retrofit/RestMethodInfo.java",
"retrofit/src/main/java/retrofit/appengine/UrlFetchClient.java",
"retrofit/src/main/java/retrofit/client/ApacheClient.java",
"retrofit/src/main/java/retrofit/client/Client.java",
"retrofit/src/main/java/retrofit/client/UrlConnectionClient.java"
] | [
"retrofit/src/main/java/retrofit/RequestBuilder.java",
"retrofit/src/main/java/retrofit/RestAdapter.java",
"retrofit/src/main/java/retrofit/RestMethodInfo.java",
"retrofit/src/main/java/retrofit/appengine/UrlFetchClient.java",
"retrofit/src/main/java/retrofit/client/ApacheClient.java",
"retrofit/src/main/java/retrofit/client/Client.java",
"retrofit/src/main/java/retrofit/client/UrlConnectionClient.java"
] | [
"retrofit/src/test/java/retrofit/RequestBuilderTest.java",
"retrofit/src/test/java/retrofit/appengine/UrlFetchClientTest.java",
"retrofit/src/test/java/retrofit/client/ApacheClientTest.java",
"retrofit/src/test/java/retrofit/client/UrlConnectionClientTest.java"
] | diff --git a/retrofit/src/main/java/retrofit/RequestBuilder.java b/retrofit/src/main/java/retrofit/RequestBuilder.java
index 725094aa2a..dbee94a2f6 100644
--- a/retrofit/src/main/java/retrofit/RequestBuilder.java
+++ b/retrofit/src/main/java/retrofit/RequestBuilder.java
@@ -48,6 +48,7 @@ final class RequestBuilder implements RequestInterceptor.RequestFacade {
private String relativeUrl;
private StringBuilder queryParams;
private List<Header> headers;
+ private boolean hasContentTypeHeader;
RequestBuilder(String apiUrl, RestMethodInfo methodInfo, Converter converter) {
this.apiUrl = apiUrl;
@@ -62,6 +63,7 @@ final class RequestBuilder implements RequestInterceptor.RequestFacade {
if (methodInfo.headers != null) {
headers = new ArrayList<Header>(methodInfo.headers);
}
+ hasContentTypeHeader = methodInfo.hasContentTypeHeader;
relativeUrl = methodInfo.requestUrl;
@@ -100,6 +102,10 @@ final class RequestBuilder implements RequestInterceptor.RequestFacade {
this.headers = headers = new ArrayList<Header>(2);
}
headers.add(new Header(name, value));
+
+ if ("Content-Type".equalsIgnoreCase(name)) {
+ hasContentTypeHeader = true;
+ }
}
@Override public void addPathParam(String name, String value) {
@@ -309,6 +315,20 @@ Request build() throws UnsupportedEncodingException {
url.append(queryParams);
}
+ TypedOutput body = this.body;
+ if (body != null) {
+ // Only add Content-Type header from the body if one is not already set.
+ if (!hasContentTypeHeader) {
+ addHeader("Content-Type", body.mimeType());
+ }
+
+ // Only add Content-Length header from the body if it is known.
+ long length = body.length();
+ if (length != -1) {
+ addHeader("Content-Length", String.valueOf(length));
+ }
+ }
+
return new Request(requestMethod, url.toString(), headers, body);
}
}
diff --git a/retrofit/src/main/java/retrofit/RestAdapter.java b/retrofit/src/main/java/retrofit/RestAdapter.java
index 11762f3147..be98cca8f3 100644
--- a/retrofit/src/main/java/retrofit/RestAdapter.java
+++ b/retrofit/src/main/java/retrofit/RestAdapter.java
@@ -444,14 +444,6 @@ Request logAndReplaceRequest(String name, Request request) throws IOException {
TypedOutput body = request.getBody();
if (body != null) {
bodySize = body.length();
- String bodyMime = body.mimeType();
-
- if (bodyMime != null) {
- log.log("Content-Type: " + bodyMime);
- }
- if (bodySize != -1) {
- log.log("Content-Length: " + bodySize);
- }
if (logLevel.ordinal() >= LogLevel.FULL.ordinal()) {
if (!request.getHeaders().isEmpty()) {
@@ -465,7 +457,7 @@ Request logAndReplaceRequest(String name, Request request) throws IOException {
byte[] bodyBytes = ((TypedByteArray) body).getBytes();
bodySize = bodyBytes.length;
- String bodyCharset = MimeUtil.parseCharset(bodyMime);
+ String bodyCharset = MimeUtil.parseCharset(body.mimeType());
log.log(new String(bodyBytes, bodyCharset));
}
}
diff --git a/retrofit/src/main/java/retrofit/RestMethodInfo.java b/retrofit/src/main/java/retrofit/RestMethodInfo.java
index 0e1bf42e04..ebd28ebfde 100644
--- a/retrofit/src/main/java/retrofit/RestMethodInfo.java
+++ b/retrofit/src/main/java/retrofit/RestMethodInfo.java
@@ -97,6 +97,7 @@ enum RequestType {
Set<String> requestUrlParamNames;
String requestQuery;
List<retrofit.client.Header> headers;
+ boolean hasContentTypeHeader;
// Parameter-level details
String[] requestParamNames;
@@ -221,7 +222,7 @@ private void parsePath(String path) {
requestQuery = query;
}
- private List<retrofit.client.Header> parseHeaders(String[] headers) {
+ List<retrofit.client.Header> parseHeaders(String[] headers) {
List<retrofit.client.Header> headerList = new ArrayList<retrofit.client.Header>();
for (String header : headers) {
int colon = header.indexOf(':');
@@ -229,8 +230,12 @@ private List<retrofit.client.Header> parseHeaders(String[] headers) {
throw methodError("@Headers value must be in the form \"Name: Value\". Found: \"%s\"",
header);
}
- headerList.add(new retrofit.client.Header(header.substring(0, colon),
- header.substring(colon + 1).trim()));
+ String headerName = header.substring(0, colon);
+ String headerValue = header.substring(colon + 1).trim();
+ if ("Content-Type".equalsIgnoreCase(headerName)) {
+ hasContentTypeHeader = true;
+ }
+ headerList.add(new retrofit.client.Header(headerName, headerValue));
}
return headerList;
}
@@ -372,6 +377,10 @@ private void parseParameters() {
paramNames[i] = name;
paramUsage[i] = ParamUsage.HEADER;
+
+ if ("Content-Type".equalsIgnoreCase(name)) {
+ hasContentTypeHeader = true;
+ }
} else if (annotationType == Field.class) {
if (requestType != RequestType.FORM_URL_ENCODED) {
throw parameterError(i, "@Field parameters can only be used with form encoding.");
diff --git a/retrofit/src/main/java/retrofit/appengine/UrlFetchClient.java b/retrofit/src/main/java/retrofit/appengine/UrlFetchClient.java
index fd25039c34..5bc2298615 100644
--- a/retrofit/src/main/java/retrofit/appengine/UrlFetchClient.java
+++ b/retrofit/src/main/java/retrofit/appengine/UrlFetchClient.java
@@ -71,12 +71,6 @@ static HTTPRequest createRequest(Request request) throws IOException {
TypedOutput body = request.getBody();
if (body != null) {
- fetchRequest.setHeader(new HTTPHeader("Content-Type", body.mimeType()));
- long length = body.length();
- if (length != -1) {
- fetchRequest.setHeader(new HTTPHeader("Content-Length", String.valueOf(length)));
- }
-
ByteArrayOutputStream baos = new ByteArrayOutputStream();
body.writeTo(baos);
fetchRequest.setPayload(baos.toByteArray());
diff --git a/retrofit/src/main/java/retrofit/client/ApacheClient.java b/retrofit/src/main/java/retrofit/client/ApacheClient.java
index 236e7005ec..727101c464 100644
--- a/retrofit/src/main/java/retrofit/client/ApacheClient.java
+++ b/retrofit/src/main/java/retrofit/client/ApacheClient.java
@@ -131,7 +131,6 @@ static class TypedOutputEntity extends AbstractHttpEntity {
TypedOutputEntity(TypedOutput typedOutput) {
this.typedOutput = typedOutput;
- setContentType(typedOutput.mimeType());
}
@Override public boolean isRepeatable() {
diff --git a/retrofit/src/main/java/retrofit/client/Client.java b/retrofit/src/main/java/retrofit/client/Client.java
index 5608b53522..53a75b2ebd 100644
--- a/retrofit/src/main/java/retrofit/client/Client.java
+++ b/retrofit/src/main/java/retrofit/client/Client.java
@@ -25,6 +25,10 @@ public interface Client {
/**
* Synchronously execute an HTTP represented by {@code request} and encapsulate all response data
* into a {@link Response} instance.
+ * <p>
+ * Note: If the request has a body, its length and mime type will have already been added to the
+ * header list as {@code Content-Length} and {@code Content-Type}, respectively. Do NOT alter
+ * these values as they might have been set as a result of an application-level configuration.
*/
Response execute(Request request) throws IOException;
diff --git a/retrofit/src/main/java/retrofit/client/UrlConnectionClient.java b/retrofit/src/main/java/retrofit/client/UrlConnectionClient.java
index cd7872e673..a052b82086 100644
--- a/retrofit/src/main/java/retrofit/client/UrlConnectionClient.java
+++ b/retrofit/src/main/java/retrofit/client/UrlConnectionClient.java
@@ -57,11 +57,9 @@ void prepareRequest(HttpURLConnection connection, Request request) throws IOExce
TypedOutput body = request.getBody();
if (body != null) {
connection.setDoOutput(true);
- connection.addRequestProperty("Content-Type", body.mimeType());
long length = body.length();
if (length != -1) {
connection.setFixedLengthStreamingMode((int) length);
- connection.addRequestProperty("Content-Length", String.valueOf(length));
} else {
connection.setChunkedStreamingMode(CHUNK_SIZE);
}
| diff --git a/retrofit/src/test/java/retrofit/RequestBuilderTest.java b/retrofit/src/test/java/retrofit/RequestBuilderTest.java
index 1a18628110..81dfcc5f61 100644
--- a/retrofit/src/test/java/retrofit/RequestBuilderTest.java
+++ b/retrofit/src/test/java/retrofit/RequestBuilderTest.java
@@ -7,6 +7,7 @@
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
+import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
@@ -420,7 +421,9 @@ public class RequestBuilderTest {
.setBody(Arrays.asList("quick", "brown", "fox")) //
.build();
assertThat(request.getMethod()).isEqualTo("POST");
- assertThat(request.getHeaders()).isEmpty();
+ assertThat(request.getHeaders()).containsExactly(
+ new Header("Content-Type", "application/json; charset=UTF-8"),
+ new Header("Content-Length", "23"));
assertThat(request.getUrl()).isEqualTo("http://example.com/foo/bar/");
assertTypedBytes(request.getBody(), "[\"quick\",\"brown\",\"fox\"]");
}
@@ -451,7 +454,9 @@ public class RequestBuilderTest {
.addPathParam("kit", "kat") //
.build();
assertThat(request.getMethod()).isEqualTo("POST");
- assertThat(request.getHeaders()).isEmpty();
+ assertThat(request.getHeaders()).containsExactly(
+ new Header("Content-Type", "application/json; charset=UTF-8"),
+ new Header("Content-Length", "23"));
assertThat(request.getUrl()).isEqualTo("http://example.com/foo/bar/pong/kat/");
assertTypedBytes(request.getBody(), "[\"quick\",\"brown\",\"fox\"]");
}
@@ -467,7 +472,9 @@ public class RequestBuilderTest {
.addPart("kit", new TypedString("kat")) //
.build();
assertThat(request.getMethod()).isEqualTo("POST");
- assertThat(request.getHeaders()).isEmpty();
+ assertThat(request.getHeaders()).hasSize(2);
+ assertThat(request.getHeaders().get(0).getName()).isEqualTo("Content-Type");
+ assertThat(request.getHeaders().get(1)).isEqualTo(new Header("Content-Length", "414"));
assertThat(request.getUrl()).isEqualTo("http://example.com/foo/bar/");
MultipartTypedOutput body = (MultipartTypedOutput) request.getBody();
@@ -494,7 +501,9 @@ public class RequestBuilderTest {
.addPart("fizz", null) //
.build();
assertThat(request.getMethod()).isEqualTo("POST");
- assertThat(request.getHeaders()).isEmpty();
+ assertThat(request.getHeaders()).hasSize(2);
+ assertThat(request.getHeaders().get(0).getName()).isEqualTo("Content-Type");
+ assertThat(request.getHeaders().get(1)).isEqualTo(new Header("Content-Length", "228"));
assertThat(request.getUrl()).isEqualTo("http://example.com/foo/bar/");
MultipartTypedOutput body = (MultipartTypedOutput) request.getBody();
@@ -617,8 +626,7 @@ public class RequestBuilderTest {
.setMethod("GET") //
.setUrl("http://example.com") //
.setPath("/foo/bar/") //
- .addHeader("ping", "pong") //
- .addHeader("kit", "kat") //
+ .addHeaders("ping: pong", "kit: kat") //
.build();
assertThat(request.getMethod()).isEqualTo("GET");
assertThat(request.getHeaders()) //
@@ -647,7 +655,7 @@ public class RequestBuilderTest {
.setMethod("GET") //
.setUrl("http://example.com") //
.setPath("/foo/bar/") //
- .addHeader("ping", "pong") //
+ .addHeaders("ping: pong") //
.addInterceptorHeader("kit", "kat") //
.build();
assertThat(request.getMethod()).isEqualTo("GET");
@@ -662,7 +670,7 @@ public class RequestBuilderTest {
.setMethod("GET") //
.setUrl("http://example.com") //
.setPath("/foo/bar/") //
- .addHeader("ping", "pong") //
+ .addHeaders("ping: pong") //
.addInterceptorHeader("kit", "kat") //
.addHeaderParam("fizz", "buzz") //
.build();
@@ -678,7 +686,7 @@ public class RequestBuilderTest {
.setMethod("GET") //
.setUrl("http://example.com") //
.setPath("/foo/bar/") //
- .addHeader("ping", "pong") //
+ .addHeaders("ping: pong") //
.addHeaderParam("kit", "kat") //
.build();
assertThat(request.getMethod()).isEqualTo("GET");
@@ -693,7 +701,7 @@ public class RequestBuilderTest {
.setMethod("GET") //
.setUrl("http://example.com") //
.setPath("/foo/bar/") //
- .addHeader("ping", "pong") //
+ .addHeaders("ping: pong") //
.addHeaderParam("kit", "kat") //
.build();
assertThat(request.getMethod()).isEqualTo("GET");
@@ -712,6 +720,32 @@ public class RequestBuilderTest {
assertThat(request.getUrl()).isEqualTo("http://example.com/foo/bar/");
}
+ @Test public void contentTypeAnnotationHeaderOverrides() throws Exception {
+ Request request = new Helper() //
+ .setMethod("POST") //
+ .setUrl("http://example.com") //
+ .setPath("/") //
+ .addHeaders("Content-Type: text/not-plain") //
+ .setBody(new TypedString("Plain")) //
+ .build();
+ assertThat(request.getHeaders()) //
+ .containsExactly(new Header("Content-Type", "text/not-plain"),
+ new Header("Content-Length", "5"));
+ }
+
+ @Test public void contentTypeParameterHeaderOverrides() throws Exception {
+ Request request = new Helper() //
+ .setMethod("POST") //
+ .setUrl("http://example.com") //
+ .setPath("/") //
+ .addHeaderParam("Content-Type", "text/not-plain") //
+ .setBody(new TypedString("Plain")) //
+ .build();
+ assertThat(request.getHeaders()) //
+ .containsExactly(new Header("Content-Type", "text/not-plain"),
+ new Header("Content-Length", "5"));
+ }
+
private static void assertTypedBytes(TypedOutput bytes, String expected) throws IOException {
assertThat(bytes).isNotNull();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
@@ -730,7 +764,7 @@ private static class Helper {
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 final List<String> headers = new ArrayList<String>();
private final List<Header> interceptorHeaders = new ArrayList<Header>();
private final Map<String, String> interceptorPathParams = new LinkedHashMap<String, String>();
private final Map<String, String> interceptorQueryParams = new LinkedHashMap<String, String>();
@@ -838,8 +872,8 @@ Helper addHeaderParam(String name, Object value) {
return this;
}
- Helper addHeader(String name, String value) {
- headers.add(new Header(name, value));
+ Helper addHeaders(String... headers) {
+ Collections.addAll(this.headers, headers);
return this;
}
@@ -887,7 +921,7 @@ Request build() throws Exception {
methodInfo.requestQuery = query;
methodInfo.requestParamNames = paramNames.toArray(new String[paramNames.size()]);
methodInfo.requestParamUsage = paramUsages.toArray(new ParamUsage[paramUsages.size()]);
- methodInfo.headers = headers;
+ methodInfo.headers = methodInfo.parseHeaders(headers.toArray(new String[headers.size()]));
methodInfo.loaded = true;
RequestBuilder requestBuilder = new RequestBuilder(url, methodInfo, GSON);
diff --git a/retrofit/src/test/java/retrofit/appengine/UrlFetchClientTest.java b/retrofit/src/test/java/retrofit/appengine/UrlFetchClientTest.java
index 2fd5010df0..35455fb651 100644
--- a/retrofit/src/test/java/retrofit/appengine/UrlFetchClientTest.java
+++ b/retrofit/src/test/java/retrofit/appengine/UrlFetchClientTest.java
@@ -48,9 +48,7 @@ public class UrlFetchClientTest {
assertThat(fetchRequest.getMethod()).isEqualTo(POST);
assertThat(fetchRequest.getURL().toString()).isEqualTo(HOST + "/foo/bar/");
List<HTTPHeader> fetchHeaders = fetchRequest.getHeaders();
- assertThat(fetchHeaders).hasSize(2);
- assertHeader(fetchHeaders.get(0), "Content-Type", "text/plain; charset=UTF-8");
- assertHeader(fetchHeaders.get(1), "Content-Length", "2");
+ assertThat(fetchHeaders).hasSize(0);
assertBytes(fetchRequest.getPayload(), "hi");
}
@@ -65,11 +63,7 @@ public class UrlFetchClientTest {
assertThat(fetchRequest.getMethod()).isEqualTo(POST);
assertThat(fetchRequest.getURL().toString()).isEqualTo(HOST + "/that/");
List<HTTPHeader> fetchHeaders = fetchRequest.getHeaders();
- assertThat(fetchHeaders).hasSize(2);
- HTTPHeader headerZero = fetchHeaders.get(0);
- assertThat(headerZero.getName()).isEqualTo("Content-Type");
- assertThat(headerZero.getValue()).startsWith("multipart/form-data; boundary=");
- assertHeader(fetchHeaders.get(1), "Content-Length", String.valueOf(body.length()));
+ assertThat(fetchHeaders).hasSize(0);
assertThat(fetchRequest.getPayload()).isNotEmpty();
}
diff --git a/retrofit/src/test/java/retrofit/client/ApacheClientTest.java b/retrofit/src/test/java/retrofit/client/ApacheClientTest.java
index a9e64ebbbd..4cb15bbb83 100644
--- a/retrofit/src/test/java/retrofit/client/ApacheClientTest.java
+++ b/retrofit/src/test/java/retrofit/client/ApacheClientTest.java
@@ -56,7 +56,6 @@ public class ApacheClientTest {
HttpEntity entity = entityRequest.getEntity();
assertThat(entity).isNotNull();
assertBytes(ByteStreams.toByteArray(entity.getContent()), "hi");
- assertThat(entity.getContentType().getValue()).isEqualTo("text/plain; charset=UTF-8");
}
@Test public void multipart() {
diff --git a/retrofit/src/test/java/retrofit/client/UrlConnectionClientTest.java b/retrofit/src/test/java/retrofit/client/UrlConnectionClientTest.java
index 3539ef0a3a..c07afa9476 100644
--- a/retrofit/src/test/java/retrofit/client/UrlConnectionClientTest.java
+++ b/retrofit/src/test/java/retrofit/client/UrlConnectionClientTest.java
@@ -46,10 +46,7 @@ public class UrlConnectionClientTest {
assertThat(connection.getRequestMethod()).isEqualTo("POST");
assertThat(connection.getURL().toString()).isEqualTo(HOST + "/foo/bar/");
- assertThat(connection.getRequestProperties()).hasSize(2);
- assertThat(connection.getRequestProperty("Content-Type")) //
- .isEqualTo("text/plain; charset=UTF-8");
- assertThat(connection.getRequestProperty("Content-Length")).isEqualTo("2");
+ assertThat(connection.getRequestProperties()).hasSize(0);
assertBytes(connection.getOutputStream().toByteArray(), "hi");
}
@@ -67,9 +64,7 @@ public class UrlConnectionClientTest {
assertThat(connection.getRequestMethod()).isEqualTo("POST");
assertThat(connection.getURL().toString()).isEqualTo(HOST + "/that/");
- assertThat(connection.getRequestProperties()).hasSize(2);
- assertThat(connection.getRequestProperty("Content-Type")).startsWith("multipart/form-data;");
- assertThat(connection.getRequestProperty("Content-Length")).isEqualTo(String.valueOf(output.length));
+ assertThat(connection.getRequestProperties()).hasSize(0);
assertThat(output.length).isGreaterThan(0);
}
| train | train | 2014-03-14T19:09:59 | "2014-03-12T10:55:18Z" | ionull | val |
square/retrofit/445_447 | square/retrofit | square/retrofit/445 | square/retrofit/447 | [
"timestamp(timedelta=0.0, similarity=0.9030215593025896)"
] | dba12d66041fcec93467a17704b5757cd29d7933 | 7a50eacdcc9d4032e2174cf59143f6526a625074 | [
"Yep. Will fix.\n"
] | [] | "2014-03-24T17:32:53Z" | [] | MockRestAdapter ignores ErrorHandler configuration | Steps to reproduce:
1. Create a `RestAdapter` with an `ErrorHandler` set.
2. Create a mock of your adapter using `MockRestAdapter mockRestAdapter = MockRestAdapter.from(restAdapter);`.
3. Create a concrete instance of you API interface using the mock adapter.
4. Call a method which return an error.
5. Notice that the `ErrorHandler` is not called.
| [
"retrofit-mock/src/main/java/retrofit/MockRestAdapter.java"
] | [
"retrofit-mock/src/main/java/retrofit/MockRestAdapter.java"
] | [
"retrofit-mock/src/test/java/retrofit/MockRestAdapterTest.java"
] | diff --git a/retrofit-mock/src/main/java/retrofit/MockRestAdapter.java b/retrofit-mock/src/main/java/retrofit/MockRestAdapter.java
index d0db49bf98..b0bb6d8834 100644
--- a/retrofit-mock/src/main/java/retrofit/MockRestAdapter.java
+++ b/retrofit-mock/src/main/java/retrofit/MockRestAdapter.java
@@ -17,6 +17,7 @@
import rx.schedulers.Schedulers;
import static retrofit.RestAdapter.LogLevel;
+import static retrofit.RetrofitError.unexpectedError;
/**
* Wraps mocks implementations of API interfaces so that they exhibit the delay and error
@@ -239,7 +240,16 @@ public MockHandler(Object mockService, Map<Method, RestMethodInfo> methodInfoCac
final RestMethodInfo methodInfo = RestAdapter.getMethodInfo(methodInfoCache, method);
if (methodInfo.isSynchronous) {
- return invokeSync(methodInfo, restAdapter.requestInterceptor, args);
+ try {
+ return invokeSync(methodInfo, restAdapter.requestInterceptor, args);
+ } catch (RetrofitError error) {
+ Throwable newError = restAdapter.errorHandler.handleError(error);
+ if (newError == null) {
+ throw new IllegalStateException("Error handler returned null for wrapped exception.",
+ error);
+ }
+ throw newError;
+ }
}
if (restAdapter.httpExecutor == null || restAdapter.callbackExecutor == null) {
@@ -367,13 +377,16 @@ private void invokeAsync(RestMethodInfo methodInfo, RequestInterceptor intercept
if (calculateIsFailure()) {
sleep(calculateDelayForError());
- final IOException exception = new IOException("Mock network error!");
+ IOException exception = new IOException("Mock network error!");
if (restAdapter.logLevel.log()) {
restAdapter.logException(exception, url);
}
+ RetrofitError error = RetrofitError.networkError(url, exception);
+ Throwable cause = restAdapter.errorHandler.handleError(error);
+ final RetrofitError e = cause == error ? error : unexpectedError(error.getUrl(), cause);
restAdapter.callbackExecutor.execute(new Runnable() {
@Override public void run() {
- realCallback.failure(RetrofitError.networkError(url, exception));
+ realCallback.failure(e);
}
});
return;
@@ -416,10 +429,12 @@ private void invokeAsync(RestMethodInfo methodInfo, RequestInterceptor intercept
}
}
- final RetrofitError error = new MockHttpRetrofitError(url, response, httpEx.responseBody);
+ RetrofitError error = new MockHttpRetrofitError(url, response, httpEx.responseBody);
+ Throwable cause = restAdapter.errorHandler.handleError(error);
+ final RetrofitError e = cause == error ? error : unexpectedError(error.getUrl(), cause);
restAdapter.callbackExecutor.execute(new Runnable() {
@Override public void run() {
- realCallback.failure(error);
+ realCallback.failure(e);
}
});
}
@@ -511,9 +526,11 @@ private static long uptimeMillis() {
/** Indirection to avoid VerifyError if RxJava isn't present. */
private static class MockRxSupport {
private final Scheduler scheduler;
+ private final ErrorHandler errorHandler;
MockRxSupport(RestAdapter restAdapter) {
scheduler = Schedulers.executor(restAdapter.httpExecutor);
+ errorHandler = restAdapter.errorHandler;
}
Observable createMockObservable(final MockHandler mockHandler, final RestMethodInfo methodInfo,
@@ -525,8 +542,10 @@ Observable createMockObservable(final MockHandler mockHandler, final RestMethodI
(Observable) mockHandler.invokeSync(methodInfo, interceptor, args);
//noinspection unchecked
observable.subscribe(subscriber);
- } catch (Throwable throwable) {
- Observable.error(throwable).subscribe(subscriber);
+ } catch (RetrofitError e) {
+ subscriber.onError(errorHandler.handleError(e));
+ } catch (Throwable e) {
+ subscriber.onError(e);
}
}
}).subscribeOn(scheduler);
| diff --git a/retrofit-mock/src/test/java/retrofit/MockRestAdapterTest.java b/retrofit-mock/src/test/java/retrofit/MockRestAdapterTest.java
index a2f53e353c..311680f099 100644
--- a/retrofit-mock/src/test/java/retrofit/MockRestAdapterTest.java
+++ b/retrofit-mock/src/test/java/retrofit/MockRestAdapterTest.java
@@ -2,6 +2,7 @@
package retrofit;
import java.io.IOException;
+import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
@@ -16,6 +17,7 @@
import rx.Observable;
import rx.functions.Action1;
+import static java.util.concurrent.TimeUnit.SECONDS;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;
import static org.mockito.Matchers.any;
@@ -46,6 +48,7 @@ interface ObservableExample {
private Executor callbackExecutor;
private MockRestAdapter mockRestAdapter;
private ValueChangeListener valueChangeListener;
+ private Throwable nextError;
@Before public void setUp() throws IOException {
Client client = mock(Client.class);
@@ -59,6 +62,16 @@ interface ObservableExample {
.setExecutors(httpExecutor, callbackExecutor)
.setEndpoint("http://example.com")
.setLogLevel(RestAdapter.LogLevel.NONE)
+ .setErrorHandler(new ErrorHandler() {
+ @Override public Throwable handleError(RetrofitError cause) {
+ if (nextError != null) {
+ Throwable error = nextError;
+ nextError = null;
+ return error;
+ }
+ return cause;
+ }
+ })
.build();
valueChangeListener = mock(ValueChangeListener.class);
@@ -476,4 +489,86 @@ class MockAsyncExample implements AsyncExample {
"Calling failure directly is not supported. Throw MockHttpException instead.");
}
}
+
+ @Test public void syncErrorUsesErrorHandler() {
+ mockRestAdapter.setDelay(100);
+ mockRestAdapter.setVariancePercentage(0);
+ mockRestAdapter.setErrorPercentage(0);
+
+ class MockSyncExample implements SyncExample {
+ @Override public Object doStuff() {
+ throw MockHttpException.newNotFound(new Object());
+ }
+ }
+
+ SyncExample mockService = mockRestAdapter.create(SyncExample.class, new MockSyncExample());
+ nextError = new IllegalArgumentException("Test");
+
+ try {
+ mockService.doStuff();
+ fail();
+ } catch (IllegalArgumentException e) {
+ assertThat(e).hasMessage("Test");
+ }
+ }
+
+ @Test public void asyncErrorUsesErrorHandler() throws InterruptedException {
+ mockRestAdapter.setDelay(100);
+ mockRestAdapter.setVariancePercentage(0);
+ mockRestAdapter.setErrorPercentage(0);
+
+ class MockAsyncExample implements AsyncExample {
+ @Override public void doStuff(Callback<Object> cb) {
+ throw MockHttpException.newNotFound(new Object());
+ }
+ }
+
+ AsyncExample mockService = mockRestAdapter.create(AsyncExample.class, new MockAsyncExample());
+ nextError = new IllegalArgumentException("Test");
+
+ final CountDownLatch latch = new CountDownLatch(1);
+ mockService.doStuff(new Callback<Object>() {
+ @Override public void success(Object o, Response response) {
+ throw new AssertionError();
+ }
+
+ @Override public void failure(RetrofitError error) {
+ assertThat(error.getCause()).hasMessage("Test");
+ latch.countDown();
+ }
+ });
+ latch.await(5, SECONDS);
+ }
+
+ @Test public void observableErrorUsesErrorHandler() throws InterruptedException {
+ mockRestAdapter.setDelay(100);
+ mockRestAdapter.setVariancePercentage(0);
+ mockRestAdapter.setErrorPercentage(0);
+
+ class MockObservableExample implements ObservableExample {
+ @Override public Observable<Object> doStuff() {
+ throw MockHttpException.newNotFound(new Object());
+ }
+ }
+
+ ObservableExample mockService =
+ mockRestAdapter.create(ObservableExample.class, new MockObservableExample());
+ nextError = new IllegalArgumentException("Test");
+
+ final CountDownLatch latch = new CountDownLatch(1);
+ final AtomicBoolean called = new AtomicBoolean();
+ mockService.doStuff().subscribe(new Action1<Object>() {
+ @Override public void call(Object o) {
+ throw new AssertionError();
+ }
+ }, new Action1<Throwable>() {
+ @Override public void call(Throwable error) {
+ assertThat(error).hasMessage("Test");
+ called.set(true);
+ latch.countDown();
+ }
+ });
+ latch.await(5, SECONDS);
+ assertThat(called.get()).isTrue();
+ }
}
| test | train | 2014-03-21T07:52:06 | "2014-03-22T03:16:12Z" | niqo01 | val |
square/retrofit/478_489 | square/retrofit | square/retrofit/478 | square/retrofit/489 | [
"timestamp(timedelta=5.0, similarity=0.8981003484833187)"
] | c4e50903407a2fdbe667eac56e0278c7d2b700d3 | ec4e18933c40f86494e2ef00eb4ea96a4d5ab31a | [] | [] | "2014-05-22T08:59:03Z" | [] | Add @Raw or similiar to avoid convertig body stream to byte[] in Response object | Hey there,
first of all thanks for providing Retrofit! It's an amazing framework that impressively simplifies calling REST-APIs!
We use it in one of our server application to communicate with another remote server to download binary data (i.e. files) from there using Response as return type for the interface method. Our server operates as a proxy and copies the response.getBody().in() to the the user requesting resources. This approach works as expected, but has a performance flaw.
At the moment Retrofit converts every Response body stream to a byte array (see RestAdapter.java):
``` java
if (type.equals(Response.class)) {
// Read the entire stream and replace with one backed by a byte[]
response = Utils.readBodyToBytesIfNecessary(response);
if (methodInfo.isSynchronous) {
return response;
}
return new ResponseWrapper(response, response);
}
```
If you just want to proxy the stream, converting to a byte[] first can result in a real performance hit. The larger the binary data, the worse it will be. We would like to see _response = Utils.readBodyToBytesIfNecessary(response);_ optional, e.g. by annotating the interface method with Response return type with an additional _@Raw_.
What do you think of this approach? Maybe something like this is already planned?
If not and if you consider this a valid approach, we can also prepare a pull request to implement this behaviour.
| [
"retrofit/src/main/java/retrofit/RestAdapter.java",
"retrofit/src/main/java/retrofit/RestMethodInfo.java"
] | [
"retrofit/src/main/java/retrofit/RestAdapter.java",
"retrofit/src/main/java/retrofit/RestMethodInfo.java",
"retrofit/src/main/java/retrofit/http/Raw.java"
] | [
"retrofit/src/test/java/retrofit/RestMethodInfoTest.java"
] | diff --git a/retrofit/src/main/java/retrofit/RestAdapter.java b/retrofit/src/main/java/retrofit/RestAdapter.java
index bdd1412f2c..d0ae8b8b0a 100644
--- a/retrofit/src/main/java/retrofit/RestAdapter.java
+++ b/retrofit/src/main/java/retrofit/RestAdapter.java
@@ -338,8 +338,10 @@ private Object invokeRequest(RequestInterceptor requestInterceptor, RestMethodIn
if (statusCode >= 200 && statusCode < 300) { // 2XX == successful request
// Caller requested the raw Response object directly.
if (type.equals(Response.class)) {
- // Read the entire stream and replace with one backed by a byte[]
- response = Utils.readBodyToBytesIfNecessary(response);
+ if (!methodInfo.isRaw) {
+ // Read the entire stream and replace with one backed by a byte[]
+ response = Utils.readBodyToBytesIfNecessary(response);
+ }
if (methodInfo.isSynchronous) {
return response;
diff --git a/retrofit/src/main/java/retrofit/RestMethodInfo.java b/retrofit/src/main/java/retrofit/RestMethodInfo.java
index 3371bef75f..340bb58901 100644
--- a/retrofit/src/main/java/retrofit/RestMethodInfo.java
+++ b/retrofit/src/main/java/retrofit/RestMethodInfo.java
@@ -27,6 +27,7 @@
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
+import retrofit.client.Response;
import retrofit.http.Body;
import retrofit.http.EncodedPath;
import retrofit.http.EncodedQuery;
@@ -42,6 +43,7 @@
import retrofit.http.Path;
import retrofit.http.Query;
import retrofit.http.QueryMap;
+import retrofit.http.Raw;
import retrofit.http.RestMethod;
import rx.Observable;
@@ -100,6 +102,7 @@ enum RequestType {
String requestQuery;
List<retrofit.client.Header> headers;
String contentTypeHeader;
+ boolean isRaw;
// Parameter-level details
String[] requestParamNames;
@@ -178,6 +181,13 @@ private void parseMethodAnnotations() {
throw methodError("Only one encoding annotation is allowed.");
}
requestType = RequestType.FORM_URL_ENCODED;
+ } else if (annotationType == Raw.class) {
+ if (responseObjectType != Response.class) {
+ throw methodError(
+ "Only methods having %s as response data type are allowed to have @%s annotation.",
+ Response.class.getSimpleName(), Raw.class.getSimpleName());
+ }
+ isRaw = true;
}
}
diff --git a/retrofit/src/main/java/retrofit/http/Raw.java b/retrofit/src/main/java/retrofit/http/Raw.java
new file mode 100644
index 0000000000..3aba33dd1d
--- /dev/null
+++ b/retrofit/src/main/java/retrofit/http/Raw.java
@@ -0,0 +1,34 @@
+/*
+ * Copyright (C) 2014 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.http;
+
+import java.lang.annotation.Documented;
+import java.lang.annotation.Retention;
+import java.lang.annotation.Target;
+
+import static java.lang.annotation.ElementType.METHOD;
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+
+/**
+ * Treat the response body on methods returning {@link retrofit.client.Response} as is, i.e.
+ * without converting {@link retrofit.client.Response#getBody()} to byte[].
+ */
+@Documented
+@Target(METHOD)
+@Retention(RUNTIME)
+public @interface Raw {
+
+}
| diff --git a/retrofit/src/test/java/retrofit/RestMethodInfoTest.java b/retrofit/src/test/java/retrofit/RestMethodInfoTest.java
index ece88dd5ce..1d4ee6a5ab 100644
--- a/retrofit/src/test/java/retrofit/RestMethodInfoTest.java
+++ b/retrofit/src/test/java/retrofit/RestMethodInfoTest.java
@@ -32,6 +32,7 @@
import retrofit.http.Path;
import retrofit.http.Query;
import retrofit.http.QueryMap;
+import retrofit.http.Raw;
import retrofit.http.RestMethod;
import retrofit.mime.TypedOutput;
import rx.Observable;
@@ -219,6 +220,70 @@ class Example {
assertThat(methodInfo.responseObjectType).isEqualTo(expected);
}
+ @Test public void rawResponse() {
+ class Example {
+ @GET("/foo") @Raw retrofit.client.Response a() {
+ return null;
+ }
+ }
+
+ Method method = TestingUtils.getMethod(Example.class, "a");
+ RestMethodInfo methodInfo = new RestMethodInfo(method);
+ methodInfo.init();
+
+ assertThat(methodInfo.isRaw).isTrue();
+ assertThat(methodInfo.responseObjectType).isEqualTo(retrofit.client.Response.class);
+ }
+
+ @Test public void rawResponseWithCallback() {
+ class Example {
+ @GET("/foo") @Raw void a(Callback<retrofit.client.Response> callback) {
+ }
+ }
+
+ Method method = TestingUtils.getMethod(Example.class, "a");
+ RestMethodInfo methodInfo = new RestMethodInfo(method);
+ methodInfo.init();
+
+ assertThat(methodInfo.isRaw).isTrue();
+ assertThat(methodInfo.responseObjectType).isEqualTo(retrofit.client.Response.class);
+ }
+
+ @Test public void rawResponseNotAllowed() {
+ class Example {
+ @GET("/foo") @Raw String a() {
+ return null;
+ }
+ }
+
+ Method method = TestingUtils.getMethod(Example.class, "a");
+ RestMethodInfo methodInfo = new RestMethodInfo(method);
+ try {
+ methodInfo.init();
+ fail();
+ } catch (IllegalArgumentException e) {
+ assertThat(e).hasMessage(
+ "Example.a: Only methods having Response as response data type are allowed to have @Raw annotation.");
+ }
+ }
+
+ @Test public void rawResponseWithCallbackNotAllowed() {
+ class Example {
+ @GET("/foo") @Raw void a(Callback<String> callback) {
+ }
+ }
+
+ Method method = TestingUtils.getMethod(Example.class, "a");
+ RestMethodInfo methodInfo = new RestMethodInfo(method);
+ try {
+ methodInfo.init();
+ fail();
+ } catch (IllegalArgumentException e) {
+ assertThat(e).hasMessage(
+ "Example.a: Only methods having Response as response data type are allowed to have @Raw annotation.");
+ }
+ }
+
@Test public void observableResponse() {
class Example {
@GET("/foo") Observable<Response> a() {
| val | train | 2014-06-03T00:57:24 | "2014-05-12T14:29:33Z" | rzimmer | val |
square/retrofit/488_491 | square/retrofit | square/retrofit/488 | square/retrofit/491 | [
"keyword_pr_to_issue"
] | cb22c3901533801e0fdb1e7345d0964d3d9aae26 | d18e92a2320f51e05ff8689123654120dd2791a3 | [
"The `null` check is good. Want to submit a PR?\n",
"I should be able to do that :p\nI'll send a PR later then.\n\nThanks.\n",
"Does it make sense to add tests for this ?\nI guess that would just be createError / check accessor results tests, not sure it'd be very very useful.\n",
"No, you can skip that.\n"
] | [] | "2014-05-22T17:51:33Z" | [] | NPE trying to get the body of a RetrofitError without response | In `RetrofitError` we have
``` java
public Object getBody() {
TypedInput body = response.getBody();
if (body == null) {
return null;
}
try {
return converter.fromBody(body, successType);
} catch (ConversionException e) {
throw new RuntimeException(e);
}
}
```
and something similar for `getBodyAs(Type)`.
if `response` is null, as is the case for a network error for example (`UnknownHostException` etc), an NPE is thrown.
Now I didn't submit a fix yet because maybe you want to explicitly fail in this case ("don't try to get the body of an error without a response"), not sure, but in any case I usually consider NPEs as bug.
I think adding
``` java
if (response == null) {
return null;
}
```
before would be consistent, but in case where we want to fail we should at least throw a more explicit exception.
| [
"retrofit/src/main/java/retrofit/RetrofitError.java"
] | [
"retrofit/src/main/java/retrofit/RetrofitError.java"
] | [] | diff --git a/retrofit/src/main/java/retrofit/RetrofitError.java b/retrofit/src/main/java/retrofit/RetrofitError.java
index 3ee113207d..39438fc26b 100644
--- a/retrofit/src/main/java/retrofit/RetrofitError.java
+++ b/retrofit/src/main/java/retrofit/RetrofitError.java
@@ -77,6 +77,9 @@ public boolean isNetworkError() {
* the generic type of the supplied {@link Callback} parameter.
*/
public Object getBody() {
+ if (response == null) {
+ return null;
+ }
TypedInput body = response.getBody();
if (body == null) {
return null;
@@ -90,6 +93,9 @@ public Object getBody() {
/** HTTP response body converted to specified {@code type}. */
public Object getBodyAs(Type type) {
+ if (response == null) {
+ return null;
+ }
TypedInput body = response.getBody();
if (body == null) {
return null;
| null | train | train | 2014-05-17T00:30:11 | "2014-05-21T14:59:22Z" | desseim | val |
square/retrofit/521_524 | square/retrofit | square/retrofit/521 | square/retrofit/524 | [
"timestamp(timedelta=0.0, similarity=0.8732408878427275)"
] | 94c3e9ff43c7b2e67b0de730a42d34f32a5bd8fc | faa1cf411518752ba91eab6fa1e99ddd1324cf90 | [] | [
"This is a bug that testing for this feature exposed.\n",
"?\n"
] | "2014-06-05T18:03:34Z" | [] | Feature request: Add getSuccessType method to RetrofitError | For most cases, I'm using a generic implementation of `Callback`. It would be helpful to me if `successType` were exposed. Right now my implementation looks like this:
``` java
public class ResponseCallback<T extends ResponseBase> implements Callback<T> {
public void success(T t, Response response) {
// Wrap t if desired.
// Post event (t or wrapped t).
}
public void failure(RetrofitError error) {
// Use reflection to get successType.
// Create new instance of successType - t.
t.addError(error);
// Wrap t if desired.
// Post event (t or wrapped t).
}
}
public abstract class ResponseBase {
private transient List<RetrofitError> mErrors;
public ResponseBase() {
}
public boolean successful() {
return mErrors == null || mErrors.isEmpty();
}
public List<RetrofitError> getErrors() {
return mErrors;
}
public void addError(RetrofitError error) {
if (mErrors == null) {
mErrors = new ArrayList<RetrofitError>();
}
mErrors.add(error);
}
}
```
It would be nice to avoid the reflection in `failure()` by exposing `successType`. I realize that `ResponseCallback` could be constructed with the type, but the API is nicer without it and it's already in `RetrofitError`.
My implementation works as is (until `successType` is renamed), but I hope you'll consider it.
| [
"retrofit-mock/src/main/java/retrofit/MockHttpRetrofitError.java",
"retrofit/src/main/java/retrofit/RestAdapter.java",
"retrofit/src/main/java/retrofit/RetrofitError.java"
] | [
"retrofit-mock/src/main/java/retrofit/MockHttpRetrofitError.java",
"retrofit/src/main/java/retrofit/RestAdapter.java",
"retrofit/src/main/java/retrofit/RetrofitError.java"
] | [
"retrofit-mock/src/test/java/retrofit/MockRestAdapterTest.java",
"retrofit/src/test/java/retrofit/RestAdapterTest.java"
] | diff --git a/retrofit-mock/src/main/java/retrofit/MockHttpRetrofitError.java b/retrofit-mock/src/main/java/retrofit/MockHttpRetrofitError.java
index 831f8a5a13..7c2809fd6a 100644
--- a/retrofit-mock/src/main/java/retrofit/MockHttpRetrofitError.java
+++ b/retrofit-mock/src/main/java/retrofit/MockHttpRetrofitError.java
@@ -8,7 +8,7 @@ class MockHttpRetrofitError extends RetrofitError {
private final Object body;
MockHttpRetrofitError(String message, String url, Response response, Object body) {
- super(message, url, response, null, null, false, null);
+ super(message, url, response, null, body.getClass(), false, null);
this.body = body;
}
diff --git a/retrofit/src/main/java/retrofit/RestAdapter.java b/retrofit/src/main/java/retrofit/RestAdapter.java
index bdd1412f2c..0044157872 100644
--- a/retrofit/src/main/java/retrofit/RestAdapter.java
+++ b/retrofit/src/main/java/retrofit/RestAdapter.java
@@ -349,6 +349,9 @@ private Object invokeRequest(RequestInterceptor requestInterceptor, RestMethodIn
TypedInput body = response.getBody();
if (body == null) {
+ if (methodInfo.isSynchronous) {
+ return null;
+ }
return new ResponseWrapper(response, null);
}
diff --git a/retrofit/src/main/java/retrofit/RetrofitError.java b/retrofit/src/main/java/retrofit/RetrofitError.java
index 909c2f9fc5..7b923e8f35 100644
--- a/retrofit/src/main/java/retrofit/RetrofitError.java
+++ b/retrofit/src/main/java/retrofit/RetrofitError.java
@@ -83,6 +83,14 @@ public Object getBody() {
return getBodyAs(successType);
}
+ /**
+ * The type declared by either the interface method return type or the generic type of the
+ * supplied {@link Callback} parameter.
+ */
+ public Type getSuccessType() {
+ return successType;
+ }
+
/**
* HTTP response body converted to specified {@code type}. {@code null} if there is no response.
*/
| diff --git a/retrofit-mock/src/test/java/retrofit/MockRestAdapterTest.java b/retrofit-mock/src/test/java/retrofit/MockRestAdapterTest.java
index b0fb6923a4..2eb1225bb3 100644
--- a/retrofit-mock/src/test/java/retrofit/MockRestAdapterTest.java
+++ b/retrofit-mock/src/test/java/retrofit/MockRestAdapterTest.java
@@ -37,7 +37,7 @@ interface SyncExample {
}
interface AsyncExample {
- @GET("/") void doStuff(Callback<Object> cb);
+ @GET("/") void doStuff(Callback<String> cb);
}
interface AsyncCallbackSubtypeExample {
@@ -47,7 +47,7 @@ abstract class Foo implements Callback<String> {}
}
interface ObservableExample {
- @GET("/") Observable<Object> doStuff();
+ @GET("/") Observable<String> doStuff();
}
private Executor httpExecutor;
@@ -242,7 +242,7 @@ class MockSyncExample implements SyncExample {
mockRestAdapter.setErrorPercentage(100);
class MockAsyncExample implements AsyncExample {
- @Override public void doStuff(Callback<Object> cb) {
+ @Override public void doStuff(Callback<String> cb) {
throw new AssertionError();
}
}
@@ -250,8 +250,8 @@ class MockAsyncExample implements AsyncExample {
AsyncExample mockService = mockRestAdapter.create(AsyncExample.class, new MockAsyncExample());
final AtomicReference<RetrofitError> errorRef = new AtomicReference<RetrofitError>();
- mockService.doStuff(new Callback<Object>() {
- @Override public void success(Object o, Response response) {
+ mockService.doStuff(new Callback<String>() {
+ @Override public void success(String o, Response response) {
throw new AssertionError();
}
@@ -298,9 +298,11 @@ class MockSyncExample implements SyncExample {
mockRestAdapter.setVariancePercentage(0);
mockRestAdapter.setErrorPercentage(0);
- final Object expected = new Object();
+ @SuppressWarnings("RedundantStringConstructorCall") // Allocated on-heap.
+ final String expected = new String("Hi");
+
class MockAsyncExample implements AsyncExample {
- @Override public void doStuff(Callback<Object> cb) {
+ @Override public void doStuff(Callback<String> cb) {
cb.success(expected, null);
}
}
@@ -310,8 +312,8 @@ class MockAsyncExample implements AsyncExample {
final long startNanos = System.nanoTime();
final AtomicLong tookMs = new AtomicLong();
final AtomicReference<Object> actual = new AtomicReference<Object>();
- mockService.doStuff(new Callback<Object>() {
- @Override public void success(Object result, Response response) {
+ mockService.doStuff(new Callback<String>() {
+ @Override public void success(String result, Response response) {
tookMs.set(TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNanos));
actual.set(result);
}
@@ -333,9 +335,11 @@ class MockAsyncExample implements AsyncExample {
mockRestAdapter.setVariancePercentage(0);
mockRestAdapter.setErrorPercentage(0);
- final Object expected = new Object();
+ @SuppressWarnings("RedundantStringConstructorCall") // Allocated on-heap.
+ final String expected = new String("Hello");
+
class MockObservableExample implements ObservableExample {
- @Override public Observable<Object> doStuff() {
+ @Override public Observable<String> doStuff() {
return Observable.from(expected);
}
}
@@ -373,9 +377,11 @@ class MockObservableExample implements ObservableExample {
mockRestAdapter.setVariancePercentage(0);
mockRestAdapter.setErrorPercentage(0);
- final Object expected = new Object();
+ @SuppressWarnings("RedundantStringConstructorCall") // Allocated on-heap.
+ final String expected = new String("Hello");
+
class MockSyncExample implements SyncExample {
- @Override public Object doStuff() {
+ @Override public String doStuff() {
throw new MockHttpException(404, "Not Found", expected);
}
}
@@ -393,6 +399,7 @@ class MockSyncExample implements SyncExample {
assertThat(e.getResponse().getStatus()).isEqualTo(404);
assertThat(e.getResponse().getReason()).isEqualTo("Not Found");
assertThat(e.getBody()).isSameAs(expected);
+ assertThat(e.getSuccessType()).isEqualTo(String.class);
}
}
@@ -401,9 +408,11 @@ class MockSyncExample implements SyncExample {
mockRestAdapter.setVariancePercentage(0);
mockRestAdapter.setErrorPercentage(0);
- final Object expected = new Object();
+ @SuppressWarnings("RedundantStringConstructorCall") // Allocated on-heap.
+ final String expected = new String("Greetings");
+
class MockAsyncExample implements AsyncExample {
- @Override public void doStuff(Callback<Object> cb) {
+ @Override public void doStuff(Callback<String> cb) {
throw new MockHttpException(404, "Not Found", expected);
}
}
@@ -413,8 +422,8 @@ class MockAsyncExample implements AsyncExample {
final long startNanos = System.nanoTime();
final AtomicLong tookMs = new AtomicLong();
final AtomicReference<RetrofitError> errorRef = new AtomicReference<RetrofitError>();
- mockService.doStuff(new Callback<Object>() {
- @Override public void success(Object o, Response response) {
+ mockService.doStuff(new Callback<String>() {
+ @Override public void success(String o, Response response) {
throw new AssertionError();
}
@@ -433,6 +442,7 @@ class MockAsyncExample implements AsyncExample {
assertThat(error.getResponse().getStatus()).isEqualTo(404);
assertThat(error.getResponse().getReason()).isEqualTo("Not Found");
assertThat(error.getBody()).isSameAs(expected);
+ assertThat(error.getSuccessType()).isEqualTo(String.class);
}
@Test public void observableHttpExceptionBecomesError() {
@@ -440,9 +450,11 @@ class MockAsyncExample implements AsyncExample {
mockRestAdapter.setVariancePercentage(0);
mockRestAdapter.setErrorPercentage(0);
- final Object expected = new Object();
+ @SuppressWarnings("RedundantStringConstructorCall") // Allocated on-heap.
+ final String expected = new String("Hi");
+
class MockObservableExample implements ObservableExample {
- @Override public Observable<Object> doStuff() {
+ @Override public Observable<String> doStuff() {
throw new MockHttpException(404, "Not Found", expected);
}
}
@@ -474,6 +486,7 @@ class MockObservableExample implements ObservableExample {
assertThat(error.getResponse().getStatus()).isEqualTo(404);
assertThat(error.getResponse().getReason()).isEqualTo("Not Found");
assertThat(error.getBody()).isSameAs(expected);
+ assertThat(error.getSuccessType()).isEqualTo(String.class);
}
@Test public void syncErrorUsesErrorHandler() {
@@ -504,7 +517,7 @@ class MockSyncExample implements SyncExample {
mockRestAdapter.setErrorPercentage(0);
class MockAsyncExample implements AsyncExample {
- @Override public void doStuff(Callback<Object> cb) {
+ @Override public void doStuff(Callback<String> cb) {
throw MockHttpException.newNotFound(new Object());
}
}
@@ -513,8 +526,8 @@ class MockAsyncExample implements AsyncExample {
nextError = new IllegalArgumentException("Test");
final CountDownLatch latch = new CountDownLatch(1);
- mockService.doStuff(new Callback<Object>() {
- @Override public void success(Object o, Response response) {
+ mockService.doStuff(new Callback<String>() {
+ @Override public void success(String o, Response response) {
throw new AssertionError();
}
@@ -532,7 +545,7 @@ class MockAsyncExample implements AsyncExample {
mockRestAdapter.setErrorPercentage(0);
class MockObservableExample implements ObservableExample {
- @Override public Observable<Object> doStuff() {
+ @Override public Observable<String> doStuff() {
throw MockHttpException.newNotFound(new Object());
}
}
diff --git a/retrofit/src/test/java/retrofit/RestAdapterTest.java b/retrofit/src/test/java/retrofit/RestAdapterTest.java
index ffcfb3bd65..4dda2761b8 100644
--- a/retrofit/src/test/java/retrofit/RestAdapterTest.java
+++ b/retrofit/src/test/java/retrofit/RestAdapterTest.java
@@ -34,9 +34,7 @@
import static org.assertj.core.api.Assertions.fail;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyInt;
-import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
-import static org.mockito.Matchers.isA;
import static org.mockito.Matchers.same;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.doReturn;
@@ -68,16 +66,16 @@ public class RestAdapterTest {
}
@Override public InputStream in() throws IOException {
- return new ByteArrayInputStream("{}".getBytes("UTF-8"));
+ return new ByteArrayInputStream("Hi".getBytes("UTF-8"));
}
};
private interface Example {
@Headers("Foo: Bar")
- @GET("/") Object something();
+ @GET("/") String something();
@Headers("Foo: Bar")
@POST("/") Object something(@Body TypedOutput body);
- @GET("/") void something(Callback<Object> callback);
+ @GET("/") void something(Callback<String> callback);
@GET("/") Response direct();
@GET("/") void direct(Callback<Response> callback);
@POST("/") Observable<String> observable(@Body String body);
@@ -127,7 +125,7 @@ private interface InvalidExample extends Example {
Object data = new Object();
when(mockProfiler.beforeCall()).thenReturn(data);
when(mockClient.execute(any(Request.class))) //
- .thenReturn(new Response("http://example.com/", 200, "OK", NO_HEADERS, null));
+ .thenReturn(new Response("http://example.com/", 200, "OK", NO_HEADERS, new TypedString("Hey")));
example.something();
@@ -155,7 +153,7 @@ public void log(String message) {
.create(Example.class);
when(mockClient.execute(any(Request.class))) //
- .thenReturn(new Response("http://example.com/", 200, "OK", TWO_HEADERS, new TypedString("{}")));
+ .thenReturn(new Response("http://example.com/", 200, "OK", TWO_HEADERS, new TypedString("Hi")));
example.something();
assertThat(logMessages).hasSize(2);
@@ -182,7 +180,7 @@ public void log(String message) {
.create(Example.class);
when(mockClient.execute(any(Request.class))) //
- .thenReturn(new Response("http://example.com/", 200, "OK", TWO_HEADERS, new TypedString("{}")));
+ .thenReturn(new Response("http://example.com/", 200, "OK", TWO_HEADERS, new TypedString("Hi")));
example.something();
assertThat(logMessages).hasSize(7);
@@ -302,13 +300,13 @@ public void log(String message) {
assertThat(logMessages.get(4)).isEqualTo("Content-Type: application/json");
assertThat(logMessages.get(5)).isEqualTo("Content-Length: 42");
assertThat(logMessages.get(6)).isEqualTo("");
- assertThat(logMessages.get(7)).isEqualTo("{}");
+ assertThat(logMessages.get(7)).isEqualTo("Hi");
assertThat(logMessages.get(8)).isEqualTo("<--- END HTTP (2-byte body)");
}
@Test public void synchronousDoesNotUseExecutors() throws Exception {
when(mockClient.execute(any(Request.class))) //
- .thenReturn(new Response("http://example.com/", 200, "OK", NO_HEADERS, null));
+ .thenReturn(new Response("http://example.com/", 200, "OK", NO_HEADERS, new TypedString("Hi")));
example.something();
@@ -317,15 +315,15 @@ public void log(String message) {
}
@Test public void asynchronousUsesExecutors() throws Exception {
- Response response = new Response("http://example.com/", 200, "OK", NO_HEADERS, new TypedString("{}"));
+ Response response = new Response("http://example.com/", 200, "OK", NO_HEADERS, new TypedString("Hey"));
when(mockClient.execute(any(Request.class))).thenReturn(response);
- Callback<Object> callback = mock(Callback.class);
+ Callback<String> callback = mock(Callback.class);
example.something(callback);
verify(mockRequestExecutor).execute(any(CallbackRunnable.class));
verify(mockCallbackExecutor).execute(any(Runnable.class));
- verify(callback).success(anyString(), same(response));
+ verify(callback).success(eq("Hey"), same(response));
}
@Test public void malformedResponseThrowsConversionException() throws Exception {
@@ -351,6 +349,7 @@ public void log(String message) {
fail("RetrofitError expected on non-2XX response code.");
} catch (RetrofitError e) {
assertThat(e.getResponse().getStatus()).isEqualTo(500);
+ assertThat(e.getSuccessType()).isEqualTo(String.class);
}
}
@@ -392,7 +391,7 @@ public void log(String message) {
assertThat(logMessages.get(4)).isEqualTo("Content-Type: application/json");
assertThat(logMessages.get(5)).isEqualTo("Content-Length: 42");
assertThat(logMessages.get(6)).isEqualTo("");
- assertThat(logMessages.get(7)).isEqualTo("{}");
+ assertThat(logMessages.get(7)).isEqualTo("Hi");
assertThat(logMessages.get(8)).isEqualTo("<--- END HTTP (2-byte body)");
}
@@ -510,7 +509,7 @@ public void log(String message) {
}
@Test public void getResponseDirectlyAsync() throws Exception {
- Response response = new Response("http://example.com/", 200, "OK", NO_HEADERS, null);
+ Response response = new Response("http://example.com/", 200, "OK", NO_HEADERS, new TypedString("Hey"));
when(mockClient.execute(any(Request.class))) //
.thenReturn(response);
Callback<Response> callback = mock(Callback.class);
@@ -522,6 +521,43 @@ public void log(String message) {
verify(callback).success(eq(response), same(response));
}
+ @Test public void getAsync() throws Exception {
+ Response response = new Response("http://example.com/", 200, "OK", NO_HEADERS, new TypedString("Hey"));
+ when(mockClient.execute(any(Request.class))) //
+ .thenReturn(response);
+ Callback<String> callback = mock(Callback.class);
+
+ example.something(callback);
+
+ verify(mockRequestExecutor).execute(any(CallbackRunnable.class));
+ verify(mockCallbackExecutor).execute(any(Runnable.class));
+
+ ArgumentCaptor<String> responseCaptor = ArgumentCaptor.forClass(String.class);
+ verify(callback).success(responseCaptor.capture(), same(response));
+ assertThat(responseCaptor.getValue()).isEqualTo("Hey");
+ }
+
+
+ @Test public void errorAsync() throws Exception {
+ Response response = new Response("http://example.com/", 500, "Broken!", NO_HEADERS, new TypedString("Hey"));
+ when(mockClient.execute(any(Request.class))) //
+ .thenReturn(response);
+ Callback<String> callback = mock(Callback.class);
+
+ example.something(callback);
+
+ verify(mockRequestExecutor).execute(any(CallbackRunnable.class));
+ verify(mockCallbackExecutor).execute(any(Runnable.class));
+
+ ArgumentCaptor<RetrofitError> errorCaptor = ArgumentCaptor.forClass(RetrofitError.class);
+ verify(callback).failure(errorCaptor.capture());
+ RetrofitError error = errorCaptor.getValue();
+ assertThat(error.getResponse().getStatus()).isEqualTo(500);
+ assertThat(error.getResponse().getReason()).isEqualTo("Broken!");
+ assertThat(error.getSuccessType()).isEqualTo(String.class);
+ assertThat(error.getBody()).isEqualTo("Hey");
+ }
+
@Test public void observableCallsOnNext() throws Exception {
when(mockClient.execute(any(Request.class))) //
.thenReturn(new Response("http://example.com/", 200, "OK", NO_HEADERS, new TypedString("hello")));
@@ -537,7 +573,11 @@ public void log(String message) {
Action1<Throwable> onError = mock(Action1.class);
example.observable("Howdy").subscribe(onSuccess, onError);
verifyZeroInteractions(onSuccess);
- verify(onError).call(isA(RetrofitError.class));
+
+ ArgumentCaptor<RetrofitError> errorCaptor = ArgumentCaptor.forClass(RetrofitError.class);
+ verify(onError).call(errorCaptor.capture());
+ RetrofitError value = errorCaptor.getValue();
+ assertThat(value.getSuccessType()).isEqualTo(String.class);
}
@Test public void observableHandlesParams() throws Exception {
| train | train | 2014-06-05T19:47:45 | "2014-06-05T15:47:16Z" | pardom-zz | val |
square/retrofit/557_558 | square/retrofit | square/retrofit/557 | square/retrofit/558 | [
"timestamp(timedelta=0.0, similarity=0.862128618608575)"
] | 92e3b2627275b0c46bef7780d57552672a0aafc0 | e38cc3a63adb258b93627914618cba567e8ea78d | [
"Good catch. Will fix and put out a dot release!\nOn Jul 8, 2014 8:39 AM, \"Miguel Lavigne\" [email protected] wrote:\n\n> The headers list in RequestBuilder class is lazily initialized and in the\n> case where you add the \"Content-Type\" header ONLY through a\n> RequestInterceptor the headers list isn't initialized. This ends with a\n> NullPointerException when executing the build() method in the\n> RequestBuilder.\n> \n> This issue disappear as soon as you add an extra header different than\n> \"Content-Type\". \"Content-Type\" header is treated differently in the code\n> and if it's the only header provided this issue occurs otherwise everything\n> is fine.\n> \n> In the case where \"Content-Type\" is the only header you would want to\n> intercept the workaround would be the provide the header through annotation\n> on your interface.\n> \n> —\n> Reply to this email directly or view it on GitHub\n> https://github.com/square/retrofit/issues/557.\n",
"That's awesome, thx!\n"
] | [] | "2014-07-08T17:25:51Z" | [] | RequestInterceptor.addHeader("Content-Type", "...") only crash with NullPointerException | The headers list in RequestBuilder class is lazily initialized and in the case where you add the "Content-Type" header ONLY through a RequestInterceptor the headers list isn't initialized. This ends with a NullPointerException when executing the build() method in the RequestBuilder.
This issue disappear as soon as you add an extra header different than "Content-Type". "Content-Type" header is treated differently in the code and if it's the only header provided this issue occurs otherwise everything is fine.
In the case where "Content-Type" is the only header you would want to intercept the workaround would be the provide the header through annotation on your interface.
Here's the stackoverflow question that sparked this issue http://stackoverflow.com/questions/24627695/retrofit-headers-nullpointerexception/
| [
"retrofit/src/main/java/retrofit/RequestBuilder.java"
] | [
"retrofit/src/main/java/retrofit/RequestBuilder.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 777aaefabe..d04bb19152 100644
--- a/retrofit/src/main/java/retrofit/RequestBuilder.java
+++ b/retrofit/src/main/java/retrofit/RequestBuilder.java
@@ -21,6 +21,7 @@
import java.lang.reflect.Array;
import java.net.URLEncoder;
import java.util.ArrayList;
+import java.util.Arrays;
import java.util.List;
import java.util.Map;
import retrofit.client.Header;
@@ -341,7 +342,12 @@ Request build() throws UnsupportedEncodingException {
if (body != null) {
body = new MimeOverridingTypedOutput(body, contentTypeHeader);
} else {
- headers.add(new Header("Content-Type", contentTypeHeader));
+ Header header = new Header("Content-Type", contentTypeHeader);
+ if (headers == null) {
+ headers = Arrays.asList(header);
+ } else {
+ headers.add(header);
+ }
}
}
| diff --git a/retrofit/src/test/java/retrofit/RequestBuilderTest.java b/retrofit/src/test/java/retrofit/RequestBuilderTest.java
index 98d78f5147..5fe78daab3 100644
--- a/retrofit/src/test/java/retrofit/RequestBuilderTest.java
+++ b/retrofit/src/test/java/retrofit/RequestBuilderTest.java
@@ -764,6 +764,16 @@ public class RequestBuilderTest {
assertThat(request.getHeaders()).contains(new Header("Content-Type", "text/not-plain"));
}
+ @Test public void contentTypeInterceptorHeaderAddsHeaderWithNoBody() throws Exception {
+ Request request = new Helper() //
+ .setMethod("DELETE") //
+ .setUrl("http://example.com") //
+ .setPath("/") //
+ .addInterceptorHeader("Content-Type", "text/not-plain") //
+ .build();
+ assertThat(request.getHeaders()).contains(new Header("Content-Type", "text/not-plain"));
+ }
+
@Test public void contentTypeParameterHeaderOverrides() throws Exception {
Request request = new Helper() //
.setMethod("POST") //
@@ -957,7 +967,8 @@ Request build() throws Exception {
methodInfo.requestQuery = query;
methodInfo.requestParamNames = paramNames.toArray(new String[paramNames.size()]);
methodInfo.requestParamUsage = paramUsages.toArray(new ParamUsage[paramUsages.size()]);
- methodInfo.headers = methodInfo.parseHeaders(headers.toArray(new String[headers.size()]));
+ methodInfo.headers = headers.isEmpty() ? null
+ : methodInfo.parseHeaders(headers.toArray(new String[headers.size()]));
methodInfo.loaded = true;
RequestBuilder requestBuilder = new RequestBuilder(url, methodInfo, GSON);
| test | train | 2014-07-02T21:25:56 | "2014-07-08T15:39:11Z" | MiguelLavigne | val |
square/retrofit/575_576 | square/retrofit | square/retrofit/575 | square/retrofit/576 | [
"timestamp(timedelta=44.0, similarity=0.8557326538113457)"
] | 816e551ebcf76d4b31eca6b6439de02b2f9ccf32 | a3098980bc027ce2f90f29f325204fbf844f5f8f | [
"`.toString()` is called for `@Header` values: https://github.com/square/retrofit/blob/816e551ebcf76d4b31eca6b6439de02b2f9ccf32/retrofit/src/main/java/retrofit/RequestBuilder.java#L241-243\n",
"Ah, but we reject non-`String` types: https://github.com/square/retrofit/blob/816e551ebcf76d4b31eca6b6439de02b2f9ccf32/retrofit/src/main/java/retrofit/RestMethodInfo.java#L386-L389\n\nYeah want to send a PR?\n",
"Yeah, it'd be fun to mess around with the Retrofit code a bit. I'll update\nthis check, the test, and the markdown doc.\n"
] | [
"nit: two-space indent\n",
"two-space indent for this whole test\n",
"This block seems to have odd spacing.\n"
] | "2014-07-25T03:19:13Z" | [] | Allow objects attached to @Header arguments | Is there any reason not to allow Header fields to have arbitrary objects, and toString them, just like FormUrlEncoded Field params are today?
The current String-only behavior encourages lax typing for things like cookies or other Strings with specific semantic meaning.
| [
"retrofit/src/main/java/retrofit/RestMethodInfo.java",
"website/index.html"
] | [
"retrofit/src/main/java/retrofit/RestMethodInfo.java",
"website/index.html"
] | [
"retrofit/src/test/java/retrofit/RequestBuilderTest.java",
"retrofit/src/test/java/retrofit/RestMethodInfoTest.java"
] | diff --git a/retrofit/src/main/java/retrofit/RestMethodInfo.java b/retrofit/src/main/java/retrofit/RestMethodInfo.java
index cf73f9491f..c14b00ff9c 100644
--- a/retrofit/src/main/java/retrofit/RestMethodInfo.java
+++ b/retrofit/src/main/java/retrofit/RestMethodInfo.java
@@ -383,10 +383,6 @@ private void parseParameters() {
paramUsage[i] = ParamUsage.ENCODED_QUERY_MAP;
} else if (annotationType == Header.class) {
String name = ((Header) parameterAnnotation).value();
- if (parameterType != String.class) {
- throw parameterError(i, "@Header parameter type must be String. Found: %s.",
- parameterType.getSimpleName());
- }
paramNames[i] = name;
paramUsage[i] = ParamUsage.HEADER;
diff --git a/website/index.html b/website/index.html
index 36b4bbe260..5f8b52991d 100644
--- a/website/index.html
+++ b/website/index.html
@@ -114,7 +114,7 @@ <h4>Header Manipulation</h4>
@GET("/users/{username}")
User getUser(@Path("username") String username);</pre>
<p>Note that headers do not overwrite each other. All headers with the same name will be included in the request.</p>
- <p>A request Header can be updated dynamically using the <code>@Header</code> annotation. A corresponding String parameter must be provided to the <code>@Header</code>. If the value is null, the header will be omitted.</p>
+ <p>A request Header can be updated dynamically using the <code>@Header</code> annotation. A corresponding parameter must be provided to the <code>@Header</code>. If the value is null, the header will be omitted. Otherwise, <code>toString</code> will be called on the value, and the result used.</p>
<pre class="prettyprint">@GET("/user")
void getUser(@Header("Authorization") String authorization, Callback<User> callback)</pre>
<p>Headers that need to be added to every request can be specified using a <code>RequestInterceptor</code>. The following code creates a <code>RequestInterceptor</code> that will add a <code>User-Agent</code> header to every request.</p>
| diff --git a/retrofit/src/test/java/retrofit/RequestBuilderTest.java b/retrofit/src/test/java/retrofit/RequestBuilderTest.java
index 5fe78daab3..1cfbd46b90 100644
--- a/retrofit/src/test/java/retrofit/RequestBuilderTest.java
+++ b/retrofit/src/test/java/retrofit/RequestBuilderTest.java
@@ -5,6 +5,7 @@
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.lang.reflect.Method;
+import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
@@ -719,6 +720,21 @@ public class RequestBuilderTest {
assertThat(request.getBody()).isNull();
}
+ @Test public void headerParamToString() throws Exception {
+ Object toStringHeaderParam = new BigInteger("1234");
+ Request request = new Helper() //
+ .setMethod("GET") //
+ .setUrl("http://example.com") //
+ .setPath("/foo/bar/") //
+ .addHeaderParam("kit", toStringHeaderParam) //
+ .build();
+ assertThat(request.getMethod()).isEqualTo("GET");
+ assertThat(request.getHeaders()) //
+ .containsExactly(new Header("kit", "1234"));
+ assertThat(request.getUrl()).isEqualTo("http://example.com/foo/bar/");
+ assertThat(request.getBody()).isNull();
+ }
+
@Test public void headerParam() throws Exception {
Request request = new Helper() //
.setMethod("GET") //
diff --git a/retrofit/src/test/java/retrofit/RestMethodInfoTest.java b/retrofit/src/test/java/retrofit/RestMethodInfoTest.java
index fcf67096f2..1a118eba7c 100644
--- a/retrofit/src/test/java/retrofit/RestMethodInfoTest.java
+++ b/retrofit/src/test/java/retrofit/RestMethodInfoTest.java
@@ -6,6 +6,7 @@
import java.lang.annotation.Target;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
+import java.math.BigInteger;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
@@ -1219,23 +1220,19 @@ Response a(@Header("a") String a, @Header("b") String b) {
assertThat(methodInfo.requestParamUsage).containsExactly(HEADER, HEADER);
}
- @Test public void headerParamMustBeString() {
+ @Test public void headerConvertedToString() {
class Example {
- @GET("/")
- Response a(@Header("a") TypedOutput a, @Header("b") int b) {
+ @GET("/") Response a(@Header("first") BigInteger bi) {
return null;
}
}
Method method = TestingUtils.getMethod(Example.class, "a");
RestMethodInfo methodInfo = new RestMethodInfo(method);
- try {
- methodInfo.init();
- fail();
- } catch (IllegalArgumentException e) {
- assertThat(e).hasMessage(
- "Example.a: @Header parameter type must be String. Found: TypedOutput. (parameter #1)");
- }
+ methodInfo.init();
+
+ assertThat(methodInfo.requestParamNames).containsExactly("first");
+ assertThat(methodInfo.requestParamUsage).containsExactly(HEADER);
}
@Test public void onlyOneEncodingIsAllowedMultipartFirst() {
| train | train | 2014-07-08T19:44:26 | "2014-07-24T23:40:41Z" | LukeStClair | val |
square/retrofit/567_578 | square/retrofit | square/retrofit/567 | square/retrofit/578 | [
"keyword_pr_to_issue",
"timestamp(timedelta=0.0, similarity=0.8425423677540886)"
] | 60b497046d2474f8ea50142115ac18cd5420f748 | f45ff6fa705f476fd1df422cd02d289425cc6ab9 | [
"I found a better way to fix this which allows my chained observables to run on different schedulers:\n\n```\n private static class MockRxSupport {\n private final ErrorHandler errorHandler;\n\n MockRxSupport(RestAdapter restAdapter) {\n errorHandler = restAdapter.errorHandler;\n }\n\n Observable createMockObservable(final MockHandler mockHandler, final RestMethodInfo methodInfo,\n final RequestInterceptor interceptor, final Object[] args) {\n return Observable.create(new Observable.OnSubscribe<Object>() {\n @Override\n public void call(final Subscriber<? super Object> subscriber) {\n try {\n if (subscriber.isUnsubscribed()) return;\n Observable observable =\n (Observable) mockHandler.invokeSync(methodInfo, interceptor, args);\n\n //noinspection unchecked\n observable.subscribe(new Subscriber<Object>() {\n @Override public void onCompleted() {\n subscriber.onCompleted();\n }\n @Override public void onError(Throwable e) {\n subscriber.onError(e);\n }\n @Override public void onNext(Object value) {\n subscriber.onNext(value);\n }\n });\n\n } catch (RetrofitError e) {\n subscriber.onError(errorHandler.handleError(e));\n } catch (Throwable e) {\n subscriber.onError(e);\n }\n }\n });\n }\n }\n```\n",
"Is this what I am running into? Works fine running against the real server, but neither success nor failure gets called on the subscriber running in mock mode.\n\n```\nmApi.replyToken(mParentId)\n .flatMap(new Func1<ReplyToken, Observable<Response>>() {\n @Override public Observable<Response> call(ReplyToken replyToken) {\n Timber.d(\"replyToken = \" + replyToken);\n return mApi.reply(mParentId, replyToken.getHmac(), reply);\n }\n })\n .observeOn(AndroidSchedulers.mainThread())\n .subscribeOn(Schedulers.io())\n .subscribe(new Action1<Response>() {\n @Override public void call(Response response) {\n Timber.e(\"Error: when replying, success is indicated by a 302 with a redirect.\");\n onReplyFailed();\n }\n }, new Action1<Throwable>() {\n @Override public void call(Throwable throwable) {\n handleThrowable(throwable);\n }\n });\n```\n\nAnyone know of a workaround or a fix? \n",
"Try using a synchronous Executor in mock mode and see if it help. See the example here http://stackoverflow.com/questions/24748656/chaining-retrofit-services-w-rxjava-support?answertab=votes#tab-top\n",
"Ok, that worked. Thanks!\n"
] | [
"unused?\n",
"is this intentional? seems like the test used to confirm that the http call was made and now it doesn't?\n",
"you might be right. the delay still exists without the executor, but i think it happens synchronously now. i was on the wrong end of my balmer peak...\n",
"How did this even work before? The test wasn't correct at all.\n"
] | "2014-08-02T08:20:21Z" | [] | Retrofit-Mock chained observable scheduling problem | There seems to be a bug in the MockRestAdapter$MockRxSupport:createMockObservable private class. The way the scheduling is done with respect to subscribing the subscriber to the observable seems wrong. Subscribing to the final observable comes after in the HttpExecutor thread itself is started. I believe the original flow which comes in most cases would come from Schedulers.io() thread is completed and unsubscribed before the mockHandler.invokeSync returned Observable can be subscribed to.
This causes multiple Retrofit Observable chained together to be unable to complete properly.
Using the new Schedulers.from() added in rxjava 0.19.\* seems to solve the issue when passed the httpExecutor in conjunction with using subscribeOn on the mocked observable returned by the mockHandler.invokeSync.
Observable observable =
(Observable) mockHandler.invokeSync(methodInfo, interceptor, args);
observable.subscribeOn(Schedulers.from(httpExecutor));
observable.subscribe(subscriber);
This Stackoverflow question is where the issue was found from http://stackoverflow.com/questions/24748656/chaining-retrofit-services-w-rxjava-support
| [
"retrofit-mock/src/main/java/retrofit/MockRestAdapter.java"
] | [
"retrofit-mock/src/main/java/retrofit/MockRestAdapter.java"
] | [
"retrofit-mock/src/test/java/retrofit/MockRestAdapterTest.java"
] | diff --git a/retrofit-mock/src/main/java/retrofit/MockRestAdapter.java b/retrofit-mock/src/main/java/retrofit/MockRestAdapter.java
index 75026d8834..20e7a639c3 100644
--- a/retrofit-mock/src/main/java/retrofit/MockRestAdapter.java
+++ b/retrofit-mock/src/main/java/retrofit/MockRestAdapter.java
@@ -8,12 +8,13 @@
import java.lang.reflect.Proxy;
import java.util.Map;
import java.util.Random;
-import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
import retrofit.client.Request;
import retrofit.client.Response;
import rx.Observable;
-import rx.Subscriber;
+import rx.Scheduler;
+import rx.functions.Func1;
+import rx.schedulers.Schedulers;
import static retrofit.RestAdapter.LogLevel;
import static retrofit.RetrofitError.unexpectedError;
@@ -468,36 +469,28 @@ private static long uptimeMillis() {
/** Indirection to avoid VerifyError if RxJava isn't present. */
private static class MockRxSupport {
- private final Executor httpExecutor;
+ private final Scheduler httpScheduler;
private final ErrorHandler errorHandler;
MockRxSupport(RestAdapter restAdapter) {
- httpExecutor = restAdapter.httpExecutor;
+ httpScheduler = Schedulers.from(restAdapter.httpExecutor);
errorHandler = restAdapter.errorHandler;
}
Observable createMockObservable(final MockHandler mockHandler, final RestMethodInfo methodInfo,
final RequestInterceptor interceptor, final Object[] args) {
- return Observable.create(new Observable.OnSubscribe<Object>() {
- @Override public void call(final Subscriber<? super Object> subscriber) {
- if (subscriber.isUnsubscribed()) return;
- httpExecutor.execute(new Runnable() {
- @Override public void run() {
+ return Observable.just("nothing") //
+ .flatMap(new Func1<String, Observable<?>>() {
+ @Override public Observable<?> call(String s) {
try {
- if (subscriber.isUnsubscribed()) return;
- Observable observable =
- (Observable) mockHandler.invokeSync(methodInfo, interceptor, args);
- //noinspection unchecked
- observable.subscribe(subscriber);
+ return (Observable) mockHandler.invokeSync(methodInfo, interceptor, args);
} catch (RetrofitError e) {
- subscriber.onError(errorHandler.handleError(e));
- } catch (Throwable e) {
- subscriber.onError(e);
+ return Observable.error(errorHandler.handleError(e));
+ } catch (Throwable throwable) {
+ return Observable.error(throwable);
}
}
- });
- }
- });
+ }).subscribeOn(httpScheduler);
}
}
}
| diff --git a/retrofit-mock/src/test/java/retrofit/MockRestAdapterTest.java b/retrofit-mock/src/test/java/retrofit/MockRestAdapterTest.java
index 412cf7d5ba..680ffdfffc 100644
--- a/retrofit-mock/src/test/java/retrofit/MockRestAdapterTest.java
+++ b/retrofit-mock/src/test/java/retrofit/MockRestAdapterTest.java
@@ -477,7 +477,7 @@ class MockObservableExample implements ObservableExample {
}
});
- verify(httpExecutor, atLeastOnce()).execute(any(Runnable.class));
+ verify(httpExecutor).execute(any(Runnable.class));
verifyZeroInteractions(callbackExecutor);
RetrofitError error = errorRef.get();
@@ -518,7 +518,7 @@ class MockObservableExample implements ObservableExample {
}
});
- verify(httpExecutor, atLeastOnce()).execute(any(Runnable.class));
+ verify(httpExecutor).execute(any(Runnable.class));
verifyZeroInteractions(callbackExecutor);
RetrofitError error = errorRef.get();
| test | train | 2014-10-07T02:49:21 | "2014-07-15T14:52:19Z" | MiguelLavigne | val |
square/retrofit/595_597 | square/retrofit | square/retrofit/595 | square/retrofit/597 | [
"timestamp(timedelta=0.0, similarity=1.0)",
"keyword_pr_to_issue"
] | 3ce5556c31e627cc5e47fddf0a639f9e1fa32a3b | 633974b952a8645ae3be831b69c464f76d44339b | [] | [] | "2014-09-08T20:15:07Z" | [] | @Path/Query exception message update | > URL query string must not have replace block.
Should read something like:
> URL query string must not have replace block. For dynamic query parameters use @Query.
http://stackoverflow.com/q/25658885/132047
| [
"retrofit/src/main/java/retrofit/RestMethodInfo.java"
] | [
"retrofit/src/main/java/retrofit/RestMethodInfo.java"
] | [
"retrofit/src/test/java/retrofit/RestMethodInfoTest.java"
] | diff --git a/retrofit/src/main/java/retrofit/RestMethodInfo.java b/retrofit/src/main/java/retrofit/RestMethodInfo.java
index c14b00ff9c..5905f25771 100644
--- a/retrofit/src/main/java/retrofit/RestMethodInfo.java
+++ b/retrofit/src/main/java/retrofit/RestMethodInfo.java
@@ -223,7 +223,8 @@ private void parsePath(String path) {
// Ensure the query string does not have any named parameters.
Matcher queryParamMatcher = PARAM_URL_REGEX.matcher(query);
if (queryParamMatcher.find()) {
- throw methodError("URL query string \"%s\" must not have replace block.", query);
+ throw methodError("URL query string \"%s\" must not have replace block. For dynamic query"
+ + " parameters use @Query.", query);
}
}
| diff --git a/retrofit/src/test/java/retrofit/RestMethodInfoTest.java b/retrofit/src/test/java/retrofit/RestMethodInfoTest.java
index 1a118eba7c..696fee28f6 100644
--- a/retrofit/src/test/java/retrofit/RestMethodInfoTest.java
+++ b/retrofit/src/test/java/retrofit/RestMethodInfoTest.java
@@ -1307,7 +1307,8 @@ class Example {
fail();
} catch (IllegalArgumentException e) {
assertThat(e).hasMessage(
- "Example.a: URL query string \"bar={bar}\" must not have replace block.");
+ "Example.a: URL query string \"bar={bar}\" must not have replace block. For dynamic query"
+ + " parameters use @Query.");
}
}
| train | train | 2014-09-12T02:55:29 | "2014-09-04T16:27:07Z" | JakeWharton | val |
square/retrofit/594_617 | square/retrofit | square/retrofit/594 | square/retrofit/617 | [
"keyword_pr_to_issue"
] | 7faab3062fdf0de67da119499e5ffeb43f40945d | 63f5eaeaacfe13642e20ebb47a8926d4193766a5 | [] | [] | "2014-10-03T16:53:53Z" | [] | UrlFetchClient: missing Content-Type | UrlFetchClient doesn't set the Content-Type from the body, but only relies from request's headers.
Quick Fix:
```
static HTTPRequest createRequest(Request request) throws IOException {
HTTPMethod httpMethod = getHttpMethod(request.getMethod());
URL url = new URL(request.getUrl());
HTTPRequest fetchRequest = new HTTPRequest(url, httpMethod);
for (Header header : request.getHeaders()) {
fetchRequest.addHeader(new HTTPHeader(header.getName(), header.getValue()));
}
TypedOutput body = request.getBody();
if (body != null) {
/*----> Set Content-Type from body <---- */
if(body.mimeType() != null)
fetchRequest.addHeader(new HTTPHeader("Content-Type", body.mimeType()));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
body.writeTo(baos);
fetchRequest.setPayload(baos.toByteArray());
}
return fetchRequest;
}
```
| [
"retrofit/src/main/java/retrofit/appengine/UrlFetchClient.java"
] | [
"retrofit/src/main/java/retrofit/appengine/UrlFetchClient.java"
] | [
"retrofit/src/test/java/retrofit/appengine/UrlFetchClientTest.java"
] | diff --git a/retrofit/src/main/java/retrofit/appengine/UrlFetchClient.java b/retrofit/src/main/java/retrofit/appengine/UrlFetchClient.java
index 5bc2298615..4c6c49716c 100644
--- a/retrofit/src/main/java/retrofit/appengine/UrlFetchClient.java
+++ b/retrofit/src/main/java/retrofit/appengine/UrlFetchClient.java
@@ -51,7 +51,7 @@ public UrlFetchClient(URLFetchService urlFetchService) {
@Override public Response execute(Request request) throws IOException {
HTTPRequest fetchRequest = createRequest(request);
HTTPResponse fetchResponse = execute(urlFetchService, fetchRequest);
- return parseResponse(fetchResponse);
+ return parseResponse(fetchResponse, fetchRequest);
}
/** Execute the specified {@code request} using the provided {@code urlFetchService}. */
@@ -79,8 +79,11 @@ static HTTPRequest createRequest(Request request) throws IOException {
return fetchRequest;
}
- static Response parseResponse(HTTPResponse response) {
- String url = response.getFinalUrl().toString();
+ static Response parseResponse(HTTPResponse response, HTTPRequest creatingRequest) {
+ // Response URL will be null if it is the same as the request URL.
+ URL responseUrl = response.getFinalUrl();
+ String urlString = (responseUrl != null ? responseUrl : creatingRequest.getURL()).toString();
+
int status = response.getResponseCode();
List<HTTPHeader> fetchHeaders = response.getHeaders();
@@ -101,6 +104,6 @@ static Response parseResponse(HTTPResponse response) {
body = new TypedByteArray(contentType, fetchBody);
}
- return new Response(url, status, "", headers, body);
+ return new Response(urlString, status, "", headers, body);
}
}
| diff --git a/retrofit/src/test/java/retrofit/appengine/UrlFetchClientTest.java b/retrofit/src/test/java/retrofit/appengine/UrlFetchClientTest.java
index 35455fb651..212b9d1290 100644
--- a/retrofit/src/test/java/retrofit/appengine/UrlFetchClientTest.java
+++ b/retrofit/src/test/java/retrofit/appengine/UrlFetchClientTest.java
@@ -24,6 +24,7 @@
import static java.util.Arrays.asList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import static retrofit.TestingUtils.assertBytes;
@@ -81,6 +82,8 @@ public class UrlFetchClientTest {
}
@Test public void response() throws Exception {
+ HTTPRequest creatingRequest = mock(HTTPRequest.class);
+
HTTPResponse fetchResponse = mock(HTTPResponse.class);
when(fetchResponse.getHeaders()).thenReturn(
asList(new HTTPHeader("foo", "bar"), new HTTPHeader("kit", "kat"),
@@ -89,7 +92,32 @@ public class UrlFetchClientTest {
when(fetchResponse.getFinalUrl()).thenReturn(new URL(HOST + "/foo/bar/"));
when(fetchResponse.getResponseCode()).thenReturn(200);
- Response response = UrlFetchClient.parseResponse(fetchResponse);
+ Response response = UrlFetchClient.parseResponse(fetchResponse, creatingRequest);
+
+ assertThat(response.getUrl()).isEqualTo(HOST + "/foo/bar/");
+ assertThat(response.getStatus()).isEqualTo(200);
+ assertThat(response.getReason()).isEqualTo("");
+ assertThat(response.getHeaders()).hasSize(3) //
+ .containsOnly(new Header("foo", "bar"), new Header("kit", "kat"),
+ new Header("Content-Type", "text/plain"));
+ assertBytes(ByteStreams.toByteArray(response.getBody().in()), "hello");
+
+ verifyNoMoreInteractions(creatingRequest);
+ }
+
+ @Test public void responseNullUrlPullsFromRequest() throws Exception {
+ HTTPRequest creatingRequest = mock(HTTPRequest.class);
+ when(creatingRequest.getURL()).thenReturn(new URL(HOST + "/foo/bar/"));
+
+ HTTPResponse fetchResponse = mock(HTTPResponse.class);
+ when(fetchResponse.getHeaders()).thenReturn(
+ asList(new HTTPHeader("foo", "bar"), new HTTPHeader("kit", "kat"),
+ new HTTPHeader("Content-Type", "text/plain")));
+ when(fetchResponse.getContent()).thenReturn("hello".getBytes("UTF-8"));
+ when(fetchResponse.getFinalUrl()).thenReturn(null);
+ when(fetchResponse.getResponseCode()).thenReturn(200);
+
+ Response response = UrlFetchClient.parseResponse(fetchResponse, creatingRequest);
assertThat(response.getUrl()).isEqualTo(HOST + "/foo/bar/");
assertThat(response.getStatus()).isEqualTo(200);
@@ -101,6 +129,8 @@ public class UrlFetchClientTest {
}
@Test public void emptyResponse() throws Exception {
+ HTTPRequest creatingRequest = mock(HTTPRequest.class);
+
HTTPResponse fetchResponse = mock(HTTPResponse.class);
when(fetchResponse.getHeaders()).thenReturn(
asList(new HTTPHeader("foo", "bar"), new HTTPHeader("kit", "kat")));
@@ -108,7 +138,7 @@ public class UrlFetchClientTest {
when(fetchResponse.getFinalUrl()).thenReturn(new URL(HOST + "/foo/bar/"));
when(fetchResponse.getResponseCode()).thenReturn(200);
- Response response = UrlFetchClient.parseResponse(fetchResponse);
+ Response response = UrlFetchClient.parseResponse(fetchResponse, creatingRequest);
assertThat(response.getUrl()).isEqualTo(HOST + "/foo/bar/");
assertThat(response.getStatus()).isEqualTo(200);
@@ -116,6 +146,8 @@ public class UrlFetchClientTest {
assertThat(response.getHeaders()).hasSize(2) //
.containsExactly(new Header("foo", "bar"), new Header("kit", "kat"));
assertThat(response.getBody()).isNull();
+
+ verifyNoMoreInteractions(creatingRequest);
}
private static void assertHeader(HTTPHeader header, String name, String value) {
| val | train | 2014-09-27T15:20:24 | "2014-09-04T09:40:58Z" | renaudcerrato | val |
square/retrofit/560_622 | square/retrofit | square/retrofit/560 | square/retrofit/622 | [
"keyword_pr_to_issue"
] | 3436cfb51e67f229a2656cc46e4baa775c16c535 | ddad8b1f310d05caab5e2012b95ab1f08b2f117e | [
"The first exception should have crashed your app.\n",
"It should indeed. Unfortunately there is no direct way to check for \"RetrofitError.unexpectedError()\", so I'm now using something like this in my callbacks:\n\n``` java\n/**\n * Makes sure unexpected errors crash the app\n * https://github.com/square/retrofit/issues/560\n * @param retrofitError the retrofit error\n */\n private static void failOnUnexpectedError(RetrofitError retrofitError) {\n // see RetrofitError.unexpectedError() for reasoning\n if(!retrofitError.isNetworkError() && retrofitError.getResponse() == null){\n throw new RuntimeException(retrofitError.getMessage(), retrofitError);\n }\n }\n```\n\nWould you propose something else? If not I suppose this can be closed.\n",
"Yeah that's unfortunately the best way right now. Let's leave this issue open and we can look into a better way of identifying what type of failure happened to make things like this easier.\n"
] | [
"Maybe split this into 4xx, 5xx status codes? Or the caller can do that with access to the code anyway\n",
"Should this be a RetrofitError or a RuntimeException?\n",
"Does this include malformed HTTP? It probably does!\n",
"Should these be RetrofitError subclasses? NetworkError, HttpError, ConversionError ?\n",
"(it guarantees that you'll get the problem kind in your crash logs!)\n",
"It should be a `RuntimeException` but we're type-limited to `RetrofitError` because of `Callback`'s API signature.\n\nAll these things we can address in v2, though!\n",
"We don't hand you any of the response body for network errors, even if the `IOException` happens on the very last byte.\n",
"Hmm, possibly. I generally fear the type explosion, but we seem pretty stable on the number of these things. Pre-1.0 Retrofit disambiguated the 4xx vs. 5xx stuff which I collapsed for the 1.0 release. I'll see what this looks like.\n",
"Ahh.\n"
] | "2014-10-04T08:42:51Z" | [] | Only one HTTP method is allowed. Found: POST and POST | Same as #473 , the real cause (malformed interface) is thrown the first time and then the code continues with half initialised state leading to a misleading exception.
actual exception thrown once
```
07-09 10:37:21.792 31834-32136/com.xxx.client D/MyRestClient﹕ java.lang.IllegalArgumentException:MyRestApi.postRawData: No Retrofit annotation found. (parameter #1)
at retrofit.RestMethodInfo.methodError(RestMethodInfo.java:123)
at retrofit.RestMethodInfo.parameterError(RestMethodInfo.java:127)
at retrofit.RestMethodInfo.parseParameters(RestMethodInfo.java:450)
at retrofit.RestMethodInfo.init(RestMethodInfo.java:134)
at retrofit.RestHandler$RestHandler.invokeRequest(RestAdapter.java:294)
```
misleading exception thrown on subsequent calls
```
07-09 10:37:22.792 31834-32137/com.xxx.client D/MyRestClient﹕ java.lang.IllegalArgumentException: MyRestApi.postRawData: Only one HTTP method is allowed. Found: POST and POST.
at retrofit.RestMethodInfo.methodError(RestMethodInfo.java:123)
at retrofit.RestMethodInfo.parseMethodAnnotations(RestMethodInfo.java:155)
at retrofit.RestMethodInfo.init(RestMethodInfo.java:133)
at retrofit.RestAdapter$RestHandler.invokeRequest(RestAdapter.java:294)
```
| [
"retrofit-mock/src/main/java/retrofit/MockHttpRetrofitError.java",
"retrofit/src/main/java/retrofit/RetrofitError.java"
] | [
"retrofit-mock/src/main/java/retrofit/MockHttpRetrofitError.java",
"retrofit/src/main/java/retrofit/RetrofitError.java"
] | [
"retrofit-mock/src/test/java/retrofit/MockRestAdapterTest.java",
"retrofit/src/test/java/retrofit/RestAdapterTest.java"
] | diff --git a/retrofit-mock/src/main/java/retrofit/MockHttpRetrofitError.java b/retrofit-mock/src/main/java/retrofit/MockHttpRetrofitError.java
index 8fff9d212c..8cc23faece 100644
--- a/retrofit-mock/src/main/java/retrofit/MockHttpRetrofitError.java
+++ b/retrofit-mock/src/main/java/retrofit/MockHttpRetrofitError.java
@@ -9,7 +9,7 @@ class MockHttpRetrofitError extends RetrofitError {
MockHttpRetrofitError(String message, String url, Response response, Object body,
Type responseType) {
- super(message, url, response, null, responseType, false, null);
+ super(message, url, response, null, responseType, Kind.HTTP, null);
this.body = body;
}
diff --git a/retrofit/src/main/java/retrofit/RetrofitError.java b/retrofit/src/main/java/retrofit/RetrofitError.java
index 9b335c8424..584b40664c 100644
--- a/retrofit/src/main/java/retrofit/RetrofitError.java
+++ b/retrofit/src/main/java/retrofit/RetrofitError.java
@@ -24,39 +24,56 @@
public class RetrofitError extends RuntimeException {
public static RetrofitError networkError(String url, IOException exception) {
- return new RetrofitError(exception.getMessage(), url, null, null, null, true, exception);
+ return new RetrofitError(exception.getMessage(), url, null, null, null, Kind.NETWORK,
+ exception);
}
public static RetrofitError conversionError(String url, Response response, Converter converter,
Type successType, ConversionException exception) {
- return new RetrofitError(exception.getMessage(), url, response, converter, successType, false,
- exception);
+ return new RetrofitError(exception.getMessage(), url, response, converter, successType,
+ Kind.CONVERSION, exception);
}
public static RetrofitError httpError(String url, Response response, Converter converter,
Type successType) {
String message = response.getStatus() + " " + response.getReason();
- return new RetrofitError(message, url, response, converter, successType, false, null);
+ return new RetrofitError(message, url, response, converter, successType, Kind.HTTP, null);
}
public static RetrofitError unexpectedError(String url, Throwable exception) {
- return new RetrofitError(exception.getMessage(), url, null, null, null, false, exception);
+ return new RetrofitError(exception.getMessage(), url, null, null, null, Kind.UNEXPECTED,
+ exception);
+ }
+
+ /** Identifies the event kind which triggered a {@link RetrofitError}. */
+ public enum Kind {
+ /** An {@link IOException} occurred while communicating to the server. */
+ NETWORK,
+ /** An exception was thrown while (de)serializing a body. */
+ CONVERSION,
+ /** A non-200 HTTP status code was received from the server. */
+ HTTP,
+ /**
+ * An internal error occurred while attempting to execute a request. It is best practice to
+ * re-throw this exception so your application crashes.
+ */
+ UNEXPECTED
}
private final String url;
private final Response response;
private final Converter converter;
private final Type successType;
- private final boolean networkError;
+ private final Kind kind;
RetrofitError(String message, String url, Response response, Converter converter,
- Type successType, boolean networkError, Throwable exception) {
+ Type successType, Kind kind, Throwable exception) {
super(message, exception);
this.url = url;
this.response = response;
this.converter = converter;
this.successType = successType;
- this.networkError = networkError;
+ this.kind = kind;
}
/** The request URL which produced the error. */
@@ -69,14 +86,23 @@ public Response getResponse() {
return response;
}
- /** Whether or not this error was the result of a network error. */
- public boolean isNetworkError() {
- return networkError;
+ /**
+ * Whether or not this error was the result of a network error.
+ *
+ * @deprecated Use {@link #getKind() getKind() == Kind.NETWORK}.
+ */
+ @Deprecated public boolean isNetworkError() {
+ return kind == Kind.NETWORK;
+ }
+
+ /** The event kind which triggered this error. */
+ public Kind getKind() {
+ return kind;
}
/**
- * HTTP response body converted to the type declared by either the interface method return type or
- * the generic type of the supplied {@link Callback} parameter. {@code null} if there is no
+ * HTTP response body converted to the type declared by either the interface method return type
+ * or the generic type of the supplied {@link Callback} parameter. {@code null} if there is no
* response.
*
* @throws RuntimeException if unable to convert the body to the {@link #getSuccessType() success
| diff --git a/retrofit-mock/src/test/java/retrofit/MockRestAdapterTest.java b/retrofit-mock/src/test/java/retrofit/MockRestAdapterTest.java
index f2c894e6b9..412cf7d5ba 100644
--- a/retrofit-mock/src/test/java/retrofit/MockRestAdapterTest.java
+++ b/retrofit-mock/src/test/java/retrofit/MockRestAdapterTest.java
@@ -232,7 +232,7 @@ class MockSyncExample implements SyncExample {
mockService.doStuff();
fail();
} catch (RetrofitError e) {
- assertThat(e.isNetworkError()).isTrue();
+ assertThat(e.getKind()).isEqualTo(RetrofitError.Kind.NETWORK);
assertThat(e.getCause()).hasMessage("Mock network error!");
}
}
@@ -264,7 +264,7 @@ class MockAsyncExample implements AsyncExample {
verify(callbackExecutor).execute(any(Runnable.class));
RetrofitError error = errorRef.get();
- assertThat(error.isNetworkError()).isTrue();
+ assertThat(error.getKind()).isEqualTo(RetrofitError.Kind.NETWORK);
assertThat(error.getCause()).hasMessage("Mock network error!");
}
@@ -395,7 +395,7 @@ class MockSyncExample implements SyncExample {
} catch (RetrofitError e) {
long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNanos);
assertThat(tookMs).isGreaterThanOrEqualTo(100);
- assertThat(e.isNetworkError()).isFalse();
+ assertThat(e.getKind()).isEqualTo(RetrofitError.Kind.HTTP);
assertThat(e.getResponse().getStatus()).isEqualTo(404);
assertThat(e.getResponse().getReason()).isEqualTo("Not Found");
assertThat(e.getBody()).isSameAs(expected);
@@ -438,7 +438,7 @@ class MockAsyncExample implements AsyncExample {
RetrofitError error = errorRef.get();
assertThat(tookMs.get()).isGreaterThanOrEqualTo(100);
- assertThat(error.isNetworkError()).isFalse();
+ assertThat(error.getKind()).isEqualTo(RetrofitError.Kind.HTTP);
assertThat(error.getResponse().getStatus()).isEqualTo(404);
assertThat(error.getResponse().getReason()).isEqualTo("Not Found");
assertThat(error.getBody()).isSameAs(expected);
@@ -482,7 +482,7 @@ class MockObservableExample implements ObservableExample {
RetrofitError error = errorRef.get();
assertThat(tookMs.get()).isGreaterThanOrEqualTo(100);
- assertThat(error.isNetworkError()).isFalse();
+ assertThat(error.getKind()).isEqualTo(RetrofitError.Kind.HTTP);
assertThat(error.getResponse().getStatus()).isEqualTo(404);
assertThat(error.getResponse().getReason()).isEqualTo("Not Found");
assertThat(error.getBody()).isSameAs(expected);
@@ -523,7 +523,7 @@ class MockObservableExample implements ObservableExample {
RetrofitError error = errorRef.get();
assertThat(tookMs.get()).isGreaterThanOrEqualTo(100);
- assertThat(error.isNetworkError()).isFalse();
+ assertThat(error.getKind()).isEqualTo(RetrofitError.Kind.HTTP);
assertThat(error.getResponse().getStatus()).isEqualTo(400);
assertThat(error.getResponse().getReason()).isEqualTo("Bad Request");
assertThat(error.getBody()).isNull();
diff --git a/retrofit/src/test/java/retrofit/RestAdapterTest.java b/retrofit/src/test/java/retrofit/RestAdapterTest.java
index f56b3d20ad..c303788b74 100644
--- a/retrofit/src/test/java/retrofit/RestAdapterTest.java
+++ b/retrofit/src/test/java/retrofit/RestAdapterTest.java
@@ -446,6 +446,7 @@ private interface InvalidExample extends Example {
example.something();
fail("RetrofitError expected on malformed response body.");
} catch (RetrofitError e) {
+ assertThat(e.getKind()).isEqualTo(RetrofitError.Kind.CONVERSION);
assertThat(e.getResponse().getStatus()).isEqualTo(200);
assertThat(e.getCause()).isInstanceOf(ConversionException.class);
assertThat(e.getResponse().getBody()).isNull();
@@ -460,6 +461,7 @@ private interface InvalidExample extends Example {
example.something();
fail("RetrofitError expected on non-2XX response code.");
} catch (RetrofitError e) {
+ assertThat(e.getKind()).isEqualTo(RetrofitError.Kind.HTTP);
assertThat(e.getResponse().getStatus()).isEqualTo(500);
assertThat(e.getSuccessType()).isEqualTo(String.class);
}
@@ -553,6 +555,7 @@ private interface InvalidExample extends Example {
example.something();
fail("RetrofitError expected when client throws exception.");
} catch (RetrofitError e) {
+ assertThat(e.getKind()).isEqualTo(RetrofitError.Kind.NETWORK);
assertThat(e.getCause()).isSameAs(exception);
}
}
@@ -573,6 +576,7 @@ private interface InvalidExample extends Example {
example.something();
fail("RetrofitError expected on malformed response body.");
} catch (RetrofitError e) {
+ assertThat(e.getKind()).isEqualTo(RetrofitError.Kind.NETWORK);
assertThat(e.isNetworkError());
assertThat(e.getCause()).isInstanceOf(IOException.class);
assertThat(e.getCause()).hasMessage("I'm broken!");
@@ -587,6 +591,7 @@ private interface InvalidExample extends Example {
example.something();
fail("RetrofitError expected when unexpected exception thrown.");
} catch (RetrofitError e) {
+ assertThat(e.getKind()).isEqualTo(RetrofitError.Kind.UNEXPECTED);
assertThat(e.getCause()).isSameAs(exception);
}
}
| val | train | 2014-10-07T01:29:10 | "2014-07-09T09:01:26Z" | francisdb | val |
square/retrofit/635_665 | square/retrofit | square/retrofit/635 | square/retrofit/665 | [
"timestamp(timedelta=17.0, similarity=0.8514047274896722)"
] | 9b0cc00cd6198a42974f8c3683e165138632d2d0 | 96567bc65a44fd11e818233446960de555a681e6 | [
"4c38147577d47227b05c0bdb0e8bfefd0f995dec\n"
] | [
"Isn't this a change in behavior? At the very least, not matching it to `@Field` is strange.\n",
"Oops, that was accidental. Fixed. \n",
"This is a very unfortunate public API that we have to expose. Can we at least pair up the `boolean` params with their `String` counterpart.\n",
"`true` is the default, no need to specify\n",
"don't specify the `true` defualt\n"
] | "2014-11-22T18:03:34Z" | [] | @Field.encodeName/Value support | Hi there!
What do you think about implementing `encodeName` and `encodeName` for the `@Field` annotation, similar to you recent commit for `@Query` (https://github.com/square/retrofit/commit/46598adb1da0f6d2498d9f8b815b170bf95fe1f8)? It will allow not to URL-encode specific fields (at the moment they are being encoded unconditionally).
I need this for my project, and I'd be happy to implement this, would it be okay?
The actual reason I need something like that this is because `URLEncoder.encode` converts spaces to "+" signs, whereas I need to convert them to "%20" (I can't alter the decoding behavior on the server side), and there seems no way of intercepting encoding in Retrofit, since `URLEncoder` usage is hardcoded.
A more generic solution would be a dependency injection, like: `new RestAdapter.Builder().setURLEncoder(myURLEncoder)`. However, I am not sure if a lot of people suffer of a similar problem and really need this, so I think I will be fine with annotating that one field with `@Field(encodeValue = false)`.
| [
"retrofit/src/main/java/retrofit/RequestBuilder.java",
"retrofit/src/main/java/retrofit/http/Field.java",
"retrofit/src/main/java/retrofit/http/FieldMap.java",
"retrofit/src/main/java/retrofit/mime/FormUrlEncodedTypedOutput.java"
] | [
"retrofit/src/main/java/retrofit/RequestBuilder.java",
"retrofit/src/main/java/retrofit/http/Field.java",
"retrofit/src/main/java/retrofit/http/FieldMap.java",
"retrofit/src/main/java/retrofit/mime/FormUrlEncodedTypedOutput.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 913581f35f..be6fe6404e 100644
--- a/retrofit/src/main/java/retrofit/RequestBuilder.java
+++ b/retrofit/src/main/java/retrofit/RequestBuilder.java
@@ -272,26 +272,32 @@ void setArguments(Object[] args) {
}
} else if (annotationType == Field.class) {
if (value != null) { // Skip null values.
- String name = ((Field) annotation).value();
+ Field field = (Field) annotation;
+ String name = field.value();
+ boolean encodeName = field.encodeName();
+ boolean encodeValue = field.encodeValue();
if (value instanceof Iterable) {
for (Object iterableValue : (Iterable<?>) value) {
if (iterableValue != null) { // Skip null values.
- formBody.addField(name, iterableValue.toString());
+ formBody.addField(name, iterableValue.toString(), encodeName, encodeValue);
}
}
} else if (value.getClass().isArray()) {
for (int x = 0, arrayLength = Array.getLength(value); x < arrayLength; x++) {
Object arrayValue = Array.get(value, x);
if (arrayValue != null) { // Skip null values.
- formBody.addField(name, arrayValue.toString());
+ formBody.addField(name, arrayValue.toString(), encodeName, encodeValue);
}
}
} else {
- formBody.addField(name, value.toString());
+ formBody.addField(name, value.toString(), encodeName, encodeValue);
}
}
} else if (annotationType == FieldMap.class) {
if (value != null) { // Skip null values.
+ FieldMap fieldMap = (FieldMap) annotation;
+ boolean encodeNames = fieldMap.encodeNames();
+ boolean encodeValues = fieldMap.encodeValues();
for (Map.Entry<?, ?> entry : ((Map<?, ?>) value).entrySet()) {
Object entryKey = entry.getKey();
if (entryKey == null) {
@@ -300,7 +306,8 @@ void setArguments(Object[] args) {
}
Object entryValue = entry.getValue();
if (entryValue != null) { // Skip null values.
- formBody.addField(entryKey.toString(), entryValue.toString());
+ formBody.addField(entryKey.toString(), entryValue.toString(),
+ encodeNames, encodeValues);
}
}
}
diff --git a/retrofit/src/main/java/retrofit/http/Field.java b/retrofit/src/main/java/retrofit/http/Field.java
index cdceca1a67..fce09d9c0e 100644
--- a/retrofit/src/main/java/retrofit/http/Field.java
+++ b/retrofit/src/main/java/retrofit/http/Field.java
@@ -56,4 +56,10 @@
@Retention(RUNTIME)
public @interface Field {
String value();
+
+ /** Specifies whether {@link #value()} is URL encoded. */
+ boolean encodeName() default true;
+
+ /** Specifies whether the argument value to the annotated method parameter is URL encoded. */
+ boolean encodeValue() default true;
}
diff --git a/retrofit/src/main/java/retrofit/http/FieldMap.java b/retrofit/src/main/java/retrofit/http/FieldMap.java
index df1b925e89..09b6f4c0de 100644
--- a/retrofit/src/main/java/retrofit/http/FieldMap.java
+++ b/retrofit/src/main/java/retrofit/http/FieldMap.java
@@ -44,4 +44,9 @@
@Target(PARAMETER)
@Retention(RUNTIME)
public @interface FieldMap {
+ /** Specifies whether parameter names (keys in the map) are URL encoded. */
+ boolean encodeNames() default true;
+
+ /** Specifies whether parameter values (values in the map) are URL encoded. */
+ boolean encodeValues() default true;
}
diff --git a/retrofit/src/main/java/retrofit/mime/FormUrlEncodedTypedOutput.java b/retrofit/src/main/java/retrofit/mime/FormUrlEncodedTypedOutput.java
index d807195a29..73c8f70667 100644
--- a/retrofit/src/main/java/retrofit/mime/FormUrlEncodedTypedOutput.java
+++ b/retrofit/src/main/java/retrofit/mime/FormUrlEncodedTypedOutput.java
@@ -24,6 +24,10 @@ public final class FormUrlEncodedTypedOutput implements TypedOutput {
final ByteArrayOutputStream content = new ByteArrayOutputStream();
public void addField(String name, String value) {
+ addField(name, value, true, true);
+ }
+
+ public void addField(String name, String value, boolean encodeName, boolean encodeValue) {
if (name == null) {
throw new NullPointerException("name");
}
@@ -34,8 +38,12 @@ public void addField(String name, String value) {
content.write('&');
}
try {
- name = URLEncoder.encode(name, "UTF-8");
- value = URLEncoder.encode(value, "UTF-8");
+ if (encodeName) {
+ name = URLEncoder.encode(name, "UTF-8");
+ }
+ if (encodeValue) {
+ value = URLEncoder.encode(value, "UTF-8");
+ }
content.write(name.getBytes("UTF-8"));
content.write('=');
| diff --git a/retrofit/src/test/java/retrofit/RequestBuilderTest.java b/retrofit/src/test/java/retrofit/RequestBuilderTest.java
index 5c2af1caf7..9a331f358c 100644
--- a/retrofit/src/test/java/retrofit/RequestBuilderTest.java
+++ b/retrofit/src/test/java/retrofit/RequestBuilderTest.java
@@ -1456,6 +1456,30 @@ Response method(@Field("foo") String foo, @Field("ping") String ping) {
assertTypedBytes(request.getBody(), "foo=bar&ping=pong");
}
+ @Test public void formEncodedWithEncodedNameFieldParam() {
+ class Example {
+ @FormUrlEncoded //
+ @POST("/foo") //
+ Response method(@Field(value = "na+me", encodeName = false, encodeValue = true) String foo) {
+ return null;
+ }
+ }
+ Request request = buildRequest(Example.class, "ba r");
+ assertTypedBytes(request.getBody(), "na+me=ba+r");
+ }
+
+ @Test public void formEncodedWithEncodedValueFieldParam() {
+ class Example {
+ @FormUrlEncoded //
+ @POST("/foo") //
+ Response method(@Field(value = "na me", encodeName = true, encodeValue = false) String foo) {
+ return null;
+ }
+ }
+ Request request = buildRequest(Example.class, "ba+r");
+ assertTypedBytes(request.getBody(), "na+me=ba+r");
+ }
+
@Test public void formEncodedFieldOptional() {
class Example {
@FormUrlEncoded //
@@ -1511,6 +1535,40 @@ Response method(@Field("foo") int[] fields, @Field("kit") String kit) {
assertTypedBytes(request.getBody(), "foo=1&foo=2&foo=3&kit=kat");
}
+ @Test public void formEncodedWithEncodedNameFieldParamMap() {
+ class Example {
+ @FormUrlEncoded //
+ @POST("/foo") //
+ Response method(@FieldMap(encodeNames = false, encodeValues = true) Map<String, Object> fieldMap) {
+ return null;
+ }
+ }
+
+ Map<String, Object> fieldMap = new LinkedHashMap<String, Object>();
+ fieldMap.put("k+it", "k at");
+ fieldMap.put("pin+g", "po ng");
+
+ Request request = buildRequest(Example.class, fieldMap);
+ assertTypedBytes(request.getBody(), "k+it=k+at&pin+g=po+ng");
+ }
+
+ @Test public void formEncodedWithEncodedValueFieldParamMap() {
+ class Example {
+ @FormUrlEncoded //
+ @POST("/foo") //
+ Response method(@FieldMap(encodeNames = true, encodeValues = false) Map<String, Object> fieldMap) {
+ return null;
+ }
+ }
+
+ Map<String, Object> fieldMap = new LinkedHashMap<String, Object>();
+ fieldMap.put("k it", "k+at");
+ fieldMap.put("pin g", "po+ng");
+
+ Request request = buildRequest(Example.class, fieldMap);
+ assertTypedBytes(request.getBody(), "k+it=k+at&pin+g=po+ng");
+ }
+
@Test public void formEncodedFieldMap() {
class Example {
@FormUrlEncoded //
| train | train | 2014-11-23T14:02:39 | "2014-10-14T18:57:17Z" | karlicoss | val |
square/retrofit/117_803 | square/retrofit | square/retrofit/117 | square/retrofit/803 | [
"keyword_pr_to_issue"
] | bfeaaa5c67c65fcad643d69ec552d811eafd05ea | 2706892b9a8eaa5a3aa077db8d17b25913a90ca5 | [
"Can you try `--keep class retrofit.http.** { *; }` ?\n",
"Proguard is an advanced, powerful tool. It would be far too hard for us to maintain documentation on all of our libraries for proper usage. We recommend you just keep everything in each library until you are comfortable with tweaking and testing the values yourself. Keeping everything is especially useful in complex libraries like this since we rely heavily on reflection for certain aspects of the configuration which breaks with stripping and obfuscation.\n",
"Thanks Jake, you're right, ProGuard is dangerous. I started this application with the Android Bootstrap initially. Adding Retrofit seems to have required some or all of the following to be added, plus or minus:\n\n```\n-keep class com.google.gson.** { *; }\n-keep class com.google.inject.** { *; }\n-keep class org.apache.http.** { *; }\n-keep class org.apache.james.mime4j.** { *; }\n-keep class javax.inject.** { *; }\n-keep class retrofit.** { *; }\n```\n\nI also added a -keep statement for the interface that I used to build my REST interface with Retrofit. All is working now.\n",
"I've step tested my rules for retrofit for maximum proguard usage, i could let work my code as expected with the following rules:\n<pre><code>\n-keep class com.viselabs.aquariummanager.util.seneye.SeneyeService { _; }\n-keep class com.viselabs.aquariummanager.util.seneye.model._\\* { _; }\n-keep class retrofit.http._\\* { *; }\n</pre></code>\n\nThe first line are your interface the second line are your models. This is very minimal to achieve maximum of proguard. It would nice to share experience about this. \n\nThank you for reading.\nDaniel \n",
"A more generic approach is to use\n\n```\n-keepclassmembernames interface * {\n @retrofit.http.* <methods>;\n}\n```\n\nfor the service interfaces so that you end up with following:\n\n```\n-keep class retrofit.** { *; }\n-keep class package.with.model.classes.** { *; }\n-keepclassmembernames interface * {\n @retrofit.http.* <methods>;\n}\n```\n",
"@ralphhm Your approach is quite handy\n",
"@JakeWharton Maybe publish it on the website http://square.github.io/retrofit/ ?\n",
"Not a ProGuard user. Someone can send a PR for it.\n\nOn Sat, Mar 14, 2015 at 12:21 AM Sebastian Roth [email protected]\nwrote:\n\n> @JakeWharton https://github.com/JakeWharton Maybe publish it on the\n> website http://square.github.io/retrofit/ ?\n> \n> —\n> Reply to this email directly or view it on GitHub\n> https://github.com/square/retrofit/issues/117#issuecomment-79839705.\n",
"There are still some missing pieces not mentioned above that my team has found out the hard way. This is our take:\n\n```\n-dontwarn retrofit.**\n-keep class retrofit.** { *; }\n-keepattributes Signature\n-keepattributes Exceptions\n```\n\nYou need `-keepattributes Signature` if in your rest service interface you use methods with `Callback` argument. This argument is of generic type and Retrofit checks it at runtime. Proguard strips generic type information by default and this flag keeps it.\n\n`-keepattributes Exceptions` is needed if your rest service methods throw custom exceptions, because you've defined an `ErrorHandler` that returns such exceptions. Again, at runtime Retrofit verifies if an exception returned by an `ErrorHandler` was declared on the interface. And again, Proguard by default strips information about exceptions declared on methods and this flag tells it to keep them.\n\nYou can find answers for specific problems on Stack Overflow once you come across them and have an exception to paste into Google. But this should help to prevent those problems for all the people who find this issue after searching Google with much more generic search term.\n\nOne other thing to note is that by default Retrofit uses GSON to convert server responses and you need some more Proguard configuration for GSON. But that is covered well on Stack Overflow and [by the GSON team](http://google-gson.googlecode.com/svn/trunk/examples/android-proguard-example/proguard.cfg) (though some of their configuration is not need on Android or do not apply to Android).\n\n@JakeWharton I'd love to contribute our configuration to the Retrofit website. Is adding a new section for it between \"Download\" and \"Contributing\" all right? If not, it'd be great if you suggested an acceptable place for it.\n",
"@JakeWharton, you said you are \n\n> Not a ProGuard user.\n\nDo you use something else for obfuscating code?\n",
"As @ralphhm wrote, you have to keep web service Models from obfuscation, don't know why \r\n(android 6.0 does not require, android 4.1 requires. 4.1 returns null fields for all web response models in **onNext(LIst<MyModel) list){}** callback:\r\n`-keep class package.with.model.classes.** { *; }`\r\n\r\nAlso note this, if you have Modules in your project, you have to write \r\n `consumerProguardFiles 'proguard-rules.pro'` and no `minifyEnabled` text in `build.gradle` file of Modules",
"Following the suggestions here, when we use proguard with Retrofit (3.6.0) then I can see that the rest APIs paths are still kept readable. Any hint or suggestion on how to be able to make them obfuscated as well?",
"You cannot\n\nOn Thu, Jul 6, 2017, 7:09 AM Ale <[email protected]> wrote:\n\n> Following the suggestions here, when we use proguard with Retrofit (3.6.0)\n> then I can see that the rest APIs paths are still kept readable. Any hint\n> or suggestion on how to be able to make them obfuscated as well?\n>\n> —\n> You are receiving this because you were mentioned.\n> Reply to this email directly, view it on GitHub\n> <https://github.com/square/retrofit/issues/117#issuecomment-313366540>,\n> or mute the thread\n> <https://github.com/notifications/unsubscribe-auth/AAEEESFkSOoUNilOU30VKhhP7LdRrTmZks5sLMBVgaJpZM4AToWu>\n> .\n>\n"
] | [] | "2015-04-08T11:32:18Z" | [] | ProGuard and Retrofit don't enjoy each other... | I think some documentation on proper proguard configuration for Retrofit would be great. Any idea what lines I would put into progaurd.cfg to avoid the following errors:
```
12-10 17:18:11.523: WARN/RestAdapter(3135): Method not annotated with GET, POST, PUT, or DELETE: public abstract void com.calgaryscientific.oncall.service.OnCallServiceAsync.deleteUser(java.lang.String,retrofit.http.Callback) from https://csi-oncall.herokuapp.com/
java.lang.IllegalStateException: Method not annotated with GET, POST, PUT, or DELETE: public abstract void com.calgaryscientific.oncall.service.OnCallServiceAsync.deleteUser(java.lang.String,retrofit.http.Callback)
at retrofit.http.RequestLine.fromMethod(RequestLine.java:64)
at retrofit.http.HttpRequestBuilder.setMethod(HttpRequestBuilder.java:52)
at retrofit.http.RestAdapter$RestHandler.invokeRequest(RestAdapter.java:137)
at retrofit.http.RestAdapter$RestHandler.access$400(RestAdapter.java:102)
at retrofit.http.RestAdapter$RestHandler$1.obtainResponse(RestAdapter.java:115)
at retrofit.http.CallbackRunnable.run(CallbackRunnable.java:30)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
at retrofit.http.Platform$Android$2$1.run(Platform.java:93)
at java.lang.Thread.run(Thread.java:856)
```
| [
"website/index.html"
] | [
"website/index.html"
] | [] | diff --git a/website/index.html b/website/index.html
index cfd04f78b7..5e6ba8882d 100644
--- a/website/index.html
+++ b/website/index.html
@@ -258,6 +258,14 @@ <h4>Gradle</h4>
<pre class="prettyprint">
compile 'com.squareup.okhttp:okhttp-urlconnection:2.0.0'
compile 'com.squareup.okhttp:okhttp:2.0.0'
+</pre>
+ <h4>ProGuard</h4>
+ <p>If you are using Proguard in your project add the following lines to your configuration:</p>
+ <pre class="prettyprint">
+-dontwarn retrofit.**
+-keep class retrofit.** { *; }
+-keepattributes Signature
+-keepattributes Exceptions
</pre>
<h3 id="contributing">Contributing</h3>
<p>If you would like to contribute code you can do so through GitHub by forking the repository and sending a pull request.</p>
| null | val | train | 2015-03-20T05:06:09 | "2012-12-11T00:21:12Z" | thorinside | val |
square/retrofit/735_815 | square/retrofit | square/retrofit/735 | square/retrofit/815 | [
"timestamp(timedelta=3327.0, similarity=0.8938397557651852)"
] | f7c759b0f927cf5c6b5ec2cfb944ba8992bf750a | 09b637f0d779601d05728da0d2b497ac2f0a87cc | [
"https://github.com/square/retrofit/pull/815\n"
] | [
"This is never true of an OkHttp response.\n",
"Not a protocol exception? Somewhat harsh to crash the client when the server made the mistake.\n",
"(not sure what's default in Retrofit)\n",
"Ahhh . . . it gets wrapped. Cool.\n"
] | "2015-04-19T20:14:41Z" | [] | HTTP 204, 205 do not have response bodies. | Per the spec, emphasis mine:
> #### 10.2.5 204 No Content
>
> The server has fulfilled the request but does not need to return an entity-body, and might want to return updated metainformation. The response MAY include new or updated metainformation in the form of entity-headers, which if present SHOULD be associated with the requested variant.
>
> If the client is a user agent, it SHOULD NOT change its document view from that which caused the request to be sent. This response is primarily intended to allow input for actions to take place without causing a change to the user agent's active document view, although any new or updated metainformation SHOULD be applied to the document currently in the user agent's active view.
>
> The 204 response **MUST NOT include a message-body**, and thus is always terminated by the first empty line after the header fields.
> #### 10.2.6 205 Reset Content
>
> The server has fulfilled the request and the user agent SHOULD reset the document view which caused the request to be sent. This response is primarily intended to allow input for actions to take place via user input, followed by a clearing of the form in which the input is given so that the user can easily initiate another input action. The response **MUST NOT include an entity**.
We should not even call the `Converter` for these response codes.
| [
"retrofit/src/main/java/retrofit/RestAdapter.java"
] | [
"retrofit/src/main/java/retrofit/RestAdapter.java"
] | [
"retrofit/src/test/java/retrofit/RestAdapterTest.java"
] | diff --git a/retrofit/src/main/java/retrofit/RestAdapter.java b/retrofit/src/main/java/retrofit/RestAdapter.java
index 2da591820f..422806cf32 100644
--- a/retrofit/src/main/java/retrofit/RestAdapter.java
+++ b/retrofit/src/main/java/retrofit/RestAdapter.java
@@ -291,7 +291,12 @@ private Object parseResult(MethodInfo methodInfo, Response response)
}
ResponseBody body = response.body();
- if (body == null) {
+ if (statusCode == 204 || statusCode == 205) {
+ // HTTP 204 No Content "...response MUST NOT include a message-body"
+ // HTTP 205 Reset Content "...response MUST NOT include an entity"
+ if (body.contentLength() > 0) {
+ throw new IllegalStateException(statusCode + " response must not include body.");
+ }
return null;
}
| diff --git a/retrofit/src/test/java/retrofit/RestAdapterTest.java b/retrofit/src/test/java/retrofit/RestAdapterTest.java
index 1776c3f12e..171f5c77a2 100644
--- a/retrofit/src/test/java/retrofit/RestAdapterTest.java
+++ b/retrofit/src/test/java/retrofit/RestAdapterTest.java
@@ -12,6 +12,8 @@
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
+import retrofit.converter.Converter;
+import retrofit.converter.GsonConverter;
import retrofit.http.Body;
import retrofit.http.GET;
import retrofit.http.Headers;
@@ -25,6 +27,8 @@
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.verifyNoMoreInteractions;
import static retrofit.Utils.SynchronousExecutor;
public class RestAdapterTest {
@@ -44,14 +48,18 @@ private interface InvalidExample extends Example {
@Rule public final MockWebServerRule server = new MockWebServerRule();
private Example example;
+ private Converter converter;
@Before public void setUp() {
OkHttpClient client = new OkHttpClient();
+ converter = spy(new GsonConverter());
+
example = new RestAdapter.Builder() //
.setClient(client)
.setCallbackExecutor(new SynchronousExecutor())
.setEndpoint(server.getUrl("/").toString())
+ .setConverter(converter)
.build()
.create(Example.class);
}
@@ -71,6 +79,56 @@ private interface InvalidExample extends Example {
}
}
+ @Test public void http204SkipsConverter() {
+ server.enqueue(new MockResponse().setStatus("HTTP/1.1 204 Nothin"));
+ assertThat(example.something()).isNull();
+ verifyNoMoreInteractions(converter);
+ }
+
+ @Test public void http204Response() {
+ server.enqueue(new MockResponse().setStatus("HTTP/1.1 204 Nothin"));
+ Response response = example.direct();
+ assertThat(response.code()).isEqualTo(204);
+ }
+
+ @Test public void http204WithBodyThrows() {
+ server.enqueue(new MockResponse().setStatus("HTTP/1.1 204 Nothin").setBody("Hey"));
+ try {
+ example.something();
+ fail();
+ } catch (RetrofitError e) {
+ assertThat(e).hasMessage("204 response must not include body.");
+ Throwable cause = e.getCause();
+ assertThat(cause).isInstanceOf(IllegalStateException.class);
+ assertThat(cause).hasMessage("204 response must not include body.");
+ }
+ }
+
+ @Test public void http205SkipsConverter() {
+ server.enqueue(new MockResponse().setStatus("HTTP/1.1 205 Nothin"));
+ assertThat(example.something()).isNull();
+ verifyNoMoreInteractions(converter);
+ }
+
+ @Test public void http205Response() {
+ server.enqueue(new MockResponse().setStatus("HTTP/1.1 205 Nothin"));
+ Response response = example.direct();
+ assertThat(response.code()).isEqualTo(205);
+ }
+
+ @Test public void http205WithBodyThrows() {
+ server.enqueue(new MockResponse().setStatus("HTTP/1.1 205 Nothin").setBody("Hey"));
+ try {
+ example.something();
+ fail();
+ } catch (RetrofitError e) {
+ assertThat(e).hasMessage("205 response must not include body.");
+ Throwable cause = e.getCause();
+ assertThat(cause).isInstanceOf(IllegalStateException.class);
+ assertThat(cause).hasMessage("205 response must not include body.");
+ }
+ }
+
@Test public void successfulRequestResponseWhenMimeTypeMissing() throws Exception {
server.enqueue(new MockResponse().setBody("Hi").removeHeader("Content-Type"));
String string = example.something();
| val | train | 2015-04-16T23:43:17 | "2015-02-03T06:35:52Z" | JakeWharton | val |
square/retrofit/807_885 | square/retrofit | square/retrofit/807 | square/retrofit/885 | [
"keyword_pr_to_issue"
] | 9cc80b1f94be55f1133c48bda531957593aca6d5 | 17003f0263ed2a6494f7e4f8b51385325e7853b5 | [
"This will never work because we do not have access to the type information. I will leave the issue open as a reminder to throw an exception when parsing the method in this case.\n"
] | [
"Not a type variable\n"
] | "2015-06-04T01:46:55Z" | [] | Can't get the genericity? | # my service
```
public interface BaseHttpService {
@POST("/{requestUrl}")
<T> void post(@Path("requestUrl") String requestUrl, @QueryMap Map<String, Object> map, Callback<T> callback);
}
```
# my request
```
BaseHttpService service = restAdapter.create(BaseHttpService.class);
Map<String, Object> params = new HashMap<>();
addParams(0, params);
service.post("xxx", params, callback);
```
# my callback
```
private Callback<DishListResponse<DishDetail>> callback = new Callback<DishListResponse<DishDetail>>() {
@Override
public void success(DishListResponse<DishDetail> dishListResponse, Response response) {
}
@Override
public void failure(RetrofitError retrofitError) {
}
};
```
# the exception
```
java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to xxx.DishListResponse
at xxx$2.success(DishKitchenFragment.java:116)
at retrofit.CallbackRunnable$1.run(CallbackRunnable.java:45)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4898)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1008)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:775)
at dalvik.system.NativeStart.main(Native Method)
```
# but change callback like this , it's ok.
```
@POST("/xxx")
void listDish(@QueryMap Map<String, Object> map, Callback<DishListResponse<DishDetail>> callback);
```
| [
"retrofit/src/main/java/retrofit/MethodInfo.java",
"retrofit/src/main/java/retrofit/Utils.java"
] | [
"retrofit/src/main/java/retrofit/MethodInfo.java",
"retrofit/src/main/java/retrofit/Utils.java"
] | [
"retrofit/src/test/java/retrofit/RestAdapterTest.java"
] | diff --git a/retrofit/src/main/java/retrofit/MethodInfo.java b/retrofit/src/main/java/retrofit/MethodInfo.java
index d766030e1a..ff50e6cf42 100644
--- a/retrofit/src/main/java/retrofit/MethodInfo.java
+++ b/retrofit/src/main/java/retrofit/MethodInfo.java
@@ -236,6 +236,9 @@ private void parseResponseType() {
+ factories);
}
Type responseType = adapter.responseType();
+ if (Utils.hasTypeVariable(responseType)) {
+ throw methodError("Method response type must not include a type variable.");
+ }
if (converter == null && responseType != ResponseBody.class) {
throw methodError("Method response type is "
+ responseType
diff --git a/retrofit/src/main/java/retrofit/Utils.java b/retrofit/src/main/java/retrofit/Utils.java
index 6bec958783..8c8d1c33bc 100644
--- a/retrofit/src/main/java/retrofit/Utils.java
+++ b/retrofit/src/main/java/retrofit/Utils.java
@@ -81,6 +81,33 @@ public static Type getSingleParameterUpperBound(ParameterizedType type) {
return paramType;
}
+ public static boolean hasTypeVariable(Type type) {
+ if (type instanceof Class<?>) {
+ return false;
+ }
+ if (type instanceof ParameterizedType) {
+ ParameterizedType parameterizedType = (ParameterizedType) type;
+ for (Type typeArgument : parameterizedType.getActualTypeArguments()) {
+ if (hasTypeVariable(typeArgument)) {
+ return true;
+ }
+ }
+ return false;
+ }
+ if (type instanceof GenericArrayType) {
+ return hasTypeVariable(((GenericArrayType) type).getGenericComponentType());
+ }
+ if (type instanceof TypeVariable) {
+ return true;
+ }
+ if (type instanceof WildcardType) {
+ return true;
+ }
+ String className = type == null ? "null" : type.getClass().getName();
+ throw new IllegalArgumentException("Expected a Class, ParameterizedType, or "
+ + "GenericArrayType, but <" + type + "> is of type " + className);
+ }
+
// This method is copyright 2008 Google Inc. and is taken from Gson under the Apache 2.0 license.
public static Class<?> getRawType(Type type) {
if (type instanceof Class<?>) {
| diff --git a/retrofit/src/test/java/retrofit/RestAdapterTest.java b/retrofit/src/test/java/retrofit/RestAdapterTest.java
index 07bbca54fd..fa4aedb6a4 100644
--- a/retrofit/src/test/java/retrofit/RestAdapterTest.java
+++ b/retrofit/src/test/java/retrofit/RestAdapterTest.java
@@ -9,6 +9,9 @@
import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicBoolean;
import org.junit.Rule;
@@ -34,6 +37,14 @@ interface FutureMethod {
}
interface Extending extends CallMethod {
}
+ interface StringService {
+ @GET("/") String get();
+ }
+ interface BoundsService {
+ @GET("/") <T> Call<T> none();
+ @GET("/") <T extends ResponseBody> Call<T> upper();
+ @GET("/") <T> Call<List<Map<String, Set<T[]>>>> crazy();
+ }
@SuppressWarnings("EqualsBetweenInconvertibleTypes") // We are explicitly testing this behavior.
@Test public void objectMethodsStillWork() {
@@ -99,10 +110,6 @@ class MyCallAdapterFactory implements CallAdapter.Factory {
assertThat(adapterCalled.get()).isTrue();
}
- interface StringService {
- @GET("/") String get();
- }
-
@Test public void customReturnTypeAdapter() {
class GreetingCallAdapterFactory implements CallAdapter.Factory {
@Override public CallAdapter<?> get(Type returnType) {
@@ -154,7 +161,9 @@ class GreetingCallAdapterFactory implements CallAdapter.Factory {
example.disallowed("Hi!");
fail();
} catch (IllegalArgumentException e) {
- assertThat(e).hasMessage("CallMethod.disallowed: @Body parameter is class java.lang.String but no converter registered. Either add a converter to the RestAdapter or use RequestBody. (parameter #1)");
+ assertThat(e).hasMessage(
+ "CallMethod.disallowed: @Body parameter is class java.lang.String but no converter registered. "
+ + "Either add a converter to the RestAdapter or use RequestBody. (parameter #1)");
}
}
@@ -170,7 +179,9 @@ class GreetingCallAdapterFactory implements CallAdapter.Factory {
example.disallowed();
fail();
} catch (IllegalArgumentException e) {
- assertThat(e).hasMessage("CallMethod.disallowed: Method response type is class java.lang.String but no converter registered. Either add a converter to the RestAdapter or use ResponseBody.");
+ assertThat(e).hasMessage(
+ "CallMethod.disallowed: Method response type is class java.lang.String but no converter registered. "
+ + "Either add a converter to the RestAdapter or use ResponseBody.");
}
}
@@ -200,4 +211,52 @@ class GreetingCallAdapterFactory implements CallAdapter.Factory {
assertThat(server.takeRequest().getBody().readUtf8()).isEqualTo("Hey");
}
+
+ @Test public void typeVariableNoBoundThrows() {
+ RestAdapter ra = new RestAdapter.Builder()
+ .endpoint(server.getUrl("/").toString())
+ .converter(new StringConverter())
+ .build();
+ BoundsService example = ra.create(BoundsService.class);
+
+ try {
+ example.none();
+ fail();
+ } catch (IllegalArgumentException e) {
+ assertThat(e).hasMessage(
+ "BoundsService.none: Method response type must not include a type variable.");
+ }
+ }
+
+ @Test public void typeVariableUpperBoundThrows() {
+ RestAdapter ra = new RestAdapter.Builder()
+ .endpoint(server.getUrl("/").toString())
+ .converter(new StringConverter())
+ .build();
+ BoundsService example = ra.create(BoundsService.class);
+
+ try {
+ example.upper();
+ fail();
+ } catch (IllegalArgumentException e) {
+ assertThat(e).hasMessage(
+ "BoundsService.upper: Method response type must not include a type variable.");
+ }
+ }
+
+ @Test public void typeVariableNestedThrows() {
+ RestAdapter ra = new RestAdapter.Builder()
+ .endpoint(server.getUrl("/").toString())
+ .converter(new StringConverter())
+ .build();
+ BoundsService example = ra.create(BoundsService.class);
+
+ try {
+ example.crazy();
+ fail();
+ } catch (IllegalArgumentException e) {
+ assertThat(e).hasMessage(
+ "BoundsService.crazy: Method response type must not include a type variable.");
+ }
+ }
}
| test | train | 2015-06-04T01:03:13 | "2015-04-14T03:44:25Z" | BiaoWu | val |
square/retrofit/433_885 | square/retrofit | square/retrofit/433 | square/retrofit/885 | [
"keyword_pr_to_issue"
] | 9cc80b1f94be55f1133c48bda531957593aca6d5 | 17003f0263ed2a6494f7e4f8b51385325e7853b5 | [
"How many subclasses would you have out of curiosity?\n",
"Jake, for now, is a proof-of-concept app, with one class. I have a previous dificulty with data synchronization on Android, so, I'm building a kind of \"kit\" with bootstrap for sync data.\n\nMy goal is create a kind of \"plug / implements models / call sync / all done\" lib.\n\nSo, the number of classes can grow.\n\nI containerized retrofit, gson and RabbitMQ on that lib, to avoid installing all on app again.\n\nI think that is possible to implement all I want, if the app provides one \"wrapper\" to API using retrofit, but I prefer to don't implement these way if possible.\n",
"I'm in a similar situation. A SyncAdapter syncing 18 tables, each represented by an entity with a common base class. I thought this might be due to Java's type erasure with generics. Many mostly-duplicate lines of code could be replaced by one API call if we can somehow support generics in Retrofit API interfaces, any new thoughts on this?\n\nEDIT: Digging into the source I see how problematic this would be, and goes against explicit API contracts, so perhaps it's better to just write more code in this case.\n"
] | [
"Not a type variable\n"
] | "2015-06-04T01:46:55Z" | [] | Generic API interfaces | Hello guys,
First of all, thank you for this amazing project. It saves a lot of coding for me!
Now, I came across a small problem.
My API is simple and virtually all trafficked objects are similar. Therefore all have the same parent class. However, I can not create an API interface based on that parent class, or using generics. For example:
``` java
public class BaseModel {
// ...
}
public class TodoItem extends BaseModel {
// ...
}
// ------------
public interface SyncApi {
@GET("/some/url/with/{id}")
TodoItem get(@Path("id") long id); // This works well :)
@GET("/some/url/with/{id}")
BaseModel get(@Path("id") long id); // This fail because GsonConverter does not have an known de/serializer for BaseModel
@GET("/some/url/with/{id}")
<T extends BaseModel> T get(@Path("id") long id); // This return a LinkedTreeMap from Gson
}
// ---------
public interface SyncApi<T extends BaseModel> {
@GET("/some/url/with/{id}")
T get(@Path("id") long id);
}
public interface TodoItemApi extends SyncApi<TodoItem> {
// This raises exception from Retrofit validation about heritance
}
```
Have you some suggestion?
| [
"retrofit/src/main/java/retrofit/MethodInfo.java",
"retrofit/src/main/java/retrofit/Utils.java"
] | [
"retrofit/src/main/java/retrofit/MethodInfo.java",
"retrofit/src/main/java/retrofit/Utils.java"
] | [
"retrofit/src/test/java/retrofit/RestAdapterTest.java"
] | diff --git a/retrofit/src/main/java/retrofit/MethodInfo.java b/retrofit/src/main/java/retrofit/MethodInfo.java
index d766030e1a..ff50e6cf42 100644
--- a/retrofit/src/main/java/retrofit/MethodInfo.java
+++ b/retrofit/src/main/java/retrofit/MethodInfo.java
@@ -236,6 +236,9 @@ private void parseResponseType() {
+ factories);
}
Type responseType = adapter.responseType();
+ if (Utils.hasTypeVariable(responseType)) {
+ throw methodError("Method response type must not include a type variable.");
+ }
if (converter == null && responseType != ResponseBody.class) {
throw methodError("Method response type is "
+ responseType
diff --git a/retrofit/src/main/java/retrofit/Utils.java b/retrofit/src/main/java/retrofit/Utils.java
index 6bec958783..8c8d1c33bc 100644
--- a/retrofit/src/main/java/retrofit/Utils.java
+++ b/retrofit/src/main/java/retrofit/Utils.java
@@ -81,6 +81,33 @@ public static Type getSingleParameterUpperBound(ParameterizedType type) {
return paramType;
}
+ public static boolean hasTypeVariable(Type type) {
+ if (type instanceof Class<?>) {
+ return false;
+ }
+ if (type instanceof ParameterizedType) {
+ ParameterizedType parameterizedType = (ParameterizedType) type;
+ for (Type typeArgument : parameterizedType.getActualTypeArguments()) {
+ if (hasTypeVariable(typeArgument)) {
+ return true;
+ }
+ }
+ return false;
+ }
+ if (type instanceof GenericArrayType) {
+ return hasTypeVariable(((GenericArrayType) type).getGenericComponentType());
+ }
+ if (type instanceof TypeVariable) {
+ return true;
+ }
+ if (type instanceof WildcardType) {
+ return true;
+ }
+ String className = type == null ? "null" : type.getClass().getName();
+ throw new IllegalArgumentException("Expected a Class, ParameterizedType, or "
+ + "GenericArrayType, but <" + type + "> is of type " + className);
+ }
+
// This method is copyright 2008 Google Inc. and is taken from Gson under the Apache 2.0 license.
public static Class<?> getRawType(Type type) {
if (type instanceof Class<?>) {
| diff --git a/retrofit/src/test/java/retrofit/RestAdapterTest.java b/retrofit/src/test/java/retrofit/RestAdapterTest.java
index 07bbca54fd..fa4aedb6a4 100644
--- a/retrofit/src/test/java/retrofit/RestAdapterTest.java
+++ b/retrofit/src/test/java/retrofit/RestAdapterTest.java
@@ -9,6 +9,9 @@
import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicBoolean;
import org.junit.Rule;
@@ -34,6 +37,14 @@ interface FutureMethod {
}
interface Extending extends CallMethod {
}
+ interface StringService {
+ @GET("/") String get();
+ }
+ interface BoundsService {
+ @GET("/") <T> Call<T> none();
+ @GET("/") <T extends ResponseBody> Call<T> upper();
+ @GET("/") <T> Call<List<Map<String, Set<T[]>>>> crazy();
+ }
@SuppressWarnings("EqualsBetweenInconvertibleTypes") // We are explicitly testing this behavior.
@Test public void objectMethodsStillWork() {
@@ -99,10 +110,6 @@ class MyCallAdapterFactory implements CallAdapter.Factory {
assertThat(adapterCalled.get()).isTrue();
}
- interface StringService {
- @GET("/") String get();
- }
-
@Test public void customReturnTypeAdapter() {
class GreetingCallAdapterFactory implements CallAdapter.Factory {
@Override public CallAdapter<?> get(Type returnType) {
@@ -154,7 +161,9 @@ class GreetingCallAdapterFactory implements CallAdapter.Factory {
example.disallowed("Hi!");
fail();
} catch (IllegalArgumentException e) {
- assertThat(e).hasMessage("CallMethod.disallowed: @Body parameter is class java.lang.String but no converter registered. Either add a converter to the RestAdapter or use RequestBody. (parameter #1)");
+ assertThat(e).hasMessage(
+ "CallMethod.disallowed: @Body parameter is class java.lang.String but no converter registered. "
+ + "Either add a converter to the RestAdapter or use RequestBody. (parameter #1)");
}
}
@@ -170,7 +179,9 @@ class GreetingCallAdapterFactory implements CallAdapter.Factory {
example.disallowed();
fail();
} catch (IllegalArgumentException e) {
- assertThat(e).hasMessage("CallMethod.disallowed: Method response type is class java.lang.String but no converter registered. Either add a converter to the RestAdapter or use ResponseBody.");
+ assertThat(e).hasMessage(
+ "CallMethod.disallowed: Method response type is class java.lang.String but no converter registered. "
+ + "Either add a converter to the RestAdapter or use ResponseBody.");
}
}
@@ -200,4 +211,52 @@ class GreetingCallAdapterFactory implements CallAdapter.Factory {
assertThat(server.takeRequest().getBody().readUtf8()).isEqualTo("Hey");
}
+
+ @Test public void typeVariableNoBoundThrows() {
+ RestAdapter ra = new RestAdapter.Builder()
+ .endpoint(server.getUrl("/").toString())
+ .converter(new StringConverter())
+ .build();
+ BoundsService example = ra.create(BoundsService.class);
+
+ try {
+ example.none();
+ fail();
+ } catch (IllegalArgumentException e) {
+ assertThat(e).hasMessage(
+ "BoundsService.none: Method response type must not include a type variable.");
+ }
+ }
+
+ @Test public void typeVariableUpperBoundThrows() {
+ RestAdapter ra = new RestAdapter.Builder()
+ .endpoint(server.getUrl("/").toString())
+ .converter(new StringConverter())
+ .build();
+ BoundsService example = ra.create(BoundsService.class);
+
+ try {
+ example.upper();
+ fail();
+ } catch (IllegalArgumentException e) {
+ assertThat(e).hasMessage(
+ "BoundsService.upper: Method response type must not include a type variable.");
+ }
+ }
+
+ @Test public void typeVariableNestedThrows() {
+ RestAdapter ra = new RestAdapter.Builder()
+ .endpoint(server.getUrl("/").toString())
+ .converter(new StringConverter())
+ .build();
+ BoundsService example = ra.create(BoundsService.class);
+
+ try {
+ example.crazy();
+ fail();
+ } catch (IllegalArgumentException e) {
+ assertThat(e).hasMessage(
+ "BoundsService.crazy: Method response type must not include a type variable.");
+ }
+ }
}
| val | train | 2015-06-04T01:03:13 | "2014-03-10T01:37:16Z" | geovanisouza92 | val |
square/retrofit/904_906 | square/retrofit | square/retrofit/904 | square/retrofit/906 | [
"timestamp(timedelta=0.0, similarity=0.903290977901474)"
] | ad683db827cfd92b9c25a6d130e88d4e6f5372db | 82e8dd07fe5210d4a34388b2e13c65e10f7cc1c6 | [] | [
"This really should be needed, but for some reason the older Okio dependency from Wire's runtime is beating out the newer version which is specified by OkHttp (itself a transitive dependency of Retrofit).\n",
"Nit: comma\n",
"Bizarre.\n",
"(Probably worthwhile to grep and make sure 100% of your projects are consistent.)\n",
"`while (jsonReader.hasNext())`\n\n... Unless you're going for symmetry with the other libraries!\n",
"The converter factory also lets you fast fail here.\n",
"Proto encoding is weird.\n",
"Can we be more specific than RuntimeException in what we their here? Moshi's JsonDataException seems like a usability win.\n",
"Yep. We were erroneously fast-tracking an empty body to `null` in 1.x which broke this use case.\n",
":+1: \n",
"who writes code like this?\n",
"moved file or mistake?\n",
"bothWays ?\n",
"win\n",
"nested class -> top-level class\n",
"Hah. IDEA probably generated this craziness.\n",
"Follow-up. There's also problems with Wire here.\n"
] | "2015-06-18T05:47:19Z" | [] | Switch each converter's tests from unit to integration | We should be testing these as installed in a `Retrofit` instance with `MockWebServer`.
| [
"pom.xml",
"retrofit-converters/gson/pom.xml",
"retrofit-converters/jackson/pom.xml",
"retrofit-converters/moshi/pom.xml",
"retrofit-converters/moshi/src/main/java/retrofit/MoshiConverter.java",
"retrofit-converters/protobuf/pom.xml",
"retrofit-converters/simplexml/pom.xml",
"retrofit-converters/simplexml/src/main/java/retrofit/SimpleXmlConverter.java",
"retrofit-converters/wire/pom.xml",
"retrofit/src/main/java/retrofit/RequestBuilder.java"
] | [
"pom.xml",
"retrofit-converters/gson/pom.xml",
"retrofit-converters/jackson/pom.xml",
"retrofit-converters/moshi/pom.xml",
"retrofit-converters/moshi/src/main/java/retrofit/MoshiConverter.java",
"retrofit-converters/protobuf/pom.xml",
"retrofit-converters/simplexml/pom.xml",
"retrofit-converters/simplexml/src/main/java/retrofit/SimpleXmlConverter.java",
"retrofit-converters/wire/pom.xml",
"retrofit/src/main/java/retrofit/RequestBuilder.java"
] | [
"retrofit-converters/gson/src/test/java/retrofit/GsonConverterTest.java",
"retrofit-converters/jackson/src/test/java/retrofit/JacksonConverterTest.java",
"retrofit-converters/moshi/src/test/java/retrofit/MoshiConverterTest.java",
"retrofit-converters/protobuf/src/test/java/retrofit/ProtoConverterTest.java",
"retrofit-converters/simplexml/src/test/java/retrofit/MyObject.java",
"retrofit-converters/simplexml/src/test/java/retrofit/SimpleXmlConverterTest.java",
"retrofit-converters/wire/src/test/java/retrofit/Phone.java",
"retrofit-converters/wire/src/test/java/retrofit/WireConverterTest.java"
] | diff --git a/pom.xml b/pom.xml
index eadd587503..f9adffe1db 100644
--- a/pom.xml
+++ b/pom.xml
@@ -59,7 +59,7 @@
<gson.version>2.3.1</gson.version>
<protobuf.version>2.5.0</protobuf.version>
<jackson.version>2.4.3</jackson.version>
- <wire.version>1.5.2</wire.version>
+ <wire.version>1.7.0</wire.version>
<simplexml.version>2.7.1</simplexml.version>
<moshi.version>0.9.0</moshi.version>
diff --git a/retrofit-converters/gson/pom.xml b/retrofit-converters/gson/pom.xml
index e353bb3253..0cb591aced 100644
--- a/retrofit-converters/gson/pom.xml
+++ b/retrofit-converters/gson/pom.xml
@@ -30,13 +30,13 @@
<scope>test</scope>
</dependency>
<dependency>
- <groupId>org.assertj</groupId>
- <artifactId>assertj-core</artifactId>
+ <groupId>com.squareup.okhttp</groupId>
+ <artifactId>mockwebserver</artifactId>
<scope>test</scope>
</dependency>
<dependency>
- <groupId>com.google.guava</groupId>
- <artifactId>guava</artifactId>
+ <groupId>org.assertj</groupId>
+ <artifactId>assertj-core</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
diff --git a/retrofit-converters/jackson/pom.xml b/retrofit-converters/jackson/pom.xml
index 06c5a2992e..18d0340b4c 100644
--- a/retrofit-converters/jackson/pom.xml
+++ b/retrofit-converters/jackson/pom.xml
@@ -30,13 +30,13 @@
<scope>test</scope>
</dependency>
<dependency>
- <groupId>org.assertj</groupId>
- <artifactId>assertj-core</artifactId>
+ <groupId>com.squareup.okhttp</groupId>
+ <artifactId>mockwebserver</artifactId>
<scope>test</scope>
</dependency>
<dependency>
- <groupId>com.google.guava</groupId>
- <artifactId>guava</artifactId>
+ <groupId>org.assertj</groupId>
+ <artifactId>assertj-core</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
diff --git a/retrofit-converters/moshi/pom.xml b/retrofit-converters/moshi/pom.xml
index ad40686622..627c62b992 100644
--- a/retrofit-converters/moshi/pom.xml
+++ b/retrofit-converters/moshi/pom.xml
@@ -30,13 +30,13 @@
<scope>test</scope>
</dependency>
<dependency>
- <groupId>org.assertj</groupId>
- <artifactId>assertj-core</artifactId>
+ <groupId>com.squareup.okhttp</groupId>
+ <artifactId>mockwebserver</artifactId>
<scope>test</scope>
</dependency>
<dependency>
- <groupId>com.google.guava</groupId>
- <artifactId>guava</artifactId>
+ <groupId>org.assertj</groupId>
+ <artifactId>assertj-core</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
diff --git a/retrofit-converters/moshi/src/main/java/retrofit/MoshiConverter.java b/retrofit-converters/moshi/src/main/java/retrofit/MoshiConverter.java
index 6dcaa686e5..b3f803ad4f 100644
--- a/retrofit-converters/moshi/src/main/java/retrofit/MoshiConverter.java
+++ b/retrofit-converters/moshi/src/main/java/retrofit/MoshiConverter.java
@@ -38,7 +38,7 @@ public MoshiConverter() {
public MoshiConverter(Moshi moshi) {
if (moshi == null) throw new NullPointerException("moshi == null");
this.moshi = moshi;
- this.mediaType = MediaType.parse("application/json; charset=utf-8");
+ this.mediaType = MediaType.parse("application/json; charset=UTF-8");
}
@Override public Object fromBody(ResponseBody body, Type type) throws IOException {
diff --git a/retrofit-converters/protobuf/pom.xml b/retrofit-converters/protobuf/pom.xml
index d2808b7eac..c635c4854a 100644
--- a/retrofit-converters/protobuf/pom.xml
+++ b/retrofit-converters/protobuf/pom.xml
@@ -30,13 +30,13 @@
<scope>test</scope>
</dependency>
<dependency>
- <groupId>org.assertj</groupId>
- <artifactId>assertj-core</artifactId>
+ <groupId>com.squareup.okhttp</groupId>
+ <artifactId>mockwebserver</artifactId>
<scope>test</scope>
</dependency>
<dependency>
- <groupId>com.google.guava</groupId>
- <artifactId>guava</artifactId>
+ <groupId>org.assertj</groupId>
+ <artifactId>assertj-core</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
diff --git a/retrofit-converters/simplexml/pom.xml b/retrofit-converters/simplexml/pom.xml
index 4a83d0a787..1eba174cb4 100644
--- a/retrofit-converters/simplexml/pom.xml
+++ b/retrofit-converters/simplexml/pom.xml
@@ -30,13 +30,13 @@
<scope>test</scope>
</dependency>
<dependency>
- <groupId>org.assertj</groupId>
- <artifactId>assertj-core</artifactId>
+ <groupId>com.squareup.okhttp</groupId>
+ <artifactId>mockwebserver</artifactId>
<scope>test</scope>
</dependency>
<dependency>
- <groupId>com.google.guava</groupId>
- <artifactId>guava</artifactId>
+ <groupId>org.assertj</groupId>
+ <artifactId>assertj-core</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
diff --git a/retrofit-converters/simplexml/src/main/java/retrofit/SimpleXmlConverter.java b/retrofit-converters/simplexml/src/main/java/retrofit/SimpleXmlConverter.java
index 36ba06f86f..c737dba241 100644
--- a/retrofit-converters/simplexml/src/main/java/retrofit/SimpleXmlConverter.java
+++ b/retrofit-converters/simplexml/src/main/java/retrofit/SimpleXmlConverter.java
@@ -1,3 +1,18 @@
+/*
+ * 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 com.squareup.okhttp.MediaType;
@@ -46,8 +61,12 @@ public SimpleXmlConverter(Serializer serializer, boolean strict) {
@Override public Object fromBody(ResponseBody body, Type type) throws IOException {
InputStream is = body.byteStream();
try {
- return serializer.read((Class<?>) type, is, strict);
- } catch (IOException e) {
+ Object read = serializer.read((Class<?>) type, is, strict);
+ if (read == null) {
+ throw new IllegalStateException("Could not deserialize body as " + type);
+ }
+ return read;
+ } catch (RuntimeException | IOException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException(e);
@@ -60,17 +79,15 @@ public SimpleXmlConverter(Serializer serializer, boolean strict) {
}
@Override public RequestBody toBody(Object source, Type type) {
- byte[] bytes;
+ Buffer buffer = new Buffer();
try {
- Buffer buffer = new Buffer();
OutputStreamWriter osw = new OutputStreamWriter(buffer.outputStream(), CHARSET);
serializer.write(source, osw);
osw.flush();
- bytes = buffer.readByteArray();
} catch (Exception e) {
- throw new AssertionError(e);
+ throw new RuntimeException(e);
}
- return RequestBody.create(MEDIA_TYPE, bytes);
+ return RequestBody.create(MEDIA_TYPE, buffer.readByteString());
}
public boolean isStrict() {
diff --git a/retrofit-converters/wire/pom.xml b/retrofit-converters/wire/pom.xml
index f56ef5fcbe..d2bf06f14c 100644
--- a/retrofit-converters/wire/pom.xml
+++ b/retrofit-converters/wire/pom.xml
@@ -26,6 +26,13 @@
<dependency>
<groupId>com.squareup.wire</groupId>
<artifactId>wire-runtime</artifactId>
+ <exclusions>
+ <!-- Make sure OkHttp's transitive version wins (itself transitive from Retrofit). -->
+ <exclusion>
+ <groupId>com.squareup.okio</groupId>
+ <artifactId>okio</artifactId>
+ </exclusion>
+ </exclusions>
</dependency>
<dependency>
@@ -34,13 +41,13 @@
<scope>test</scope>
</dependency>
<dependency>
- <groupId>org.assertj</groupId>
- <artifactId>assertj-core</artifactId>
+ <groupId>com.squareup.okhttp</groupId>
+ <artifactId>mockwebserver</artifactId>
<scope>test</scope>
</dependency>
<dependency>
- <groupId>com.google.guava</groupId>
- <artifactId>guava</artifactId>
+ <groupId>org.assertj</groupId>
+ <artifactId>assertj-core</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
diff --git a/retrofit/src/main/java/retrofit/RequestBuilder.java b/retrofit/src/main/java/retrofit/RequestBuilder.java
index 55951df769..cf06d4b18d 100644
--- a/retrofit/src/main/java/retrofit/RequestBuilder.java
+++ b/retrofit/src/main/java/retrofit/RequestBuilder.java
@@ -26,6 +26,7 @@
import java.io.UnsupportedEncodingException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Array;
+import java.lang.reflect.Type;
import java.net.URLEncoder;
import java.util.Map;
import okio.BufferedSink;
@@ -47,6 +48,7 @@ final class RequestBuilder {
private final Annotation[] paramAnnotations;
private final String requestMethod;
private final boolean requestHasBody;
+ private final Type requestType;
private final HttpUrl.Builder urlBuilder;
private MultipartBuilder multipartBuilder;
@@ -63,6 +65,7 @@ final class RequestBuilder {
paramAnnotations = methodInfo.requestParamAnnotations;
requestMethod = methodInfo.requestMethod;
requestHasBody = methodInfo.requestHasBody;
+ requestType = methodInfo.requestType;
if (methodInfo.headers != null) {
headers = methodInfo.headers.newBuilder();
@@ -317,10 +320,11 @@ void setArguments(Object[] args) {
if (value == null) {
throw new IllegalArgumentException("Body parameter value must not be null.");
}
- if (value instanceof RequestBody) {
+ if (requestType == RequestBody.class
+ || (requestType == Object.class && value instanceof RequestBody)) {
body = (RequestBody) value;
} else {
- body = converter.toBody(value, value.getClass());
+ body = converter.toBody(value, requestType);
}
} else {
throw new IllegalArgumentException(
| diff --git a/retrofit-converters/gson/src/test/java/retrofit/GsonConverterTest.java b/retrofit-converters/gson/src/test/java/retrofit/GsonConverterTest.java
index a4449757cf..a303727668 100644
--- a/retrofit-converters/gson/src/test/java/retrofit/GsonConverterTest.java
+++ b/retrofit-converters/gson/src/test/java/retrofit/GsonConverterTest.java
@@ -1,36 +1,47 @@
-// Copyright 2015 Square, Inc.
+/*
+ * Copyright (C) 2015 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 com.google.gson.Gson;
import com.google.gson.GsonBuilder;
-import com.google.gson.JsonElement;
-import com.google.gson.JsonObject;
-import com.google.gson.JsonSerializationContext;
-import com.google.gson.JsonSerializer;
-import com.squareup.okhttp.MediaType;
-import com.squareup.okhttp.RequestBody;
-import com.squareup.okhttp.ResponseBody;
+import com.google.gson.TypeAdapter;
+import com.google.gson.stream.JsonReader;
+import com.google.gson.stream.JsonToken;
+import com.google.gson.stream.JsonWriter;
+import com.squareup.okhttp.mockwebserver.MockResponse;
+import com.squareup.okhttp.mockwebserver.RecordedRequest;
+import com.squareup.okhttp.mockwebserver.rule.MockWebServerRule;
import java.io.IOException;
-import java.lang.reflect.Type;
-import okio.Buffer;
-import org.assertj.core.api.AbstractCharSequenceAssert;
import org.junit.Before;
+import org.junit.Rule;
import org.junit.Test;
+import retrofit.http.Body;
+import retrofit.http.POST;
import static org.assertj.core.api.Assertions.assertThat;
-import static org.junit.Assert.assertEquals;
public final class GsonConverterTest {
- private Converter converter;
-
- interface Example {
+ interface AnInterface {
String getName();
}
- class Impl implements Example {
+ static class AnImplementation implements AnInterface {
private final String theName;
- Impl(String name) {
+ AnImplementation(String name) {
theName = name;
}
@@ -39,40 +50,75 @@ class Impl implements Example {
}
}
+ static class AnInterfaceAdapter extends TypeAdapter<AnInterface> {
+ @Override public void write(JsonWriter jsonWriter, AnInterface anInterface) throws IOException {
+ jsonWriter.beginObject();
+ jsonWriter.name("name").value(anInterface.getName());
+ jsonWriter.endObject();
+ }
+
+ @Override public AnInterface read(JsonReader jsonReader) throws IOException {
+ jsonReader.beginObject();
+
+ String name = null;
+ while (jsonReader.peek() != JsonToken.END_OBJECT) {
+ switch (jsonReader.nextName()) {
+ case "name":
+ name = jsonReader.nextString();
+ break;
+ }
+ }
+
+ jsonReader.endObject();
+ return new AnImplementation(name);
+ }
+ }
+
+ interface Service {
+ @POST("/") Call<AnImplementation> anImplementation(@Body AnImplementation impl);
+ @POST("/") Call<AnInterface> anInterface(@Body AnInterface impl);
+ }
+
+ @Rule public final MockWebServerRule server = new MockWebServerRule();
+
+ private Service service;
+
@Before public void setUp() {
Gson gson = new GsonBuilder()
- .registerTypeAdapter(Example.class, new JsonSerializer<Example>() {
- @Override public JsonElement serialize(Example example, Type type,
- JsonSerializationContext json) {
- JsonObject object = new JsonObject();
- object.addProperty("name", example.getName());
- return object;
- }
- })
+ .registerTypeAdapter(AnInterface.class, new AnInterfaceAdapter())
.create();
- converter = new GsonConverter(gson);
+ Converter converter = new GsonConverter(gson);
+ Retrofit retrofit = new Retrofit.Builder()
+ .endpoint(server.getUrl("/").toString())
+ .converter(converter)
+ .build();
+ service = retrofit.create(Service.class);
}
- @Test public void serialization() throws IOException {
- RequestBody body = converter.toBody(new Impl("value"), Impl.class);
- assertBody(body).isEqualTo("{\"theName\":\"value\"}");
- }
+ @Test public void anInterface() throws IOException, InterruptedException {
+ server.enqueue(new MockResponse().setBody("{\"name\":\"value\"}"));
- @Test public void serializationTypeUsed() throws IOException {
- RequestBody body = converter.toBody(new Impl("value"), Example.class);
- assertBody(body).isEqualTo("{\"name\":\"value\"}");
- }
+ Call<AnInterface> call = service.anInterface(new AnImplementation("value"));
+ Response<AnInterface> response = call.execute();
+ AnInterface body = response.body();
+ assertThat(body.getName()).isEqualTo("value");
- @Test public void deserialization() throws IOException {
- ResponseBody body =
- ResponseBody.create(MediaType.parse("text/plain"), "{\"theName\":\"value\"}");
- Impl impl = (Impl) converter.fromBody(body, Impl.class);
- assertEquals("value", impl.getName());
+ RecordedRequest request = server.takeRequest();
+ assertThat(request.getBody().readUtf8()).isEqualTo("{\"name\":\"value\"}");
+ assertThat(request.getHeader("Content-Type")).isEqualTo("application/json; charset=UTF-8");
}
- private static AbstractCharSequenceAssert<?, String> assertBody(RequestBody body) throws IOException {
- Buffer buffer = new Buffer();
- body.writeTo(buffer);
- return assertThat(buffer.readUtf8());
+ @Test public void anImplementation() throws IOException, InterruptedException {
+ server.enqueue(new MockResponse().setBody("{\"theName\":\"value\"}"));
+
+ Call<AnImplementation> call = service.anImplementation(new AnImplementation("value"));
+ Response<AnImplementation> response = call.execute();
+ AnImplementation body = response.body();
+ assertThat(body.theName).isEqualTo("value");
+
+ RecordedRequest request = server.takeRequest();
+ assertThat(request.getBody().readUtf8()).isEqualTo("{\"theName\":\"value\"}");
+ assertThat(request.getHeader("Content-Type")).isEqualTo("application/json; charset=UTF-8");
+
}
}
diff --git a/retrofit-converters/jackson/src/test/java/retrofit/JacksonConverterTest.java b/retrofit-converters/jackson/src/test/java/retrofit/JacksonConverterTest.java
index 8df5529d9b..d552b7bc3d 100644
--- a/retrofit-converters/jackson/src/test/java/retrofit/JacksonConverterTest.java
+++ b/retrofit-converters/jackson/src/test/java/retrofit/JacksonConverterTest.java
@@ -1,89 +1,156 @@
+/*
+ * 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 com.fasterxml.jackson.annotation.JsonProperty;
-import com.fasterxml.jackson.databind.JsonMappingException;
-import com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException;
-import com.squareup.okhttp.MediaType;
-import com.squareup.okhttp.RequestBody;
-import com.squareup.okhttp.ResponseBody;
+import com.fasterxml.jackson.annotation.JsonAutoDetect;
+import com.fasterxml.jackson.core.JsonGenerator;
+import com.fasterxml.jackson.core.JsonParser;
+import com.fasterxml.jackson.core.JsonToken;
+import com.fasterxml.jackson.databind.DeserializationContext;
+import com.fasterxml.jackson.databind.MapperFeature;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.SerializerProvider;
+import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
+import com.fasterxml.jackson.databind.module.SimpleModule;
+import com.fasterxml.jackson.databind.ser.std.StdSerializer;
+import com.squareup.okhttp.mockwebserver.MockResponse;
+import com.squareup.okhttp.mockwebserver.RecordedRequest;
+import com.squareup.okhttp.mockwebserver.rule.MockWebServerRule;
import java.io.IOException;
-import okio.Buffer;
-import org.assertj.core.api.AbstractCharSequenceAssert;
+import org.junit.Before;
+import org.junit.Rule;
import org.junit.Test;
+import retrofit.http.Body;
+import retrofit.http.POST;
import static org.assertj.core.api.Assertions.assertThat;
public class JacksonConverterTest {
- private static final MediaType MEDIA_TYPE = MediaType.parse("application/json; charset=UTF-8");
- private static final MyObject OBJECT = new MyObject("hello world", 10);
- private final String JSON = "{\"message\":\"hello world\",\"count\":10}";
+ interface AnInterface {
+ String getName();
+ }
- private final JacksonConverter converter = new JacksonConverter();
+ static class AnImplementation implements AnInterface {
+ private String theName;
- @Test public void serialize() throws Exception {
- RequestBody body = converter.toBody(OBJECT, MyObject.class);
- assertThat(body.contentType()).isEqualTo(MEDIA_TYPE);
- assertBody(body).isEqualTo(JSON);
- }
+ AnImplementation() {
+ }
+
+ AnImplementation(String name) {
+ theName = name;
+ }
- @Test public void deserialize() throws Exception {
- ResponseBody body = ResponseBody.create(MEDIA_TYPE, JSON);
- MyObject result = (MyObject) converter.fromBody(body, MyObject.class);
- assertThat(result).isEqualTo(OBJECT);
+ @Override public String getName() {
+ return theName;
+ }
}
- @Test public void deserializeWrongValue() throws Exception {
- ResponseBody body = ResponseBody.create(MEDIA_TYPE, "{\"foo\":\"bar\"}");
- try {
- converter.fromBody(body, MyObject.class);
- } catch (UnrecognizedPropertyException ignored) {
+ static class AnInterfaceSerializer extends StdSerializer<AnInterface> {
+ AnInterfaceSerializer() {
+ super(AnInterface.class);
+ }
+
+ @Override public void serialize(AnInterface anInterface, JsonGenerator jsonGenerator,
+ SerializerProvider serializerProvider) throws IOException {
+ jsonGenerator.writeStartObject();
+ jsonGenerator.writeFieldName("name");
+ jsonGenerator.writeString(anInterface.getName());
+ jsonGenerator.writeEndObject();
}
}
- @Test public void deserializeWrongClass() throws Exception {
- ResponseBody body = ResponseBody.create(MEDIA_TYPE, JSON);
- try {
- converter.fromBody(body, String.class);
- } catch (JsonMappingException ignored) {
+ static class AnInterfaceDeserializer extends StdDeserializer<AnInterface> {
+ AnInterfaceDeserializer() {
+ super(AnInterface.class);
+ }
+
+ @Override public AnInterface deserialize(JsonParser jp, DeserializationContext ctxt)
+ throws IOException {
+ if (jp.getCurrentToken() != JsonToken.START_OBJECT) {
+ throw new AssertionError("Expected start object.");
+ }
+
+ String name = null;
+
+ while (jp.nextToken() != JsonToken.END_OBJECT) {
+ switch (jp.getCurrentName()) {
+ case "name":
+ name = jp.getValueAsString();
+ break;
+ }
+ }
+
+ return new AnImplementation(name);
}
}
- private static AbstractCharSequenceAssert<?, String> assertBody(RequestBody body) throws IOException {
- Buffer buffer = new Buffer();
- body.writeTo(buffer);
- return assertThat(buffer.readUtf8());
+ interface Service {
+ @POST("/") Call<AnImplementation> anImplementation(@Body AnImplementation impl);
+ @POST("/") Call<AnInterface> anInterface(@Body AnInterface impl);
}
- static class MyObject {
- private final String message;
- private final int count;
+ @Rule public final MockWebServerRule server = new MockWebServerRule();
+
+ private Service service;
+
+ @Before public void setUp() {
+ SimpleModule module = new SimpleModule();
+ module.addSerializer(AnInterface.class, new AnInterfaceSerializer());
+ module.addDeserializer(AnInterface.class, new AnInterfaceDeserializer());
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.registerModule(module);
+ mapper.configure(MapperFeature.AUTO_DETECT_GETTERS, false);
+ mapper.configure(MapperFeature.AUTO_DETECT_SETTERS, false);
+ mapper.configure(MapperFeature.AUTO_DETECT_IS_GETTERS, false);
+ mapper.setVisibilityChecker(mapper.getSerializationConfig()
+ .getDefaultVisibilityChecker()
+ .withFieldVisibility(JsonAutoDetect.Visibility.ANY));
+
+ Converter converter = new JacksonConverter(mapper);
+ Retrofit retrofit = new Retrofit.Builder()
+ .endpoint(server.getUrl("/").toString())
+ .converter(converter)
+ .build();
+ service = retrofit.create(Service.class);
+ }
- public MyObject(@JsonProperty("message") String message, @JsonProperty("count") int count) {
- this.message = message;
- this.count = count;
- }
+ @Test public void anInterface() throws IOException, InterruptedException {
+ server.enqueue(new MockResponse().setBody("{\"name\":\"value\"}"));
- public String getMessage() {
- return message;
- }
+ Call<AnInterface> call = service.anInterface(new AnImplementation("value"));
+ Response<AnInterface> response = call.execute();
+ AnInterface body = response.body();
+ assertThat(body.getName()).isEqualTo("value");
- public int getCount() {
- return count;
- }
+ RecordedRequest request = server.takeRequest();
+ assertThat(request.getBody().readUtf8()).isEqualTo("{\"name\":\"value\"}");
+ assertThat(request.getHeader("Content-Type")).isEqualTo("application/json; charset=UTF-8");
+ }
- @Override public boolean equals(Object o) {
- if (this == o) return true;
- if (o == null || getClass() != o.getClass()) return false;
+ @Test public void anImplementation() throws IOException, InterruptedException {
+ server.enqueue(new MockResponse().setBody("{\"theName\":\"value\"}"));
- MyObject myObject = (MyObject) o;
- return count == myObject.count
- && !(message != null ? !message.equals(myObject.message) : myObject.message != null);
- }
+ Call<AnImplementation> call = service.anImplementation(new AnImplementation("value"));
+ Response<AnImplementation> response = call.execute();
+ AnImplementation body = response.body();
+ assertThat(body.theName).isEqualTo("value");
- @Override public int hashCode() {
- int result = message != null ? message.hashCode() : 0;
- result = 31 * result + count;
- return result;
- }
+ RecordedRequest request = server.takeRequest();
+ // TODO figure out how to get Jackson to stop using AnInterface's serializer here.
+ assertThat(request.getBody().readUtf8()).isEqualTo("{\"name\":\"value\"}");
+ assertThat(request.getHeader("Content-Type")).isEqualTo("application/json; charset=UTF-8");
}
}
diff --git a/retrofit-converters/moshi/src/test/java/retrofit/MoshiConverterTest.java b/retrofit-converters/moshi/src/test/java/retrofit/MoshiConverterTest.java
index 072745cd9b..2e7213084a 100644
--- a/retrofit-converters/moshi/src/test/java/retrofit/MoshiConverterTest.java
+++ b/retrofit-converters/moshi/src/test/java/retrofit/MoshiConverterTest.java
@@ -20,29 +20,27 @@
import com.squareup.moshi.JsonWriter;
import com.squareup.moshi.Moshi;
import com.squareup.moshi.ToJson;
-import com.squareup.okhttp.MediaType;
-import com.squareup.okhttp.RequestBody;
-import com.squareup.okhttp.ResponseBody;
+import com.squareup.okhttp.mockwebserver.MockResponse;
+import com.squareup.okhttp.mockwebserver.RecordedRequest;
+import com.squareup.okhttp.mockwebserver.rule.MockWebServerRule;
import java.io.IOException;
-import okio.Buffer;
-import org.assertj.core.api.AbstractCharSequenceAssert;
import org.junit.Before;
+import org.junit.Rule;
import org.junit.Test;
+import retrofit.http.Body;
+import retrofit.http.POST;
import static org.assertj.core.api.Assertions.assertThat;
-import static org.junit.Assert.assertEquals;
public final class MoshiConverterTest {
- private Converter converter;
-
- interface Example {
+ interface AnInterface {
String getName();
}
- static class Impl implements Example {
+ static class AnImplementation implements AnInterface {
private final String theName;
- Impl(String name) {
+ AnImplementation(String name) {
theName = name;
}
@@ -51,45 +49,75 @@ static class Impl implements Example {
}
}
- static class ExampleAdapter {
- @ToJson public void to(JsonWriter writer, Example example) throws IOException {
- writer.beginObject();
- writer.name("name").value(example.getName());
- writer.endObject();
+ static class AnInterfaceAdapter {
+ @ToJson public void write(JsonWriter jsonWriter, AnInterface anInterface) throws IOException {
+ System.out.println("TO JSON: " + anInterface);
+ jsonWriter.beginObject();
+ jsonWriter.name("name").value(anInterface.getName());
+ jsonWriter.endObject();
}
- @FromJson public Example from(JsonReader reader) throws IOException {
- throw new UnsupportedOperationException(); // Moshi requires this method to exist.
+ @FromJson public AnInterface read(JsonReader jsonReader) throws IOException {
+ jsonReader.beginObject();
+
+ String name = null;
+ while (jsonReader.hasNext()) {
+ switch (jsonReader.nextName()) {
+ case "name":
+ name = jsonReader.nextString();
+ break;
+ }
+ }
+
+ jsonReader.endObject();
+ return new AnImplementation(name);
}
}
+ interface Service {
+ @POST("/") Call<AnImplementation> anImplementation(@Body AnImplementation impl);
+ @POST("/") Call<AnInterface> anInterface(@Body AnInterface impl);
+ }
+
+ @Rule public final MockWebServerRule server = new MockWebServerRule();
+
+ private Service service;
+
@Before public void setUp() {
- Moshi gson = new Moshi.Builder()
- .add(new ExampleAdapter())
+ Moshi moshi = new Moshi.Builder()
+ .add(new AnInterfaceAdapter())
+ .build();
+ Converter converter = new MoshiConverter(moshi);
+ Retrofit retrofit = new Retrofit.Builder()
+ .endpoint(server.getUrl("/").toString())
+ .converter(converter)
.build();
- converter = new MoshiConverter(gson);
+ service = retrofit.create(Service.class);
}
- @Test public void serialization() throws IOException {
- RequestBody body = converter.toBody(new Impl("value"), Impl.class);
- assertBody(body).isEqualTo("{\"theName\":\"value\"}");
- }
+ @Test public void anInterface() throws IOException, InterruptedException {
+ server.enqueue(new MockResponse().setBody("{\"name\":\"value\"}"));
- @Test public void serializationTypeUsed() throws IOException {
- RequestBody body = converter.toBody(new Impl("value"), Example.class);
- assertBody(body).isEqualTo("{\"name\":\"value\"}");
- }
+ Call<AnInterface> call = service.anInterface(new AnImplementation("value"));
+ Response<AnInterface> response = call.execute();
+ AnInterface body = response.body();
+ assertThat(body.getName()).isEqualTo("value");
- @Test public void deserialization() throws IOException {
- ResponseBody body =
- ResponseBody.create(MediaType.parse("text/plain"), "{\"theName\":\"value\"}");
- Impl impl = (Impl) converter.fromBody(body, Impl.class);
- assertEquals("value", impl.getName());
+ RecordedRequest request = server.takeRequest();
+ assertThat(request.getBody().readUtf8()).isEqualTo("{\"name\":\"value\"}");
+ assertThat(request.getHeader("Content-Type")).isEqualTo("application/json; charset=UTF-8");
}
- private static AbstractCharSequenceAssert<?, String> assertBody(RequestBody body) throws IOException {
- Buffer buffer = new Buffer();
- body.writeTo(buffer);
- return assertThat(buffer.readUtf8());
+ @Test public void anImplementation() throws IOException, InterruptedException {
+ server.enqueue(new MockResponse().setBody("{\"theName\":\"value\"}"));
+
+ Call<AnImplementation> call = service.anImplementation(new AnImplementation("value"));
+ Response<AnImplementation> response = call.execute();
+ AnImplementation body = response.body();
+ assertThat(body.theName).isEqualTo("value");
+
+ RecordedRequest request = server.takeRequest();
+ assertThat(request.getBody().readUtf8()).isEqualTo("{\"theName\":\"value\"}");
+ assertThat(request.getHeader("Content-Type")).isEqualTo("application/json; charset=UTF-8");
}
}
diff --git a/retrofit-converters/protobuf/src/test/java/retrofit/ProtoConverterTest.java b/retrofit-converters/protobuf/src/test/java/retrofit/ProtoConverterTest.java
index e10956d9bf..e04065a014 100644
--- a/retrofit-converters/protobuf/src/test/java/retrofit/ProtoConverterTest.java
+++ b/retrofit-converters/protobuf/src/test/java/retrofit/ProtoConverterTest.java
@@ -1,73 +1,119 @@
-// Copyright 2013 Square, Inc.
+/*
+ * 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 com.google.protobuf.InvalidProtocolBufferException;
-import com.squareup.okhttp.MediaType;
-import com.squareup.okhttp.RequestBody;
-import com.squareup.okhttp.ResponseBody;
+import com.squareup.okhttp.mockwebserver.MockResponse;
+import com.squareup.okhttp.mockwebserver.RecordedRequest;
+import com.squareup.okhttp.mockwebserver.rule.MockWebServerRule;
import java.io.IOException;
-import java.util.ArrayList;
+import java.util.List;
import okio.Buffer;
import okio.ByteString;
-import org.assertj.core.api.AbstractCharSequenceAssert;
+import org.junit.Before;
+import org.junit.Rule;
import org.junit.Test;
+import retrofit.http.Body;
+import retrofit.http.GET;
+import retrofit.http.POST;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;
import static retrofit.PhoneProtos.Phone;
public final class ProtoConverterTest {
- private static final Phone PROTO = Phone.newBuilder().setNumber("(519) 867-5309").build();
- private static final String ENCODED_PROTO = "Cg4oNTE5KSA4NjctNTMwOQ==";
+ interface Service {
+ @GET("/") Call<Phone> get();
+ @POST("/") Call<Phone> post(@Body Phone impl);
+ @GET("/") Call<String> wrongClass();
+ @GET("/") Call<List<String>> wrongType();
+ }
+
+ @Rule public final MockWebServerRule server = new MockWebServerRule();
- private final ProtoConverter converter = new ProtoConverter();
+ private Service service;
- @Test public void serialize() throws Exception {
- RequestBody body = converter.toBody(PROTO, Phone.class);
- assertThat(body.contentType().toString()).isEqualTo("application/x-protobuf");
- assertBody(body).isEqualTo(ENCODED_PROTO);
+ @Before public void setUp() {
+ Retrofit retrofit = new Retrofit.Builder()
+ .endpoint(server.getUrl("/").toString())
+ .converter(new ProtoConverter())
+ .build();
+ service = retrofit.create(Service.class);
}
- @Test public void deserialize() throws Exception {
- Object proto = converter.fromBody(protoResponse(ENCODED_PROTO), Phone.class);
- assertThat(proto).isEqualTo(PROTO);
+ @Test public void serializeAndDeserialize() throws IOException, InterruptedException {
+ ByteString encoded = ByteString.decodeBase64("Cg4oNTE5KSA4NjctNTMwOQ==");
+ server.enqueue(new MockResponse().setBody(new Buffer().write(encoded)));
+
+ Call<Phone> call = service.post(Phone.newBuilder().setNumber("(519) 867-5309").build());
+ Response<Phone> response = call.execute();
+ Phone body = response.body();
+ assertThat(body.getNumber()).isEqualTo("(519) 867-5309");
+
+ RecordedRequest request = server.takeRequest();
+ assertThat(request.getBody().readByteString()).isEqualTo(encoded);
+ assertThat(request.getHeader("Content-Type")).isEqualTo("application/x-protobuf");
+ }
+
+ @Test public void deserializeEmpty() throws IOException {
+ server.enqueue(new MockResponse());
+
+ Call<Phone> call = service.get();
+ Response<Phone> response = call.execute();
+ Phone body = response.body();
+ assertThat(body.hasNumber()).isFalse();
}
- @Test public void deserializeWrongClass() throws Exception {
+ @Test public void deserializeWrongClass() throws IOException {
+ ByteString encoded = ByteString.decodeBase64("Cg4oNTE5KSA4NjctNTMwOQ==");
+ server.enqueue(new MockResponse().setBody(new Buffer().write(encoded)));
+
+ Call<?> call = service.wrongClass();
try {
- converter.fromBody(protoResponse(ENCODED_PROTO), String.class);
+ call.execute();
fail();
} catch (IllegalArgumentException e) {
assertThat(e).hasMessage("Expected a protobuf message but was java.lang.String");
}
}
- @Test public void deserializeWrongType() throws Exception {
+ @Test public void deserializeWrongType() throws IOException {
+ ByteString encoded = ByteString.decodeBase64("Cg4oNTE5KSA4NjctNTMwOQ==");
+ server.enqueue(new MockResponse().setBody(new Buffer().write(encoded)));
+
+ Call<?> call = service.wrongType();
try {
- converter.fromBody(protoResponse(ENCODED_PROTO), ArrayList.class.getGenericSuperclass());
+ call.execute();
fail();
} catch (IllegalArgumentException e) {
- assertThat(e).hasMessage("Expected a raw Class<?> but was java.util.AbstractList<E>");
+ assertThat(e).hasMessage("Expected a raw Class<?> but was java.util.List<java.lang.String>");
}
}
- @Test public void deserializeWrongValue() throws Exception {
+ @Test public void deserializeWrongValue() throws IOException {
+ ByteString encoded = ByteString.decodeBase64("////");
+ server.enqueue(new MockResponse().setBody(new Buffer().write(encoded)));
+
+ Call<?> call = service.get();
try {
- converter.fromBody(protoResponse("////"), Phone.class);
+ call.execute();
fail();
- } catch (RuntimeException expected) {
- assertThat(expected.getCause() instanceof InvalidProtocolBufferException);
+ } catch (RuntimeException e) {
+ assertThat(e.getCause()).isInstanceOf(InvalidProtocolBufferException.class)
+ .hasMessageContaining("input ended unexpectedly");
}
}
-
- private static ResponseBody protoResponse(String encodedProto) {
- return ResponseBody.create(MediaType.parse("application/x-protobuf"), ByteString.decodeBase64(
- encodedProto).toByteArray());
- }
-
- private static AbstractCharSequenceAssert<?, String> assertBody(RequestBody body) throws IOException {
- Buffer buffer = new Buffer();
- body.writeTo(buffer);
- return assertThat(buffer.readByteString().base64());
- }
}
diff --git a/retrofit-converters/simplexml/src/test/java/retrofit/MyObject.java b/retrofit-converters/simplexml/src/test/java/retrofit/MyObject.java
new file mode 100644
index 0000000000..398854c194
--- /dev/null
+++ b/retrofit-converters/simplexml/src/test/java/retrofit/MyObject.java
@@ -0,0 +1,65 @@
+/*
+ * 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 org.simpleframework.xml.Default;
+import org.simpleframework.xml.DefaultType;
+import org.simpleframework.xml.Element;
+
+@Default(value = DefaultType.FIELD)
+final class MyObject {
+ @Element private String message;
+ @Element private int count;
+
+ public MyObject() {
+ }
+
+ public MyObject(String message, int count) {
+ this.message = message;
+ this.count = count;
+ }
+
+ public void setMessage(String message) {
+ this.message = message;
+ }
+
+ public String getMessage() {
+ return message;
+ }
+
+ public void setCount(int count) {
+ this.count = count;
+ }
+
+ public int getCount() {
+ return count;
+ }
+
+ @Override public int hashCode() {
+ int result = 1;
+ result = result * 31 + count;
+ result = result * 31 + (message == null ? 0 : message.hashCode());
+ return result;
+ }
+
+ @Override public boolean equals(Object obj) {
+ if (obj == this) return true;
+ if (!(obj instanceof MyObject)) return false;
+ MyObject other = (MyObject) obj;
+ return count == other.count
+ && (message == null ? other.message == null : message.equals(other.message));
+ }
+}
diff --git a/retrofit-converters/simplexml/src/test/java/retrofit/SimpleXmlConverterTest.java b/retrofit-converters/simplexml/src/test/java/retrofit/SimpleXmlConverterTest.java
index e47c44a6fb..1c1d0f9a74 100644
--- a/retrofit-converters/simplexml/src/test/java/retrofit/SimpleXmlConverterTest.java
+++ b/retrofit-converters/simplexml/src/test/java/retrofit/SimpleXmlConverterTest.java
@@ -1,128 +1,100 @@
+/*
+ * 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 com.squareup.okhttp.MediaType;
-import com.squareup.okhttp.RequestBody;
-import com.squareup.okhttp.ResponseBody;
+import com.squareup.okhttp.mockwebserver.MockResponse;
+import com.squareup.okhttp.mockwebserver.RecordedRequest;
+import com.squareup.okhttp.mockwebserver.rule.MockWebServerRule;
import java.io.IOException;
-import okio.Buffer;
-import org.assertj.core.api.AbstractCharSequenceAssert;
import org.junit.Before;
+import org.junit.Rule;
import org.junit.Test;
-import org.simpleframework.xml.Default;
-import org.simpleframework.xml.DefaultType;
-import org.simpleframework.xml.Element;
+import org.simpleframework.xml.core.ElementException;
import org.simpleframework.xml.core.Persister;
import org.simpleframework.xml.stream.Format;
import org.simpleframework.xml.stream.HyphenStyle;
import org.simpleframework.xml.stream.Verbosity;
+import retrofit.http.Body;
+import retrofit.http.GET;
+import retrofit.http.POST;
import static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.Assert.fail;
public class SimpleXmlConverterTest {
- private static final MediaType MEDIA_TYPE = MediaType.parse("application/xml; charset=UTF-8");
- private static final MyObject OBJ = new MyObject("hello world", 10);
- private static final String XML =
- "<my-object><message>hello world</message><count>10</count></my-object>";
+ interface Service {
+ @GET("/") Call<MyObject> get();
+ @POST("/") Call<MyObject> post(@Body MyObject impl);
+ @GET("/") Call<String> wrongClass();
+ }
+
+ @Rule public final MockWebServerRule server = new MockWebServerRule();
- private Converter converter;
+ private Service service;
@Before public void setUp() {
Format format = new Format(0, null, new HyphenStyle(), Verbosity.HIGH);
Persister persister = new Persister(format);
- converter = new SimpleXmlConverter(persister);
- }
-
- @Test public void serialize() throws Exception {
- RequestBody body = converter.toBody(OBJ, MyObject.class);
- assertThat(body.contentType()).isEqualTo(MEDIA_TYPE);
- assertBody(body).isEqualTo(XML);
- }
-
- @Test public void deserialize() throws Exception {
- ResponseBody body = ResponseBody.create(MEDIA_TYPE, XML);
- MyObject result = (MyObject) converter.fromBody(body, MyObject.class);
- assertThat(result).isEqualTo(OBJ);
+ Converter converter = new SimpleXmlConverter(persister);
+ Retrofit retrofit = new Retrofit.Builder()
+ .endpoint(server.getUrl("/").toString())
+ .converter(converter)
+ .build();
+ service = retrofit.create(Service.class);
}
- @Test public void deserializeWrongValue() throws Exception {
- ResponseBody body = ResponseBody.create(MEDIA_TYPE, "<myObject><foo/><bar/></myObject>");
- try {
- converter.fromBody(body, MyObject.class);
- } catch (RuntimeException ignored) {
- }
- }
+ @Test public void bodyWays() throws IOException, InterruptedException {
+ server.enqueue(new MockResponse().setBody(
+ "<my-object><message>hello world</message><count>10</count></my-object>"));
- @Test public void deserializeWrongClass() throws Exception {
- ResponseBody body = ResponseBody.create(MEDIA_TYPE, XML);
- Object result = converter.fromBody(body, String.class);
- assertThat(result).isNull();
- }
+ Call<MyObject> call = service.post(new MyObject("hello world", 10));
+ Response<MyObject> response = call.execute();
+ MyObject body = response.body();
+ assertThat(body.getMessage()).isEqualTo("hello world");
+ assertThat(body.getCount()).isEqualTo(10);
- private static AbstractCharSequenceAssert<?, String> assertBody(RequestBody body)
- throws IOException {
- Buffer buffer = new Buffer();
- body.writeTo(buffer);
- return assertThat(buffer.readUtf8());
+ RecordedRequest request = server.takeRequest();
+ assertThat(request.getBody().readUtf8()).isEqualTo(
+ "<my-object><message>hello world</message><count>10</count></my-object>");
+ assertThat(request.getHeader("Content-Type")).isEqualTo("application/xml; charset=UTF-8");
}
- @Default(value = DefaultType.FIELD) static class MyObject {
- @Element private String message;
- @Element private int count;
-
- public MyObject() {
- }
-
- public MyObject(String message, int count) {
- this.message = message;
- this.count = count;
- }
-
- public void setMessage(String message) {
- this.message = message;
- }
-
- public String getMessage() {
- return message;
- }
-
- public void setCount(int count) {
- this.count = count;
- }
+ @Test public void deserializeWrongValue() throws IOException {
+ server.enqueue(new MockResponse().setBody("<myObject><foo/><bar/></myObject>"));
- public int getCount() {
- return count;
+ Call<?> call = service.get();
+ try {
+ call.execute();
+ fail();
+ } catch (RuntimeException e) {
+ assertThat(e.getCause()).isInstanceOf(ElementException.class)
+ .hasMessageStartingWith("Element 'foo' does not have a match in class retrofit.MyObject");
}
+ }
- @Override public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result + count;
- result = prime * result + ((message == null) ? 0 : message.hashCode());
- return result;
- }
+ @Test public void deserializeWrongClass() throws IOException {
+ server.enqueue(new MockResponse().setBody(
+ "<my-object><message>hello world</message><count>10</count></my-object>"));
- @Override public boolean equals(Object obj) {
- if (this == obj) {
- return true;
- }
- if (obj == null) {
- return false;
- }
- if (getClass() != obj.getClass()) {
- return false;
- }
- MyObject other = (MyObject) obj;
- if (count != other.count) {
- return false;
- }
- if (message == null) {
- if (other.message != null) {
- return false;
- }
- } else if (!message.equals(other.message)) {
- return false;
- }
- return true;
+ Call<?> call = service.wrongClass();
+ try {
+ call.execute();
+ fail();
+ } catch (RuntimeException e) {
+ assertThat(e).hasMessage("Could not deserialize body as class java.lang.String");
}
}
}
diff --git a/retrofit-converters/wire/src/test/java/retrofit/Person.java b/retrofit-converters/wire/src/test/java/retrofit/Person.java
deleted file mode 100644
index daf0bc3222..0000000000
--- a/retrofit-converters/wire/src/test/java/retrofit/Person.java
+++ /dev/null
@@ -1,248 +0,0 @@
-// Code generated by Wire protocol buffer compiler, do not edit.
-// Source file: ../wire-runtime/src/test/proto/person.proto
-package retrofit;
-
-import com.squareup.wire.Message;
-import com.squareup.wire.ProtoEnum;
-import com.squareup.wire.ProtoField;
-import java.util.Collections;
-import java.util.List;
-
-import static com.squareup.wire.Message.Datatype.ENUM;
-import static com.squareup.wire.Message.Datatype.INT32;
-import static com.squareup.wire.Message.Datatype.STRING;
-import static com.squareup.wire.Message.Label.REPEATED;
-import static com.squareup.wire.Message.Label.REQUIRED;
-
-public final class Person extends Message {
-
- public static final String DEFAULT_NAME = "";
- public static final Integer DEFAULT_ID = 0;
- public static final String DEFAULT_EMAIL = "";
- public static final List<PhoneNumber> DEFAULT_PHONE = Collections.emptyList();
-
- /**
- * The customer's full name.
- */
- @ProtoField(tag = 1, type = STRING, label = REQUIRED)
- public final String name;
-
- /**
- * The customer's ID number.
- */
- @ProtoField(tag = 2, type = INT32, label = REQUIRED)
- public final Integer id;
-
- /**
- * Email address for the customer.
- */
- @ProtoField(tag = 3, type = STRING)
- public final String email;
-
- /**
- * A list of the customer's phone numbers.
- */
- @ProtoField(tag = 4, label = REPEATED)
- public final List<PhoneNumber> phone;
-
- public Person(String name, Integer id, String email, List<PhoneNumber> phone) {
- this.name = name;
- this.id = id;
- this.email = email;
- this.phone = immutableCopyOf(phone);
- }
-
- private Person(Builder builder) {
- this(builder.name, builder.id, builder.email, builder.phone);
- setBuilder(builder);
- }
-
- @Override
- public boolean equals(Object other) {
- if (other == this) return true;
- if (!(other instanceof Person)) return false;
- Person o = (Person) other;
- return equals(name, o.name)
- && equals(id, o.id)
- && equals(email, o.email)
- && equals(phone, o.phone);
- }
-
- @Override
- public int hashCode() {
- int result = hashCode;
- if (result == 0) {
- result = name != null ? name.hashCode() : 0;
- result = result * 37 + (id != null ? id.hashCode() : 0);
- result = result * 37 + (email != null ? email.hashCode() : 0);
- result = result * 37 + (phone != null ? phone.hashCode() : 1);
- hashCode = result;
- }
- return result;
- }
-
- public static final class Builder extends Message.Builder<Person> {
-
- public String name;
- public Integer id;
- public String email;
- public List<PhoneNumber> phone;
-
- public Builder() {
- }
-
- public Builder(Person message) {
- super(message);
- if (message == null) return;
- this.name = message.name;
- this.id = message.id;
- this.email = message.email;
- this.phone = copyOf(message.phone);
- }
-
- /**
- * The customer's full name.
- */
- public Builder name(String name) {
- this.name = name;
- return this;
- }
-
- /**
- * The customer's ID number.
- */
- public Builder id(Integer id) {
- this.id = id;
- return this;
- }
-
- /**
- * Email address for the customer.
- */
- public Builder email(String email) {
- this.email = email;
- return this;
- }
-
- /**
- * A list of the customer's phone numbers.
- */
- public Builder phone(List<PhoneNumber> phone) {
- this.phone = checkForNulls(phone);
- return this;
- }
-
- @Override
- public Person build() {
- checkRequiredFields();
- return new Person(this);
- }
- }
-
- public enum PhoneType
- implements ProtoEnum {
- MOBILE(0),
- HOME(1),
- /**
- * Could be phone or fax.
- */
- WORK(2);
-
- private final int value;
-
- private PhoneType(int value) {
- this.value = value;
- }
-
- @Override
- public int getValue() {
- return value;
- }
- }
-
- public static final class PhoneNumber extends Message {
-
- public static final String DEFAULT_NUMBER = "";
- public static final PhoneType DEFAULT_TYPE = PhoneType.HOME;
-
- /**
- * The customer's phone number.
- */
- @ProtoField(tag = 1, type = STRING, label = REQUIRED)
- public final String number;
-
- /**
- * The type of phone stored here.
- */
- @ProtoField(tag = 2, type = ENUM)
- public final PhoneType type;
-
- public PhoneNumber(String number, PhoneType type) {
- this.number = number;
- this.type = type;
- }
-
- private PhoneNumber(Builder builder) {
- this(builder.number, builder.type);
- setBuilder(builder);
- }
-
- @Override
- public boolean equals(Object other) {
- if (other == this) return true;
- if (!(other instanceof PhoneNumber)) return false;
- PhoneNumber o = (PhoneNumber) other;
- return equals(number, o.number)
- && equals(type, o.type);
- }
-
- @Override
- public int hashCode() {
- int result = hashCode;
- if (result == 0) {
- result = number != null ? number.hashCode() : 0;
- result = result * 37 + (type != null ? type.hashCode() : 0);
- hashCode = result;
- }
- return result;
- }
-
- public static final class Builder extends Message.Builder<PhoneNumber> {
-
- public String number;
- public PhoneType type;
-
- public Builder() {
- }
-
- public Builder(PhoneNumber message) {
- super(message);
- if (message == null) return;
- this.number = message.number;
- this.type = message.type;
- }
-
- /**
- * The customer's phone number.
- */
- public Builder number(String number) {
- this.number = number;
- return this;
- }
-
- /**
- * The type of phone stored here.
- */
- public Builder type(PhoneType type) {
- this.type = type;
- return this;
- }
-
- @Override
- public PhoneNumber build() {
- checkRequiredFields();
- return new PhoneNumber(this);
- }
- }
- }
-}
diff --git a/retrofit-converters/wire/src/test/java/retrofit/Phone.java b/retrofit-converters/wire/src/test/java/retrofit/Phone.java
new file mode 100644
index 0000000000..e8a47989d8
--- /dev/null
+++ b/retrofit-converters/wire/src/test/java/retrofit/Phone.java
@@ -0,0 +1,69 @@
+// Code generated by Wire protocol buffer compiler, do not edit.
+// Source file: ../wire-runtime/src/test/proto/person.proto
+package retrofit;
+
+import com.squareup.wire.Message;
+import com.squareup.wire.ProtoField;
+
+import static com.squareup.wire.Message.Datatype.STRING;
+import static com.squareup.wire.Message.Label.OPTIONAL;
+
+public final class Phone extends Message {
+
+ public static final String DEFAULT_PHONE = "";
+
+ @ProtoField(tag = 1, type = STRING, label = OPTIONAL)
+ public final String number;
+
+ public Phone(String number) {
+ this.number = number;
+ }
+
+ private Phone(Builder builder) {
+ this(builder.number);
+ setBuilder(builder);
+ }
+
+ @Override
+ public boolean equals(Object other) {
+ if (other == this) return true;
+ if (!(other instanceof Phone)) return false;
+ Phone o = (Phone) other;
+ return equals(number, o.number);
+ }
+
+ @Override
+ public int hashCode() {
+ int result = hashCode;
+ if (result == 0) {
+ result = number != null ? number.hashCode() : 0;
+ hashCode = result;
+ }
+ return result;
+ }
+
+ public static final class Builder extends Message.Builder<Phone> {
+
+ public String number;
+
+ public Builder() {
+ }
+
+ public Builder(Phone message) {
+ super(message);
+ if (message == null) return;
+ this.number = message.number;
+ }
+
+ public Builder number(String name) {
+ this.number = name;
+ return this;
+ }
+
+ @Override
+ public Phone build() {
+ checkRequiredFields();
+ return new Phone(this);
+ }
+ }
+}
diff --git a/retrofit-converters/wire/src/test/java/retrofit/WireConverterTest.java b/retrofit-converters/wire/src/test/java/retrofit/WireConverterTest.java
index b72c1f5fe0..47e615f70b 100644
--- a/retrofit-converters/wire/src/test/java/retrofit/WireConverterTest.java
+++ b/retrofit-converters/wire/src/test/java/retrofit/WireConverterTest.java
@@ -1,72 +1,116 @@
-// Copyright 2013 Square, Inc.
+/*
+ * 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 com.squareup.okhttp.MediaType;
-import com.squareup.okhttp.RequestBody;
-import com.squareup.okhttp.ResponseBody;
+import com.squareup.okhttp.mockwebserver.MockResponse;
+import com.squareup.okhttp.mockwebserver.RecordedRequest;
+import com.squareup.okhttp.mockwebserver.rule.MockWebServerRule;
+import java.io.EOFException;
import java.io.IOException;
-import java.util.ArrayList;
+import java.util.List;
import okio.Buffer;
import okio.ByteString;
-import org.assertj.core.api.AbstractCharSequenceAssert;
+import org.junit.Before;
+import org.junit.Rule;
import org.junit.Test;
+import retrofit.http.Body;
+import retrofit.http.GET;
+import retrofit.http.POST;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;
public final class WireConverterTest {
- private static final Person PROTO =
- new Person.Builder().id(42).name("Omar Little").email("[email protected]").build();
- private static final String ENCODED_PROTO = "CgtPbWFyIExpdHRsZRAqGhBvbWFyQHRoZWtpbmcub3Jn";
+ interface Service {
+ @GET("/") Call<Phone> get();
+ @POST("/") Call<Phone> post(@Body Phone impl);
+ @GET("/") Call<String> wrongClass();
+ @GET("/") Call<List<String>> wrongType();
+ }
+
+ @Rule public final MockWebServerRule server = new MockWebServerRule();
- private final WireConverter converter = new WireConverter();
+ private Service service;
- @Test public void serialize() throws Exception {
- RequestBody body = converter.toBody(PROTO, Person.class);
- assertThat(body.contentType().toString()).isEqualTo("application/x-protobuf");
- assertBody(body).isEqualTo(ENCODED_PROTO);
+ @Before public void setUp() {
+ Retrofit retrofit = new Retrofit.Builder()
+ .endpoint(server.getUrl("/").toString())
+ .converter(new WireConverter())
+ .build();
+ service = retrofit.create(Service.class);
}
- @Test public void deserialize() throws Exception {
- Object proto = converter.fromBody(protoResponse(ENCODED_PROTO), Person.class);
- assertThat(proto).isEqualTo(PROTO);
+ @Test public void serializeAndDeserialize() throws IOException, InterruptedException {
+ ByteString encoded = ByteString.decodeBase64("Cg4oNTE5KSA4NjctNTMwOQ==");
+ server.enqueue(new MockResponse().setBody(new Buffer().write(encoded)));
+
+ Call<Phone> call = service.post(new Phone("(519) 867-5309"));
+ Response<Phone> response = call.execute();
+ Phone body = response.body();
+ assertThat(body.number).isEqualTo("(519) 867-5309");
+
+ RecordedRequest request = server.takeRequest();
+ assertThat(request.getBody().readByteString()).isEqualTo(encoded);
+ assertThat(request.getHeader("Content-Type")).isEqualTo("application/x-protobuf");
+ }
+
+ @Test public void deserializeEmpty() throws IOException {
+ server.enqueue(new MockResponse());
+
+ Call<Phone> call = service.get();
+ Response<Phone> response = call.execute();
+ Phone body = response.body();
+ assertThat(body.number).isNull();
}
- @Test public void deserializeWrongClass() throws Exception {
+ @Test public void deserializeWrongClass() throws IOException {
+ ByteString encoded = ByteString.decodeBase64("Cg4oNTE5KSA4NjctNTMwOQ==");
+ server.enqueue(new MockResponse().setBody(new Buffer().write(encoded)));
+
+ Call<?> call = service.wrongClass();
try {
- converter.fromBody(protoResponse(ENCODED_PROTO), String.class);
+ call.execute();
fail();
} catch (IllegalArgumentException e) {
assertThat(e).hasMessage("Expected a proto message but was java.lang.String");
}
}
- @Test public void deserializeWrongType() throws Exception {
+ @Test public void deserializeWrongType() throws IOException {
+ ByteString encoded = ByteString.decodeBase64("Cg4oNTE5KSA4NjctNTMwOQ==");
+ server.enqueue(new MockResponse().setBody(new Buffer().write(encoded)));
+
+ Call<?> call = service.wrongType();
try {
- converter.fromBody(protoResponse(ENCODED_PROTO),
- ArrayList.class.getGenericSuperclass());
+ call.execute();
fail();
} catch (IllegalArgumentException e) {
- assertThat(e).hasMessage("Expected a raw Class<?> but was java.util.AbstractList<E>");
+ assertThat(e).hasMessage("Expected a raw Class<?> but was java.util.List<java.lang.String>");
}
}
- @Test public void deserializeWrongValue() throws Exception {
+ @Test public void deserializeWrongValue() throws IOException {
+ ByteString encoded = ByteString.decodeBase64("////");
+ server.enqueue(new MockResponse().setBody(new Buffer().write(encoded)));
+
+ Call<?> call = service.get();
try {
- converter.fromBody(protoResponse("////"), Person.class);
+ call.execute();
fail();
- } catch (IOException ignored) {
+ } catch (EOFException ignored) {
}
}
-
- private static ResponseBody protoResponse(String encodedProto) {
- return ResponseBody.create(MediaType.parse("application/x-protobuf"),
- ByteString.decodeBase64(encodedProto).toByteArray());
- }
-
- private static AbstractCharSequenceAssert<?, String> assertBody(RequestBody body) throws IOException {
- Buffer buffer = new Buffer();
- body.writeTo(buffer);
- return assertThat(buffer.readByteString().base64());
- }
}
| train | train | 2015-06-17T20:02:36 | "2015-06-16T16:06:15Z" | JakeWharton | val |
square/retrofit/959_961 | square/retrofit | square/retrofit/959 | square/retrofit/961 | [
"timestamp(timedelta=0.0, similarity=0.8557995426325004)"
] | e4d416db7c3a039adb341419144cfa6d26a7d010 | d596cdaca65c16596400a011cbbfed5aa00f07fe | [
"That's completely broken. a `Call<List<? extends Repo>>` is definitely not the same thing as a `Call<List<Repo>>`. The former `List` cannot receive a call to `add()` of anything but null; the latter can.\n\nIs there a Kotlin bug for this?\n",
"I've found this: https://youtrack.jetbrains.com/issue/KT-5792\n\nIt suggest to change `List` to `MutableList`. Retrofit will complain with this error:\n\n> Exception in thread \"main\" java.lang.IllegalArgumentException: Method response type is java.util.List<retrofit.example.Repo> but no converter factory registered. Either add a converter factory to the Retrofit instance or use ResponseBody.\n",
"I guess this is unrelated and the new Retrofit API requires me to explicitely define a `Converter`.\n",
"Yup.\n",
"Right. We no longer use any converter as a default. You can add a dependency to `converter-gson` and just do `.converterFactory(GsonConverterFactory.create())` when you create the Retrofit instance.\n\nAs to the Kotlin stuff, I guess this will just serve as a recommended practice.\n",
"Already got it, thanks! I use `compile \"com.squareup.retrofit:converter-moshi:2.0.0-SNAPSHOT\"` and `.converterFactory(MoshiConverterFactory.create())`.\n\nAnother error is\n\n> Exception in thread \"main\" java.lang.IllegalArgumentException: Multiple Retrofit annotations found, only one allowed. (parameter #1) for method GitHubService.listRepos\n\nfor this interface\n\n``` kotlin\ninterface GitHubService {\n @GET(\"/users/{user}/repos?per_page=1\")\n fun listRepos(@Path(\"user\") user: String,\n @Query(\"page\") page: Int): Call<MutableList<Repo>>\n}\n```\n\nSorry for posting this unrelated error. But I don't understand the error message, found no solution in the changeset that introduced this error check and it even complains with only a single Retrofit annotation.\n",
"It somehow sees two annotations on a single parameter. I'll have to try it tomorrow unless you can run `javap -c` on the class file and post it.\n",
"`javap -c GitHubService.class`:\n\n```\nCompiled from \"retrobug.kt\"\npublic interface retrobug.GitHubService {\n public static final kotlin.reflect.KClass $kotlinClass;\n\n static {};\n Code:\n 0: ldc #2 // class retrobug/GitHubService\n 2: invokestatic #38 // Method kotlin/jvm/internal/Reflection.createKotlinClass:(Ljava/lang/Class;)Lkotlin/reflect/KClass;\n 5: putstatic #40 // Field $kotlinClass:Lkotlin/reflect/KClass;\n 8: return\n\n public abstract retrofit.Call<java.util.List<retrobug.Repo>> listRepos(java.lang.String, int);\n}\n```\n\n`javap -c GitHubService$$TImpl.class`:\n\n```\nCompiled from \"retrobug.kt\"\npublic final class retrobug.GitHubService$$TImpl {\n}\n```\n",
"It definately worked with the same interface in Kotlin (minus the usage of `Call`) and Retrofit 1.9.0.\n",
"I adapted the `SimpleService` sample [1] to Kotlin and set a breakpoint to a line in `RequestFactoryParser#parseParameters()` [2].\n\n![retrofit-bug-01](https://cloud.githubusercontent.com/assets/496255/8691233/1768e636-2ac0-11e5-8a94-bcea656eb543.png)\n\nSeems that the `IllegalArgumentException` is due to the additional Kotlin annotation `\n@JetValueParameter`.\n\n[1] https://github.com/square/retrofit/blob/904bf94b7c/samples/src/main/java/com/example/retrofit/SimpleService.java#L25\n[2] https://github.com/square/retrofit/blob/bf02efdf30/retrofit/src/main/java/retrofit/RequestFactoryParser.java#L208\n\n---\n\n``` kotlin\nimport retrofit.Call\nimport retrofit.MoshiConverterFactory\nimport retrofit.Retrofit\nimport retrofit.http.GET\nimport retrofit.http.Path\n\ndata class Contributor(val login: String,\n val contributions: Int)\n\ninterface GitHubService {\n @GET(\"/repos/{owner}/{repo}/contributors\")\n fun contributors(@Path(\"owner\") owner: String,\n @Path(\"repo\") repo: String): Call<MutableList<Contributor>>\n}\n\nfun main(args: Array<String>) {\n val retrofit = Retrofit.Builder()\n .baseUrl(\"https://api.github.com\")\n .converterFactory(MoshiConverterFactory.create())\n .build()\n\n val service = retrofit.create(javaClass<GitHubService>())\n\n val response = service.contributors(\"square\", \"retrofit\").execute()\n response.body().forEach { println(it) }\n}\n```\n",
"Looks like a simple bug. We should be ignoring annotations we don't recognize.\n",
"Updated to the newest snapshot. Everything works fine. Thanks a lot, great work!\n\nSmall note: I got an error that \"service methods cannot return void\". Obviously the approach with `Callback` as method argument is superseded by `Call` that also allows `Callback` using `enqueue()`. This seems to be a great API change in order to improve testability.\n"
] | [] | "2015-07-15T05:32:17Z" | [] | Additional parameter annotations not ignored. | Hey, I'm using Retrofit 2.0.0-SNAPSHOT.
My REST service interface is written in Kotlin and Kotlin seems to always add an extends-wildcard to generics.
Retrofit complains with
> Exception in thread "main" java.lang.IllegalArgumentException: Method return type must not include a type variable or wildcard: retrofit.Call<java.util.List<? extends retrofit.Repo>>
My Kotlin code is
``` kotlin
interface GitHubService {
@GET("/users/{user}/repos?per_page=1")
fun listRepos(@Path("user") user: String,
@Query("page") page: Int): Call<List<Repo>>
@GET("/users/{user}/repos?per_page=1")
fun listRepos(@Path("user") user: String,
@Query("page") page: Int,
callback: Callback<List<Repo>>)
}
```
I wonder whether the check for the wildcards is necessary.
| [
"retrofit/src/main/java/retrofit/RequestFactory.java",
"retrofit/src/main/java/retrofit/RequestFactoryParser.java"
] | [
"retrofit/src/main/java/retrofit/RequestFactory.java",
"retrofit/src/main/java/retrofit/RequestFactoryParser.java"
] | [
"retrofit/src/test/java/retrofit/RequestBuilderTest.java"
] | diff --git a/retrofit/src/main/java/retrofit/RequestFactory.java b/retrofit/src/main/java/retrofit/RequestFactory.java
index 99f0891e80..63527aabeb 100644
--- a/retrofit/src/main/java/retrofit/RequestFactory.java
+++ b/retrofit/src/main/java/retrofit/RequestFactory.java
@@ -51,6 +51,13 @@ Request create(Object... args) {
if (args != null) {
RequestBuilderAction[] actions = requestBuilderActions;
+ if (actions.length != args.length) {
+ throw new IllegalArgumentException("Argument count ("
+ + args.length
+ + ") doesn't match action count ("
+ + actions.length
+ + ")");
+ }
for (int i = 0, count = args.length; i < count; i++) {
actions[i].perform(requestBuilder, args[i]);
}
diff --git a/retrofit/src/main/java/retrofit/RequestFactoryParser.java b/retrofit/src/main/java/retrofit/RequestFactoryParser.java
index bdac016cd8..79337ee2c2 100644
--- a/retrofit/src/main/java/retrofit/RequestFactoryParser.java
+++ b/retrofit/src/main/java/retrofit/RequestFactoryParser.java
@@ -48,7 +48,6 @@
import static retrofit.Utils.methodError;
-/** Request metadata about a service interface declaration. */
final class RequestFactoryParser {
// Upper and lower characters, digits, underscores, and hyphens, starting with a character.
private static final String PARAM = "[a-zA-Z][a-zA-Z0-9_-]*";
@@ -205,10 +204,7 @@ private void parseParameters(Converter.Factory converterFactory) {
Annotation[] methodParameterAnnotations = methodParameterAnnotationArrays[i];
if (methodParameterAnnotations != null) {
for (Annotation methodParameterAnnotation : methodParameterAnnotations) {
- if (requestBuilderActions[i] != null) {
- throw parameterError(i, "Multiple Retrofit annotations found, only one allowed.");
- }
-
+ RequestBuilderAction action = null;
if (methodParameterAnnotation instanceof Url) {
if (gotUrl) {
throw parameterError(i, "Multiple @Url method annotations found.");
@@ -226,7 +222,7 @@ private void parseParameters(Converter.Factory converterFactory) {
throw parameterError(i, "@Url cannot be used with @%s URL", httpMethod);
}
gotUrl = true;
- requestBuilderActions[i] = new RequestBuilderAction.Url();
+ action = new RequestBuilderAction.Url();
} else if (methodParameterAnnotation instanceof Path) {
if (gotQuery) {
@@ -244,12 +240,11 @@ private void parseParameters(Converter.Factory converterFactory) {
Path path = (Path) methodParameterAnnotation;
String name = path.value();
validatePathName(i, name);
- requestBuilderActions[i] = new RequestBuilderAction.Path(name, path.encoded());
+ action = new RequestBuilderAction.Path(name, path.encoded());
} else if (methodParameterAnnotation instanceof Query) {
Query query = (Query) methodParameterAnnotation;
- requestBuilderActions[i] =
- new RequestBuilderAction.Query(query.value(), query.encoded());
+ action = new RequestBuilderAction.Query(query.value(), query.encoded());
gotQuery = true;
} else if (methodParameterAnnotation instanceof QueryMap) {
@@ -257,19 +252,18 @@ private void parseParameters(Converter.Factory converterFactory) {
throw parameterError(i, "@QueryMap parameter type must be Map.");
}
QueryMap queryMap = (QueryMap) methodParameterAnnotation;
- requestBuilderActions[i] = new RequestBuilderAction.QueryMap(queryMap.encoded());
+ action = new RequestBuilderAction.QueryMap(queryMap.encoded());
} else if (methodParameterAnnotation instanceof Header) {
Header header = (Header) methodParameterAnnotation;
- requestBuilderActions[i] = new RequestBuilderAction.Header(header.value());
+ action = new RequestBuilderAction.Header(header.value());
} else if (methodParameterAnnotation instanceof Field) {
if (!isFormEncoded) {
throw parameterError(i, "@Field parameters can only be used with form encoding.");
}
Field field = (Field) methodParameterAnnotation;
- requestBuilderActions[i] =
- new RequestBuilderAction.Field(field.value(), field.encoded());
+ action = new RequestBuilderAction.Field(field.value(), field.encoded());
gotField = true;
} else if (methodParameterAnnotation instanceof FieldMap) {
@@ -280,7 +274,7 @@ private void parseParameters(Converter.Factory converterFactory) {
throw parameterError(i, "@FieldMap parameter type must be Map.");
}
FieldMap fieldMap = (FieldMap) methodParameterAnnotation;
- requestBuilderActions[i] = new RequestBuilderAction.FieldMap(fieldMap.encoded());
+ action = new RequestBuilderAction.FieldMap(fieldMap.encoded());
gotField = true;
} else if (methodParameterAnnotation instanceof Part) {
@@ -303,7 +297,7 @@ private void parseParameters(Converter.Factory converterFactory) {
}
converter = converterFactory.get(methodParameterType);
}
- requestBuilderActions[i] = new RequestBuilderAction.Part<>(headers, converter);
+ action = new RequestBuilderAction.Part<>(headers, converter);
gotPart = true;
} else if (methodParameterAnnotation instanceof PartMap) {
@@ -315,8 +309,7 @@ private void parseParameters(Converter.Factory converterFactory) {
throw parameterError(i, "@PartMap parameter type must be Map.");
}
PartMap partMap = (PartMap) methodParameterAnnotation;
- requestBuilderActions[i] =
- new RequestBuilderAction.PartMap(converterFactory, partMap.encoding());
+ action = new RequestBuilderAction.PartMap(converterFactory, partMap.encoding());
gotPart = true;
} else if (methodParameterAnnotation instanceof Body) {
@@ -341,9 +334,16 @@ private void parseParameters(Converter.Factory converterFactory) {
converter = converterFactory.get(methodParameterType);
}
- requestBuilderActions[i] = new RequestBuilderAction.Body<>(converter);
+ action = new RequestBuilderAction.Body<>(converter);
gotBody = true;
}
+
+ if (action != null) {
+ if (requestBuilderActions[i] != null) {
+ throw parameterError(i, "Multiple Retrofit annotations found, only one allowed.");
+ }
+ requestBuilderActions[i] = action;
+ }
}
}
| diff --git a/retrofit/src/test/java/retrofit/RequestBuilderTest.java b/retrofit/src/test/java/retrofit/RequestBuilderTest.java
index d097628f6c..6fc52cb7d7 100644
--- a/retrofit/src/test/java/retrofit/RequestBuilderTest.java
+++ b/retrofit/src/test/java/retrofit/RequestBuilderTest.java
@@ -162,6 +162,19 @@ Call<Object> method(@Body @Query("nope") Object o) {
}
}
+ @interface NonNull {}
+
+ @Test public void multipleParameterAnnotationsOnlyOneRetrofitAllowed() throws Exception {
+ class Example {
+ @GET("/") //
+ Call<Object> method(@Query("maybe") @NonNull Object o) {
+ return null;
+ }
+ }
+ Request request = buildRequest(Example.class, "yep");
+ assertThat(request.urlString()).isEqualTo("http://example.com/?maybe=yep");
+ }
+
@Test public void twoMethodsFail() {
class Example {
@PATCH("/foo") //
| train | train | 2015-07-15T04:35:13 | "2015-07-15T00:44:06Z" | hastebrot | val |
square/retrofit/969_979 | square/retrofit | square/retrofit/969 | square/retrofit/979 | [
"timestamp(timedelta=0.0, similarity=0.9052924631525661)"
] | b4001c6892003af1968918aca5733fe32c7f543a | 3ee50a75ef41c5f800e58f8306125779e0acd076 | [
"We are aware and it may be added. It's experimental nature adds a level of\nvolatility that if we choose to add it as the API may change in a\nbackwards-incompatible way.\n\nOn Tue, Jul 21, 2015, 3:12 AM Sergii Pechenizkyi [email protected]\nwrote:\n\n> With rx.Single released as experimented type of Observable do you see the\n> value in supporting it as a return type for network requests?\n> https://github.com/ReactiveX/RxJava/blob/1.x/CHANGES.md#rxsingle\n> ReactiveX/RxJava#1594 (comment)\n> https://github.com/ReactiveX/RxJava/issues/1594#issuecomment-101300655\n> \n> Quote from there:\n> \n> A Single will always behave in one of 3 ways:\n> \n> 1) respond with an error\n> 2) never respond\n> 3) respond with a success\n> \n> An Observable on the other hand may:\n> \n> 1) response with an error\n> 2) never respond\n> 3) respond successfully with no data and terminate\n> 4) respond successfully with a single value and terminate\n> 5) respond successfully with multiple values and terminate\n> 7) respond successfully with one or more values and never terminate (waiting for more data)\n> \n> —\n> Reply to this email directly or view it on GitHub\n> https://github.com/square/retrofit/issues/969.\n",
"+1 for `Single` :)\n"
] | [] | "2015-07-24T21:52:28Z" | [] | Support rx.Single from RxJava? | With `rx.Single` released as experimented type of `Observable` do you see the value in supporting it as a return type for network requests?
https://github.com/ReactiveX/RxJava/blob/1.x/CHANGES.md#rxsingle
https://github.com/ReactiveX/RxJava/issues/1594#issuecomment-101300655
Quote from there:
```
A Single will always behave in one of 3 ways:
1) respond with an error
2) never respond
3) respond with a success
An Observable on the other hand may:
1) response with an error
2) never respond
3) respond successfully with no data and terminate
4) respond successfully with a single value and terminate
5) respond successfully with multiple values and terminate
7) respond successfully with one or more values and never terminate (waiting for more data)
```
| [
"pom.xml",
"retrofit-adapters/rxjava/src/main/java/retrofit/ObservableCallAdapterFactory.java"
] | [
"pom.xml",
"retrofit-adapters/rxjava/src/main/java/retrofit/ObservableCallAdapterFactory.java"
] | [
"retrofit-adapters/rxjava/src/test/java/retrofit/ObservableCallAdapterFactoryTest.java"
] | diff --git a/pom.xml b/pom.xml
index 51f8203296..439fd2ff6f 100644
--- a/pom.xml
+++ b/pom.xml
@@ -53,7 +53,7 @@
<okhttp.version>2.5.0-SNAPSHOT</okhttp.version>
<!-- Adapter Dependencies -->
- <rxjava.version>1.0.10</rxjava.version>
+ <rxjava.version>1.0.13</rxjava.version>
<!-- Converter Dependencies -->
<gson.version>2.3.1</gson.version>
diff --git a/retrofit-adapters/rxjava/src/main/java/retrofit/ObservableCallAdapterFactory.java b/retrofit-adapters/rxjava/src/main/java/retrofit/ObservableCallAdapterFactory.java
index 65f6da878f..a621805879 100644
--- a/retrofit-adapters/rxjava/src/main/java/retrofit/ObservableCallAdapterFactory.java
+++ b/retrofit-adapters/rxjava/src/main/java/retrofit/ObservableCallAdapterFactory.java
@@ -18,12 +18,13 @@
import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
-import rx.Observable;
-import rx.Subscriber;
+import rx.Single;
+import rx.SingleSubscriber;
import rx.functions.Action0;
import rx.functions.Func1;
import rx.subscriptions.Subscriptions;
+
/**
* TODO docs
*/
@@ -43,7 +44,7 @@ private ObservableCallAdapterFactory() {
}
@Override public CallAdapter<?> get(Type returnType) {
- if (Utils.getRawType(returnType) != Observable.class) {
+ if (Utils.getRawType(returnType) != Single.class) {
return null;
}
if (!(returnType instanceof ParameterizedType)) {
@@ -75,14 +76,14 @@ private ObservableCallAdapterFactory() {
return new SimpleCallAdapter(observableType);
}
- static final class CallOnSubscribe<T> implements Observable.OnSubscribe<Response<T>> {
+ static final class CallOnSubscribe<T> implements Single.OnSubscribe<Response<T>> {
private final Call<T> originalCall;
private CallOnSubscribe(Call<T> originalCall) {
this.originalCall = originalCall;
}
- @Override public void call(final Subscriber<? super Response<T>> subscriber) {
+ @Override public void call(final SingleSubscriber<? super Response<T>> subscriber) {
// Since Call is a one-shot type, clone it for each new subscriber.
final Call<T> call = originalCall.clone();
@@ -99,12 +100,10 @@ private CallOnSubscribe(Call<T> originalCall) {
return;
}
try {
- subscriber.onNext(response);
+ subscriber.onSuccess(response);
} catch (Throwable t) {
subscriber.onError(t);
- return;
}
- subscriber.onCompleted();
}
@Override public void onFailure(Throwable t) {
@@ -128,8 +127,8 @@ static final class ResponseCallAdapter<T> implements CallAdapter<T> {
return responseType;
}
- @Override public Observable<Response<T>> adapt(Call<T> call) {
- return Observable.create(new CallOnSubscribe<>(call));
+ @Override public Single<Response<T>> adapt(Call<T> call) {
+ return Single.create(new CallOnSubscribe<>(call));
}
}
@@ -144,14 +143,14 @@ static final class SimpleCallAdapter<T> implements CallAdapter<T> {
return responseType;
}
- @Override public Observable<T> adapt(Call<T> call) {
- return Observable.create(new CallOnSubscribe<>(call)) //
- .flatMap(new Func1<Response<T>, Observable<T>>() {
- @Override public Observable<T> call(Response<T> response) {
+ @Override public Single<T> adapt(Call<T> call) {
+ return Single.create(new CallOnSubscribe<>(call)) //
+ .flatMap(new Func1<Response<T>, Single<T>>() {
+ @Override public Single<T> call(Response<T> response) {
if (response.isSuccess()) {
- return Observable.just(response.body());
+ return Single.just(response.body());
}
- return Observable.error(new IOException()); // TODO non-suck message.
+ return Single.error(new IOException()); // TODO non-suck message.
}
});
}
@@ -168,8 +167,8 @@ static final class ResultCallAdapter<T> implements CallAdapter<T> {
return responseType;
}
- @Override public Observable<Result<T>> adapt(Call<T> call) {
- return Observable.create(new CallOnSubscribe<>(call)) //
+ @Override public Single<Result<T>> adapt(Call<T> call) {
+ return Single.create(new CallOnSubscribe<>(call)) //
.map(new Func1<Response<T>, Result<T>>() {
@Override public Result<T> call(Response<T> response) {
return Result.fromResponse(response);
| diff --git a/retrofit-adapters/rxjava/src/test/java/retrofit/ObservableCallAdapterFactoryTest.java b/retrofit-adapters/rxjava/src/test/java/retrofit/ObservableCallAdapterFactoryTest.java
index 87eedb1192..03b78b708f 100644
--- a/retrofit-adapters/rxjava/src/test/java/retrofit/ObservableCallAdapterFactoryTest.java
+++ b/retrofit-adapters/rxjava/src/test/java/retrofit/ObservableCallAdapterFactoryTest.java
@@ -28,7 +28,7 @@
import org.junit.Rule;
import org.junit.Test;
import retrofit.http.GET;
-import rx.Observable;
+import rx.Single;
import rx.observables.BlockingObservable;
import static com.squareup.okhttp.mockwebserver.SocketPolicy.DISCONNECT_AFTER_REQUEST;
@@ -39,9 +39,9 @@ public final class ObservableCallAdapterFactoryTest {
@Rule public final MockWebServer server = new MockWebServer();
interface Service {
- @GET("/") Observable<String> body();
- @GET("/") Observable<Response<String>> response();
- @GET("/") Observable<Result<String>> result();
+ @GET("/") Single<String> body();
+ @GET("/") Single<Response<String>> response();
+ @GET("/") Single<Result<String>> result();
}
private Service service;
@@ -58,14 +58,14 @@ interface Service {
@Test public void bodySuccess200() {
server.enqueue(new MockResponse().setBody("Hi"));
- BlockingObservable<String> o = service.body().toBlocking();
+ BlockingObservable<String> o = service.body().toObservable().toBlocking();
assertThat(o.first()).isEqualTo("Hi");
}
@Test public void bodySuccess404() {
server.enqueue(new MockResponse().setResponseCode(404));
- BlockingObservable<String> o = service.body().toBlocking();
+ BlockingObservable<String> o = service.body().toObservable().toBlocking();
try {
o.first();
fail();
@@ -77,7 +77,7 @@ interface Service {
@Test public void bodyFailure() {
server.enqueue(new MockResponse().setSocketPolicy(DISCONNECT_AFTER_REQUEST));
- BlockingObservable<String> o = service.body().toBlocking();
+ BlockingObservable<String> o = service.body().toObservable().toBlocking();
try {
o.first();
fail();
@@ -89,7 +89,7 @@ interface Service {
@Test public void responseSuccess200() {
server.enqueue(new MockResponse().setBody("Hi"));
- BlockingObservable<Response<String>> o = service.response().toBlocking();
+ BlockingObservable<Response<String>> o = service.response().toObservable().toBlocking();
Response<String> response = o.first();
assertThat(response.isSuccess()).isTrue();
assertThat(response.body()).isEqualTo("Hi");
@@ -98,7 +98,7 @@ interface Service {
@Test public void responseSuccess404() throws IOException {
server.enqueue(new MockResponse().setResponseCode(404).setBody("Hi"));
- BlockingObservable<Response<String>> o = service.response().toBlocking();
+ BlockingObservable<Response<String>> o = service.response().toObservable().toBlocking();
Response<String> response = o.first();
assertThat(response.isSuccess()).isFalse();
assertThat(response.errorBody().string()).isEqualTo("Hi");
@@ -107,7 +107,7 @@ interface Service {
@Test public void responseFailure() {
server.enqueue(new MockResponse().setSocketPolicy(DISCONNECT_AFTER_REQUEST));
- BlockingObservable<Response<String>> o = service.response().toBlocking();
+ BlockingObservable<Response<String>> o = service.response().toObservable().toBlocking();
try {
o.first();
fail();
@@ -119,7 +119,7 @@ interface Service {
@Test public void resultSuccess200() {
server.enqueue(new MockResponse().setBody("Hi"));
- BlockingObservable<Result<String>> o = service.result().toBlocking();
+ BlockingObservable<Result<String>> o = service.result().toObservable().toBlocking();
Result<String> result = o.first();
assertThat(result.isError()).isFalse();
Response<String> response = result.response();
@@ -130,7 +130,7 @@ interface Service {
@Test public void resultSuccess404() throws IOException {
server.enqueue(new MockResponse().setResponseCode(404).setBody("Hi"));
- BlockingObservable<Result<String>> o = service.result().toBlocking();
+ BlockingObservable<Result<String>> o = service.result().toObservable().toBlocking();
Result<String> result = o.first();
assertThat(result.isError()).isFalse();
Response<String> response = result.response();
@@ -141,7 +141,7 @@ interface Service {
@Test public void resultFailure() {
server.enqueue(new MockResponse().setSocketPolicy(DISCONNECT_AFTER_REQUEST));
- BlockingObservable<Result<String>> o = service.result().toBlocking();
+ BlockingObservable<Result<String>> o = service.result().toObservable().toBlocking();
Result<String> result = o.first();
assertThat(result.isError()).isTrue();
assertThat(result.error()).isInstanceOf(IOException.class);
@@ -149,16 +149,16 @@ interface Service {
@Test public void responseType() {
CallAdapter.Factory factory = ObservableCallAdapterFactory.create();
- Type classType = new TypeToken<Observable<String>>() {}.getType();
+ Type classType = new TypeToken<Single<String>>() {}.getType();
assertThat(factory.get(classType).responseType()).isEqualTo(String.class);
- Type wilcardType = new TypeToken<Observable<? extends String>>() {}.getType();
+ Type wilcardType = new TypeToken<Single<? extends String>>() {}.getType();
assertThat(factory.get(wilcardType).responseType()).isEqualTo(String.class);
- Type genericType = new TypeToken<Observable<List<String>>>() {}.getType();
+ Type genericType = new TypeToken<Single<List<String>>>() {}.getType();
assertThat(factory.get(genericType).responseType()) //
.isEqualTo(new TypeToken<List<String>>() {}.getType());
- Type responseType = new TypeToken<Observable<Response<String>>>() {}.getType();
+ Type responseType = new TypeToken<Single<Response<String>>>() {}.getType();
assertThat(factory.get(responseType).responseType()).isEqualTo(String.class);
- Type resultType = new TypeToken<Observable<Response<String>>>() {}.getType();
+ Type resultType = new TypeToken<Single<Response<String>>>() {}.getType();
assertThat(factory.get(resultType).responseType()).isEqualTo(String.class);
}
@@ -169,7 +169,7 @@ interface Service {
}
@Test public void rawTypeThrows() {
- Type type = new TypeToken<Observable>() {}.getType();
+ Type type = new TypeToken<Single>() {}.getType();
CallAdapter.Factory factory = ObservableCallAdapterFactory.create();
try {
factory.get(type);
@@ -180,7 +180,7 @@ interface Service {
}
@Test public void rawResponseTypeThrows() {
- Type type = new TypeToken<Observable<Response>>() {}.getType();
+ Type type = new TypeToken<Single<Response>>() {}.getType();
CallAdapter.Factory factory = ObservableCallAdapterFactory.create();
try {
factory.get(type);
@@ -191,7 +191,7 @@ interface Service {
}
@Test public void rawResultTypeThrows() {
- Type type = new TypeToken<Observable<Result>>() {}.getType();
+ Type type = new TypeToken<Single<Result>>() {}.getType();
CallAdapter.Factory factory = ObservableCallAdapterFactory.create();
try {
factory.get(type);
| test | train | 2015-07-24T21:41:03 | "2015-07-21T07:12:08Z" | plastiv | val |
square/retrofit/762_988 | square/retrofit | square/retrofit/762 | square/retrofit/988 | [
"timestamp(timedelta=33.0, similarity=0.8772209524745627)"
] | 27a09992e1a0a13f6102abf0d56c058e34f866e0 | 05a562c960a2992772322b7c0e42878592406bb2 | [
"Go for it.\n",
"I will try to find some time to work on this over weekend. Keep you updated\n",
"Found [that](https://gist.github.com/aurae/8427b93b27483763d9cb) at https://github.com/bluelinelabs/LoganSquare/issues/5 \n\nLooks good so far and works for me\n",
"I already saw this @sockeqwe , but the thing is that it works for the current version of retrofit, but it won't work for next version, as some base in the converters has changed\n",
"Hi guys, sorry for delaying in the response. I am really busy lately and I don't know when I will be ready to develop this feature, so if anyone is interested in working on this, do it. In case this is not something urgent and nobody is interested on developing this converter, I will do it when I find some time. Thanks\n",
"It's not urgent. Next significant version won't ship for at least two\nmonths.\n\nOn Mon, Apr 6, 2015 at 2:20 PM Jonathan Fragoso Pérez <\[email protected]> wrote:\n\n> Hi guys, sorry for delaying in the response. I am really busy lately and I\n> don't know when I will be ready to develop this feature, so if anyone is\n> interested in working on this, do it. In case this is not something urgent\n> and nobody is interested on developing this converter, I will do it when I\n> find some time. Thanks\n> \n> —\n> Reply to this email directly or view it on GitHub\n> https://github.com/square/retrofit/issues/762#issuecomment-90183333.\n",
"Alright, in this case I will try to find some time to work on this during next week. Thanks @JakeWharton \n",
"Proposed in Pull Request #988 \n",
"We aren't going to be adding any more JSON converters. Copying a response I put on another PR for explanation:\n\nRetrofit already offers 3 first-party JSON converters. Gson and Jackson are the two leading serializers for which we offer converters, and we include Moshi just because it's a Square library. Similarly, we have two first-party protocol buffer converters, one using the official library and one with Wire because it's a Square library. We have a single XML converter because... well no one really knows.\n\nThere are many more eclectic and specialized JSON converters just as there are for other serialization formats. Maintaining a bunch of these is burdensome as we have to track the APIs and changes in 6 external libraries which have nothing to do with Retrofit's core. I can think of at least 5 other JSON libraries that have popped up recently almost always just being built on top of Jackson or Gson.\n\nRetrofit was modified (by me, actually) to be agnostic to converters well before it hit 1.0 a few years ago. The point was that as libraries and formats change in popularity, no changes in Retrofit would be needed to support them. This is very much the case with the forthcoming version 2.0 as well.\n\nAs such, we won't be adding any more first-party converters unless a compelling reason can be made as to why we should. Since we already have 3 JSON converters, there is little argument to be made for more.\n\nHowever, there's no reason that these cannot be turned into third-party libraries that exist on their own. I have [made a wiki page](https://github.com/square/retrofit/wiki/Converters) for listing third-party converters so that they are able to be discovered in one place.\n\nThanks for taking the time to implement this, despite that fact that we aren't able to accept it into the main repo.\n",
"@jfragosoperez @sockeqwe Version 1.0.0 of the LoganSquare converter has been released [and added to the wiki](https://github.com/square/retrofit/wiki/Converters)! Further maintenance will happen in its dedicated repository from now on.\n",
"Awesome! Thanks!\n",
"Awesome. Thanks @aurae for your contribution\n"
] | [
"Remove this whole comment. This class isn't public.\n",
"Indent with two spaces\n",
"Delete comment\n",
"Delete comment\n",
"Delete comment\n",
"change \"as its conversion backbone\" to \"for JSON\" to match others.\n",
"Remove author tag\n",
"Add private constructor and static `create()` method which calls it\n",
"This needs to check if the `type` is not a `Class` and throw an exception with a meaningful message. The implicit `ClassCastException` that's thrown here is unsatisfactory.\n\nAlso, does this mean I can't use LoganSquare on a `List` of objects? That's really strange...\n",
"Delete whole comment\n",
"Add `final`\n",
"Needs a test verifying that using a type of `List<Foo>` throws an appropriate error message.\n",
"(that applies to all these files)\n",
"The second paragraph of other converters focuses on details you need to know for configuring. Since this library has no runtime configuration, you end up describing implementation details of the converter here.\n\nMaybe change it to \"The `JsonMapper` instances generated by the compiler are used for conversion.\"\n",
"You absolutely can use it on Lists (and String-keyed Maps, for that matter). I'm not sure what I was thinking here. I will update the PR with List and Map support asap.\n"
] | "2015-07-31T13:45:51Z" | [] | Add first-party LoganSquare converter. | I had in mind to build a LoganSquare converter, but checking if you had already done it, I have seen that you are working on changes for next release, talking about the converters part. I was wondering if you have already a fixed date for the update or you have to deal with many other milestones before releasing. I wait for your feedback. Thanks a lot
| [] | [
"retrofit-converters/logansquare/README.md",
"retrofit-converters/logansquare/pom.xml",
"retrofit-converters/logansquare/src/main/java/retrofit/LoganSquareConverterFactory.java",
"retrofit-converters/logansquare/src/main/java/retrofit/LoganSquareConverterUtils.java",
"retrofit-converters/logansquare/src/main/java/retrofit/LoganSquareListConverter.java",
"retrofit-converters/logansquare/src/main/java/retrofit/LoganSquareMapConverter.java",
"retrofit-converters/logansquare/src/main/java/retrofit/LoganSquareObjectConverter.java"
] | [
"retrofit-converters/logansquare/src/test/java/retrofit/LoganSquareConverterTest.java"
] | diff --git a/retrofit-converters/logansquare/README.md b/retrofit-converters/logansquare/README.md
new file mode 100644
index 0000000000..be97bde11b
--- /dev/null
+++ b/retrofit-converters/logansquare/README.md
@@ -0,0 +1,8 @@
+LoganSquare Converter
+=================
+
+A `Converter` which uses [LoganSquare][1] for serialization to and from JSON.
+
+The `JsonMapper` instances generated by the compiler are used for conversion.
+
+ [1]: https://github.com/bluelinelabs/LoganSquare
diff --git a/retrofit-converters/logansquare/pom.xml b/retrofit-converters/logansquare/pom.xml
new file mode 100644
index 0000000000..04c9b6185d
--- /dev/null
+++ b/retrofit-converters/logansquare/pom.xml
@@ -0,0 +1,45 @@
+<?xml version="1.0" encoding="UTF-8"?>
+
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+
+ <parent>
+ <groupId>com.squareup.retrofit</groupId>
+ <artifactId>retrofit-converters</artifactId>
+ <version>2.0.0-SNAPSHOT</version>
+ <relativePath>../pom.xml</relativePath>
+ </parent>
+
+ <artifactId>converter-logansquare</artifactId>
+ <name>Converter: LoganSquare</name>
+
+ <dependencies>
+ <dependency>
+ <groupId>com.squareup.retrofit</groupId>
+ <artifactId>retrofit</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+
+ <dependency>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>com.squareup.okhttp</groupId>
+ <artifactId>mockwebserver</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.assertj</groupId>
+ <artifactId>assertj-core</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>com.bluelinelabs</groupId>
+ <artifactId>logansquare-compiler</artifactId>
+ <version>1.1.0</version>
+ <scope>test</scope>
+ </dependency>
+ </dependencies>
+</project>
diff --git a/retrofit-converters/logansquare/src/main/java/retrofit/LoganSquareConverterFactory.java b/retrofit-converters/logansquare/src/main/java/retrofit/LoganSquareConverterFactory.java
new file mode 100644
index 0000000000..84207cb208
--- /dev/null
+++ b/retrofit-converters/logansquare/src/main/java/retrofit/LoganSquareConverterFactory.java
@@ -0,0 +1,67 @@
+package retrofit;
+
+import com.bluelinelabs.logansquare.JsonMapper;
+import com.bluelinelabs.logansquare.LoganSquare;
+
+import java.lang.reflect.ParameterizedType;
+import java.lang.reflect.Type;
+import java.util.Map;
+
+
+/**
+ * A {@linkplain Converter.Factory converter} which uses LoganSquare for JSON.
+ *
+ * @see <a>https://github.com/bluelinelabs/LoganSquare</a>
+ */
+public final class LoganSquareConverterFactory implements Converter.Factory {
+ /**
+ * Create an instance. Encoding to JSON and decoding from JSON will use UTF-8.
+ */
+ public static LoganSquareConverterFactory create() {
+ return new LoganSquareConverterFactory();
+ }
+
+
+ private LoganSquareConverterFactory() {
+ }
+
+
+ private JsonMapper<?> mapperFor(Type type) {
+ return LoganSquare.mapperFor((Class<?>) type);
+ }
+
+
+ @Override public Converter<?> get(Type type) {
+ if (type instanceof Class) {
+ // Return a plain Object converter
+ return new LoganSquareObjectConverter<>(mapperFor(type));
+
+ } else if (type instanceof ParameterizedType) {
+ // Return a List or Map converter
+ ParameterizedType parameterizedType = (ParameterizedType) type;
+ Type[] typeArguments = parameterizedType.getActualTypeArguments();
+ Type firstType = typeArguments[0];
+
+ // Check for Map arguments
+ if (parameterizedType.getRawType() == Map.class) {
+ Type secondType = typeArguments[1];
+
+ // Perform validity checks on the type arguments, since LoganSquare works only on String keys
+ if (firstType != String.class) throw new RuntimeException("LoganSquareConverter can't convert Map keys of type '" + firstType + '\'');
+ if (!(secondType instanceof Class)) throw new RuntimeException("LoganSquareConverter can't convert Map values of type '" + secondType + '\'');
+
+ // Return a Map converter
+ return new LoganSquareMapConverter<>(mapperFor(secondType));
+
+ } else {
+ // Otherwise, access the ParametrizedType's only type argument and perform validity checks on it
+ if (!(firstType instanceof Class)) throw new RuntimeException("LoganSquareConverter can't convert List items of type '" + firstType + '\'');
+
+ // Return a List converter
+ return new LoganSquareListConverter<>(mapperFor(firstType));
+ }
+ }
+
+ throw new RuntimeException("LoganSquareConverter encountered non-convertable type '" + type + '\'');
+ }
+}
diff --git a/retrofit-converters/logansquare/src/main/java/retrofit/LoganSquareConverterUtils.java b/retrofit-converters/logansquare/src/main/java/retrofit/LoganSquareConverterUtils.java
new file mode 100644
index 0000000000..f57667be73
--- /dev/null
+++ b/retrofit-converters/logansquare/src/main/java/retrofit/LoganSquareConverterUtils.java
@@ -0,0 +1,8 @@
+package retrofit;
+
+import com.squareup.okhttp.MediaType;
+
+
+abstract class LoganSquareConverterUtils {
+ static final MediaType MEDIA_TYPE = MediaType.parse("application/json; charset=UTF-8");
+}
diff --git a/retrofit-converters/logansquare/src/main/java/retrofit/LoganSquareListConverter.java b/retrofit-converters/logansquare/src/main/java/retrofit/LoganSquareListConverter.java
new file mode 100644
index 0000000000..b02e95f33f
--- /dev/null
+++ b/retrofit-converters/logansquare/src/main/java/retrofit/LoganSquareListConverter.java
@@ -0,0 +1,38 @@
+package retrofit;
+
+import com.bluelinelabs.logansquare.JsonMapper;
+import com.squareup.okhttp.RequestBody;
+import com.squareup.okhttp.ResponseBody;
+
+import java.io.IOException;
+import java.util.List;
+
+import static retrofit.LoganSquareConverterUtils.MEDIA_TYPE;
+
+
+final class LoganSquareListConverter<T> implements Converter<List<T>> {
+
+
+ private final JsonMapper<T> mapper;
+
+
+ public LoganSquareListConverter(JsonMapper<T> mapper) {
+ this.mapper = mapper;
+ }
+
+
+ @Override public List<T> fromBody(ResponseBody body) throws IOException {
+ return mapper.parseList(body.byteStream());
+ }
+
+
+ @Override public RequestBody toBody(List<T> value) {
+ String serializedValue;
+ try {
+ serializedValue = mapper.serialize(value);
+ } catch (IOException ex) {
+ throw new AssertionError(ex);
+ }
+ return RequestBody.create(MEDIA_TYPE, serializedValue);
+ }
+}
diff --git a/retrofit-converters/logansquare/src/main/java/retrofit/LoganSquareMapConverter.java b/retrofit-converters/logansquare/src/main/java/retrofit/LoganSquareMapConverter.java
new file mode 100644
index 0000000000..d38eddab4e
--- /dev/null
+++ b/retrofit-converters/logansquare/src/main/java/retrofit/LoganSquareMapConverter.java
@@ -0,0 +1,38 @@
+package retrofit;
+
+import com.bluelinelabs.logansquare.JsonMapper;
+import com.squareup.okhttp.RequestBody;
+import com.squareup.okhttp.ResponseBody;
+
+import java.io.IOException;
+import java.util.Map;
+
+import static retrofit.LoganSquareConverterUtils.MEDIA_TYPE;
+
+
+final class LoganSquareMapConverter<T> implements Converter<Map<String, T>> {
+
+
+ private final JsonMapper<T> mapper;
+
+
+ public LoganSquareMapConverter(JsonMapper<T> mapper) {
+ this.mapper = mapper;
+ }
+
+
+ @Override public Map<String, T> fromBody(ResponseBody body) throws IOException {
+ return mapper.parseMap(body.byteStream());
+ }
+
+
+ @Override public RequestBody toBody(Map<String, T> value) {
+ String serializedValue;
+ try {
+ serializedValue = mapper.serialize(value);
+ } catch (IOException ex) {
+ throw new AssertionError(ex);
+ }
+ return RequestBody.create(MEDIA_TYPE, serializedValue);
+ }
+}
diff --git a/retrofit-converters/logansquare/src/main/java/retrofit/LoganSquareObjectConverter.java b/retrofit-converters/logansquare/src/main/java/retrofit/LoganSquareObjectConverter.java
new file mode 100644
index 0000000000..6d4f558355
--- /dev/null
+++ b/retrofit-converters/logansquare/src/main/java/retrofit/LoganSquareObjectConverter.java
@@ -0,0 +1,37 @@
+package retrofit;
+
+import com.bluelinelabs.logansquare.JsonMapper;
+import com.squareup.okhttp.RequestBody;
+import com.squareup.okhttp.ResponseBody;
+
+import java.io.IOException;
+
+import static retrofit.LoganSquareConverterUtils.MEDIA_TYPE;
+
+
+final class LoganSquareObjectConverter<T> implements Converter<T> {
+
+
+ private final JsonMapper<T> mapper;
+
+
+ public LoganSquareObjectConverter(JsonMapper<T> mapper) {
+ this.mapper = mapper;
+ }
+
+
+ @Override public T fromBody(ResponseBody body) throws IOException {
+ return mapper.parse(body.byteStream());
+ }
+
+
+ @Override public RequestBody toBody(T value) {
+ String serializedValue;
+ try {
+ serializedValue = mapper.serialize(value);
+ } catch (IOException ex) {
+ throw new AssertionError(ex);
+ }
+ return RequestBody.create(MEDIA_TYPE, serializedValue);
+ }
+}
| diff --git a/retrofit-converters/logansquare/src/test/java/retrofit/LoganSquareConverterTest.java b/retrofit-converters/logansquare/src/test/java/retrofit/LoganSquareConverterTest.java
new file mode 100644
index 0000000000..7a419672d0
--- /dev/null
+++ b/retrofit-converters/logansquare/src/test/java/retrofit/LoganSquareConverterTest.java
@@ -0,0 +1,286 @@
+package retrofit;
+
+import com.bluelinelabs.logansquare.annotation.JsonField;
+import com.bluelinelabs.logansquare.annotation.JsonObject;
+import com.bluelinelabs.logansquare.typeconverters.TypeConverter;
+import com.fasterxml.jackson.core.JsonGenerator;
+import com.fasterxml.jackson.core.JsonParser;
+import com.squareup.okhttp.mockwebserver.MockResponse;
+import com.squareup.okhttp.mockwebserver.MockWebServer;
+import com.squareup.okhttp.mockwebserver.RecordedRequest;
+
+import org.assertj.core.api.Assertions;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import retrofit.http.Body;
+import retrofit.http.POST;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+/**
+ * Tests for the {@linkplain LoganSquareObjectConverter}.
+ *
+ * @author marcel
+ */
+public class LoganSquareConverterTest {
+
+ @JsonObject
+ static class Implementation {
+
+ @JsonField
+ String name;
+
+ @JsonField(typeConverter = CustomTypeConverter.class)
+ CustomType customType;
+
+ @JsonField(name = "list")
+ List<String> values;
+
+ String notSerialized;
+
+ public Implementation() {
+
+ }
+
+ public Implementation(String name, String notSerialized, CustomType customType, List<String> values) {
+ this();
+ this.name = name;
+ this.notSerialized = notSerialized;
+ this.customType = customType;
+ this.values = values;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public String getNotSerialized() {
+ return notSerialized;
+ }
+
+ public CustomType getCustomType() {
+ return customType;
+ }
+
+ public List<String> getValues() {
+ return values;
+ }
+ }
+
+ enum CustomType {
+ VAL_1(1),
+ VAL_2(2);
+
+ private int val;
+
+ CustomType(int val) {
+ this.val = val;
+ }
+
+ static CustomType fromInt(int val) {
+ for (CustomType customType : values()) {
+ if (customType.val == val) return customType;
+ }
+ throw new AssertionError("custom type with value " + val + " not found.");
+ }
+ }
+
+ static class CustomTypeConverter implements TypeConverter<CustomType> {
+
+ @Override public CustomType parse(JsonParser jsonParser) throws IOException {
+ return CustomType.fromInt(jsonParser.getIntValue());
+ }
+
+ @Override public void serialize(CustomType object, String fieldName, boolean writeFieldNameForObject, JsonGenerator jsonGenerator) throws IOException {
+ jsonGenerator.writeFieldName(fieldName);
+ jsonGenerator.writeNumber(object.val);
+ }
+ }
+
+ interface Service {
+ @POST("/") Call<Implementation> callImplementation(@Body Implementation body);
+ @POST("/") Call<List<Implementation>> callList(@Body List<Implementation> body);
+ @POST("/") Call<Implementation> callListWrongType(@Body List<List<Implementation>> body);
+ @POST("/") Call<Map<String, Implementation>> callMap(@Body Map<String, Implementation> body);
+ @POST("/") Call<Map<Integer, Implementation>> callMapWrongKey(@Body Map<Integer, Implementation> body);
+ @POST("/") Call<Map<String, List<Implementation>>> callMapWrongValue(@Body Map<String, List<Implementation>> body);
+ @POST("/") Call<Implementation[]> callArray(@Body Implementation[] body);
+ }
+
+ @Rule public final MockWebServer mockWebServer = new MockWebServer();
+
+ private Service service;
+
+ @Before public void setUp() {
+ service = new Retrofit.Builder()
+ .baseUrl(mockWebServer.url("/"))
+ .converterFactory(LoganSquareConverterFactory.create())
+ .build()
+ .create(Service.class);
+ }
+
+ @Test public void testObject() throws IOException, InterruptedException {
+ // Enqueue a mock response
+ mockWebServer.enqueue(new MockResponse().setBody("{\"customType\":2,\"name\":\"LOGAN SQUARE IS COOL\",\"list\":[\"value1\",\"value2\"]}"));
+
+ // Setup the mock object
+ List<String> values = new ArrayList<>();
+ values.add("value1");
+ values.add("value2");
+ Implementation requestBody = new Implementation("LOGAN SQUARE IS COOL", "Not serialized", CustomType.VAL_2, values);
+
+ // Call the API and execute it
+ Call<Implementation> call = service.callImplementation(requestBody);
+ Response<Implementation> response = call.execute();
+ Implementation responseBody = response.body();
+
+ // Assert that conversions worked
+ // 1) Standard field declaration
+ assertThat(responseBody.getName()).isEqualTo("LOGAN SQUARE IS COOL");
+ // 2) Named field declaration & List serialization
+ assertThat(responseBody.getValues()).containsExactly("value1", "value2");
+ // 3) Custom Type adapter serialization
+ assertThat(responseBody.getCustomType()).isEqualTo(CustomType.VAL_2);
+ // 4) Excluded field
+ assertThat(responseBody.getNotSerialized()).isNull();
+
+ // Check request body and the received header
+ RecordedRequest request = mockWebServer.takeRequest();
+ assertThat(request.getBody().readUtf8()).isEqualTo("{\"customType\":2,\"name\":\"LOGAN SQUARE IS COOL\",\"list\":[\"value1\",\"value2\"]}");
+ assertThat(request.getHeader("Content-Type")).isEqualTo("application/json; charset=UTF-8");
+ }
+
+ @Test public void testList() throws IOException, InterruptedException {
+ // Enqueue a mock response
+ mockWebServer.enqueue(new MockResponse().setBody("[{\"customType\":2,\"name\":\"LOGAN SQUARE IS COOL\",\"list\":[\"value1\",\"value2\"]},{\"customType\":1,\"name\":\"LOGAN SQUARE IS COOL2\",\"list\":[\"value1\",\"value2\"]}]"));
+
+ // Setup the mock object
+ List<String> values = new ArrayList<>();
+ values.add("value1");
+ values.add("value2");
+ List<Implementation> requestBody = new ArrayList<>();
+ requestBody.add(new Implementation("LOGAN SQUARE IS COOL", "Not serialized", CustomType.VAL_2, values));
+ requestBody.add(new Implementation("LOGAN SQUARE IS COOL2", "Not serialized", CustomType.VAL_1, values));
+
+ // Call the API and execute it
+ Call<List<Implementation>> call = service.callList(requestBody);
+ Response<List<Implementation>> response = call.execute();
+ List<Implementation> responseBody = response.body();
+
+ // Assert that conversions worked
+ // Number of objects
+ assertThat(responseBody).hasSize(2);
+ // Member values of first object
+ Implementation o1 = responseBody.get(0);
+ assertThat(o1.getName()).isEqualTo("LOGAN SQUARE IS COOL");
+ assertThat(o1.getValues()).containsExactly("value1", "value2");
+ assertThat(o1.getCustomType()).isEqualTo(CustomType.VAL_2);
+ assertThat(o1.getNotSerialized()).isNull();
+ // Member values of second object
+ Implementation o2 = responseBody.get(1);
+ assertThat(o2.getName()).isEqualTo("LOGAN SQUARE IS COOL2");
+ assertThat(o2.getValues()).containsExactly("value1", "value2");
+ assertThat(o2.getCustomType()).isEqualTo(CustomType.VAL_1);
+ assertThat(o2.getNotSerialized()).isNull();
+
+ // Check request body and the received header
+ RecordedRequest request = mockWebServer.takeRequest();
+ assertThat(request.getBody().readUtf8()).isEqualTo("[{\"customType\":2,\"name\":\"LOGAN SQUARE IS COOL\",\"list\":[\"value1\",\"value2\"]},{\"customType\":1,\"name\":\"LOGAN SQUARE IS COOL2\",\"list\":[\"value1\",\"value2\"]}]");
+ assertThat(request.getHeader("Content-Type")).isEqualTo("application/json; charset=UTF-8");
+ }
+
+ @Test public void testListWrongType() throws IOException {
+ // Setup the mock object with an incompatible type argument
+ List<List<Implementation>> body = new ArrayList<>();
+
+ // Setup the API call and fire it
+ try {
+ service.callListWrongType(body);
+ Assertions.failBecauseExceptionWasNotThrown(RuntimeException.class);
+ } catch (RuntimeException ex) {
+ }
+ }
+
+ @Test public void testMap() throws IOException, InterruptedException {
+ // Enqueue a mock response
+ mockWebServer.enqueue(new MockResponse().setBody("{\"item1\":{\"customType\":2,\"name\":\"LOGAN SQUARE IS COOL\",\"list\":[\"value1\",\"value2\"]},\"item2\":{\"customType\":1,\"name\":\"LOGAN SQUARE IS COOL2\",\"list\":[\"value1\",\"value2\"]}}"));
+
+ // Setup the mock object
+ List<String> values = new ArrayList<>();
+ values.add("value1");
+ values.add("value2");
+ Map<String, Implementation> requestBody = new HashMap<>();
+ requestBody.put("item1", new Implementation("LOGAN SQUARE IS COOL", "Not serialized", CustomType.VAL_2, values));
+ requestBody.put("item2", new Implementation("LOGAN SQUARE IS COOL2", "Not serialized", CustomType.VAL_1, values));
+
+ // Call the API and execute it
+ Call<Map<String, Implementation>> call = service.callMap(requestBody);
+ Response<Map<String, Implementation>> response = call.execute();
+ Map<String, Implementation> responseBody = response.body();
+
+ // Assert that conversions worked
+ // Number of objects
+ assertThat(responseBody).hasSize(2);
+ // Member values of first object
+ Implementation o1 = responseBody.get("item1");
+ assertThat(o1.getName()).isEqualTo("LOGAN SQUARE IS COOL");
+ assertThat(o1.getValues()).containsExactly("value1", "value2");
+ assertThat(o1.getCustomType()).isEqualTo(CustomType.VAL_2);
+ assertThat(o1.getNotSerialized()).isNull();
+ // Member values of second object
+ Implementation o2 = responseBody.get("item2");
+ assertThat(o2.getName()).isEqualTo("LOGAN SQUARE IS COOL2");
+ assertThat(o2.getValues()).containsExactly("value1", "value2");
+ assertThat(o2.getCustomType()).isEqualTo(CustomType.VAL_1);
+ assertThat(o2.getNotSerialized()).isNull();
+
+ // Check request body and the received header
+ RecordedRequest request = mockWebServer.takeRequest();
+ assertThat(request.getBody().readUtf8()).isEqualTo("{\"item2\":{\"customType\":1,\"name\":\"LOGAN SQUARE IS COOL2\",\"list\":[\"value1\",\"value2\"]},\"item1\":{\"customType\":2,\"name\":\"LOGAN SQUARE IS COOL\",\"list\":[\"value1\",\"value2\"]}}");
+ assertThat(request.getHeader("Content-Type")).isEqualTo("application/json; charset=UTF-8");
+ }
+
+ @Test public void testMapWrongKeyType() throws IOException {
+ // Setup the mock object with an incompatible type argument
+ Map<Integer, Implementation> body = new HashMap<>();
+
+ // Setup the API call and fire it
+ try {
+ service.callMapWrongKey(body);
+ Assertions.failBecauseExceptionWasNotThrown(RuntimeException.class);
+ } catch (RuntimeException ex) {
+ }
+ }
+
+ @Test public void testMapWrongValueType() throws IOException {
+ // Setup the mock object with an incompatible type argument
+ Map<String, List<Implementation>> body = new HashMap<>();
+
+ // Setup the API call and fire it
+ try {
+ service.callMapWrongValue(body);
+ Assertions.failBecauseExceptionWasNotThrown(RuntimeException.class);
+ } catch (RuntimeException ex) {
+ }
+ }
+
+ @Test public void testFailWhenArray() throws IOException {
+ // Setup the mock object with an incompatible type argument
+ Implementation[] body = new Implementation[0];
+
+ // Setup the API call and fire it
+ try {
+ service.callArray(body);
+ Assertions.failBecauseExceptionWasNotThrown(RuntimeException.class);
+ } catch (RuntimeException ex) {
+ }
+ }
+}
| test | train | 2015-07-30T05:13:16 | "2015-02-25T18:08:48Z" | jfragosoperez | val |
square/retrofit/1020_1021 | square/retrofit | square/retrofit/1020 | square/retrofit/1021 | [
"timestamp(timedelta=106257.0, similarity=0.8426597074492586)"
] | fafb6811794fb43250d3dd94e06e7679c56a1f3f | f9d25d64fe204ef29eab42cdcfea7f14eee9c514 | [
"GitHub issues are not a support forum but are a place to track bugs and feature requests. Please post to StackOverflow with the 'retrofit' tag which will not only garner more attention for a solution, but serve as an easily searchable place for the question to be archived for others.\n"
] | [
"(We don't do a great job of overriding `toString()` throughout Retrofit)\n",
"Unused import\n",
"Unused import\n"
] | "2015-08-22T13:36:18Z" | [] | Using retrofit + okhttp + gson | Hello,
I writed a function to get data from json with okhttp, it work for all class:
```
public class GetDataFromAPI<T> extends AsyncTask<ApiFormat, Void, T> {
private static final String TAG = "GetDataFromAPI";
final Class<T> classType;
public GetDataFromAPI(Class<T> classType){
this.classType = classType;
}
@Override
protected T doInBackground(ApiFormat... params) {
String method = params[0].getMethod();
String url = params[0].getUrl();
RequestBody requestBody = params[0].getRequestBody();
if (url == null){
return null;
}
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(url)
.method(method, requestBody)
.build();
Response responses = null;
InputStream inputStream = null;
if (isCancelled()){
return null;
}
try {
responses = client.newCall(request).execute();
if (responses.code() == 200){
try {
inputStream = responses.body().byteStream();
}catch (IOException e){
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
}
return load(inputStream, classType);
}
private <T> T load(final InputStream inputStream, final Class<T> clazz) {
T result = null;
try {
if (inputStream != null) {
final Gson gson = new Gson();
final BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
result = gson.fromJson(reader, clazz);
return result;
}
return null;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
```
However, now i want cache json to my app can be work offline. I know retrofit can be config with RequestAdapter (as Request on okhttp). I tried and not success.
Please help me change my function to it work
| [
"retrofit/src/main/java/retrofit/Converter.java",
"retrofit/src/main/java/retrofit/Retrofit.java",
"retrofit/src/main/java/retrofit/http/Part.java",
"retrofit/src/main/java/retrofit/http/PartMap.java"
] | [
"retrofit/src/main/java/retrofit/Converter.java",
"retrofit/src/main/java/retrofit/Retrofit.java",
"retrofit/src/main/java/retrofit/http/Part.java",
"retrofit/src/main/java/retrofit/http/PartMap.java"
] | [
"retrofit/src/test/java/retrofit/RetrofitTest.java"
] | diff --git a/retrofit/src/main/java/retrofit/Converter.java b/retrofit/src/main/java/retrofit/Converter.java
index 5df86878ac..6a82784a80 100644
--- a/retrofit/src/main/java/retrofit/Converter.java
+++ b/retrofit/src/main/java/retrofit/Converter.java
@@ -20,7 +20,11 @@
import java.io.IOException;
import java.lang.reflect.Type;
-/** Convert objects to and from their representation as HTTP bodies. */
+/**
+ * Convert objects to and from their representation as HTTP bodies. Register a converter with
+ * Retrofit using {@link Retrofit.Builder#addConverter(Type, Converter)} or {@link
+ * Retrofit.Builder#addConverterFactory(Factory)}.
+ */
public interface Converter<T> {
/** Convert an HTTP response body to a concrete object of the specified type. */
T fromBody(ResponseBody body) throws IOException;
diff --git a/retrofit/src/main/java/retrofit/Retrofit.java b/retrofit/src/main/java/retrofit/Retrofit.java
index 3f0561eac0..c28ba5924b 100644
--- a/retrofit/src/main/java/retrofit/Retrofit.java
+++ b/retrofit/src/main/java/retrofit/Retrofit.java
@@ -22,6 +22,7 @@
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
+import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
@@ -205,6 +206,21 @@ public Builder baseUrl(BaseUrl baseUrl) {
return this;
}
+ /** Add converter for serialization and deserialization of {@code type}. */
+ public <T> Builder addConverter(final Type type, final Converter<T> converter) {
+ checkNotNull(type, "type == null");
+ checkNotNull(converter, "converter == null");
+ converterFactories.add(new Converter.Factory() {
+ @Override public Converter<?> get(Type candidate) {
+ return candidate.equals(type) ? converter : null;
+ }
+ @Override public String toString() {
+ return "ConverterFactory(type=" + type + ",converter=" + converter + ")";
+ }
+ });
+ return this;
+ }
+
/** Add converter factory for serialization and deserialization of objects. */
public Builder addConverterFactory(Converter.Factory converterFactory) {
converterFactories.add(checkNotNull(converterFactory, "converterFactory == null"));
diff --git a/retrofit/src/main/java/retrofit/http/Part.java b/retrofit/src/main/java/retrofit/http/Part.java
index 154af60868..0f59137775 100644
--- a/retrofit/src/main/java/retrofit/http/Part.java
+++ b/retrofit/src/main/java/retrofit/http/Part.java
@@ -18,7 +18,7 @@
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
-import retrofit.Retrofit;
+import retrofit.Converter;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
@@ -31,7 +31,7 @@
* <li>If the type is {@link String} the value will also be used directly with a {@code text/plain}
* content type.</li>
* <li>Other object types will be converted to an appropriate representation by using
- * {@linkplain Retrofit#converterFactory() a converter}.</li>
+ * {@linkplain Converter a converter}.</li>
* </ul>
* <p>
* Values may be {@code null} which will omit them from the request body.
diff --git a/retrofit/src/main/java/retrofit/http/PartMap.java b/retrofit/src/main/java/retrofit/http/PartMap.java
index 512f3545fb..a8d788447b 100644
--- a/retrofit/src/main/java/retrofit/http/PartMap.java
+++ b/retrofit/src/main/java/retrofit/http/PartMap.java
@@ -18,7 +18,7 @@
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
-import retrofit.Retrofit;
+import retrofit.Converter;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
@@ -31,7 +31,7 @@
* <li>If the type is {@link String} the value will also be used directly with a {@code text/plain}
* content type.</li>
* <li>Other object types will be converted to an appropriate representation by using
- * {@linkplain Retrofit#converterFactory() a converter}.</li>
+ * {@linkplain Converter a converter}.</li>
* </ul>
* <p>
* <pre>
| diff --git a/retrofit/src/test/java/retrofit/RetrofitTest.java b/retrofit/src/test/java/retrofit/RetrofitTest.java
index 6934c6c057..e5a7ea5efd 100644
--- a/retrofit/src/test/java/retrofit/RetrofitTest.java
+++ b/retrofit/src/test/java/retrofit/RetrofitTest.java
@@ -11,6 +11,7 @@
import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
+import java.math.BigInteger;
import java.util.List;
import java.util.Map;
import java.util.Set;
@@ -38,6 +39,24 @@
public final class RetrofitTest {
@Rule public final MockWebServer server = new MockWebServer();
+ static final Converter<BigInteger> bigIntegerConverter = new Converter<BigInteger>() {
+ @Override public BigInteger fromBody(ResponseBody body) throws IOException {
+ return new BigInteger(body.string());
+ }
+ @Override public RequestBody toBody(BigInteger value) {
+ return RequestBody.create(MediaType.parse("text/plain"), value.toString());
+ }
+ };
+ static final Converter<CharSequence> charSequenceConverter = new Converter<CharSequence>() {
+ @Override public CharSequence fromBody(ResponseBody body) throws IOException {
+ return new StringBuilder().append(body.string());
+ }
+
+ @Override public RequestBody toBody(CharSequence value) {
+ return RequestBody.create(MediaType.parse("text/plain"), value.toString());
+ }
+ };
+
interface CallMethod {
@GET("/") Call<String> disallowed();
@POST("/") Call<ResponseBody> disallowed(@Body String body);
@@ -62,6 +81,10 @@ interface Unresolvable {
interface VoidService {
@GET("/") void nope();
}
+ interface CustomConverter {
+ @POST("/a") Call<BigInteger> call(@Body BigInteger bigInteger);
+ @POST("/b") Call<CharSequence> call(@Body CharSequence charSequence);
+ }
@SuppressWarnings("EqualsBetweenInconvertibleTypes") // We are explicitly testing this behavior.
@Test public void objectMethodsStillWork() {
@@ -244,7 +267,7 @@ class GreetingCallAdapterFactory implements CallAdapter.Factory {
+ " for method CallMethod.disallowed");
assertThat(e.getCause()).hasMessage(
"Could not locate converter for class java.lang.String. Tried:\n"
- + " * retrofit.RetrofitTest$1\n"
+ + " * retrofit.RetrofitTest$3\n"
+ " * retrofit.OkHttpBodyConverterFactory");
}
}
@@ -456,6 +479,43 @@ class GreetingCallAdapterFactory implements CallAdapter.Factory {
assertThat(retrofit.callAdapterFactories()).isNotEmpty();
}
+ @Test public void addConverter() throws Exception {
+ Retrofit retrofit = new Retrofit.Builder()
+ .baseUrl(server.url("/"))
+ .addConverter(BigInteger.class, bigIntegerConverter)
+ .addConverter(CharSequence.class, charSequenceConverter)
+ .build();
+ CustomConverter api = retrofit.create(CustomConverter.class);
+
+ server.enqueue(new MockResponse().setBody("456"));
+ assertThat(api.call(new BigInteger("123")).execute().body())
+ .isEqualTo(new BigInteger("456"));
+ assertThat(server.takeRequest().getBody().readUtf8()).isEqualTo("123");
+
+ server.enqueue(new MockResponse().setBody("DEF"));
+ assertThat(api.call(new StringBuilder("ABC")).execute().body())
+ .matches("DEF");
+ assertThat(server.takeRequest().getBody().readUtf8()).isEqualTo("ABC");
+ }
+
+ @Test public void addConverterNullType() throws Exception {
+ try {
+ new Retrofit.Builder().addConverter(null, bigIntegerConverter);
+ fail();
+ } catch (NullPointerException expected) {
+ assertThat(expected).hasMessage("type == null");
+ }
+ }
+
+ @Test public void addConverterNullConverter() throws Exception {
+ try {
+ new Retrofit.Builder().addConverter(BigInteger.class, null);
+ fail();
+ } catch (NullPointerException expected) {
+ assertThat(expected).hasMessage("converter == null");
+ }
+ }
+
@Test public void callAdapterFactoryPropagated() {
CallAdapter.Factory factory = mock(CallAdapter.Factory.class);
Retrofit retrofit = new Retrofit.Builder()
| train | train | 2015-08-22T23:02:41 | "2015-08-21T15:40:14Z" | mdtuyen | val |
square/retrofit/1050_1051 | square/retrofit | square/retrofit/1050 | square/retrofit/1051 | [
"timestamp(timedelta=0.0, similarity=0.8521335141891109)"
] | 53cad188dedea05862373a2822da2e6ad1a25378 | 69e3a757aa165c639b8ee2239033b2c290f19f3d | [] | [] | "2015-09-03T03:39:33Z" | [] | Allow Void as first-party supported response body type. | Unlike just specifying `ResponseBody` (which buffers the body), `Void` would just close the underlying body after capturing the metadata.
| [
"retrofit/src/main/java/retrofit/OkHttpBodyConverterFactory.java",
"retrofit/src/main/java/retrofit/Retrofit.java"
] | [
"retrofit/src/main/java/retrofit/BuiltInConverterFactory.java",
"retrofit/src/main/java/retrofit/Retrofit.java",
"retrofit/src/main/java/retrofit/VoidConverter.java"
] | [
"retrofit-converters/protobuf/src/test/java/retrofit/ProtoConverterFactoryTest.java",
"retrofit-converters/wire/src/test/java/retrofit/WireConverterFactoryTest.java",
"retrofit/src/test/java/retrofit/RequestBuilderTest.java",
"retrofit/src/test/java/retrofit/RetrofitTest.java"
] | diff --git a/retrofit/src/main/java/retrofit/OkHttpBodyConverterFactory.java b/retrofit/src/main/java/retrofit/BuiltInConverterFactory.java
similarity index 90%
rename from retrofit/src/main/java/retrofit/OkHttpBodyConverterFactory.java
rename to retrofit/src/main/java/retrofit/BuiltInConverterFactory.java
index a7281ea204..820a260203 100644
--- a/retrofit/src/main/java/retrofit/OkHttpBodyConverterFactory.java
+++ b/retrofit/src/main/java/retrofit/BuiltInConverterFactory.java
@@ -21,7 +21,7 @@
import java.lang.reflect.Type;
import retrofit.http.Streaming;
-final class OkHttpBodyConverterFactory implements Converter.Factory {
+final class BuiltInConverterFactory implements Converter.Factory {
@Override public Converter<?> get(Type type, Annotation[] annotations) {
if (!(type instanceof Class)) {
return null;
@@ -34,6 +34,9 @@ final class OkHttpBodyConverterFactory implements Converter.Factory {
boolean streaming = Utils.isAnnotationPresent(annotations, Streaming.class);
return new OkHttpResponseBodyConverter(streaming);
}
+ if (cls == Void.class) {
+ return new VoidConverter();
+ }
return null;
}
}
diff --git a/retrofit/src/main/java/retrofit/Retrofit.java b/retrofit/src/main/java/retrofit/Retrofit.java
index 8885183c8d..568ac3c952 100644
--- a/retrofit/src/main/java/retrofit/Retrofit.java
+++ b/retrofit/src/main/java/retrofit/Retrofit.java
@@ -179,6 +179,12 @@ public static final class Builder {
private List<CallAdapter.Factory> adapterFactories = new ArrayList<>();
private Executor callbackExecutor;
+ public Builder() {
+ // Add the built-in converter factory first. This prevents overriding its behavior but also
+ // ensures correct behavior when using converters that consume all types.
+ converterFactories.add(new BuiltInConverterFactory());
+ }
+
/** The HTTP client used for requests. */
public Builder client(OkHttpClient client) {
this.client = checkNotNull(client, "client == null");
@@ -264,9 +270,8 @@ public Retrofit build() {
List<CallAdapter.Factory> adapterFactories = new ArrayList<>(this.adapterFactories);
adapterFactories.add(Platform.get().defaultCallAdapterFactory(callbackExecutor));
- // Make a defensive copy of the converters and add the default OkHttp body converter.
+ // Make a defensive copy of the converters.
List<Converter.Factory> converterFactories = new ArrayList<>(this.converterFactories);
- converterFactories.add(new OkHttpBodyConverterFactory());
return new Retrofit(client, baseUrl, converterFactories, adapterFactories, callbackExecutor);
}
diff --git a/retrofit/src/main/java/retrofit/VoidConverter.java b/retrofit/src/main/java/retrofit/VoidConverter.java
new file mode 100644
index 0000000000..f1f7800e2a
--- /dev/null
+++ b/retrofit/src/main/java/retrofit/VoidConverter.java
@@ -0,0 +1,31 @@
+/*
+ * Copyright (C) 2015 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 com.squareup.okhttp.RequestBody;
+import com.squareup.okhttp.ResponseBody;
+import java.io.IOException;
+
+final class VoidConverter implements Converter<Void> {
+ @Override public Void fromBody(ResponseBody body) throws IOException {
+ body.close();
+ return null;
+ }
+
+ @Override public RequestBody toBody(Void value) {
+ throw new UnsupportedOperationException();
+ }
+}
| diff --git a/retrofit-converters/protobuf/src/test/java/retrofit/ProtoConverterFactoryTest.java b/retrofit-converters/protobuf/src/test/java/retrofit/ProtoConverterFactoryTest.java
index 1a91f493c4..25d683f8f9 100644
--- a/retrofit-converters/protobuf/src/test/java/retrofit/ProtoConverterFactoryTest.java
+++ b/retrofit-converters/protobuf/src/test/java/retrofit/ProtoConverterFactoryTest.java
@@ -89,8 +89,8 @@ interface Service {
+ " for method Service.wrongClass");
assertThat(e.getCause()).hasMessage(
"Could not locate converter for class java.lang.String. Tried:\n"
- + " * retrofit.ProtoConverterFactory\n"
- + " * retrofit.OkHttpBodyConverterFactory");
+ + " * retrofit.BuiltInConverterFactory\n"
+ + " * retrofit.ProtoConverterFactory");
}
}
@@ -106,8 +106,8 @@ interface Service {
+ " for method Service.wrongType");
assertThat(e.getCause()).hasMessage(
"Could not locate converter for java.util.List<java.lang.String>. Tried:\n"
- + " * retrofit.ProtoConverterFactory\n"
- + " * retrofit.OkHttpBodyConverterFactory");
+ + " * retrofit.BuiltInConverterFactory\n"
+ + " * retrofit.ProtoConverterFactory");
}
}
diff --git a/retrofit-converters/wire/src/test/java/retrofit/WireConverterFactoryTest.java b/retrofit-converters/wire/src/test/java/retrofit/WireConverterFactoryTest.java
index 3d22ca7d2c..445617a501 100644
--- a/retrofit-converters/wire/src/test/java/retrofit/WireConverterFactoryTest.java
+++ b/retrofit-converters/wire/src/test/java/retrofit/WireConverterFactoryTest.java
@@ -88,8 +88,8 @@ interface Service {
+ " for method Service.wrongClass");
assertThat(e.getCause()).hasMessage(
"Could not locate converter for class java.lang.String. Tried:\n"
- + " * retrofit.WireConverterFactory\n"
- + " * retrofit.OkHttpBodyConverterFactory");
+ + " * retrofit.BuiltInConverterFactory\n"
+ + " * retrofit.WireConverterFactory");
}
}
@@ -105,8 +105,8 @@ interface Service {
+ " for method Service.wrongType");
assertThat(e.getCause()).hasMessage(
"Could not locate converter for java.util.List<java.lang.String>. Tried:\n"
- + " * retrofit.WireConverterFactory\n"
- + " * retrofit.OkHttpBodyConverterFactory");
+ + " * retrofit.BuiltInConverterFactory\n"
+ + " * retrofit.WireConverterFactory");
}
}
diff --git a/retrofit/src/test/java/retrofit/RequestBuilderTest.java b/retrofit/src/test/java/retrofit/RequestBuilderTest.java
index b2b64fdced..826b274726 100644
--- a/retrofit/src/test/java/retrofit/RequestBuilderTest.java
+++ b/retrofit/src/test/java/retrofit/RequestBuilderTest.java
@@ -1662,7 +1662,7 @@ private Request buildRequest(Class<?> cls, Object... args) {
}
};
List<Converter.Factory> converterFactories =
- Arrays.asList(new ToStringConverterFactory(), new OkHttpBodyConverterFactory());
+ Arrays.asList(new BuiltInConverterFactory(), new ToStringConverterFactory());
RequestFactory requestFactory = RequestFactoryParser.parse(method, baseUrl, converterFactories);
return requestFactory.create(args);
diff --git a/retrofit/src/test/java/retrofit/RetrofitTest.java b/retrofit/src/test/java/retrofit/RetrofitTest.java
index 361518a466..2eaaa23ee1 100644
--- a/retrofit/src/test/java/retrofit/RetrofitTest.java
+++ b/retrofit/src/test/java/retrofit/RetrofitTest.java
@@ -64,8 +64,9 @@ public final class RetrofitTest {
interface CallMethod {
@GET("/") Call<String> disallowed();
@POST("/") Call<ResponseBody> disallowed(@Body String body);
- @GET("/") Call<ResponseBody> allowed();
- @POST("/") Call<ResponseBody> allowed(@Body RequestBody body);
+ @GET("/") Call<ResponseBody> getResponseBody();
+ @GET("/") Call<Void> getVoid();
+ @POST("/") Call<ResponseBody> postRequestBody(@Body RequestBody body);
}
interface FutureMethod {
@GET("/") Future<String> method();
@@ -90,8 +91,8 @@ interface CustomConverter {
@POST("/b") Call<CharSequence> call(@Body CharSequence charSequence);
}
interface Annotated {
- @GET("/") @Foo Call<ResponseBody> method();
- @POST("/") Call<ResponseBody> parameter(@Foo @Body RequestBody param);
+ @GET("/") @Foo Call<String> method();
+ @POST("/") Call<ResponseBody> parameter(@Foo @Body String param);
@Retention(RUNTIME)
@interface Foo {}
@@ -141,7 +142,7 @@ interface Annotated {
.baseUrl(server.url("/"))
.build();
CallMethod example = retrofit.create(CallMethod.class);
- assertThat(example.allowed()).isNotNull();
+ assertThat(example.getResponseBody()).isNotNull();
}
@Test public void callCallCustomAdapter() {
@@ -171,7 +172,7 @@ class MyCallAdapterFactory implements CallAdapter.Factory {
.addCallAdapterFactory(new MyCallAdapterFactory())
.build();
CallMethod example = retrofit.create(CallMethod.class);
- assertThat(example.allowed()).isNotNull();
+ assertThat(example.getResponseBody()).isNotNull();
assertThat(factoryCalled.get()).isTrue();
assertThat(adapterCalled.get()).isTrue();
}
@@ -213,6 +214,7 @@ class MyCallAdapterFactory implements CallAdapter.Factory {
}
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(server.url("/"))
+ .addConverterFactory(new ToStringConverterFactory())
.addCallAdapterFactory(new MyCallAdapterFactory())
.build();
Annotated annotated = retrofit.create(Annotated.class);
@@ -245,7 +247,7 @@ class MyCallAdapterFactory implements CallAdapter.Factory {
class MyConverterFactory implements Converter.Factory {
@Override public Converter<?> get(Type type, Annotation[] annotations) {
annotationsRef.set(annotations);
- return null;
+ return new ToStringConverterFactory.StringConverter();
}
}
Retrofit retrofit = new Retrofit.Builder()
@@ -263,10 +265,10 @@ class MyConverterFactory implements Converter.Factory {
final AtomicReference<Annotation[]> annotationsRef = new AtomicReference<>();
class MyConverterFactory implements Converter.Factory {
@Override public Converter<?> get(Type type, Annotation[] annotations) {
- if (type == RequestBody.class) {
+ if (type == String.class) {
annotationsRef.set(annotations);
}
- return null;
+ return new ToStringConverterFactory.StringConverter();
}
}
Retrofit retrofit = new Retrofit.Builder()
@@ -294,7 +296,7 @@ class MyConverterFactory implements Converter.Factory {
+ " for method CallMethod.disallowed");
assertThat(e.getCause()).hasMessage(
"Could not locate converter for class java.lang.String. Tried:\n"
- + " * retrofit.OkHttpBodyConverterFactory");
+ + " * retrofit.BuiltInConverterFactory");
}
}
@@ -314,7 +316,7 @@ class MyConverterFactory implements Converter.Factory {
+ " for method CallMethod.disallowed");
assertThat(e.getCause()).hasMessage(
"Could not locate converter for class java.lang.String. Tried:\n"
- + " * retrofit.OkHttpBodyConverterFactory");
+ + " * retrofit.BuiltInConverterFactory");
}
}
@@ -337,8 +339,8 @@ class MyConverterFactory implements Converter.Factory {
+ " for method CallMethod.disallowed");
assertThat(e.getCause()).hasMessage(
"Could not locate converter for class java.lang.String. Tried:\n"
- + " * retrofit.RetrofitTest$3\n"
- + " * retrofit.OkHttpBodyConverterFactory");
+ + " * retrofit.BuiltInConverterFactory\n"
+ + " * retrofit.RetrofitTest$3");
}
}
@@ -350,10 +352,22 @@ class MyConverterFactory implements Converter.Factory {
server.enqueue(new MockResponse().setBody("Hi"));
- Response<ResponseBody> response = example.allowed().execute();
+ Response<ResponseBody> response = example.getResponseBody().execute();
assertThat(response.body().string()).isEqualTo("Hi");
}
+ @Test public void voidOutgoingAllowed() throws IOException {
+ Retrofit retrofit = new Retrofit.Builder()
+ .baseUrl(server.url("/"))
+ .build();
+ CallMethod example = retrofit.create(CallMethod.class);
+
+ server.enqueue(new MockResponse().setBody("Hi"));
+
+ Response<Void> response = example.getVoid().execute();
+ assertThat(response.body()).isNull();
+ }
+
@Test public void responseBodyIncomingAllowed() throws IOException, InterruptedException {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(server.url("/"))
@@ -363,7 +377,7 @@ class MyConverterFactory implements Converter.Factory {
server.enqueue(new MockResponse().setBody("Hi"));
RequestBody body = RequestBody.create(MediaType.parse("text/plain"), "Hey");
- Response<ResponseBody> response = example.allowed(body).execute();
+ Response<ResponseBody> response = example.postRequestBody(body).execute();
assertThat(response.body().string()).isEqualTo("Hi");
assertThat(server.takeRequest().getBody().readUtf8()).isEqualTo("Hey");
@@ -521,7 +535,7 @@ class MyConverterFactory implements Converter.Factory {
.build();
List<Converter.Factory> converterFactories = retrofit.converterFactories();
assertThat(converterFactories).hasSize(1);
- assertThat(converterFactories.get(0)).isInstanceOf(OkHttpBodyConverterFactory.class);
+ assertThat(converterFactories.get(0)).isInstanceOf(BuiltInConverterFactory.class);
}
@Test public void converterFactoryPropagated() {
@@ -631,7 +645,7 @@ class MyConverterFactory implements Converter.Factory {
.callbackExecutor(executor)
.build();
CallMethod service = retrofit.create(CallMethod.class);
- Call<ResponseBody> call = service.allowed();
+ Call<ResponseBody> call = service.getResponseBody();
server.enqueue(new MockResponse());
@@ -662,7 +676,7 @@ class MyConverterFactory implements Converter.Factory {
.callbackExecutor(executor)
.build();
CallMethod service = retrofit.create(CallMethod.class);
- Call<ResponseBody> call = service.allowed();
+ Call<ResponseBody> call = service.getResponseBody();
server.enqueue(new MockResponse().setSocketPolicy(DISCONNECT_AT_START));
| train | train | 2015-08-31T06:35:46 | "2015-09-02T22:06:32Z" | JakeWharton | val |
square/retrofit/1092_1096 | square/retrofit | square/retrofit/1092 | square/retrofit/1096 | [
"timestamp(timedelta=0.0, similarity=0.8992424967402999)"
] | ea6fa8d1cb4467893a14fa901193edc0fc6eba9d | a82c06a17dc30ee0f58ec18ad0baa540817c6074 | [] | [] | "2015-09-19T10:28:19Z" | [] | Multipart request subtype | As discussed in #1063 multipart upload upload still has some issues. For one, it defaults to multipart/mixed, when in [Retrofit 1.9 it used multipart/form-data](https://github.com/square/retrofit/blob/2f4caa6f5df8e7f47a881266bbfc723f537b0b47/retrofit/src/main/java/retrofit/mime/MultipartTypedOutput.java).
I suggest we use the form-data subtype as it seems to be the standard for HTTP file upload. To use it, the following needs to be changed:
- Set Content-Type header of request to `multipart/form-data; boundary=...`
- Set Content-Type header of parts to `multipart/form-data`
- Add `form-data` value to Content-Disposition header and optionally also add the filename parameter
| [
"retrofit/src/main/java/retrofit/RequestBuilder.java",
"retrofit/src/main/java/retrofit/RequestBuilderAction.java",
"retrofit/src/main/java/retrofit/RequestFactoryParser.java",
"retrofit/src/main/java/retrofit/http/PartMap.java"
] | [
"retrofit/src/main/java/retrofit/RequestBuilder.java",
"retrofit/src/main/java/retrofit/RequestBuilderAction.java",
"retrofit/src/main/java/retrofit/RequestFactoryParser.java",
"retrofit/src/main/java/retrofit/http/PartMap.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 7828dab06f..36195f0c0f 100644
--- a/retrofit/src/main/java/retrofit/RequestBuilder.java
+++ b/retrofit/src/main/java/retrofit/RequestBuilder.java
@@ -61,6 +61,7 @@ final class RequestBuilder {
} else if (isMultipart) {
// Will be set to 'body' in 'build'.
multipartBuilder = new MultipartBuilder();
+ multipartBuilder.type(MultipartBuilder.FORM);
}
}
diff --git a/retrofit/src/main/java/retrofit/RequestBuilderAction.java b/retrofit/src/main/java/retrofit/RequestBuilderAction.java
index ba302c4830..c4898e93f7 100644
--- a/retrofit/src/main/java/retrofit/RequestBuilderAction.java
+++ b/retrofit/src/main/java/retrofit/RequestBuilderAction.java
@@ -241,7 +241,7 @@ static final class PartMap extends RequestBuilderAction {
}
Headers headers = Headers.of(
- "Content-Disposition", "name=\"" + entryKey + "\"",
+ "Content-Disposition", "form-data; name=\"" + entryKey + "\"",
"Content-Transfer-Encoding", transferEncoding);
Class<?> entryClass = entryValue.getClass();
diff --git a/retrofit/src/main/java/retrofit/RequestFactoryParser.java b/retrofit/src/main/java/retrofit/RequestFactoryParser.java
index 7d30171153..50fe0d96a5 100644
--- a/retrofit/src/main/java/retrofit/RequestFactoryParser.java
+++ b/retrofit/src/main/java/retrofit/RequestFactoryParser.java
@@ -290,7 +290,7 @@ private void parseParameters(List<Converter.Factory> converterFactories) {
}
Part part = (Part) methodParameterAnnotation;
com.squareup.okhttp.Headers headers = com.squareup.okhttp.Headers.of(
- "Content-Disposition", "name=\"" + part.value() + "\"",
+ "Content-Disposition", "form-data; name=\"" + part.value() + "\"",
"Content-Transfer-Encoding", part.encoding());
Converter<?, RequestBody> converter;
try {
diff --git a/retrofit/src/main/java/retrofit/http/PartMap.java b/retrofit/src/main/java/retrofit/http/PartMap.java
index a8d788447b..338b308bd1 100644
--- a/retrofit/src/main/java/retrofit/http/PartMap.java
+++ b/retrofit/src/main/java/retrofit/http/PartMap.java
@@ -47,6 +47,6 @@
@Target(PARAMETER)
@Retention(RUNTIME)
public @interface PartMap {
- /** The {@code Content-Transfer-Encoding} of this part. */
+ /** The {@code Content-Transfer-Encoding} of the parts. */
String encoding() default "binary";
}
| diff --git a/retrofit/src/test/java/retrofit/RequestBuilderTest.java b/retrofit/src/test/java/retrofit/RequestBuilderTest.java
index 826b274726..ee6d58e518 100644
--- a/retrofit/src/test/java/retrofit/RequestBuilderTest.java
+++ b/retrofit/src/test/java/retrofit/RequestBuilderTest.java
@@ -1179,10 +1179,12 @@ Call<Object> method(@Part("ping") String ping, @Part("kit") RequestBody kit) {
String bodyString = buffer.readUtf8();
assertThat(bodyString)
+ .contains("Content-Disposition: form-data;")
.contains("name=\"ping\"\r\n")
.contains("\r\npong\r\n--");
assertThat(bodyString)
+ .contains("Content-Disposition: form-data;")
.contains("name=\"kit\"")
.contains("\r\nkat\r\n--");
}
@@ -1208,11 +1210,15 @@ Call<Object> method(@Part(value = "ping", encoding = "8-bit") String ping,
body.writeTo(buffer);
String bodyString = buffer.readUtf8();
- assertThat(bodyString).contains("name=\"ping\"\r\n")
+ assertThat(bodyString)
+ .contains("Content-Disposition: form-data;")
+ .contains("name=\"ping\"\r\n")
.contains("Content-Transfer-Encoding: 8-bit")
.contains("\r\npong\r\n--");
- assertThat(bodyString).contains("name=\"kit\"")
+ assertThat(bodyString)
+ .contains("Content-Disposition: form-data;")
+ .contains("name=\"kit\"")
.contains("Content-Transfer-Encoding: 7-bit")
.contains("\r\nkat\r\n--");
}
@@ -1242,10 +1248,12 @@ Call<Object> method(@PartMap Map<String, Object> parts) {
String bodyString = buffer.readUtf8();
assertThat(bodyString)
+ .contains("Content-Disposition: form-data;")
.contains("name=\"ping\"\r\n")
.contains("\r\npong\r\n--");
assertThat(bodyString)
+ .contains("Content-Disposition: form-data;")
.contains("name=\"kit\"")
.contains("\r\nkat\r\n--");
@@ -1276,11 +1284,15 @@ Call<Object> method(@PartMap(encoding = "8-bit") Map<String, Object> parts) {
body.writeTo(buffer);
String bodyString = buffer.readUtf8();
- assertThat(bodyString).contains("name=\"ping\"\r\n")
+ assertThat(bodyString)
+ .contains("Content-Disposition: form-data;")
+ .contains("name=\"ping\"\r\n")
.contains("Content-Transfer-Encoding: 8-bit")
.contains("\r\npong\r\n--");
- assertThat(bodyString).contains("name=\"kit\"")
+ assertThat(bodyString)
+ .contains("Content-Disposition: form-data;")
+ .contains("name=\"kit\"")
.contains("Content-Transfer-Encoding: 8-bit")
.contains("\r\nkat\r\n--");
@@ -1345,6 +1357,7 @@ Call<Object> method(@Part("ping") String ping, @Part("fizz") String fizz) {
String bodyString = buffer.readUtf8();
assertThat(bodyString)
+ .contains("Content-Disposition: form-data;")
.contains("name=\"ping\"")
.contains("\r\npong\r\n--");
}
| train | train | 2015-09-12T04:36:15 | "2015-09-18T08:53:03Z" | lukaciko | val |
square/retrofit/1045_1123 | square/retrofit | square/retrofit/1045 | square/retrofit/1123 | [
"timestamp(timedelta=0.0, similarity=0.8732448300366678)"
] | a704966767ab96f286986a3f9e0e79f6693db1ed | 0b06c8436af5be076d2b3523cbd8a1ff0a5d9d50 | [
"I'm assuming you are using something like `/nearest/{location}` and specifying the location as a parameter?\n",
"Yep, sorry. Here's the endpoint definition (with `encoded` workaround):\n\n``` java\n@GET(\"/atm-api/nearest/{coordinate}\")\nCall<AtmLocation> getNearestAtmLocation(@Path(value = \"coordinate\", encoded = true) Coordinate coordinate);\n```\n\n`Coordinate` is converted using this `toString` implementation:\n\n``` java\nreturn String.format(\"%.6f,%.6f\", latitude, longitude)\n```\n",
"Try with Retrofit 2 and OkHttp 2.5 ?\n",
"@swankjesse Yep this is with `-beta1`\n",
"This is because path encoding happens in Retrofit, not OkHttp's HttpUrl class.\n\n``` java\nString encodedValue = URLEncoder.encode(String.valueOf(value), \"UTF-8\");\n// URLEncoder encodes for use as a query parameter. Path encoding uses %20 to\n// encode spaces rather than +. Query encoding difference specified in HTML spec.\n// Any remaining plus signs represent spaces as already URLEncoded.\nencodedValue = encodedValue.replace(\"+\", \"%20\");\nrelativeUrl = relativeUrl.replace(\"{\" + name + \"}\", encodedValue);\n```\n"
] | [] | "2015-09-25T05:21:24Z" | [] | Improper encoding of path segment | Here's a test case:
https://android.api.simple.com/atm-api/nearest/45.529801,-122.683633 (works)
Retrofit encodes as:
https://android.api.simple.com/atm-api/nearest/45.529801%2C-122.683633 (doesn't work)
According to [this guide](http://blog.lunatech.com/2009/02/03/what-every-web-developer-must-know-about-url-encoding) the `,` (comma) character should be allowed unencoded in the path.
Easily worked around with `encoded=true`.
| [
"retrofit/src/main/java/retrofit/RequestBuilder.java"
] | [
"retrofit/src/main/java/retrofit/RequestBuilder.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 36195f0c0f..65eed2c1a1 100644
--- a/retrofit/src/main/java/retrofit/RequestBuilder.java
+++ b/retrofit/src/main/java/retrofit/RequestBuilder.java
@@ -23,11 +23,14 @@
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import java.io.IOException;
-import java.io.UnsupportedEncodingException;
-import java.net.URLEncoder;
+import okio.Buffer;
import okio.BufferedSink;
final class RequestBuilder {
+ private static final char[] HEX_DIGITS =
+ { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
+ private static final String PATH_SEGMENT_ENCODE_SET = " \"<>^`{}|/\\?#";
+
private final String method;
private final HttpUrl baseUrl;
@@ -82,20 +85,55 @@ void addPathParam(String name, String value, boolean encoded) {
// The relative URL is cleared when the first query parameter is set.
throw new AssertionError();
}
- try {
- if (!encoded) {
- String encodedValue = URLEncoder.encode(String.valueOf(value), "UTF-8");
- // URLEncoder encodes for use as a query parameter. Path encoding uses %20 to
- // encode spaces rather than +. Query encoding difference specified in HTML spec.
- // Any remaining plus signs represent spaces as already URLEncoded.
- encodedValue = encodedValue.replace("+", "%20");
- relativeUrl = relativeUrl.replace("{" + name + "}", encodedValue);
+ relativeUrl = relativeUrl.replace("{" + name + "}", canonicalize(value, encoded));
+ }
+
+ static String canonicalize(String input, boolean alreadyEncoded) {
+ int codePoint;
+ for (int i = 0, limit = input.length(); i < limit; i += Character.charCount(codePoint)) {
+ codePoint = input.codePointAt(i);
+ if (codePoint < 0x20 || codePoint >= 0x7f
+ || PATH_SEGMENT_ENCODE_SET.indexOf(codePoint) != -1
+ || (codePoint == '%' && !alreadyEncoded)) {
+ // Slow path: the character at i requires encoding!
+ Buffer out = new Buffer();
+ out.writeUtf8(input, 0, i);
+ canonicalize(out, input, i, limit, alreadyEncoded);
+ return out.readUtf8();
+ }
+ }
+
+ // Fast path: no characters required encoding.
+ return input;
+ }
+
+ static void canonicalize(Buffer out, String input, int pos, int limit, boolean alreadyEncoded) {
+ Buffer utf8Buffer = null; // Lazily allocated.
+ int codePoint;
+ for (int i = pos; i < limit; i += Character.charCount(codePoint)) {
+ codePoint = input.codePointAt(i);
+ if (alreadyEncoded
+ && (codePoint == '\t' || codePoint == '\n' || codePoint == '\f' || codePoint == '\r')) {
+ // Skip this character.
+ } else if (codePoint < 0x20
+ || codePoint >= 0x7f
+ || PATH_SEGMENT_ENCODE_SET.indexOf(codePoint) != -1
+ || (codePoint == '%' && !alreadyEncoded)) {
+ // Percent encode this character.
+ if (utf8Buffer == null) {
+ utf8Buffer = new Buffer();
+ }
+ utf8Buffer.writeUtf8CodePoint(codePoint);
+ while (!utf8Buffer.exhausted()) {
+ int b = utf8Buffer.readByte() & 0xff;
+ out.writeByte('%');
+ out.writeByte(HEX_DIGITS[(b >> 4) & 0xf]);
+ out.writeByte(HEX_DIGITS[b & 0xf]);
+ }
} else {
- relativeUrl = relativeUrl.replace("{" + name + "}", String.valueOf(value));
+ // This character doesn't need encoding. Just copy it over.
+ out.writeUtf8CodePoint(codePoint);
}
- } catch (UnsupportedEncodingException e) {
- throw new RuntimeException(
- "Unable to convert path parameter \"" + name + "\" value to UTF-8:" + value, e);
}
}
| diff --git a/retrofit/src/test/java/retrofit/RequestBuilderTest.java b/retrofit/src/test/java/retrofit/RequestBuilderTest.java
index a0dd9de018..404e539154 100644
--- a/retrofit/src/test/java/retrofit/RequestBuilderTest.java
+++ b/retrofit/src/test/java/retrofit/RequestBuilderTest.java
@@ -770,7 +770,7 @@ Call<Object> method(@Path("ping") String ping, @Query("kit") String kit) {
Request request = buildRequest(Example.class, "pong&", "kat&");
assertThat(request.method()).isEqualTo("GET");
assertThat(request.headers().size()).isZero();
- assertThat(request.urlString()).isEqualTo("http://example.com/foo/bar/pong%26/?kit=kat%26");
+ assertThat(request.urlString()).isEqualTo("http://example.com/foo/bar/pong&/?kit=kat%26");
assertThat(request.body()).isNull();
}
| test | train | 2015-09-24T22:28:32 | "2015-08-31T06:10:14Z" | tadfisher | val |
square/retrofit/1121_1131 | square/retrofit | square/retrofit/1121 | square/retrofit/1131 | [
"timestamp(timedelta=0.0, similarity=0.9155760637925847)"
] | 72c794f5217399f280e006cd1bbaaae1eedcda39 | 02a3ab5e9df5b88490a13ec8d7ccaf03b3432912 | [] | [] | "2015-09-27T17:51:46Z" | [] | Update to Moshi 0.10.0 / 1.0.0 | Waiting for its release (October / November), blocks our 2.0.0 release.
| [
"pom.xml",
"retrofit-converters/moshi/README.md"
] | [
"pom.xml",
"retrofit-converters/moshi/README.md"
] | [] | diff --git a/pom.xml b/pom.xml
index 3c3ecd9fba..5638a73c28 100644
--- a/pom.xml
+++ b/pom.xml
@@ -62,7 +62,7 @@
<jackson.version>2.4.3</jackson.version>
<wire.version>1.7.0</wire.version>
<simplexml.version>2.7.1</simplexml.version>
- <moshi.version>0.9.0</moshi.version>
+ <moshi.version>1.0.0</moshi.version>
<!-- Test Dependencies -->
<junit.version>4.12</junit.version>
diff --git a/retrofit-converters/moshi/README.md b/retrofit-converters/moshi/README.md
index 492e426015..9968ccd385 100644
--- a/retrofit-converters/moshi/README.md
+++ b/retrofit-converters/moshi/README.md
@@ -3,8 +3,8 @@ Moshi Converter
A `Converter` which uses [Moshi][1] for serialization to and from JSON.
-A default `Moshi` instance will be created or one can be configured and passed to the
-`MoshiConverter` construction to further control the serialization.
+A default `Moshi` instance will be created or one can be configured and passed to
+`MoshiConverterFactory.create()` to further control the serialization.
[1]: https://github.com/square/moshi
| null | train | train | 2015-09-26T17:56:36 | "2015-09-25T04:13:26Z" | JakeWharton | val |
square/retrofit/1135_1136 | square/retrofit | square/retrofit/1135 | square/retrofit/1136 | [
"timestamp(timedelta=0.0, similarity=0.9080550650582387)"
] | 07d1f3de5e0eb11fb537464bd14fdbacfc9e55a7 | 19553ac2cdde9da5c5982406403aa7920d4fbdec | [] | [
"Do we need this, though? If OkHttp throws an exception when canceled it will be automatically propagated to the callback. I think there is even a test for this already.\n",
"This change is for handling the case where the `Call` is cancelled after the response has been delivered by OkHttp, while still being delivered by the callback `Executor`. As mentioned in #1135, this would cause the result to be delivered to the callback even after cancellation.\n"
] | "2015-09-29T11:47:55Z" | [] | The callback Executor should check for cancellation before delivering the result | Currently if the callback `Executor` executes the callback on a different thread (the default on Android), then there is no check performed for `Call` cancellation, and the result may be delivered even after it has been cancelled. This is not a good design, and may confound expectations from the client code (as e.g. `AsyncTask` handles these cases properly).
| [
"retrofit/src/main/java/retrofit/ExecutorCallAdapterFactory.java"
] | [
"retrofit/src/main/java/retrofit/ExecutorCallAdapterFactory.java"
] | [] | diff --git a/retrofit/src/main/java/retrofit/ExecutorCallAdapterFactory.java b/retrofit/src/main/java/retrofit/ExecutorCallAdapterFactory.java
index 06a29ddae0..1e545d51be 100644
--- a/retrofit/src/main/java/retrofit/ExecutorCallAdapterFactory.java
+++ b/retrofit/src/main/java/retrofit/ExecutorCallAdapterFactory.java
@@ -47,14 +47,36 @@ public CallAdapter<Call<?>> get(Type returnType, Annotation[] annotations, Retro
static final class ExecutorCallbackCall<T> implements Call<T> {
private final Executor callbackExecutor;
private final Call<T> delegate;
+ private volatile boolean canceled;
ExecutorCallbackCall(Executor callbackExecutor, Call<T> delegate) {
this.callbackExecutor = callbackExecutor;
this.delegate = delegate;
}
- @Override public void enqueue(Callback<T> callback) {
- delegate.enqueue(new ExecutorCallback<>(callbackExecutor, callback));
+ @Override public void enqueue(final Callback<T> callback) {
+ delegate.enqueue(new Callback<T>() {
+ @Override public void onResponse(final Response<T> response, final Retrofit retrofit) {
+ callbackExecutor.execute(new Runnable() {
+ @Override public void run() {
+ if (canceled) {
+ // Emulate OkHttp's behavior of throwing/delivering an IOException on cancelation
+ callback.onFailure(new IOException("Canceled"));
+ } else {
+ callback.onResponse(response, retrofit);
+ }
+ }
+ });
+ }
+
+ @Override public void onFailure(final Throwable t) {
+ callbackExecutor.execute(new Runnable() {
+ @Override public void run() {
+ callback.onFailure(t);
+ }
+ });
+ }
+ });
}
@Override public Response<T> execute() throws IOException {
@@ -63,6 +85,7 @@ static final class ExecutorCallbackCall<T> implements Call<T> {
@Override public void cancel() {
delegate.cancel();
+ canceled = true;
}
@SuppressWarnings("CloneDoesntCallSuperClone") // Performing deep clone.
@@ -70,30 +93,4 @@ static final class ExecutorCallbackCall<T> implements Call<T> {
return new ExecutorCallbackCall<>(callbackExecutor, delegate.clone());
}
}
-
- static final class ExecutorCallback<T> implements Callback<T> {
- private final Executor callbackExecutor;
- private final Callback<T> delegate;
-
- ExecutorCallback(Executor callbackExecutor, Callback<T> delegate) {
- this.callbackExecutor = callbackExecutor;
- this.delegate = delegate;
- }
-
- @Override public void onResponse(final Response<T> response, final Retrofit retrofit) {
- callbackExecutor.execute(new Runnable() {
- @Override public void run() {
- delegate.onResponse(response, retrofit);
- }
- });
- }
-
- @Override public void onFailure(final Throwable t) {
- callbackExecutor.execute(new Runnable() {
- @Override public void run() {
- delegate.onFailure(t);
- }
- });
- }
- }
}
| null | train | train | 2015-09-29T16:48:26 | "2015-09-29T09:15:44Z" | 1zaman | val |
square/retrofit/1062_1163 | square/retrofit | square/retrofit/1062 | square/retrofit/1163 | [
"timestamp(timedelta=0.0, similarity=0.9113079639842123)"
] | 07d1f3de5e0eb11fb537464bd14fdbacfc9e55a7 | 3323476db01f97d918fbe8ba8d7c0d3eb1d881c7 | [
"Gson was changed to expose this property (https://github.com/google/gson/pull/700) so once it has its next release (this month or next, well before our v2.0) we can update to configuring a `JsonWriter` to serialize nulls based on the user configuration.\n",
"Waiting on 2.4 release which we're pushing for this coming week: https://github.com/google/gson/issues/668. If it happens quick enough I can squeeze this into beta2!\n",
"awesome, thanks!\n",
"Great, thank you!\n",
"I can't speak English well, I have a question.\r\nlike this:\r\nstatus:\"1\",msg:\"success\",data:{} \r\nbut:\r\nstatus:\"0\",msg:\"error\",data\"\"\r\n\r\nHow to solve\r\n\r\n"
] | [] | "2015-10-04T05:16:39Z" | [] | Update to Gson 2.4, use newJsonWriter in GsonConverterFactory | Hello guys!
Recently I found out issue with null fields serialization during request call process. It is more looks like issue of Gson and there is pretty easy workaround of issue. So far issue lies within [GsonConverterFactory](https://github.com/square/retrofit/blob/master/retrofit-converters/gson/src/main/java/retrofit/GsonConverterFactory.java#L60) which internally uses [TypeAdapter](https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/TypeAdapter.html) instead of actual gson instance. I am not sure what was intent of using TypeAdapter, but such approach ignores extra configurations of Gson object such as `serializaeNulls: false`.
Below is sample of code. Comment points out issue.
``` java
class Data {
private final String tag;
private String optionalTag;
private Data(@NonNull String tag) {
this.tag = tag;
}
public void setOptionalTag(@Nullable String optionalTag) {
this.optionalTag = optionalTag;
}
@NonNull
public String getTag() {
return tag;
}
@Nullable
public String getOptionalTag() {
return optionalTag;
}
}
interface FooService {
@POST("v1/something/create")
Call<Response<Object>> barEndpoint(@Body Data data);
}
```
``` java
@Test
public void test() {
Gson gson = new GsonBuilder().create();
Converter.Factory converterFactory = GsonConverterFactory.create(gson);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://any.api/")
.addConverterFactory(converterFactory)
.build();
Data data = new Data("my tag");
FooService service = retrofit.create(FooService.class);
// Expected result of serialization is {"tag": "my tag"}
// Actual result of serialization is {"tag": "my tag", "optionalTag": null}
service.barEndpoint(data);
}
```
Suggested fix could be to use `gson instance` and not TypeAdapter.
``` java
class GsonConverterFactory implements Converter.Factory {
/**
* Create an instance using a default {@link Gson} instance for conversion. Encoding to JSON and
* decoding from JSON (when no charset is specified by a header) will use UTF-8.
*/
public static GsonConverterFactory create() {
return create(new Gson());
}
/**
* Create an instance using {@code gson} for conversion. Encoding to JSON and
* decoding from JSON (when no charset is specified by a header) will use UTF-8.
*/
public static GsonConverterFactory create(Gson gson) {
return new GsonConverterFactory(gson);
}
private final Gson gson;
private GsonConverterFactory(Gson gson) {
if (gson == null) throw new NullPointerException("gson == null");
this.gson = gson;
}
/** Create a converter for {@code type}. */
@Override public Converter<?> get(Type type) {
return new GsonConverter<>(type, gson);
}
private static class GsonConverter<T> implements Converter<T> {
private static final MediaType MEDIA_TYPE = MediaType.parse("application/json; charset=UTF-8");
private static final Charset UTF_8 = Charset.forName("UTF-8");
private final Gson mGson;
private final Type mType;
DefaultGsonConverter(Type type, Gson gson) {
mType = type;
mGson = gson;
}
@Override public T fromBody(ResponseBody body) throws IOException {
Reader in = body.charStream();
try {
return mGson.fromJson(in, mType);
} finally {
try {
in.close();
} catch (IOException ignored) {
}
}
}
@Override public RequestBody toBody(T value) {
Buffer buffer = new Buffer();
Writer writer = new OutputStreamWriter(buffer.outputStream(), UTF_8);
try {
mGson.toJson(value, mType, writer);
writer.flush();
} catch (IOException e) {
throw new AssertionError(e); // Writing to Buffer does no I/O.
}
return RequestBody.create(MEDIA_TYPE, buffer.readByteString());
}
}
}
```
| [
"pom.xml",
"retrofit-converters/gson/src/main/java/retrofit/GsonConverterFactory.java",
"retrofit-converters/gson/src/main/java/retrofit/GsonRequestBodyConverter.java",
"retrofit-converters/gson/src/main/java/retrofit/GsonResponseBodyConverter.java"
] | [
"pom.xml",
"retrofit-converters/gson/src/main/java/retrofit/GsonConverterFactory.java",
"retrofit-converters/gson/src/main/java/retrofit/GsonRequestBodyConverter.java",
"retrofit-converters/gson/src/main/java/retrofit/GsonResponseBodyConverter.java"
] | [
"retrofit-converters/gson/src/test/java/retrofit/GsonConverterFactoryTest.java"
] | diff --git a/pom.xml b/pom.xml
index 5638a73c28..40b028a8d4 100644
--- a/pom.xml
+++ b/pom.xml
@@ -57,7 +57,7 @@
<rxjava.version>1.0.14</rxjava.version>
<!-- Converter Dependencies -->
- <gson.version>2.3.1</gson.version>
+ <gson.version>2.4</gson.version>
<protobuf.version>2.5.0</protobuf.version>
<jackson.version>2.4.3</jackson.version>
<wire.version>1.7.0</wire.version>
diff --git a/retrofit-converters/gson/src/main/java/retrofit/GsonConverterFactory.java b/retrofit-converters/gson/src/main/java/retrofit/GsonConverterFactory.java
index 59b921be02..36279874c0 100644
--- a/retrofit-converters/gson/src/main/java/retrofit/GsonConverterFactory.java
+++ b/retrofit-converters/gson/src/main/java/retrofit/GsonConverterFactory.java
@@ -16,6 +16,8 @@
package retrofit;
import com.google.gson.Gson;
+import com.google.gson.TypeAdapter;
+import com.google.gson.reflect.TypeToken;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.ResponseBody;
import java.lang.annotation.Annotation;
@@ -55,10 +57,12 @@ private GsonConverterFactory(Gson gson) {
@Override
public Converter<ResponseBody, ?> fromResponseBody(Type type, Annotation[] annotations) {
- return new GsonResponseBodyConverter<>(gson, type);
+ TypeAdapter<?> adapter = gson.getAdapter(TypeToken.get(type));
+ return new GsonResponseBodyConverter<>(adapter);
}
@Override public Converter<?, RequestBody> toRequestBody(Type type, Annotation[] annotations) {
- return new GsonRequestBodyConverter<>(gson, type);
+ TypeAdapter<?> adapter = gson.getAdapter(TypeToken.get(type));
+ return new GsonRequestBodyConverter<>(gson, adapter);
}
}
diff --git a/retrofit-converters/gson/src/main/java/retrofit/GsonRequestBodyConverter.java b/retrofit-converters/gson/src/main/java/retrofit/GsonRequestBodyConverter.java
index a2b527eadc..651b02973f 100644
--- a/retrofit-converters/gson/src/main/java/retrofit/GsonRequestBodyConverter.java
+++ b/retrofit-converters/gson/src/main/java/retrofit/GsonRequestBodyConverter.java
@@ -16,12 +16,13 @@
package retrofit;
import com.google.gson.Gson;
+import com.google.gson.TypeAdapter;
+import com.google.gson.stream.JsonWriter;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.RequestBody;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
-import java.lang.reflect.Type;
import java.nio.charset.Charset;
import okio.Buffer;
@@ -30,19 +31,20 @@ final class GsonRequestBodyConverter<T> implements Converter<T, RequestBody> {
private static final Charset UTF_8 = Charset.forName("UTF-8");
private final Gson gson;
- private final Type type;
+ private final TypeAdapter<T> adapter;
- GsonRequestBodyConverter(Gson gson, Type type) {
+ GsonRequestBodyConverter(Gson gson, TypeAdapter<T> adapter) {
this.gson = gson;
- this.type = type;
+ this.adapter = adapter;
}
@Override public RequestBody convert(T value) throws IOException {
Buffer buffer = new Buffer();
Writer writer = new OutputStreamWriter(buffer.outputStream(), UTF_8);
+ JsonWriter jsonWriter = gson.newJsonWriter(writer);
try {
- gson.toJson(value, type, writer);
- writer.flush();
+ adapter.write(jsonWriter, value);
+ jsonWriter.flush();
} catch (IOException e) {
throw new AssertionError(e); // Writing to Buffer does no I/O.
}
diff --git a/retrofit-converters/gson/src/main/java/retrofit/GsonResponseBodyConverter.java b/retrofit-converters/gson/src/main/java/retrofit/GsonResponseBodyConverter.java
index 0214cfd5ce..5444202e94 100644
--- a/retrofit-converters/gson/src/main/java/retrofit/GsonResponseBodyConverter.java
+++ b/retrofit-converters/gson/src/main/java/retrofit/GsonResponseBodyConverter.java
@@ -15,25 +15,22 @@
*/
package retrofit;
-import com.google.gson.Gson;
+import com.google.gson.TypeAdapter;
import com.squareup.okhttp.ResponseBody;
import java.io.IOException;
import java.io.Reader;
-import java.lang.reflect.Type;
final class GsonResponseBodyConverter<T> implements Converter<ResponseBody, T> {
- private final Gson gson;
- private final Type type;
+ private final TypeAdapter<T> adapter;
- GsonResponseBodyConverter(Gson gson, Type type) {
- this.gson = gson;
- this.type = type;
+ GsonResponseBodyConverter(TypeAdapter<T> adapter) {
+ this.adapter = adapter;
}
@Override public T convert(ResponseBody value) throws IOException {
Reader reader = value.charStream();
try {
- return gson.fromJson(reader, type);
+ return adapter.fromJson(reader);
} finally {
Utils.closeQuietly(reader);
}
| diff --git a/retrofit-converters/gson/src/test/java/retrofit/GsonConverterFactoryTest.java b/retrofit-converters/gson/src/test/java/retrofit/GsonConverterFactoryTest.java
index 3351fc5d04..3d4b6e4f0b 100644
--- a/retrofit-converters/gson/src/test/java/retrofit/GsonConverterFactoryTest.java
+++ b/retrofit-converters/gson/src/test/java/retrofit/GsonConverterFactoryTest.java
@@ -121,7 +121,7 @@ interface Service {
}
@Test public void serializeUsesConfiguration() throws IOException, InterruptedException {
- server.enqueue(new MockResponse());
+ server.enqueue(new MockResponse().setBody("{}"));
service.anImplementation(new AnImplementation(null)).execute();
| train | train | 2015-09-29T16:48:26 | "2015-09-07T11:05:16Z" | tomkoptel | val |
square/retrofit/1120_1230 | square/retrofit | square/retrofit/1120 | square/retrofit/1230 | [
"timestamp(timedelta=0.0, similarity=0.8906882014992401)"
] | 9f52aeb5ccaee92651fb3fcdce5c495d804aec88 | ecbb7333a7f80d08344e36a6e96f5aae35a703e4 | [] | [] | "2015-10-24T04:21:47Z" | [] | Update to Wire 2 | Waiting for its 2.0.0 final release (October), blocks our 2.0.0 release.
| [
"pom.xml",
"retrofit-converters/wire/README.md",
"retrofit-converters/wire/src/main/java/retrofit/WireConverterFactory.java",
"retrofit-converters/wire/src/main/java/retrofit/WireRequestBodyConverter.java",
"retrofit-converters/wire/src/main/java/retrofit/WireResponseBodyConverter.java"
] | [
"pom.xml",
"retrofit-converters/wire/README.md",
"retrofit-converters/wire/src/main/java/retrofit/WireConverterFactory.java",
"retrofit-converters/wire/src/main/java/retrofit/WireRequestBodyConverter.java",
"retrofit-converters/wire/src/main/java/retrofit/WireResponseBodyConverter.java"
] | [
"retrofit-converters/wire/src/test/java/retrofit/Phone.java"
] | diff --git a/pom.xml b/pom.xml
index 40b028a8d4..b26fb4a242 100644
--- a/pom.xml
+++ b/pom.xml
@@ -60,7 +60,7 @@
<gson.version>2.4</gson.version>
<protobuf.version>2.5.0</protobuf.version>
<jackson.version>2.4.3</jackson.version>
- <wire.version>1.7.0</wire.version>
+ <wire.version>2.0.0</wire.version>
<simplexml.version>2.7.1</simplexml.version>
<moshi.version>1.0.0</moshi.version>
diff --git a/retrofit-converters/wire/README.md b/retrofit-converters/wire/README.md
index 88069b48f3..9c82b143e9 100644
--- a/retrofit-converters/wire/README.md
+++ b/retrofit-converters/wire/README.md
@@ -3,8 +3,5 @@ Wire Converter
A `Converter` which uses [Wire][1] for protocol buffer-compatible serialization.
-A default `Wire` instance will be created or one can be configured and passed to the
-`WireConverter` construction to further control the serialization.
-
[1]: https://github.com/square/wire
diff --git a/retrofit-converters/wire/src/main/java/retrofit/WireConverterFactory.java b/retrofit-converters/wire/src/main/java/retrofit/WireConverterFactory.java
index 569527460a..cb108be028 100644
--- a/retrofit-converters/wire/src/main/java/retrofit/WireConverterFactory.java
+++ b/retrofit-converters/wire/src/main/java/retrofit/WireConverterFactory.java
@@ -18,33 +18,21 @@
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.ResponseBody;
import com.squareup.wire.Message;
-import com.squareup.wire.Wire;
+import com.squareup.wire.ProtoAdapter;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
/**
* A {@linkplain Converter.Factory converter} that uses Wire for protocol buffers.
* <p>
- * This converter only applies for types which extend from {@link Message} (or one of its
- * subclasses).
+ * This converter only applies for types which extend from {@link Message}.
*/
public final class WireConverterFactory extends Converter.Factory {
- /** Create an instance using a default {@link Wire} instance for conversion. */
public static WireConverterFactory create() {
- return create(new Wire());
+ return new WireConverterFactory();
}
- /** Create an instance using {@code wire} for conversion. */
- public static WireConverterFactory create(Wire wire) {
- return new WireConverterFactory(wire);
- }
-
- private final Wire wire;
-
- /** Create a converter using the supplied {@link Wire} instance. */
- private WireConverterFactory(Wire wire) {
- if (wire == null) throw new NullPointerException("wire == null");
- this.wire = wire;
+ private WireConverterFactory() {
}
@Override
@@ -57,16 +45,20 @@ private WireConverterFactory(Wire wire) {
return null;
}
//noinspection unchecked
- return new WireResponseBodyConverter<>(wire, (Class<? extends Message>) c);
+ ProtoAdapter<? extends Message> adapter = ProtoAdapter.get((Class<? extends Message>) c);
+ return new WireResponseBodyConverter<>(adapter);
}
@Override public Converter<?, RequestBody> toRequestBody(Type type, Annotation[] annotations) {
if (!(type instanceof Class<?>)) {
return null;
}
- if (!Message.class.isAssignableFrom((Class<?>) type)) {
+ Class<?> c = (Class<?>) type;
+ if (!Message.class.isAssignableFrom(c)) {
return null;
}
- return new WireRequestBodyConverter<>();
+ //noinspection unchecked
+ ProtoAdapter<? extends Message> adapter = ProtoAdapter.get((Class<? extends Message>) c);
+ return new WireRequestBodyConverter<>(adapter);
}
}
diff --git a/retrofit-converters/wire/src/main/java/retrofit/WireRequestBodyConverter.java b/retrofit-converters/wire/src/main/java/retrofit/WireRequestBodyConverter.java
index fd2defd6e0..9f90062eab 100644
--- a/retrofit-converters/wire/src/main/java/retrofit/WireRequestBodyConverter.java
+++ b/retrofit-converters/wire/src/main/java/retrofit/WireRequestBodyConverter.java
@@ -18,13 +18,22 @@
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.RequestBody;
import com.squareup.wire.Message;
+import com.squareup.wire.ProtoAdapter;
import java.io.IOException;
+import okio.Buffer;
-final class WireRequestBodyConverter<T extends Message> implements Converter<T, RequestBody> {
+final class WireRequestBodyConverter<T extends Message<T, ?>> implements Converter<T, RequestBody> {
private static final MediaType MEDIA_TYPE = MediaType.parse("application/x-protobuf");
+ private final ProtoAdapter<T> adapter;
+
+ WireRequestBodyConverter(ProtoAdapter<T> adapter) {
+ this.adapter = adapter;
+ }
+
@Override public RequestBody convert(T value) throws IOException {
- byte[] bytes = value.toByteArray();
- return RequestBody.create(MEDIA_TYPE, bytes);
+ Buffer buffer = new Buffer();
+ adapter.encode(buffer, value);
+ return RequestBody.create(MEDIA_TYPE, buffer.snapshot());
}
}
diff --git a/retrofit-converters/wire/src/main/java/retrofit/WireResponseBodyConverter.java b/retrofit-converters/wire/src/main/java/retrofit/WireResponseBodyConverter.java
index 13530a9adf..8dce25081c 100644
--- a/retrofit-converters/wire/src/main/java/retrofit/WireResponseBodyConverter.java
+++ b/retrofit-converters/wire/src/main/java/retrofit/WireResponseBodyConverter.java
@@ -17,25 +17,24 @@
import com.squareup.okhttp.ResponseBody;
import com.squareup.wire.Message;
-import com.squareup.wire.Wire;
+import com.squareup.wire.ProtoAdapter;
import java.io.IOException;
import okio.BufferedSource;
-final class WireResponseBodyConverter<T extends Message> implements Converter<ResponseBody, T> {
- private final Wire wire;
- private final Class<T> cls;
+final class WireResponseBodyConverter<T extends Message<T, ?>>
+ implements Converter<ResponseBody, T> {
+ private final ProtoAdapter<T> adapter;
- WireResponseBodyConverter(Wire wire, Class<T> cls) {
- this.wire = wire;
- this.cls = cls;
+ WireResponseBodyConverter(ProtoAdapter<T> adapter) {
+ this.adapter = adapter;
}
@Override public T convert(ResponseBody value) throws IOException {
- BufferedSource source = value.source();
try {
- return wire.parseFrom(source, cls);
+ BufferedSource source = value.source();
+ return adapter.decode(source);
} finally {
- Utils.closeQuietly(source);
+ Utils.closeQuietly(value);
}
}
}
| diff --git a/retrofit-converters/wire/src/test/java/retrofit/Phone.java b/retrofit-converters/wire/src/test/java/retrofit/Phone.java
index e8a47989d8..ab0a73683f 100644
--- a/retrofit-converters/wire/src/test/java/retrofit/Phone.java
+++ b/retrofit-converters/wire/src/test/java/retrofit/Phone.java
@@ -1,27 +1,80 @@
// Code generated by Wire protocol buffer compiler, do not edit.
-// Source file: ../wire-runtime/src/test/proto/person.proto
+// Source file: test.proto at 2:1
package retrofit;
+import com.squareup.wire.FieldEncoding;
import com.squareup.wire.Message;
-import com.squareup.wire.ProtoField;
+import com.squareup.wire.ProtoAdapter;
+import com.squareup.wire.ProtoReader;
+import com.squareup.wire.ProtoWriter;
+import java.io.IOException;
+import java.lang.Object;
+import java.lang.Override;
+import java.lang.String;
+import java.lang.StringBuilder;
+import okio.ByteString;
-import static com.squareup.wire.Message.Datatype.STRING;
-import static com.squareup.wire.Message.Label.OPTIONAL;
+public final class Phone extends Message<Phone, Phone.Builder> {
+ public static final ProtoAdapter<Phone> ADAPTER = new ProtoAdapter<Phone>(FieldEncoding.LENGTH_DELIMITED, Phone.class) {
+ @Override
+ public int encodedSize(Phone value) {
+ return (value.number != null ? ProtoAdapter.STRING.encodedSizeWithTag(1, value.number) : 0)
+ + value.unknownFields().size();
+ }
+
+ @Override
+ public void encode(ProtoWriter writer, Phone value) throws IOException {
+ if (value.number != null) ProtoAdapter.STRING.encodeWithTag(writer, 1, value.number);
+ writer.writeBytes(value.unknownFields());
+ }
+
+ @Override
+ public Phone decode(ProtoReader reader) throws IOException {
+ Builder builder = new Builder();
+ long token = reader.beginMessage();
+ for (int tag; (tag = reader.nextTag()) != -1;) {
+ switch (tag) {
+ case 1: builder.number(ProtoAdapter.STRING.decode(reader)); break;
+ default: {
+ FieldEncoding fieldEncoding = reader.peekFieldEncoding();
+ Object value = fieldEncoding.rawProtoAdapter().decode(reader);
+ builder.addUnknownField(tag, fieldEncoding, value);
+ }
+ }
+ }
+ reader.endMessage(token);
+ return builder.build();
+ }
+
+ @Override
+ public Phone redact(Phone value) {
+ Builder builder = value.newBuilder();
+ builder.clearUnknownFields();
+ return builder.build();
+ }
+ };
-public final class Phone extends Message {
+ private static final long serialVersionUID = 0L;
- public static final String DEFAULT_PHONE = "";
+ public static final String DEFAULT_NUMBER = "";
- @ProtoField(tag = 1, type = STRING, label = OPTIONAL)
public final String number;
public Phone(String number) {
+ this(number, ByteString.EMPTY);
+ }
+
+ public Phone(String number, ByteString unknownFields) {
+ super(unknownFields);
this.number = number;
}
- private Phone(Builder builder) {
- this(builder.number);
- setBuilder(builder);
+ @Override
+ public Builder newBuilder() {
+ Builder builder = new Builder();
+ builder.number = number;
+ builder.addUnknownFields(unknownFields());
+ return builder;
}
@Override
@@ -29,41 +82,42 @@ public boolean equals(Object other) {
if (other == this) return true;
if (!(other instanceof Phone)) return false;
Phone o = (Phone) other;
- return equals(number, o.number);
+ return equals(unknownFields(), o.unknownFields())
+ && equals(number, o.number);
}
@Override
public int hashCode() {
- int result = hashCode;
+ int result = super.hashCode;
if (result == 0) {
- result = number != null ? number.hashCode() : 0;
- hashCode = result;
+ result = unknownFields().hashCode();
+ result = result * 37 + (number != null ? number.hashCode() : 0);
+ super.hashCode = result;
}
return result;
}
- public static final class Builder extends Message.Builder<Phone> {
+ @Override
+ public String toString() {
+ StringBuilder builder = new StringBuilder();
+ if (number != null) builder.append(", number=").append(number);
+ return builder.replace(0, 2, "Phone{").append('}').toString();
+ }
+ public static final class Builder extends com.squareup.wire.Message.Builder<Phone, Builder> {
public String number;
public Builder() {
}
- public Builder(Phone message) {
- super(message);
- if (message == null) return;
- this.number = message.number;
- }
-
- public Builder number(String name) {
- this.number = name;
+ public Builder number(String number) {
+ this.number = number;
return this;
}
@Override
public Phone build() {
- checkRequiredFields();
- return new Phone(this);
+ return new Phone(number, buildUnknownFields());
}
}
}
| train | train | 2015-10-10T00:29:01 | "2015-09-25T04:12:46Z" | JakeWharton | val |
square/retrofit/1240_1244 | square/retrofit | square/retrofit/1240 | square/retrofit/1244 | [
"timestamp(timedelta=0.0, similarity=0.8926399144810047)"
] | 9fb8b1fbe0af19a92b63107601e03eeff8accd7d | fd61cfd9984c8a4bf5dfe5c6065c11d285cde9a4 | [
"That's fine.\n\nOn Wed, Oct 28, 2015, 7:53 AM Artem Zinnatullin [email protected]\nwrote:\n\n> validateEagerly is a great option. But at the moment developer should\n> explicitly store a reference to Retrofit.Builder to conditionally\n> enable/disable it.\n> \n> Example:\n> \n> Today:\n> \n> @Provides @NonNull @Singletonpublic SomeApi provideSomeApi(@NonNull OkHttpClient okHttpClient, @NonNull Moshi moshi) {\n> Retrofit.Builder retrofitBuilder = new Retrofit.Builder()\n> .baseUrl(\"https://someapi/v1/\")\n> .client(okHttpClient)\n> .addCallAdapterFactory(RxJavaCallAdapterFactory.create())\n> .addConverterFactory(MoshiConverterFactory.create(moshi));\n> \n> if (BuildConfig.DEBUG) { // or some other config value\n> retrofitBuilder.validateEagerly();\n> }\n> \n> return retrofitBuilder.build().create(SomeApi.class);\n> }\n> \n> A Better Tomorrow:\n> \n> @Provides @NonNull @Singletonpublic SomeApi provideSomeApi(@NonNull OkHttpClient okHttpClient, @NonNull Moshi moshi) {\n> return new Retrofit.Builder()\n> .baseUrl(\"https://someapi/v1/\")\n> .client(okHttpClient)\n> .addCallAdapterFactory(RxJavaCallAdapterFactory.create())\n> .addConverterFactory(MoshiConverterFactory.create(moshi))\n> .validateEagerly(BuildConfig.DEBUG)\n> .build()\n> .create(SomeApi.class);\n> }\n> \n> Wouldn't you be mind of PR which will change signature of validateEagerly\n> so it could accept boolean?\n> \n> Related to #1023 https://github.com/square/retrofit/issues/1023.\n> \n> —\n> Reply to this email directly or view it on GitHub\n> https://github.com/square/retrofit/issues/1240.\n"
] | [
"Missing a period here and above. [Comments should be sentences](nedbatchelder.com/blog/201401/comments_should_be_sentences.html).\n",
"Good point, thanks for the link.\n"
] | "2015-10-28T18:41:25Z" | [] | Retrofit.Builder.validateEagerly() accept boolean | `validateEagerly` is a great option. But at the moment developer should explicitly store a reference to `Retrofit.Builder` to conditionally enable/disable it.
Example:
Today:
``` java
@Provides @NonNull @Singleton
public SomeApi provideSomeApi(@NonNull OkHttpClient okHttpClient, @NonNull Moshi moshi) {
Retrofit.Builder retrofitBuilder = new Retrofit.Builder()
.baseUrl("https://someapi/v1/")
.client(okHttpClient)
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.addConverterFactory(MoshiConverterFactory.create(moshi));
if (BuildConfig.DEBUG) { // or some other config value
retrofitBuilder.validateEagerly();
}
return retrofitBuilder.build().create(SomeApi.class);
}
```
A Better Tomorrow:
``` java
@Provides @NonNull @Singleton
public SomeApi provideSomeApi(@NonNull OkHttpClient okHttpClient, @NonNull Moshi moshi) {
return new Retrofit.Builder()
.baseUrl("https://someapi/v1/")
.client(okHttpClient)
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.addConverterFactory(MoshiConverterFactory.create(moshi))
.validateEagerly(BuildConfig.DEBUG)
.build()
.create(SomeApi.class);
}
```
Wouldn't you be mind of PR which will change signature of `validateEagerly` so it could accept `boolean`?
Related to #1023.
| [
"retrofit/src/main/java/retrofit/Retrofit.java"
] | [
"retrofit/src/main/java/retrofit/Retrofit.java"
] | [
"retrofit/src/test/java/retrofit/RetrofitTest.java"
] | diff --git a/retrofit/src/main/java/retrofit/Retrofit.java b/retrofit/src/main/java/retrofit/Retrofit.java
index 4d2b040710..f6355ce89d 100644
--- a/retrofit/src/main/java/retrofit/Retrofit.java
+++ b/retrofit/src/main/java/retrofit/Retrofit.java
@@ -349,8 +349,8 @@ public Builder callbackExecutor(Executor callbackExecutor) {
* When calling {@link #create} on the resulting {@link Retrofit} instance, eagerly validate
* the configuration of all methods in the supplied interface.
*/
- public Builder validateEagerly() {
- validateEagerly = true;
+ public Builder validateEagerly(boolean validateEagerly) {
+ this.validateEagerly = validateEagerly;
return this;
}
| diff --git a/retrofit/src/test/java/retrofit/RetrofitTest.java b/retrofit/src/test/java/retrofit/RetrofitTest.java
index b129d735f4..ecfb3d91b8 100644
--- a/retrofit/src/test/java/retrofit/RetrofitTest.java
+++ b/retrofit/src/test/java/retrofit/RetrofitTest.java
@@ -115,10 +115,29 @@ interface Annotated {
}
}
+ @Test public void validateEagerlyDisabledByDefault() {
+ Retrofit retrofit = new Retrofit.Builder()
+ .baseUrl(server.url("/"))
+ .build();
+
+ // Should not throw exception about incorrect configuration of the VoidService
+ retrofit.create(VoidService.class);
+ }
+
+ @Test public void validateEagerlyDisabledByUser() {
+ Retrofit retrofit = new Retrofit.Builder()
+ .baseUrl(server.url("/"))
+ .validateEagerly(false)
+ .build();
+
+ // Should not throw exception about incorrect configuration of the VoidService
+ retrofit.create(VoidService.class);
+ }
+
@Test public void validateEagerlyFailsAtCreation() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(server.url("/"))
- .validateEagerly()
+ .validateEagerly(true)
.build();
try {
| test | train | 2015-10-26T22:50:08 | "2015-10-28T07:53:42Z" | artem-zinnatullin | val |
square/retrofit/1267_1313 | square/retrofit | square/retrofit/1267 | square/retrofit/1313 | [
"timestamp(timedelta=0.0, similarity=0.8787880966049377)"
] | 8284088f0c6c6f9bba6617a33304b8e2f10bf0fa | ed0f37503f763dc283a45f15aebeba5948642d80 | [
"For what purpose? When would you not know if a call had been executed?\n\nOn Mon, Nov 9, 2015, 9:14 AM Philip Giuliani [email protected]\nwrote:\n\n> What do you think about adding a\n> \n> boolean isExecuted();\n> \n> API to the Call interface?\n> \n> Would be helpful in some situations. Of course i could handle it by myself\n> by setting executed true in the onResponse and onFailure handling, but\n> would still be nice to have it in retrofit.\n> \n> I would also be open to add it via a PR if you are interested.\n> \n> —\n> Reply to this email directly or view it on GitHub\n> https://github.com/square/retrofit/issues/1267.\n",
"In my app i have the following, simple, usecase:\nI am loading some unimportant data in the background which i need when the users clicks on a button. Now if the data is not loaded yet and he clicks on the button, he should get a message that it's still loading.\n\nIn my case its not possible to disable the button (Leanback has no option for this...)\n",
"@swankjesse have opinions here? Right now Retrofit's Call mirrors OkHttp's, so if we expose this, ideally OkHttp would expose it as well.\n",
"It seems to be close to `tag` object in OkHttp call. For now, OkHttp allows user to build `Request` with `tag`, and OkHttpClient could `cancel` request for those tags. So IMO it would be nice if we could have more convenient methods for `tags` like `OkHttpClient#isExecuted(Object tag)`.\n",
"That would require keeping far too much state and it provides no way of\ndealing with both executed and unexecuted calls of the same tag.\n\nOn Thu, Nov 19, 2015 at 1:00 AM Nam Nguyen Hoai [email protected]\nwrote:\n\n> It seems to be close to tag object in OkHttp call. For now, OkHttp allows\n> user to build Request with tag, and OkHttpClient could cancel request for\n> those tags. So IMO it would be nice if we could have more convenient method\n> for tags like OkHttpClient#isExecuted(Object tag).\n> \n> —\n> Reply to this email directly or view it on GitHub\n> https://github.com/square/retrofit/issues/1267#issuecomment-157960228.\n",
"In OkHttp: https://github.com/square/okhttp/pull/2022\n"
] | [] | "2015-11-23T13:18:35Z" | [
"Feature"
] | [Proposal] Add isExecuted API to Call interface | What do you think about adding a
``` java
boolean isExecuted();
```
API to the Call interface?
Would be helpful in some situations. Of course i could handle it by myself by setting executed true in the onResponse and onFailure handling, but would still be nice to have it in retrofit.
I would also be open to add it via a PR if you are interested.
| [
"retrofit-mock/src/main/java/retrofit/mock/BehaviorCall.java",
"retrofit-mock/src/main/java/retrofit/mock/Calls.java",
"retrofit/src/main/java/retrofit/Call.java",
"retrofit/src/main/java/retrofit/ExecutorCallAdapterFactory.java",
"retrofit/src/main/java/retrofit/OkHttpCall.java"
] | [
"retrofit-mock/src/main/java/retrofit/mock/BehaviorCall.java",
"retrofit-mock/src/main/java/retrofit/mock/Calls.java",
"retrofit/src/main/java/retrofit/Call.java",
"retrofit/src/main/java/retrofit/ExecutorCallAdapterFactory.java",
"retrofit/src/main/java/retrofit/OkHttpCall.java"
] | [
"retrofit/src/test/java/retrofit/CallTest.java",
"retrofit/src/test/java/retrofit/ExecutorCallAdapterFactoryTest.java"
] | diff --git a/retrofit-mock/src/main/java/retrofit/mock/BehaviorCall.java b/retrofit-mock/src/main/java/retrofit/mock/BehaviorCall.java
index 170c46f8de..8edf72fab8 100644
--- a/retrofit-mock/src/main/java/retrofit/mock/BehaviorCall.java
+++ b/retrofit-mock/src/main/java/retrofit/mock/BehaviorCall.java
@@ -119,6 +119,10 @@ private void callFailure(final Throwable throwable) {
});
}
+ @Override public synchronized boolean isExecuted() {
+ return executed;
+ }
+
@Override public Response<T> execute() throws IOException {
final AtomicReference<Response<T>> responseRef = new AtomicReference<>();
final AtomicReference<Throwable> failureRef = new AtomicReference<>();
diff --git a/retrofit-mock/src/main/java/retrofit/mock/Calls.java b/retrofit-mock/src/main/java/retrofit/mock/Calls.java
index d56c9589ac..21343074ca 100644
--- a/retrofit-mock/src/main/java/retrofit/mock/Calls.java
+++ b/retrofit-mock/src/main/java/retrofit/mock/Calls.java
@@ -36,6 +36,10 @@ public static <T> Call<T> response(final Response<T> response) {
callback.onResponse(response);
}
+ @Override public boolean isExecuted() {
+ return false;
+ }
+
@Override public void cancel() {
}
@@ -60,6 +64,10 @@ public static <T> Call<T> failure(final IOException failure) {
callback.onFailure(failure);
}
+ @Override public boolean isExecuted() {
+ return false;
+ }
+
@Override public void cancel() {
}
diff --git a/retrofit/src/main/java/retrofit/Call.java b/retrofit/src/main/java/retrofit/Call.java
index 75e3e8a060..968aba8b49 100644
--- a/retrofit/src/main/java/retrofit/Call.java
+++ b/retrofit/src/main/java/retrofit/Call.java
@@ -46,6 +46,12 @@ public interface Call<T> extends Cloneable {
*/
void enqueue(Callback<T> callback);
+ /**
+ * Returns true if this call has been either {@linkplain #execute() executed} or {@linkplain
+ * #enqueue(Callback) enqueued}. It is an error to execute or enqueue a call more than once.
+ */
+ boolean isExecuted();
+
/**
* Cancel this call. An attempt will be made to cancel in-flight calls, and if the call has not
* yet been executed it never will be.
diff --git a/retrofit/src/main/java/retrofit/ExecutorCallAdapterFactory.java b/retrofit/src/main/java/retrofit/ExecutorCallAdapterFactory.java
index 2862063a0e..15ed08770c 100644
--- a/retrofit/src/main/java/retrofit/ExecutorCallAdapterFactory.java
+++ b/retrofit/src/main/java/retrofit/ExecutorCallAdapterFactory.java
@@ -78,6 +78,10 @@ static final class ExecutorCallbackCall<T> implements Call<T> {
});
}
+ @Override public boolean isExecuted() {
+ return delegate.isExecuted();
+ }
+
@Override public Response<T> execute() throws IOException {
return delegate.execute();
}
diff --git a/retrofit/src/main/java/retrofit/OkHttpCall.java b/retrofit/src/main/java/retrofit/OkHttpCall.java
index 10483380ae..70cef83158 100644
--- a/retrofit/src/main/java/retrofit/OkHttpCall.java
+++ b/retrofit/src/main/java/retrofit/OkHttpCall.java
@@ -102,6 +102,10 @@ private void callSuccess(Response<T> response) {
});
}
+ @Override public synchronized boolean isExecuted() {
+ return executed;
+ }
+
public Response<T> execute() throws IOException {
synchronized (this) {
if (executed) throw new IllegalStateException("Already executed");
| diff --git a/retrofit/src/test/java/retrofit/CallTest.java b/retrofit/src/test/java/retrofit/CallTest.java
index 09966614e3..af3b1a08fe 100644
--- a/retrofit/src/test/java/retrofit/CallTest.java
+++ b/retrofit/src/test/java/retrofit/CallTest.java
@@ -515,6 +515,41 @@ public Converter<?, RequestBody> requestBodyConverter(Type type, Annotation[] an
assertThat(rawBody.contentType().toString()).isEqualTo("text/stringy");
}
+ @Test public void reportsExecutedSync() throws IOException {
+ Retrofit retrofit = new Retrofit.Builder()
+ .baseUrl(server.url("/"))
+ .addConverterFactory(new ToStringConverterFactory())
+ .build();
+ Service example = retrofit.create(Service.class);
+
+ server.enqueue(new MockResponse().setBody("Hi"));
+
+ Call<String> call = example.getString();
+ assertThat(call.isExecuted()).isFalse();
+
+ call.execute();
+ assertThat(call.isExecuted()).isTrue();
+ }
+
+ @Test public void reportsExecutedAsync() throws InterruptedException {
+ Retrofit retrofit = new Retrofit.Builder()
+ .baseUrl(server.url("/"))
+ .addConverterFactory(new ToStringConverterFactory())
+ .build();
+ Service example = retrofit.create(Service.class);
+
+ server.enqueue(new MockResponse().setBody("Hi"));
+
+ Call<String> call = example.getString();
+ assertThat(call.isExecuted()).isFalse();
+
+ call.enqueue(new Callback<String>() {
+ @Override public void onResponse(Response<String> response) {}
+ @Override public void onFailure(Throwable t) {}
+ });
+ assertThat(call.isExecuted()).isTrue();
+ }
+
@Test public void cancelBeforeExecute() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(server.url("/"))
diff --git a/retrofit/src/test/java/retrofit/ExecutorCallAdapterFactoryTest.java b/retrofit/src/test/java/retrofit/ExecutorCallAdapterFactoryTest.java
index eab2de7bfc..474b882dba 100644
--- a/retrofit/src/test/java/retrofit/ExecutorCallAdapterFactoryTest.java
+++ b/retrofit/src/test/java/retrofit/ExecutorCallAdapterFactoryTest.java
@@ -151,6 +151,10 @@ static class EmptyCall implements Call<String> {
throw new UnsupportedOperationException();
}
+ @Override public boolean isExecuted() {
+ return false;
+ }
+
@Override public Response<String> execute() throws IOException {
throw new UnsupportedOperationException();
}
| train | train | 2015-11-19T15:43:23 | "2015-11-09T09:14:17Z" | philipgiuliani | val |
square/retrofit/1362_1371 | square/retrofit | square/retrofit/1362 | square/retrofit/1371 | [
"timestamp(timedelta=0.0, similarity=0.8745999023817711)"
] | 1a25a28c4cf87d445ff931cc1c44fcb76cee3aa4 | ae457f4dfe30af5f73b4c045b808ab08018ca8e5 | [] | [] | "2015-12-11T03:21:39Z" | [] | Fix documentation of @Path encoded parameter | Documentation of `@Path` mentions `encode` parameter but the actual annotation has the `encoded` which has the opposite meaning.
You should also mention that setting `encoded = true` still doesn’t turn of the validation so `/` still gets encoded.
| [
"retrofit/src/main/java/retrofit2/http/Path.java"
] | [
"retrofit/src/main/java/retrofit2/http/Path.java"
] | [] | diff --git a/retrofit/src/main/java/retrofit2/http/Path.java b/retrofit/src/main/java/retrofit2/http/Path.java
index 22efed8344..feaf34b273 100644
--- a/retrofit/src/main/java/retrofit2/http/Path.java
+++ b/retrofit/src/main/java/retrofit2/http/Path.java
@@ -23,7 +23,7 @@
import static java.lang.annotation.RetentionPolicy.RUNTIME;
/**
- * Named replacement in the URL path. Values are converted to string using
+ * Named replacement in a URL path segment. Values are converted to string using
* {@link String#valueOf(Object)} and URL encoded.
* <p>
* Simple example:
@@ -33,13 +33,13 @@
* }</pre>
* Calling with {@code foo.example(1)} yields {@code /image/1}.
* <p>
- * Values are URL encoded by default. Disable with {@code encode=false}.
+ * Values are URL encoded by default. Disable with {@code encoded=true}.
* <pre>{@code
* @GET("/user/{name}")
* Call<ResponseBody> encoded(@Path("name") String name);
*
* @GET("/user/{name}")
- * Call<ResponseBody> notEncoded(@Path(value="name", encode=false) String name);
+ * Call<ResponseBody> notEncoded(@Path(value="name", encoded=true) String name);
* }</pre>
* Calling {@code foo.encoded("John+Doe")} yields {@code /user/John%2BDoe} whereas
* {@code foo.notEncoded("John+Doe")} yields {@code /user/John+Doe}.
| null | train | train | 2015-12-10T16:39:15 | "2015-12-10T12:37:07Z" | iwo | val |
square/retrofit/1377_1394 | square/retrofit | square/retrofit/1377 | square/retrofit/1394 | [
"timestamp(timedelta=0.0, similarity=0.8452816887522782)"
] | 2b68ba8e6e8cba7042975f3c188ac59f7760b431 | 5449dd9452901eb18829493d29bb0368eaacfcec | [
"The hacky way to do this is with an OkHttp interceptor that calls into your HttpClient instead of calling chain.proceed().\n",
"hmmm, clever :)\n",
"The only downside here is you still can't use this to adapt to an async HttpClient because the `Interceptor` interface requires a synchronous return value: `Response intercept(Chain)`\n\nI think the place that it needs to be done is in `MethodHandler.invoke`. It currently explicitly creates a `OkHttpCall`, but if that was sometype of provider interface that I could provide my own implementation, then I can plugin in my client...\n\n```\ninterface CallProvider {\n <T> Call<T> provide(Retrofit, RequestFactory, Converter<ResponseBody, T>, Object...)\n}\n```\n\nThen `MethodHandler.invoke()` would be:\n\n```\nObject invoke(Object... args) {\n return callAdapter.adapt(callProvider.provide(retrofit, requestFactory, responseConverter, args));\n}\n```\n\nAnd we'd just need a way to pass the `CallProvider` that far down.\n",
"That or allow a `CallAdapter` to get a handle on the original Request, so it could adapt the call by doing it's own actions.\n",
"Hmm, I probably wouldn't make this hypothetical type aware of the mechanism for creating a `Request`. Something like:\n\n```\ninterface Call.Factory {\n <T> Call<T> create(Request request, Converter<ResponseBody, T> converter);\n}\n```\n",
"@JakeWharton are you thinking this interface would go into the `withClient()` method in `Retrofit`?\nI'd be happy to code up a PR with some direction.\n",
"Give me a day or two to think about it? We explicitly chose not to support multiple HTTP clients, but re-using OkHttp's value types as a model for abstracting different HTTP clients is an interesting one. I need to re-frame some things in my head.\n",
"Sure thing. I'll wait to hear back from you on here. Like I said, I don't mind doing the leg work and if you want to provide an initial path than I can code it up and we can re-work that as much as you want.\n",
"Ok I'm thinking:\n\n``` java\nabstract class Client {\n abstract <T> Call<T> newCall(Request request, Converter<ResponseBody, T> converter);\n}\n```\n\nalong with special treatment in the public API for taking in an `OkHttpClient` and wrapping it internally.\n\nThe abstract class buys us the ability to add a method in the future for creating a hypothetical `WebSocketCall<T>` (#924) which can default to `throw new UnsupportedOperationException();`.\n",
"@JakeWharton in case you're curious, I finally got around to implementing this in Ratpack - https://ratpack.io/manual/1.4.0/retrofit.html#retrofit_type_safe_clients\n"
] | [
"I originally used `Callable<Request>` for this, but the fact that it throws a full-on `Exception` was ugly and the naming clashes severely with our `Call` and `Callback` and friends. Really low-value class here. Java 8's `Supplier` doesn't fit either because of the need to throw `IOException` (not that we can use Java 8 types anyway).\n",
"copyright\n",
"to prevent this if desired?\n"
] | "2015-12-21T18:05:38Z" | [] | Retrofit2 support for alternative HTTP clients? | I see that v2 couples very tightly to `OkHttp`. Specifically, `Retrofit.Builder.client(OkHttpClient)` only takes an implementation of `OkHttpClient` instead of an abstract interface.
I was looking to integrate v2 support in to Ratpack and I can make it work with the `CallAdapter` except that the implementation continues to use OkHttpClient behind the scenes. While functional, I was wondering if there is a way that I could replace the underlying HTTP client with Ratpack's Netty based Http client.
Is there a way to do this (even if hacky)? Is this a feature that you would be interested in supporting?
| [
"retrofit/src/main/java/retrofit2/Call.java",
"retrofit/src/main/java/retrofit2/MethodHandler.java",
"retrofit/src/main/java/retrofit2/OkHttpCall.java",
"retrofit/src/main/java/retrofit2/RequestFactory.java",
"retrofit/src/main/java/retrofit2/Retrofit.java"
] | [
"retrofit/src/main/java/retrofit2/Call.java",
"retrofit/src/main/java/retrofit2/DeferredRequest.java",
"retrofit/src/main/java/retrofit2/MethodHandler.java",
"retrofit/src/main/java/retrofit2/OkHttpCall.java",
"retrofit/src/main/java/retrofit2/OkHttpCallFactory.java",
"retrofit/src/main/java/retrofit2/RequestFactory.java",
"retrofit/src/main/java/retrofit2/Retrofit.java"
] | [
"retrofit/src/test/java/retrofit2/RetrofitTest.java"
] | diff --git a/retrofit/src/main/java/retrofit2/Call.java b/retrofit/src/main/java/retrofit2/Call.java
index 873bb0c6fe..ca57759fd7 100644
--- a/retrofit/src/main/java/retrofit2/Call.java
+++ b/retrofit/src/main/java/retrofit2/Call.java
@@ -15,6 +15,7 @@
*/
package retrofit2;
+import com.squareup.okhttp.ResponseBody;
import java.io.IOException;
/**
@@ -66,4 +67,13 @@ public interface Call<T> extends Cloneable {
* has already been.
*/
Call<T> clone();
+
+ /** Creates {@link Call} instances. */
+ interface Factory {
+ /**
+ * Returns a {@link Call} which will send {@code request} when executed or enqueue and use
+ * {@code converter} to parse the response. May not return null.
+ */
+ <T> Call<T> create(DeferredRequest request, Converter<ResponseBody, T> converter);
+ }
}
diff --git a/retrofit/src/main/java/retrofit2/DeferredRequest.java b/retrofit/src/main/java/retrofit2/DeferredRequest.java
new file mode 100644
index 0000000000..37d83711db
--- /dev/null
+++ b/retrofit/src/main/java/retrofit2/DeferredRequest.java
@@ -0,0 +1,28 @@
+/*
+ * Copyright (C) 2015 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 retrofit2;
+
+import com.squareup.okhttp.Request;
+import java.io.IOException;
+
+/**
+ * An un-built HTTP request. This class defers any work necessary to create an HTTP request until
+ * {@link #get()} is called.
+ */
+public interface DeferredRequest {
+ /** Perform the work necessary to create and then return the {@link Request}. */
+ Request get() throws IOException;
+}
diff --git a/retrofit/src/main/java/retrofit2/MethodHandler.java b/retrofit/src/main/java/retrofit2/MethodHandler.java
index 8e4fe720c0..440e78ef6c 100644
--- a/retrofit/src/main/java/retrofit2/MethodHandler.java
+++ b/retrofit/src/main/java/retrofit2/MethodHandler.java
@@ -15,7 +15,6 @@
*/
package retrofit2;
-import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.ResponseBody;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
@@ -29,7 +28,8 @@ static MethodHandler create(Retrofit retrofit, Method method) {
Converter<ResponseBody, ?> responseConverter =
createResponseConverter(method, retrofit, responseType);
RequestFactory requestFactory = RequestFactoryParser.parse(method, responseType, retrofit);
- return new MethodHandler(retrofit.client(), requestFactory, callAdapter, responseConverter);
+ return new MethodHandler(retrofit.callFactory(), requestFactory, callAdapter,
+ responseConverter);
}
private static CallAdapter<?> createCallAdapter(Method method, Retrofit retrofit) {
@@ -59,20 +59,25 @@ private static CallAdapter<?> createCallAdapter(Method method, Retrofit retrofit
}
}
- private final OkHttpClient client;
+ private final Call.Factory callFactory;
private final RequestFactory requestFactory;
private final CallAdapter<?> callAdapter;
private final Converter<ResponseBody, ?> responseConverter;
- private MethodHandler(OkHttpClient client, RequestFactory requestFactory,
+ private MethodHandler(Call.Factory callFactory, RequestFactory requestFactory,
CallAdapter<?> callAdapter, Converter<ResponseBody, ?> responseConverter) {
- this.client = client;
+ this.callFactory = callFactory;
this.requestFactory = requestFactory;
this.callAdapter = callAdapter;
this.responseConverter = responseConverter;
}
Object invoke(Object... args) {
- return callAdapter.adapt(new OkHttpCall<>(client, requestFactory, responseConverter, args));
+ DeferredRequest request = requestFactory.defer(args);
+ Call<?> call = callFactory.create(request, responseConverter);
+ if (call == null) {
+ throw new NullPointerException("Call.Factory returned null.");
+ }
+ return callAdapter.adapt(call);
}
}
diff --git a/retrofit/src/main/java/retrofit2/OkHttpCall.java b/retrofit/src/main/java/retrofit2/OkHttpCall.java
index fc2d70b6ff..3972ffed54 100644
--- a/retrofit/src/main/java/retrofit2/OkHttpCall.java
+++ b/retrofit/src/main/java/retrofit2/OkHttpCall.java
@@ -29,25 +29,23 @@
final class OkHttpCall<T> implements Call<T> {
private final OkHttpClient client;
- private final RequestFactory requestFactory;
+ private final DeferredRequest request;
private final Converter<ResponseBody, T> responseConverter;
- private final Object[] args;
private volatile com.squareup.okhttp.Call rawCall;
private boolean executed; // Guarded by this.
private volatile boolean canceled;
- OkHttpCall(OkHttpClient client, RequestFactory requestFactory,
- Converter<ResponseBody, T> responseConverter, Object[] args) {
+ OkHttpCall(OkHttpClient client, DeferredRequest request,
+ Converter<ResponseBody, T> responseConverter) {
this.client = client;
- this.requestFactory = requestFactory;
+ this.request = request;
this.responseConverter = responseConverter;
- this.args = args;
}
@SuppressWarnings("CloneDoesntCallSuperClone") // We are a final type & this saves clearing state.
@Override public OkHttpCall<T> clone() {
- return new OkHttpCall<>(client, requestFactory, responseConverter, args);
+ return new OkHttpCall<>(client, request, responseConverter);
}
@Override public void enqueue(final Callback<T> callback) {
@@ -122,7 +120,7 @@ private void callSuccess(Response<T> response) {
}
private com.squareup.okhttp.Call createRawCall() throws IOException {
- return client.newCall(requestFactory.create(args));
+ return client.newCall(request.get());
}
private Response<T> parseResponse(com.squareup.okhttp.Response rawResponse) throws IOException {
diff --git a/retrofit/src/main/java/retrofit2/OkHttpCallFactory.java b/retrofit/src/main/java/retrofit2/OkHttpCallFactory.java
new file mode 100644
index 0000000000..7c9e666bde
--- /dev/null
+++ b/retrofit/src/main/java/retrofit2/OkHttpCallFactory.java
@@ -0,0 +1,32 @@
+/*
+ * Copyright (C) 2015 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 retrofit2;
+
+import com.squareup.okhttp.OkHttpClient;
+import com.squareup.okhttp.ResponseBody;
+
+final class OkHttpCallFactory implements Call.Factory {
+ final OkHttpClient client;
+
+ OkHttpCallFactory(OkHttpClient client) {
+ this.client = client;
+ }
+
+ @Override
+ public <T> Call<T> create(DeferredRequest request, Converter<ResponseBody, T> converter) {
+ return new OkHttpCall<>(client, request, converter);
+ }
+}
diff --git a/retrofit/src/main/java/retrofit2/RequestFactory.java b/retrofit/src/main/java/retrofit2/RequestFactory.java
index 7a266483c7..23063def4b 100644
--- a/retrofit/src/main/java/retrofit2/RequestFactory.java
+++ b/retrofit/src/main/java/retrofit2/RequestFactory.java
@@ -45,6 +45,14 @@ final class RequestFactory {
this.requestActions = requestActions;
}
+ DeferredRequest defer(final Object... args) {
+ return new DeferredRequest() {
+ @Override public Request get() throws IOException {
+ return create(args);
+ }
+ };
+ }
+
Request create(Object... args) throws IOException {
RequestBuilder requestBuilder =
new RequestBuilder(method, baseUrl.url(), relativeUrl, headers, contentType, hasBody,
diff --git a/retrofit/src/main/java/retrofit2/Retrofit.java b/retrofit/src/main/java/retrofit2/Retrofit.java
index 606295a630..5427ad33e7 100644
--- a/retrofit/src/main/java/retrofit2/Retrofit.java
+++ b/retrofit/src/main/java/retrofit2/Retrofit.java
@@ -92,17 +92,17 @@
public final class Retrofit {
private final Map<Method, MethodHandler> methodHandlerCache = new LinkedHashMap<>();
- private final OkHttpClient client;
+ private final Call.Factory callFactory;
private final BaseUrl baseUrl;
private final List<Converter.Factory> converterFactories;
private final List<CallAdapter.Factory> adapterFactories;
private final Executor callbackExecutor;
private final boolean validateEagerly;
- private Retrofit(OkHttpClient client, BaseUrl baseUrl, List<Converter.Factory> converterFactories,
- List<CallAdapter.Factory> adapterFactories, Executor callbackExecutor,
- boolean validateEagerly) {
- this.client = client;
+ private Retrofit(Call.Factory callFactory, BaseUrl baseUrl,
+ List<Converter.Factory> converterFactories, List<CallAdapter.Factory> adapterFactories,
+ Executor callbackExecutor, boolean validateEagerly) {
+ this.callFactory = callFactory;
this.baseUrl = baseUrl;
this.converterFactories = converterFactories;
this.adapterFactories = adapterFactories;
@@ -156,8 +156,11 @@ MethodHandler loadMethodHandler(Method method) {
return handler;
}
- public OkHttpClient client() {
- return client;
+ /**
+ * TODO
+ */
+ public Call.Factory callFactory() {
+ return callFactory;
}
public BaseUrl baseUrl() {
@@ -344,7 +347,7 @@ public Executor callbackExecutor() {
* are optional.
*/
public static final class Builder {
- private OkHttpClient client;
+ private Call.Factory callFactory;
private BaseUrl baseUrl;
private List<Converter.Factory> converterFactories = new ArrayList<>();
private List<CallAdapter.Factory> adapterFactories = new ArrayList<>();
@@ -357,9 +360,25 @@ public Builder() {
converterFactories.add(new BuiltInConverters());
}
- /** The HTTP client used for requests. */
+ /**
+ * The HTTP client used for requests.
+ * <p>
+ * This is a convenience method for calling {@link #callFactory} with an instance that uses
+ * {@code client} for execution.
+ * <p>
+ * Note: This method <b>does not</b> make a defensive copy of {@code client}. Changes to its
+ * settings will affect subsequent requests. Pass in a {@linkplain OkHttpClient#clone() cloned}
+ * instance to prevent this if desired.
+ */
public Builder client(OkHttpClient client) {
- this.client = checkNotNull(client, "client == null");
+ return callFactory(new OkHttpCallFactory(checkNotNull(client, "client == null")));
+ }
+
+ /**
+ * TODO
+ */
+ public Builder callFactory(Call.Factory factory) {
+ this.callFactory = checkNotNull(factory, "factory == null");
return this;
}
@@ -488,9 +507,9 @@ public Retrofit build() {
throw new IllegalStateException("Base URL required.");
}
- OkHttpClient client = this.client;
- if (client == null) {
- client = new OkHttpClient();
+ Call.Factory callFactory = this.callFactory;
+ if (callFactory == null) {
+ callFactory = new OkHttpCallFactory(new OkHttpClient());
}
// Make a defensive copy of the adapters and add the default Call adapter.
@@ -500,8 +519,8 @@ public Retrofit build() {
// Make a defensive copy of the converters.
List<Converter.Factory> converterFactories = new ArrayList<>(this.converterFactories);
- return new Retrofit(client, baseUrl, converterFactories, adapterFactories, callbackExecutor,
- validateEagerly);
+ return new Retrofit(callFactory, baseUrl, converterFactories, adapterFactories,
+ callbackExecutor, validateEagerly);
}
}
}
| diff --git a/retrofit/src/test/java/retrofit2/RetrofitTest.java b/retrofit/src/test/java/retrofit2/RetrofitTest.java
index 24c3ccd362..600771966e 100644
--- a/retrofit/src/test/java/retrofit2/RetrofitTest.java
+++ b/retrofit/src/test/java/retrofit2/RetrofitTest.java
@@ -648,20 +648,92 @@ class MyConverterFactory extends Converter.Factory {
}
}
- @Test public void clientDefault() {
+ @Test public void callFactoryDefault() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://example.com")
.build();
- assertThat(retrofit.client()).isNotNull();
+ assertThat(retrofit.callFactory()).isNotNull();
}
- @Test public void clientPropagated() {
+ @Test public void callFactoryPropagated() {
+ Call.Factory callFactory = mock(Call.Factory.class);
+ Retrofit retrofit = new Retrofit.Builder()
+ .baseUrl("http://example.com/")
+ .callFactory(callFactory)
+ .build();
+ assertThat(retrofit.callFactory()).isSameAs(callFactory);
+ }
+
+ @Test public void callFactoryClientPropagated() {
OkHttpClient client = new OkHttpClient();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://example.com/")
.client(client)
.build();
- assertThat(retrofit.client()).isSameAs(client);
+ OkHttpCallFactory factory = (OkHttpCallFactory) retrofit.callFactory();
+ assertThat(factory.client).isSameAs(client);
+ }
+
+ @Test public void callFactoryUsed() {
+ final Retrofit blackbox = new Retrofit.Builder()
+ .baseUrl("http://example.com/")
+ .build();
+ Call.Factory callFactory = spy(new Call.Factory() {
+ @Override
+ public <T> Call<T> create(DeferredRequest request, Converter<ResponseBody, T> converter) {
+ // Wrap the default Call.Factory without directly relying on its implementation.
+ return blackbox.callFactory().create(request, converter);
+ }
+ });
+ Retrofit retrofit = new Retrofit.Builder()
+ .baseUrl("http://example.com/")
+ .callFactory(callFactory)
+ .build();
+ CallMethod service = retrofit.create(CallMethod.class);
+ service.getResponseBody();
+ verify(callFactory).create(any(DeferredRequest.class), any(Converter.class));
+ verifyNoMoreInteractions(callFactory);
+ }
+
+ @Test public void callFactoryReturningNullThrows() {
+ Call.Factory callFactory = new Call.Factory() {
+ @Override
+ public <T> Call<T> create(DeferredRequest request, Converter<ResponseBody, T> converter) {
+ return null;
+ }
+ };
+ Retrofit retrofit = new Retrofit.Builder()
+ .baseUrl("http://example.com/")
+ .callFactory(callFactory)
+ .build();
+ CallMethod service = retrofit.create(CallMethod.class);
+ try {
+ service.getResponseBody();
+ fail();
+ } catch (NullPointerException e) {
+ assertThat(e).hasMessage("Call.Factory returned null.");
+ }
+ }
+
+ @Test public void callFactoryThrowingPropagates() {
+ final RuntimeException cause = new RuntimeException("Broken!");
+ Call.Factory callFactory = new Call.Factory() {
+ @Override
+ public <T> Call<T> create(DeferredRequest request, Converter<ResponseBody, T> converter) {
+ throw cause;
+ }
+ };
+ Retrofit retrofit = new Retrofit.Builder()
+ .baseUrl("http://example.com/")
+ .callFactory(callFactory)
+ .build();
+ CallMethod service = retrofit.create(CallMethod.class);
+ try {
+ service.getResponseBody();
+ fail();
+ } catch (Exception e) {
+ assertThat(e).isSameAs(cause);
+ }
}
@Test public void converterNullThrows() {
| val | train | 2015-12-21T17:48:00 | "2015-12-12T20:42:34Z" | johnrengelman | val |
square/retrofit/1399_1406 | square/retrofit | square/retrofit/1399 | square/retrofit/1406 | [
"timestamp(timedelta=19076.0, similarity=0.8629422700362994)"
] | ccd17ca9d5ed60e3f5468ed3cd2e90be22a87c1d | 8e83bd12442a2e4d9e71c3c00b04ccf1a60fae08 | [
"No longer needed as of #1406 \n"
] | [] | "2015-12-24T00:07:43Z" | [
"Feature"
] | Expose public API for creating a Call.Factory from OkHttpClient instance? | This would simplify delegation by allowing implementors of `Call.Factory` instances to create a delegate from an `OkHttpClient` (and thus get `OkHttpCall` for free). Without this there's no way to create your own `C.F` that re-uses internal machinery around OkHttp.
| [
"retrofit/src/main/java/retrofit2/Call.java",
"retrofit/src/main/java/retrofit2/DeferredRequest.java",
"retrofit/src/main/java/retrofit2/MethodHandler.java",
"retrofit/src/main/java/retrofit2/OkHttpCall.java",
"retrofit/src/main/java/retrofit2/OkHttpCallFactory.java",
"retrofit/src/main/java/retrofit2/RequestFactory.java",
"retrofit/src/main/java/retrofit2/Retrofit.java"
] | [
"retrofit/src/main/java/retrofit2/Call.java",
"retrofit/src/main/java/retrofit2/MethodHandler.java",
"retrofit/src/main/java/retrofit2/OkHttpCall.java",
"retrofit/src/main/java/retrofit2/RequestFactory.java",
"retrofit/src/main/java/retrofit2/Retrofit.java"
] | [
"retrofit/src/test/java/retrofit2/RetrofitTest.java"
] | diff --git a/retrofit/src/main/java/retrofit2/Call.java b/retrofit/src/main/java/retrofit2/Call.java
index 2280a6e159..873bb0c6fe 100644
--- a/retrofit/src/main/java/retrofit2/Call.java
+++ b/retrofit/src/main/java/retrofit2/Call.java
@@ -16,7 +16,6 @@
package retrofit2;
import java.io.IOException;
-import okhttp3.ResponseBody;
/**
* An invocation of a Retrofit method that sends a request to a webserver and returns a response.
@@ -67,13 +66,4 @@ public interface Call<T> extends Cloneable {
* has already been.
*/
Call<T> clone();
-
- /** Creates {@link Call} instances. */
- interface Factory {
- /**
- * Returns a {@link Call} which will send {@code request} when executed or enqueue and use
- * {@code converter} to parse the response. May not return null.
- */
- <T> Call<T> create(DeferredRequest request, Converter<ResponseBody, T> converter);
- }
}
diff --git a/retrofit/src/main/java/retrofit2/DeferredRequest.java b/retrofit/src/main/java/retrofit2/DeferredRequest.java
deleted file mode 100644
index 2c9a8cfa18..0000000000
--- a/retrofit/src/main/java/retrofit2/DeferredRequest.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*
- * Copyright (C) 2015 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 retrofit2;
-
-import java.io.IOException;
-import okhttp3.Request;
-
-/**
- * An un-built HTTP request. This class defers any work necessary to create an HTTP request until
- * {@link #get()} is called.
- */
-public interface DeferredRequest {
- /** Perform the work necessary to create and then return the {@link Request}. */
- Request get() throws IOException;
-}
diff --git a/retrofit/src/main/java/retrofit2/MethodHandler.java b/retrofit/src/main/java/retrofit2/MethodHandler.java
index 35fcd0c259..a64afdc2c5 100644
--- a/retrofit/src/main/java/retrofit2/MethodHandler.java
+++ b/retrofit/src/main/java/retrofit2/MethodHandler.java
@@ -58,12 +58,12 @@ private static CallAdapter<?> createCallAdapter(Method method, Retrofit retrofit
}
}
- private final Call.Factory callFactory;
+ private final okhttp3.Call.Factory callFactory;
private final RequestFactory requestFactory;
private final CallAdapter<?> callAdapter;
private final Converter<ResponseBody, ?> responseConverter;
- private MethodHandler(Call.Factory callFactory, RequestFactory requestFactory,
+ private MethodHandler(okhttp3.Call.Factory callFactory, RequestFactory requestFactory,
CallAdapter<?> callAdapter, Converter<ResponseBody, ?> responseConverter) {
this.callFactory = callFactory;
this.requestFactory = requestFactory;
@@ -72,11 +72,7 @@ private MethodHandler(Call.Factory callFactory, RequestFactory requestFactory,
}
Object invoke(Object... args) {
- DeferredRequest request = requestFactory.defer(args);
- Call<?> call = callFactory.create(request, responseConverter);
- if (call == null) {
- throw new NullPointerException("Call.Factory returned null.");
- }
- return callAdapter.adapt(call);
+ return callAdapter.adapt(
+ new OkHttpCall<>(callFactory, requestFactory, args, responseConverter));
}
}
diff --git a/retrofit/src/main/java/retrofit2/OkHttpCall.java b/retrofit/src/main/java/retrofit2/OkHttpCall.java
index ea064fcd6d..6bfa8da9d8 100644
--- a/retrofit/src/main/java/retrofit2/OkHttpCall.java
+++ b/retrofit/src/main/java/retrofit2/OkHttpCall.java
@@ -17,7 +17,6 @@
import java.io.IOException;
import okhttp3.MediaType;
-import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.ResponseBody;
import okio.Buffer;
@@ -28,24 +27,26 @@
import static retrofit2.Utils.closeQuietly;
final class OkHttpCall<T> implements Call<T> {
- private final OkHttpClient client;
- private final DeferredRequest request;
+ private final okhttp3.Call.Factory callFactory;
+ private final RequestFactory requestFactory;
+ private final Object[] args;
private final Converter<ResponseBody, T> responseConverter;
private volatile okhttp3.Call rawCall;
private boolean executed; // Guarded by this.
private volatile boolean canceled;
- OkHttpCall(OkHttpClient client, DeferredRequest request,
+ OkHttpCall(okhttp3.Call.Factory callFactory, RequestFactory requestFactory, Object[] args,
Converter<ResponseBody, T> responseConverter) {
- this.client = client;
- this.request = request;
+ this.callFactory = callFactory;
+ this.requestFactory = requestFactory;
+ this.args = args;
this.responseConverter = responseConverter;
}
@SuppressWarnings("CloneDoesntCallSuperClone") // We are a final type & this saves clearing state.
@Override public OkHttpCall<T> clone() {
- return new OkHttpCall<>(client, request, responseConverter);
+ return new OkHttpCall<>(callFactory, requestFactory, args, responseConverter);
}
@Override public void enqueue(final Callback<T> callback) {
@@ -120,7 +121,11 @@ private void callSuccess(Response<T> response) {
}
private okhttp3.Call createRawCall() throws IOException {
- return client.newCall(request.get());
+ okhttp3.Call call = callFactory.newCall(requestFactory.create(args));
+ if (call == null) {
+ throw new NullPointerException("Call.Factory returned null.");
+ }
+ return call;
}
Response<T> parseResponse(okhttp3.Response rawResponse) throws IOException {
diff --git a/retrofit/src/main/java/retrofit2/OkHttpCallFactory.java b/retrofit/src/main/java/retrofit2/OkHttpCallFactory.java
deleted file mode 100644
index c8810d6f62..0000000000
--- a/retrofit/src/main/java/retrofit2/OkHttpCallFactory.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * Copyright (C) 2015 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 retrofit2;
-
-import okhttp3.OkHttpClient;
-import okhttp3.ResponseBody;
-
-final class OkHttpCallFactory implements Call.Factory {
- final OkHttpClient client;
-
- OkHttpCallFactory(OkHttpClient client) {
- this.client = client;
- }
-
- @Override
- public <T> Call<T> create(DeferredRequest request, Converter<ResponseBody, T> converter) {
- return new OkHttpCall<>(client, request, converter);
- }
-}
diff --git a/retrofit/src/main/java/retrofit2/RequestFactory.java b/retrofit/src/main/java/retrofit2/RequestFactory.java
index b8bf330290..7df67b6397 100644
--- a/retrofit/src/main/java/retrofit2/RequestFactory.java
+++ b/retrofit/src/main/java/retrofit2/RequestFactory.java
@@ -45,14 +45,6 @@ final class RequestFactory {
this.requestActions = requestActions;
}
- DeferredRequest defer(final Object... args) {
- return new DeferredRequest() {
- @Override public Request get() throws IOException {
- return create(args);
- }
- };
- }
-
Request create(Object... args) throws IOException {
RequestBuilder requestBuilder =
new RequestBuilder(method, baseUrl.url(), relativeUrl, headers, contentType, hasBody,
diff --git a/retrofit/src/main/java/retrofit2/Retrofit.java b/retrofit/src/main/java/retrofit2/Retrofit.java
index 3b798985b4..2ce5ef8e53 100644
--- a/retrofit/src/main/java/retrofit2/Retrofit.java
+++ b/retrofit/src/main/java/retrofit2/Retrofit.java
@@ -59,16 +59,16 @@
public final class Retrofit {
private final Map<Method, MethodHandler> methodHandlerCache = new LinkedHashMap<>();
- private final Call.Factory callFactory;
+ private final okhttp3.Call.Factory callFactory;
private final BaseUrl baseUrl;
private final List<Converter.Factory> converterFactories;
private final List<CallAdapter.Factory> adapterFactories;
private final Executor callbackExecutor;
private final boolean validateEagerly;
- Retrofit(Call.Factory callFactory, BaseUrl baseUrl, List<Converter.Factory> converterFactories,
- List<CallAdapter.Factory> adapterFactories, Executor callbackExecutor,
- boolean validateEagerly) {
+ Retrofit(okhttp3.Call.Factory callFactory, BaseUrl baseUrl,
+ List<Converter.Factory> converterFactories, List<CallAdapter.Factory> adapterFactories,
+ Executor callbackExecutor, boolean validateEagerly) {
this.callFactory = callFactory;
this.baseUrl = baseUrl;
this.converterFactories = converterFactories;
@@ -168,8 +168,11 @@ MethodHandler loadMethodHandler(Method method) {
return handler;
}
- /** The factory used to create {@link Call} instances. */
- public Call.Factory callFactory() {
+ /**
+ * The factory used to create {@linkplain okhttp3.Call OkHttp calls} for sending a HTTP requests.
+ * Typically an instance of {@link OkHttpClient}.
+ */
+ public okhttp3.Call.Factory callFactory() {
return callFactory;
}
@@ -358,7 +361,7 @@ public Executor callbackExecutor() {
* are optional.
*/
public static final class Builder {
- private Call.Factory callFactory;
+ private okhttp3.Call.Factory callFactory;
private BaseUrl baseUrl;
private List<Converter.Factory> converterFactories = new ArrayList<>();
private List<CallAdapter.Factory> adapterFactories = new ArrayList<>();
@@ -374,15 +377,14 @@ public Builder() {
/**
* The HTTP client used for requests.
* <p>
- * This is a convenience method for calling {@link #callFactory} with an instance that uses
- * {@code client} for execution.
+ * This is a convenience method for calling {@link #callFactory}.
* <p>
* Note: This method <b>does not</b> make a defensive copy of {@code client}. Changes to its
* settings will affect subsequent requests. Pass in a {@linkplain OkHttpClient#clone() cloned}
* instance to prevent this if desired.
*/
public Builder client(OkHttpClient client) {
- return callFactory(new OkHttpCallFactory(checkNotNull(client, "client == null")));
+ return callFactory(checkNotNull(client, "client == null"));
}
/**
@@ -390,7 +392,7 @@ public Builder client(OkHttpClient client) {
* <p>
* Note: Calling {@link #client} automatically sets this value.
*/
- public Builder callFactory(Call.Factory factory) {
+ public Builder callFactory(okhttp3.Call.Factory factory) {
this.callFactory = checkNotNull(factory, "factory == null");
return this;
}
@@ -529,9 +531,9 @@ public Retrofit build() {
throw new IllegalStateException("Base URL required.");
}
- Call.Factory callFactory = this.callFactory;
+ okhttp3.Call.Factory callFactory = this.callFactory;
if (callFactory == null) {
- callFactory = new OkHttpCallFactory(new OkHttpClient());
+ callFactory = new OkHttpClient();
}
// Make a defensive copy of the adapters and add the default Call adapter.
| diff --git a/retrofit/src/test/java/retrofit2/RetrofitTest.java b/retrofit/src/test/java/retrofit2/RetrofitTest.java
index 7110550013..d2abb06854 100644
--- a/retrofit/src/test/java/retrofit2/RetrofitTest.java
+++ b/retrofit/src/test/java/retrofit2/RetrofitTest.java
@@ -18,6 +18,7 @@
import okhttp3.HttpUrl;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
+import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import okhttp3.mockwebserver.MockResponse;
@@ -656,7 +657,7 @@ class MyConverterFactory extends Converter.Factory {
}
@Test public void callFactoryPropagated() {
- Call.Factory callFactory = mock(Call.Factory.class);
+ okhttp3.Call.Factory callFactory = mock(okhttp3.Call.Factory.class);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://example.com/")
.callFactory(callFactory)
@@ -670,35 +671,31 @@ class MyConverterFactory extends Converter.Factory {
.baseUrl("http://example.com/")
.client(client)
.build();
- OkHttpCallFactory factory = (OkHttpCallFactory) retrofit.callFactory();
- assertThat(factory.client).isSameAs(client);
+ assertThat(retrofit.callFactory()).isSameAs(client);
}
- @Test public void callFactoryUsed() {
- final Retrofit blackbox = new Retrofit.Builder()
- .baseUrl("http://example.com/")
- .build();
- Call.Factory callFactory = spy(new Call.Factory() {
- @Override
- public <T> Call<T> create(DeferredRequest request, Converter<ResponseBody, T> converter) {
- // Wrap the default Call.Factory without directly relying on its implementation.
- return blackbox.callFactory().create(request, converter);
+ @Test public void callFactoryUsed() throws IOException {
+ okhttp3.Call.Factory callFactory = spy(new okhttp3.Call.Factory() {
+ @Override public okhttp3.Call newCall(Request request) {
+ return new OkHttpClient().newCall(request);
}
});
Retrofit retrofit = new Retrofit.Builder()
- .baseUrl("http://example.com/")
+ .baseUrl(server.url("/"))
.callFactory(callFactory)
.build();
+
+ server.enqueue(new MockResponse());
+
CallMethod service = retrofit.create(CallMethod.class);
- service.getResponseBody();
- verify(callFactory).create(any(DeferredRequest.class), any(Converter.class));
+ service.getResponseBody().execute();
+ verify(callFactory).newCall(any(Request.class));
verifyNoMoreInteractions(callFactory);
}
- @Test public void callFactoryReturningNullThrows() {
- Call.Factory callFactory = new Call.Factory() {
- @Override
- public <T> Call<T> create(DeferredRequest request, Converter<ResponseBody, T> converter) {
+ @Test public void callFactoryReturningNullThrows() throws IOException {
+ okhttp3.Call.Factory callFactory = new okhttp3.Call.Factory() {
+ @Override public okhttp3.Call newCall(Request request) {
return null;
}
};
@@ -706,9 +703,13 @@ public <T> Call<T> create(DeferredRequest request, Converter<ResponseBody, T> co
.baseUrl("http://example.com/")
.callFactory(callFactory)
.build();
+
+ server.enqueue(new MockResponse());
+
CallMethod service = retrofit.create(CallMethod.class);
+ Call<ResponseBody> call = service.getResponseBody();
try {
- service.getResponseBody();
+ call.execute();
fail();
} catch (NullPointerException e) {
assertThat(e).hasMessage("Call.Factory returned null.");
@@ -717,9 +718,8 @@ public <T> Call<T> create(DeferredRequest request, Converter<ResponseBody, T> co
@Test public void callFactoryThrowingPropagates() {
final RuntimeException cause = new RuntimeException("Broken!");
- Call.Factory callFactory = new Call.Factory() {
- @Override
- public <T> Call<T> create(DeferredRequest request, Converter<ResponseBody, T> converter) {
+ okhttp3.Call.Factory callFactory = new okhttp3.Call.Factory() {
+ @Override public okhttp3.Call newCall(Request request) {
throw cause;
}
};
@@ -727,9 +727,13 @@ public <T> Call<T> create(DeferredRequest request, Converter<ResponseBody, T> co
.baseUrl("http://example.com/")
.callFactory(callFactory)
.build();
+
+ server.enqueue(new MockResponse());
+
CallMethod service = retrofit.create(CallMethod.class);
+ Call<ResponseBody> call = service.getResponseBody();
try {
- service.getResponseBody();
+ call.execute();
fail();
} catch (Exception e) {
assertThat(e).isSameAs(cause);
| train | train | 2015-12-24T00:23:36 | "2015-12-22T05:35:05Z" | JakeWharton | val |
square/retrofit/1439_1440 | square/retrofit | square/retrofit/1439 | square/retrofit/1440 | [
"keyword_pr_to_issue",
"timestamp(timedelta=0.0, similarity=0.8514079765732192)"
] | 066416243e1a076ab0920c12a59640057b7ca447 | 026829d611db0db5c2d8392a26bb955a3b380d17 | [] | [] | "2016-01-06T03:17:34Z" | [] | changelog | not 2015,it`s 2016
| [
"CHANGELOG.md"
] | [
"CHANGELOG.md"
] | [] | diff --git a/CHANGELOG.md b/CHANGELOG.md
index d0745e7988..a8fef71ff6 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,7 +1,7 @@
Change Log
==========
-Version 2.0.0-beta3 *(2015-01-05)*
+Version 2.0.0-beta3 *(2016-01-05)*
----------------------------------
* New: All classes have been migrated to the `retrofit2.*` package name. The Maven groupId is now
| null | train | train | 2016-01-05T18:24:01 | "2016-01-06T01:43:00Z" | shenghaiyang | val |
square/retrofit/1459_1478 | square/retrofit | square/retrofit/1459 | square/retrofit/1478 | [
"timestamp(timedelta=8.0, similarity=0.8910221312905938)"
] | bbc64007c33e5e3a78b1b0ce858bc6232443a83b | 3ce1a38d8e6927587d499487b8c7fdc42572f3ee | [
"I'm not sure there's enough of a use case to warrant doing this. Why do you want it?\n",
"I made a scalar response body converter to deal with a legacy API that mixes application/json and text/plain. I'm happy to make a pull request if this is a common use case.\n",
"I have exactly the same case described by @connorMathews. Also it will make the library \"converter-scalars\" more general. Thanks.\n",
"You can use ResponseBody and call .string().\n\nOn Mon, Jan 11, 2016, 10:33 AM Connor [email protected] wrote:\n\n> I made a scalar response body converter to deal with a legacy API that\n> mixes application/json and text/plain. I'm happy to make a pull request if\n> this is a common use case.\n> \n> —\n> Reply to this email directly or view it on GitHub\n> https://github.com/square/retrofit/issues/1459#issuecomment-170645686.\n",
"I have also GsonConverterFactory for application/json responses:\n Retrofit.Builder builder = new Retrofit.Builder()\n .baseUrl(sServiceUrl)\n .callFactory(getOkHttpClient())\n .addConverterFactory(ScalarsConverterFactory.create())\n .addConverterFactory(GsonConverterFactory.create(gson));\nAnd when I get a text/plain response it gets MalformedJsonException. \n",
"Use ResponseBody for those.\n",
"Yep, a converter just moves the .string() call out of the calling code. In my case, I have endpoints that return integer item ids and others that return strings. I wanted to make the distinction explicitly in the service interface definition. I think type safety is a compelling reason but I understand if this isn't common enough to include in the project.\n",
"I'm fine with the change. Feel free to make a PR, otherwise I'll get to it before 2.0 final.\n",
"This was merged in.\n"
] | [
"Copy license header from another file. Use 2016 for the date.\n",
"I'm thinking that this should assert that the string is exactly 1 character and throw an `IOException` for a non-1 length. And a test case for both the 0 and non-1 lengths.\n",
"Actually I'll just make this change locally during the merge.\n",
":+1: \n"
] | "2016-01-14T20:16:24Z" | [
"Enhancement"
] | Add converter for scalars to response body | [
"retrofit-converters/scalars/src/main/java/retrofit2/ScalarsConverterFactory.java"
] | [
"retrofit-converters/scalars/src/main/java/retrofit2/ScalarResponseBodyConverters.java",
"retrofit-converters/scalars/src/main/java/retrofit2/ScalarsConverterFactory.java"
] | [
"retrofit-converters/scalars/src/test/java/retrofit2/ScalarsConverterFactoryTest.java"
] | diff --git a/retrofit-converters/scalars/src/main/java/retrofit2/ScalarResponseBodyConverters.java b/retrofit-converters/scalars/src/main/java/retrofit2/ScalarResponseBodyConverters.java
new file mode 100644
index 0000000000..5562dab554
--- /dev/null
+++ b/retrofit-converters/scalars/src/main/java/retrofit2/ScalarResponseBodyConverters.java
@@ -0,0 +1,96 @@
+/*
+ * Copyright (C) 2016 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 retrofit2;
+
+import java.io.IOException;
+import okhttp3.ResponseBody;
+
+final class ScalarResponseBodyConverters {
+ private ScalarResponseBodyConverters() {
+ }
+
+ static final class StringResponseBodyConverter implements Converter<ResponseBody, String> {
+ static final StringResponseBodyConverter INSTANCE = new StringResponseBodyConverter();
+
+ @Override public String convert(ResponseBody value) throws IOException {
+ return value.string();
+ }
+ }
+
+ static final class BooleanResponseBodyConverter implements Converter<ResponseBody, Boolean> {
+ static final BooleanResponseBodyConverter INSTANCE = new BooleanResponseBodyConverter();
+
+ @Override public Boolean convert(ResponseBody value) throws IOException {
+ return Boolean.valueOf(value.string());
+ }
+ }
+
+ static final class ByteResponseBodyConverter implements Converter<ResponseBody, Byte> {
+ static final ByteResponseBodyConverter INSTANCE = new ByteResponseBodyConverter();
+
+ @Override public Byte convert(ResponseBody value) throws IOException {
+ return Byte.valueOf(value.string());
+ }
+ }
+
+ static final class CharacterResponseBodyConverter implements Converter<ResponseBody, Character> {
+ static final CharacterResponseBodyConverter INSTANCE = new CharacterResponseBodyConverter();
+
+ @Override public Character convert(ResponseBody value) throws IOException {
+ return value.string().charAt(0);
+ }
+ }
+
+ static final class DoubleResponseBodyConverter implements Converter<ResponseBody, Double> {
+ static final DoubleResponseBodyConverter INSTANCE = new DoubleResponseBodyConverter();
+
+ @Override public Double convert(ResponseBody value) throws IOException {
+ return Double.valueOf(value.string());
+ }
+ }
+
+ static final class FloatResponseBodyConverter implements Converter<ResponseBody, Float> {
+ static final FloatResponseBodyConverter INSTANCE = new FloatResponseBodyConverter();
+
+ @Override public Float convert(ResponseBody value) throws IOException {
+ return Float.valueOf(value.string());
+ }
+ }
+
+ static final class IntegerResponseBodyConverter implements Converter<ResponseBody, Integer> {
+ static final IntegerResponseBodyConverter INSTANCE = new IntegerResponseBodyConverter();
+
+ @Override public Integer convert(ResponseBody value) throws IOException {
+ return Integer.valueOf(value.string());
+ }
+ }
+
+ static final class LongResponseBodyConverter implements Converter<ResponseBody, Long> {
+ static final LongResponseBodyConverter INSTANCE = new LongResponseBodyConverter();
+
+ @Override public Long convert(ResponseBody value) throws IOException {
+ return Long.valueOf(value.string());
+ }
+ }
+
+ static final class ShortResponseBodyConverter implements Converter<ResponseBody, Short> {
+ static final ShortResponseBodyConverter INSTANCE = new ShortResponseBodyConverter();
+
+ @Override public Short convert(ResponseBody value) throws IOException {
+ return Short.valueOf(value.string());
+ }
+ }
+}
diff --git a/retrofit-converters/scalars/src/main/java/retrofit2/ScalarsConverterFactory.java b/retrofit-converters/scalars/src/main/java/retrofit2/ScalarsConverterFactory.java
index 5402455dab..3acc527902 100644
--- a/retrofit-converters/scalars/src/main/java/retrofit2/ScalarsConverterFactory.java
+++ b/retrofit-converters/scalars/src/main/java/retrofit2/ScalarsConverterFactory.java
@@ -18,6 +18,16 @@
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import okhttp3.RequestBody;
+import okhttp3.ResponseBody;
+import retrofit2.ScalarResponseBodyConverters.BooleanResponseBodyConverter;
+import retrofit2.ScalarResponseBodyConverters.ByteResponseBodyConverter;
+import retrofit2.ScalarResponseBodyConverters.CharacterResponseBodyConverter;
+import retrofit2.ScalarResponseBodyConverters.DoubleResponseBodyConverter;
+import retrofit2.ScalarResponseBodyConverters.FloatResponseBodyConverter;
+import retrofit2.ScalarResponseBodyConverters.IntegerResponseBodyConverter;
+import retrofit2.ScalarResponseBodyConverters.LongResponseBodyConverter;
+import retrofit2.ScalarResponseBodyConverters.ShortResponseBodyConverter;
+import retrofit2.ScalarResponseBodyConverters.StringResponseBodyConverter;
/**
* A {@linkplain Converter.Factory converter} for strings and both primitives and their boxed types
@@ -55,4 +65,37 @@ public Converter<?, RequestBody> requestBodyConverter(Type type, Annotation[] an
}
return null;
}
+
+ @Override
+ public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations,
+ Retrofit retrofit) {
+ if (type == String.class) {
+ return StringResponseBodyConverter.INSTANCE;
+ }
+ if (type == Boolean.class) {
+ return BooleanResponseBodyConverter.INSTANCE;
+ }
+ if (type == Byte.class) {
+ return ByteResponseBodyConverter.INSTANCE;
+ }
+ if (type == Character.class) {
+ return CharacterResponseBodyConverter.INSTANCE;
+ }
+ if (type == Double.class) {
+ return DoubleResponseBodyConverter.INSTANCE;
+ }
+ if (type == Float.class) {
+ return FloatResponseBodyConverter.INSTANCE;
+ }
+ if (type == Integer.class) {
+ return IntegerResponseBodyConverter.INSTANCE;
+ }
+ if (type == Long.class) {
+ return LongResponseBodyConverter.INSTANCE;
+ }
+ if (type == Short.class) {
+ return ShortResponseBodyConverter.INSTANCE;
+ }
+ return null;
+ }
}
| diff --git a/retrofit-converters/scalars/src/test/java/retrofit2/ScalarsConverterFactoryTest.java b/retrofit-converters/scalars/src/test/java/retrofit2/ScalarsConverterFactoryTest.java
index 0fe8b9be1f..d6b2146d7e 100644
--- a/retrofit-converters/scalars/src/test/java/retrofit2/ScalarsConverterFactoryTest.java
+++ b/retrofit-converters/scalars/src/test/java/retrofit2/ScalarsConverterFactoryTest.java
@@ -24,6 +24,7 @@
import org.junit.Rule;
import org.junit.Test;
import retrofit2.http.Body;
+import retrofit2.http.GET;
import retrofit2.http.POST;
import static org.assertj.core.api.Assertions.assertThat;
@@ -50,6 +51,18 @@ interface Service {
@POST("/") Call<ResponseBody> longObject(@Body Long body);
@POST("/") Call<ResponseBody> shortPrimitive(@Body short body);
@POST("/") Call<ResponseBody> shortObject(@Body Short body);
+
+ @GET("/") Call<Object> object();
+
+ @GET("/") Call<String> stringObject();
+ @GET("/") Call<Boolean> booleanObject();
+ @GET("/") Call<Byte> byteObject();
+ @GET("/") Call<Character> charObject();
+ @GET("/") Call<Double> doubleObject();
+ @GET("/") Call<Float> floatObject();
+ @GET("/") Call<Integer> integerObject();
+ @GET("/") Call<Long> longObject();
+ @GET("/") Call<Short> shortObject();
}
@Rule public final MockWebServer server = new MockWebServer();
@@ -64,7 +77,7 @@ interface Service {
service = retrofit.create(Service.class);
}
- @Test public void unsupportedTypesNotMatched() {
+ @Test public void unsupportedRequestTypesNotMatched() {
try {
service.object(null);
fail();
@@ -79,7 +92,7 @@ interface Service {
}
}
- @Test public void supportedTypes() throws IOException, InterruptedException {
+ @Test public void supportedRequestTypes() throws IOException, InterruptedException {
RecordedRequest request;
server.enqueue(new MockResponse());
@@ -201,4 +214,56 @@ interface Service {
assertThat(request.getHeader("Content-Length")).isEqualTo("2");
assertThat(request.getBody().readUtf8()).isEqualTo("11");
}
+
+ @Test public void unsupportedResponseTypesNotMatched() {
+ try {
+ service.object();
+ fail();
+ } catch (IllegalArgumentException e) {
+ assertThat(e).hasMessage(
+ "Unable to create converter for class java.lang.Object\n"
+ + " for method Service.object");
+ assertThat(e.getCause()).hasMessage(
+ "Could not locate ResponseBody converter for class java.lang.Object. Tried:\n"
+ + " * retrofit2.BuiltInConverters\n" + " * retrofit2.ScalarsConverterFactory");
+ }
+ }
+
+ @Test public void supportedResponseTypes() throws IOException, InterruptedException {
+ server.enqueue(new MockResponse().setBody("test"));
+ Response<String> stringResponse = service.stringObject().execute();
+ assertThat(stringResponse.body()).isEqualTo("test");
+
+ server.enqueue(new MockResponse().setBody("true"));
+ Response<Boolean> booleanResponse = service.booleanObject().execute();
+ assertThat(booleanResponse.body()).isTrue();
+
+ server.enqueue(new MockResponse().setBody("5"));
+ Response<Byte> byteResponse = service.byteObject().execute();
+ assertThat(byteResponse.body()).isEqualTo((byte) 5);
+
+ server.enqueue(new MockResponse().setBody("b"));
+ Response<Character> characterResponse = service.charObject().execute();
+ assertThat(characterResponse.body()).isEqualTo('b');
+
+ server.enqueue(new MockResponse().setBody("13.13"));
+ Response<Double> doubleResponse = service.doubleObject().execute();
+ assertThat(doubleResponse.body()).isEqualTo(13.13);
+
+ server.enqueue(new MockResponse().setBody("13.13"));
+ Response<Float> floatResponse = service.floatObject().execute();
+ assertThat(floatResponse.body()).isEqualTo(13.13f);
+
+ server.enqueue(new MockResponse().setBody("13"));
+ Response<Integer> integerResponse = service.integerObject().execute();
+ assertThat(integerResponse.body()).isEqualTo(13);
+
+ server.enqueue(new MockResponse().setBody("1347"));
+ Response<Long> longResponse = service.longObject().execute();
+ assertThat(longResponse.body()).isEqualTo(1347L);
+
+ server.enqueue(new MockResponse().setBody("134"));
+ Response<Short> shortResponse = service.shortObject().execute();
+ assertThat(shortResponse.body()).isEqualTo((short) 134);
+ }
}
| test | train | 2016-01-14T08:12:45 | "2016-01-11T11:27:48Z" | suren1525 | val |
|
square/retrofit/1367_1484 | square/retrofit | square/retrofit/1367 | square/retrofit/1484 | [
"timestamp(timedelta=0.0, similarity=0.8821951231038933)"
] | a0594600652b5f1716298e9c444abc0fb5cfc279 | b5105c4c9005f46c78f29a8e47752253b9ed85d0 | [
"Why expose the `Call` instead of the `Request`?\n",
"To access to the original request. But dummy from my side, the original request is not public as well.\n\nHum. which solution would be the best? I can pull request as well okhttp. Thank you a lot for your help.\n",
"In general it would be great to have an access from the proxies to the client.\n\nFor instance, the cache of okhttp is not available as well through those objects. Is there something planned in this way?\n",
"> which solution would be the best?\n\nI would prefer exposing the `Request` given the choice between the two, but I need to think more about the implications of exposing this.\n\n> In general it would be great to have an access from the proxies to the client.\n\nYou can access the client by calling `client()` on the `Retrofit` instance. The same client is shared by all created proxies.\n",
"Thank you very much for your help and your response!\n",
"The largest detractor against something like what this issue proposes is when test code (be it unit, functional, integration, or whatever) creates a fake `Call` instance. This is currently done via the `Calls` class for successful and failing responses.\n\nWhat `Request` objects would be returned from these method if this proposal was accepted? We can synthesize a good portion of them. In fact, we already do so, depending on what is provided.\n",
"Oh, god we really need this. At the moment I am working on a caching library for Retrofit2 and unfortunately this is how I build a new Request: https://github.com/dimitrovskif/Retrofit-SmartCache/blob/master/retrofit-smartcache/src/main/java/dimitrovskif/smartcache/SmartCallFactory.java#L94\n\nIt works using ugly reflection, and uses the fact that the `Call<T>` which the `CallAdapter.Factory` gets is always an `OkHttpCall<T>`, so `requestFactory.create(args)` returns a `Request` which can be later used for caching purposes. (reflection takes care of the `private` restriction)\n\nMy suggestion would be:\n- Provide `Request buildRequest()` in `Call<T>` which will return a valid call with all query params, proper method and endpoint, etc.\n- Provide `Type responseType()` and `Annotation[] annotations()` in `Call<T>` to take care of the nasty type erasure problems (I **really** need this, especially for further serialization/deserialization in calls)\n- Provide `Retrofit retrofit()` in `Call<T>`\n",
"Still not fixed? `OkHttpCall` has private request factory and the `Call` interface itself supports nothing.\n"
] | [
"fail()\n",
"fail()\n",
"fail()\n",
"fail()\n",
"fail()\n",
"throw new AssertionError ?\n",
"fail()\n",
"The latch will just timeout if the wrong thing is called. If you throw here you'll get double stack traces so I left it out.\n"
] | "2016-01-16T22:46:05Z" | [] | Provide new method to get the original request from Retrofit Call proxies | Hi,
When using Retrofit Call proxies, it's not possible to be aware of the original request through those objects. When implementing a custom response cache (not depending on response cache of okhttp), generating a cache key with the request is necessary. However we cannot access to this original request, headers, params through Call objects (okhttpcall being final as well).
Would be nice to provide in the interface Call the method CreateRawCall already implemented in private.
| [
"retrofit-mock/src/main/java/retrofit2/mock/BehaviorCall.java",
"retrofit-mock/src/main/java/retrofit2/mock/Calls.java",
"retrofit/src/main/java/retrofit2/Call.java",
"retrofit/src/main/java/retrofit2/ExecutorCallAdapterFactory.java",
"retrofit/src/main/java/retrofit2/OkHttpCall.java"
] | [
"retrofit-mock/src/main/java/retrofit2/mock/BehaviorCall.java",
"retrofit-mock/src/main/java/retrofit2/mock/Calls.java",
"retrofit/src/main/java/retrofit2/Call.java",
"retrofit/src/main/java/retrofit2/ExecutorCallAdapterFactory.java",
"retrofit/src/main/java/retrofit2/OkHttpCall.java"
] | [
"retrofit/src/test/java/retrofit2/CallTest.java",
"retrofit/src/test/java/retrofit2/ExecutorCallAdapterFactoryTest.java"
] | diff --git a/retrofit-mock/src/main/java/retrofit2/mock/BehaviorCall.java b/retrofit-mock/src/main/java/retrofit2/mock/BehaviorCall.java
index 2d8dd98f91..ac10878fa9 100644
--- a/retrofit-mock/src/main/java/retrofit2/mock/BehaviorCall.java
+++ b/retrofit-mock/src/main/java/retrofit2/mock/BehaviorCall.java
@@ -20,6 +20,7 @@
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicReference;
+import okhttp3.Request;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
@@ -46,6 +47,10 @@ final class BehaviorCall<T> implements Call<T> {
return new BehaviorCall<>(behavior, backgroundExecutor, delegate.clone());
}
+ @Override public Request request() {
+ return delegate.request();
+ }
+
@Override public void enqueue(final Callback<T> callback) {
synchronized (this) {
if (executed) throw new IllegalStateException("Already executed");
diff --git a/retrofit-mock/src/main/java/retrofit2/mock/Calls.java b/retrofit-mock/src/main/java/retrofit2/mock/Calls.java
index 2bfb73eb97..49b490aee6 100644
--- a/retrofit-mock/src/main/java/retrofit2/mock/Calls.java
+++ b/retrofit-mock/src/main/java/retrofit2/mock/Calls.java
@@ -16,6 +16,7 @@
package retrofit2.mock;
import java.io.IOException;
+import okhttp3.Request;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
@@ -51,6 +52,10 @@ public static <T> Call<T> response(final Response<T> response) {
@Override public Call<T> clone() {
return this;
}
+
+ @Override public Request request() {
+ return response.raw().request();
+ }
};
}
@@ -79,6 +84,10 @@ public static <T> Call<T> failure(final IOException failure) {
@Override public Call<T> clone() {
return this;
}
+
+ @Override public Request request() {
+ return new Request.Builder().url("http://localhost").build();
+ }
};
}
diff --git a/retrofit/src/main/java/retrofit2/Call.java b/retrofit/src/main/java/retrofit2/Call.java
index 873bb0c6fe..171d9e0c41 100644
--- a/retrofit/src/main/java/retrofit2/Call.java
+++ b/retrofit/src/main/java/retrofit2/Call.java
@@ -16,6 +16,7 @@
package retrofit2;
import java.io.IOException;
+import okhttp3.Request;
/**
* An invocation of a Retrofit method that sends a request to a webserver and returns a response.
@@ -66,4 +67,7 @@ public interface Call<T> extends Cloneable {
* has already been.
*/
Call<T> clone();
+
+ /** The original HTTP request. */
+ Request request();
}
diff --git a/retrofit/src/main/java/retrofit2/ExecutorCallAdapterFactory.java b/retrofit/src/main/java/retrofit2/ExecutorCallAdapterFactory.java
index ce6b5e602a..983b5eb401 100644
--- a/retrofit/src/main/java/retrofit2/ExecutorCallAdapterFactory.java
+++ b/retrofit/src/main/java/retrofit2/ExecutorCallAdapterFactory.java
@@ -19,6 +19,7 @@
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.concurrent.Executor;
+import okhttp3.Request;
final class ExecutorCallAdapterFactory implements CallAdapter.Factory {
final Executor callbackExecutor;
@@ -98,5 +99,9 @@ static final class ExecutorCallbackCall<T> implements Call<T> {
@Override public Call<T> clone() {
return new ExecutorCallbackCall<>(callbackExecutor, delegate.clone());
}
+
+ @Override public Request request() {
+ return delegate.request();
+ }
}
}
diff --git a/retrofit/src/main/java/retrofit2/OkHttpCall.java b/retrofit/src/main/java/retrofit2/OkHttpCall.java
index 2b6f74e8a0..a0ffa95c48 100644
--- a/retrofit/src/main/java/retrofit2/OkHttpCall.java
+++ b/retrofit/src/main/java/retrofit2/OkHttpCall.java
@@ -17,6 +17,7 @@
import java.io.IOException;
import okhttp3.MediaType;
+import okhttp3.Request;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;
@@ -29,10 +30,13 @@ final class OkHttpCall<T> implements Call<T> {
private final Object[] args;
private final Converter<ResponseBody, T> responseConverter;
- private volatile okhttp3.Call rawCall;
- private boolean executed; // Guarded by this.
private volatile boolean canceled;
+ // All guarded by this.
+ private okhttp3.Call rawCall;
+ private Throwable creationFailure; // Either a RuntimeException or IOException.
+ private boolean executed;
+
OkHttpCall(okhttp3.Call.Factory callFactory, RequestFactory requestFactory, Object[] args,
Converter<ResponseBody, T> responseConverter) {
this.callFactory = callFactory;
@@ -46,25 +50,58 @@ final class OkHttpCall<T> implements Call<T> {
return new OkHttpCall<>(callFactory, requestFactory, args, responseConverter);
}
+ @Override public synchronized Request request() {
+ okhttp3.Call call = rawCall;
+ if (call != null) {
+ return call.request();
+ }
+ if (creationFailure != null) {
+ if (creationFailure instanceof IOException) {
+ throw new RuntimeException("Unable to create request.", creationFailure);
+ } else {
+ throw (RuntimeException) creationFailure;
+ }
+ }
+ try {
+ return (rawCall = createRawCall()).request();
+ } catch (RuntimeException e) {
+ creationFailure = e;
+ throw e;
+ } catch (IOException e) {
+ creationFailure = e;
+ throw new RuntimeException("Unable to create request.", e);
+ }
+ }
+
@Override public void enqueue(final Callback<T> callback) {
+ okhttp3.Call call;
+ Throwable failure;
+
synchronized (this) {
if (executed) throw new IllegalStateException("Already executed.");
executed = true;
+
+ call = rawCall;
+ failure = creationFailure;
+ if (call == null && failure == null) {
+ try {
+ call = rawCall = createRawCall();
+ } catch (Throwable t) {
+ failure = creationFailure = t;
+ }
+ }
}
- okhttp3.Call rawCall;
- try {
- rawCall = createRawCall();
- } catch (Throwable t) {
- callback.onFailure(this, t);
+ if (failure != null) {
+ callback.onFailure(this, failure);
return;
}
+
if (canceled) {
- rawCall.cancel();
+ call.cancel();
}
- this.rawCall = rawCall;
- rawCall.enqueue(new okhttp3.Callback() {
+ call.enqueue(new okhttp3.Callback() {
@Override public void onResponse(okhttp3.Call call, okhttp3.Response rawResponse)
throws IOException {
Response<T> response;
@@ -108,18 +145,36 @@ private void callSuccess(Response<T> response) {
}
@Override public Response<T> execute() throws IOException {
+ okhttp3.Call call;
+
synchronized (this) {
if (executed) throw new IllegalStateException("Already executed.");
executed = true;
+
+ if (creationFailure != null) {
+ if (creationFailure instanceof IOException) {
+ throw (IOException) creationFailure;
+ } else {
+ throw (RuntimeException) creationFailure;
+ }
+ }
+
+ call = rawCall;
+ if (call == null) {
+ try {
+ call = rawCall = createRawCall();
+ } catch (IOException | RuntimeException e) {
+ creationFailure = e;
+ throw e;
+ }
+ }
}
- okhttp3.Call rawCall = createRawCall();
if (canceled) {
- rawCall.cancel();
+ call.cancel();
}
- this.rawCall = rawCall;
- return parseResponse(rawCall.execute());
+ return parseResponse(call.execute());
}
private okhttp3.Call createRawCall() throws IOException {
@@ -167,9 +222,13 @@ Response<T> parseResponse(okhttp3.Response rawResponse) throws IOException {
public void cancel() {
canceled = true;
- okhttp3.Call rawCall = this.rawCall;
- if (rawCall != null) {
- rawCall.cancel();
+
+ okhttp3.Call call;
+ synchronized (this) {
+ call = rawCall;
+ }
+ if (call != null) {
+ call.cancel();
}
}
| diff --git a/retrofit/src/test/java/retrofit2/CallTest.java b/retrofit/src/test/java/retrofit2/CallTest.java
index ef1e923e0e..ae08c0be6f 100644
--- a/retrofit/src/test/java/retrofit2/CallTest.java
+++ b/retrofit/src/test/java/retrofit2/CallTest.java
@@ -19,6 +19,7 @@
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
@@ -36,6 +37,7 @@
import retrofit2.http.Body;
import retrofit2.http.GET;
import retrofit2.http.POST;
+import retrofit2.http.Path;
import retrofit2.http.Streaming;
import static java.util.concurrent.TimeUnit.SECONDS;
@@ -54,6 +56,7 @@ interface Service {
@GET("/") Call<ResponseBody> getBody();
@GET("/") @Streaming Call<ResponseBody> getStreamingBody();
@POST("/") Call<String> postString(@Body String body);
+ @POST("/{a}") Call<String> postRequestBody(@Path("a") Object a);
}
@Test public void http200Sync() throws IOException {
@@ -667,4 +670,275 @@ public Converter<?, RequestBody> requestBodyConverter(Type type, Annotation[] an
assertTrue(latch.await(2, SECONDS));
assertThat(failureRef.get()).isInstanceOf(IOException.class).hasMessage("Canceled");
}
+
+ @Test public void requestBeforeExecuteCreates() throws IOException {
+ Retrofit retrofit = new Retrofit.Builder()
+ .baseUrl(server.url("/"))
+ .addConverterFactory(new ToStringConverterFactory())
+ .build();
+ Service service = retrofit.create(Service.class);
+
+ server.enqueue(new MockResponse());
+
+ final AtomicInteger writeCount = new AtomicInteger();
+ Object a = new Object() {
+ @Override public String toString() {
+ writeCount.incrementAndGet();
+ return "Hello";
+ }
+ };
+ Call<String> call = service.postRequestBody(a);
+
+ call.request();
+ assertThat(writeCount.get()).isEqualTo(1);
+
+ call.execute();
+ assertThat(writeCount.get()).isEqualTo(1);
+ }
+
+ @Test public void requestThrowingBeforeExecuteFailsExecute() throws IOException {
+ Retrofit retrofit = new Retrofit.Builder()
+ .baseUrl(server.url("/"))
+ .addConverterFactory(new ToStringConverterFactory())
+ .build();
+ Service service = retrofit.create(Service.class);
+
+ server.enqueue(new MockResponse());
+
+ final AtomicInteger writeCount = new AtomicInteger();
+ Object a = new Object() {
+ @Override public String toString() {
+ writeCount.incrementAndGet();
+ throw new RuntimeException("Broken!");
+ }
+ };
+ Call<String> call = service.postRequestBody(a);
+
+ try {
+ call.request();
+ fail();
+ } catch (RuntimeException e) {
+ assertThat(e).hasMessage("Broken!");
+ }
+ assertThat(writeCount.get()).isEqualTo(1);
+
+ try {
+ call.execute();
+ fail();
+ } catch (RuntimeException e) {
+ assertThat(e).hasMessage("Broken!");
+ }
+ assertThat(writeCount.get()).isEqualTo(1);
+ }
+
+ @Test public void requestAfterExecuteReturnsCachedValue() throws IOException {
+ Retrofit retrofit = new Retrofit.Builder()
+ .baseUrl(server.url("/"))
+ .addConverterFactory(new ToStringConverterFactory())
+ .build();
+ Service service = retrofit.create(Service.class);
+
+ server.enqueue(new MockResponse());
+
+ final AtomicInteger writeCount = new AtomicInteger();
+ Object a = new Object() {
+ @Override public String toString() {
+ writeCount.incrementAndGet();
+ return "Hello";
+ }
+ };
+ Call<String> call = service.postRequestBody(a);
+
+ call.execute();
+ assertThat(writeCount.get()).isEqualTo(1);
+
+ call.request();
+ assertThat(writeCount.get()).isEqualTo(1);
+ }
+
+ @Test public void requestAfterExecuteThrowingAlsoThrows() throws IOException {
+ Retrofit retrofit = new Retrofit.Builder()
+ .baseUrl(server.url("/"))
+ .addConverterFactory(new ToStringConverterFactory())
+ .build();
+ Service service = retrofit.create(Service.class);
+
+ server.enqueue(new MockResponse());
+
+ final AtomicInteger writeCount = new AtomicInteger();
+ Object a = new Object() {
+ @Override public String toString() {
+ writeCount.incrementAndGet();
+ throw new RuntimeException("Broken!");
+ }
+ };
+ Call<String> call = service.postRequestBody(a);
+
+ try {
+ call.execute();
+ fail();
+ } catch (RuntimeException e) {
+ assertThat(e).hasMessage("Broken!");
+ }
+ assertThat(writeCount.get()).isEqualTo(1);
+
+ try {
+ call.request();
+ fail();
+ } catch (RuntimeException e) {
+ assertThat(e).hasMessage("Broken!");
+ }
+ assertThat(writeCount.get()).isEqualTo(1);
+ }
+
+ @Test public void requestBeforeEnqueueCreates() throws IOException, InterruptedException {
+ Retrofit retrofit = new Retrofit.Builder()
+ .baseUrl(server.url("/"))
+ .addConverterFactory(new ToStringConverterFactory())
+ .build();
+ Service service = retrofit.create(Service.class);
+
+ server.enqueue(new MockResponse());
+
+ final AtomicInteger writeCount = new AtomicInteger();
+ Object a = new Object() {
+ @Override public String toString() {
+ writeCount.incrementAndGet();
+ return "Hello";
+ }
+ };
+ Call<String> call = service.postRequestBody(a);
+
+ call.request();
+ assertThat(writeCount.get()).isEqualTo(1);
+
+ final CountDownLatch latch = new CountDownLatch(1);
+ call.enqueue(new Callback<String>() {
+ @Override public void onResponse(Call<String> call, Response<String> response) {
+ assertThat(writeCount.get()).isEqualTo(1);
+ latch.countDown();
+ }
+
+ @Override public void onFailure(Call<String> call, Throwable t) {
+ }
+ });
+ assertTrue(latch.await(1, SECONDS));
+ }
+
+ @Test public void requestThrowingBeforeEnqueueFailsEnqueue()
+ throws IOException, InterruptedException {
+ Retrofit retrofit = new Retrofit.Builder()
+ .baseUrl(server.url("/"))
+ .addConverterFactory(new ToStringConverterFactory())
+ .build();
+ Service service = retrofit.create(Service.class);
+
+ server.enqueue(new MockResponse());
+
+ final AtomicInteger writeCount = new AtomicInteger();
+ Object a = new Object() {
+ @Override public String toString() {
+ writeCount.incrementAndGet();
+ throw new RuntimeException("Broken!");
+ }
+ };
+ Call<String> call = service.postRequestBody(a);
+
+ try {
+ call.request();
+ fail();
+ } catch (RuntimeException e) {
+ assertThat(e).hasMessage("Broken!");
+ }
+ assertThat(writeCount.get()).isEqualTo(1);
+
+ final CountDownLatch latch = new CountDownLatch(1);
+ call.enqueue(new Callback<String>() {
+ @Override public void onResponse(Call<String> call, Response<String> response) {
+ }
+
+ @Override public void onFailure(Call<String> call, Throwable t) {
+ assertThat(t).isExactlyInstanceOf(RuntimeException.class).hasMessage("Broken!");
+ assertThat(writeCount.get()).isEqualTo(1);
+ latch.countDown();
+ }
+ });
+ assertTrue(latch.await(1, SECONDS));
+ }
+
+ @Test public void requestAfterEnqueueReturnsCachedValue() throws IOException,
+ InterruptedException {
+ Retrofit retrofit = new Retrofit.Builder()
+ .baseUrl(server.url("/"))
+ .addConverterFactory(new ToStringConverterFactory())
+ .build();
+ Service service = retrofit.create(Service.class);
+
+ server.enqueue(new MockResponse());
+
+ final AtomicInteger writeCount = new AtomicInteger();
+ Object a = new Object() {
+ @Override public String toString() {
+ writeCount.incrementAndGet();
+ return "Hello";
+ }
+ };
+ Call<String> call = service.postRequestBody(a);
+
+ final CountDownLatch latch = new CountDownLatch(1);
+ call.enqueue(new Callback<String>() {
+ @Override public void onResponse(Call<String> call, Response<String> response) {
+ assertThat(writeCount.get()).isEqualTo(1);
+ latch.countDown();
+ }
+
+ @Override public void onFailure(Call<String> call, Throwable t) {
+ }
+ });
+ assertTrue(latch.await(1, SECONDS));
+
+ call.request();
+ assertThat(writeCount.get()).isEqualTo(1);
+ }
+
+ @Test public void requestAfterEnqueueFailingThrows() throws IOException,
+ InterruptedException {
+ Retrofit retrofit = new Retrofit.Builder()
+ .baseUrl(server.url("/"))
+ .addConverterFactory(new ToStringConverterFactory())
+ .build();
+ Service service = retrofit.create(Service.class);
+
+ server.enqueue(new MockResponse());
+
+ final AtomicInteger writeCount = new AtomicInteger();
+ Object a = new Object() {
+ @Override public String toString() {
+ writeCount.incrementAndGet();
+ throw new RuntimeException("Broken!");
+ }
+ };
+ Call<String> call = service.postRequestBody(a);
+
+ final CountDownLatch latch = new CountDownLatch(1);
+ call.enqueue(new Callback<String>() {
+ @Override public void onResponse(Call<String> call, Response<String> response) {
+ }
+
+ @Override public void onFailure(Call<String> call, Throwable t) {
+ assertThat(t).isExactlyInstanceOf(RuntimeException.class).hasMessage("Broken!");
+ assertThat(writeCount.get()).isEqualTo(1);
+ latch.countDown();
+ }
+ });
+ assertTrue(latch.await(1, SECONDS));
+
+ try {
+ call.request();
+ fail();
+ } catch (RuntimeException e) {
+ assertThat(e).hasMessage("Broken!");
+ }
+ assertThat(writeCount.get()).isEqualTo(1);
+ }
}
diff --git a/retrofit/src/test/java/retrofit2/ExecutorCallAdapterFactoryTest.java b/retrofit/src/test/java/retrofit2/ExecutorCallAdapterFactoryTest.java
index e4bcc11f78..ba45b5fe67 100644
--- a/retrofit/src/test/java/retrofit2/ExecutorCallAdapterFactoryTest.java
+++ b/retrofit/src/test/java/retrofit2/ExecutorCallAdapterFactoryTest.java
@@ -21,6 +21,7 @@
import java.lang.reflect.Type;
import java.util.List;
import java.util.concurrent.Executor;
+import okhttp3.Request;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
@@ -161,5 +162,9 @@ static class EmptyCall implements Call<String> {
@Override public Call<String> clone() {
throw new UnsupportedOperationException();
}
+
+ @Override public Request request() {
+ throw new UnsupportedOperationException();
+ }
}
}
| train | val | 2016-01-16T19:17:57 | "2015-12-10T16:05:52Z" | vpasquier | val |
square/retrofit/1584_1585 | square/retrofit | square/retrofit/1584 | square/retrofit/1585 | [
"timestamp(timedelta=9.0, similarity=0.8673022603756715)"
] | 9d6e1af1ea552e368be54b6b355f232b68d4750f | d3a1906aaf3bc8ffd94d241e835118312fdf06b6 | [
"`Single` is `@Beta` and as such [can be broken or removed at any time](https://github.com/ReactiveX/RxJava#beta). Retrofit will not put its presence in the critical path for all RxJava support until it graduates to stable.\n",
"You can tell ProGuard to not obfuscate this class for now.\n",
"Having this issue. `Single` is no longer `@Beta` since RxJava `1.2`.\n",
"And it's already been adjusted on `master` accordingly.\n",
"I'm sorry, was using `2.0.0-beta4`. I can't use latest version. How do I tell ProGuard not to obfuscate the class then?\n\n```\n-keep class retrofit2.adapter.rxjava.RxJavaCallAdapterFactory { *; }\n```\n\ndoes not seem to do the trick. Code still goes through [this execution path](https://github.com/square/retrofit/blob/2613d174be2e6f31f4f742e040412aee308849cf/retrofit-adapters/rxjava/src/main/java/retrofit2/adapter/rxjava/RxJavaCallAdapterFactory.java#L51) with the above configuration.\n",
"-keepnames class rx.Single\n\nOn Tue, Oct 11, 2016 at 2:11 PM david-perez [email protected]\nwrote:\n\n> I'm sorry, was using 2.0.0-beta4. I can't use latest version. How do I\n> tell ProGuard not to obfuscate the class then?\n> \n> -keep class retrofit2.adapter.rxjava.RxJavaCallAdapterFactory { *; }\n> \n> does not seem to do the trick. Code still goes through this execution path\n> https://github.com/square/retrofit/blob/2613d174be2e6f31f4f742e040412aee308849cf/retrofit-adapters/rxjava/src/main/java/retrofit2/adapter/rxjava/RxJavaCallAdapterFactory.java#L51\n> with the above configuration.\n> \n> —\n> You are receiving this because you modified the open/close state.\n> Reply to this email directly, view it on GitHub\n> https://github.com/square/retrofit/issues/1584#issuecomment-252998320,\n> or mute the thread\n> https://github.com/notifications/unsubscribe-auth/AAEEEVpKywmbJrzhtlUrdiOXOiltadMYks5qy9FpgaJpZM4HXGRZ\n> .\n"
] | [] | "2016-02-10T08:47:17Z" | [] | RxJavaCallAfapterFactory does not recognize rx.Single after proguarding | After proguarding application which uses retrofit service like
```
interface Service {
@GET("/something")
Single<String> getSomething();
}
```
retrofit fails with
```
java.lang.IllegalArgumentException: Could not locate call adapter for e.r<java.lang.String>.
Tried:
* retrofit2.adapter.rxjava.RxJavaCallAdapterFactory
* retrofit2.ExecutorCallAdapterFactory
at retrofit2.Retrofit.nextCallAdapter(Unknown Source)
at retrofit2.Retrofit.callAdapter(Unknown Source)
```
| [
"retrofit-adapters/rxjava/src/main/java/retrofit2/adapter/rxjava/RxJavaCallAdapterFactory.java"
] | [
"retrofit-adapters/rxjava/src/main/java/retrofit2/adapter/rxjava/RxJavaCallAdapterFactory.java"
] | [] | diff --git a/retrofit-adapters/rxjava/src/main/java/retrofit2/adapter/rxjava/RxJavaCallAdapterFactory.java b/retrofit-adapters/rxjava/src/main/java/retrofit2/adapter/rxjava/RxJavaCallAdapterFactory.java
index f4b60209a7..f40a2877f0 100644
--- a/retrofit-adapters/rxjava/src/main/java/retrofit2/adapter/rxjava/RxJavaCallAdapterFactory.java
+++ b/retrofit-adapters/rxjava/src/main/java/retrofit2/adapter/rxjava/RxJavaCallAdapterFactory.java
@@ -46,7 +46,7 @@ private RxJavaCallAdapterFactory() {
@Override
public CallAdapter<?> get(Type returnType, Annotation[] annotations, Retrofit retrofit) {
Class<?> rawType = getRawType(returnType);
- boolean isSingle = "rx.Single".equals(rawType.getCanonicalName());
+ boolean isSingle = rawType == rx.Single.class;
if (rawType != Observable.class && !isSingle) {
return null;
}
| null | train | val | 2016-02-09T17:35:02 | "2016-02-10T08:45:42Z" | krzysiekbielicki | val |
square/retrofit/1432_1594 | square/retrofit | square/retrofit/1432 | square/retrofit/1594 | [
"timestamp(timedelta=6.0, similarity=0.9274588710245079)"
] | 9d6e1af1ea552e368be54b6b355f232b68d4750f | adadced651d3f50ffe34350b5509c385dd97f0fd | [
"I don't really care. So, sure! Its implementation would be just returning `Void` as the response type and calling `toCompletable()` on the `Observable<Void>`.\n",
":+1: cool, I can look into contributing a PR for it once it's released. Would you prefer to wait until it's in the public API or are Beta/Experimental ok when it's released in 1.1.1?\n",
"Beta or Experimental is fine, but it needs to be done in a way that if the\nclass is renamed or deleted it doesn't break Retrofit. Look to the current\nSingle behavior for how to do that.\n\nOn Mon, Jan 4, 2016 at 1:19 AM Zac Sweers [email protected] wrote:\n\n> [image: :+1:] cool, I can look into contributing a PR for it once it's\n> released. Would you prefer to wait until it's in the public API or are\n> Beta/Incubating ok?\n> \n> —\n> Reply to this email directly or view it on GitHub\n> https://github.com/square/retrofit/issues/1432#issuecomment-168592256.\n",
"Kicked the tires a bit and have a working POC here if you want to take a look. Will wait until it's released before PR-ing.\n\nhttps://github.com/hzsweers/retrofit/tree/z/completable\n",
"d80d65c902648b4f1402fb85f784d57504efe1ec\n"
] | [
"This goes in the root pom.\n",
"You can delete the try/catch and `assertThat`, they don't add value\n",
"Whoops, fixed in d4a8b7c525bc4fc9a2b634d164aeb2ee02af928a\n",
"6970b1d\n",
"Why the wrapper? Just return `callAdapter` here.\n",
"Actually, this whole thing is stateless so there can be a singleton instance in a static field.\n",
"Why `CompositeSubscription` here? We should just be able to use the `Subscription` returned from `Subscriptions.create` directly.\n",
"uber nit: you don't need `else` after a `return`. Helps save indentation (and it'll make the diff look a lot nicer)\n",
"Good point! Was going by SingleHelper's implementation at first and didn't realize this could all be simplified a lot. 6f011ac\n",
"Good point, was just following what convention I saw internally in `Completable` since I wasn't sure how to test this portion. bd46587\n",
"f0b95cd\n",
"nit: remove `private` to avoid the need for a synthetic accessor method to be generated\n",
"e0f8cf0\n"
] | "2016-02-12T09:10:05Z" | [
"Enhancement",
"Blocked"
] | Proposal: Completable API support in rxjava adapter | There's a new `Completable` API coming in RxJava soon, would this be something that you'd want to support? This would basically just notify if the request failed or finished and you don't care to or want to process the response body (firing off analytics events comes to mind).
http://akarnokd.blogspot.com/2015/12/the-new-completable-api-part-1.html
Presumably would look something like this in use:
``` java
@POST('myendpoint')
Completable sendAnalyticsEvent(@Body AnalyticsEvent event)
```
| [
"pom.xml",
"retrofit-adapters/rxjava/src/main/java/retrofit2/adapter/rxjava/RxJavaCallAdapterFactory.java"
] | [
"pom.xml",
"retrofit-adapters/rxjava/src/main/java/retrofit2/adapter/rxjava/CompletableHelper.java",
"retrofit-adapters/rxjava/src/main/java/retrofit2/adapter/rxjava/RxJavaCallAdapterFactory.java"
] | [
"retrofit-adapters/rxjava/src/test/java/retrofit2/adapter/rxjava/CompletableTest.java"
] | diff --git a/pom.xml b/pom.xml
index 846b9c6c7a..1339bf0c5e 100644
--- a/pom.xml
+++ b/pom.xml
@@ -53,7 +53,7 @@
<animal.sniffer.version>1.14</animal.sniffer.version>
<!-- Adapter Dependencies -->
- <rxjava.version>1.1.0</rxjava.version>
+ <rxjava.version>1.1.1</rxjava.version>
<!-- Converter Dependencies -->
<gson.version>2.4</gson.version>
diff --git a/retrofit-adapters/rxjava/src/main/java/retrofit2/adapter/rxjava/CompletableHelper.java b/retrofit-adapters/rxjava/src/main/java/retrofit2/adapter/rxjava/CompletableHelper.java
new file mode 100644
index 0000000000..7f5980bde8
--- /dev/null
+++ b/retrofit-adapters/rxjava/src/main/java/retrofit2/adapter/rxjava/CompletableHelper.java
@@ -0,0 +1,84 @@
+/*
+ * Copyright (C) 2016 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 retrofit2.adapter.rxjava;
+
+import retrofit2.Call;
+import retrofit2.CallAdapter;
+import retrofit2.Response;
+import rx.Completable;
+import rx.Subscription;
+import rx.exceptions.Exceptions;
+import rx.functions.Action0;
+import rx.subscriptions.Subscriptions;
+
+import java.lang.reflect.Type;
+
+final class CompletableHelper {
+
+ private static final CallAdapter<Completable> COMPLETABLE_CALL_ADAPTER
+ = new CallAdapter<Completable>() {
+ @Override public Type responseType() {
+ return Void.class;
+ }
+
+ @Override public Completable adapt(Call call) {
+ return Completable.create(new CompletableCallOnSubscribe(call));
+ }
+ };
+
+ static CallAdapter<Completable> makeCompletable() {
+ return COMPLETABLE_CALL_ADAPTER;
+ }
+
+ private static final class CompletableCallOnSubscribe
+ implements Completable.CompletableOnSubscribe {
+ private final Call originalCall;
+
+ CompletableCallOnSubscribe(Call originalCall) {
+ this.originalCall = originalCall;
+ }
+
+ @Override
+ public void call(final Completable.CompletableSubscriber subscriber) {
+ // Since Call is a one-shot type, clone it for each new subscriber.
+ final Call call = originalCall.clone();
+
+ // Attempt to cancel the call if it is still in-flight on unsubscription.
+ Subscription subscription = Subscriptions.create(new Action0() {
+ @Override public void call() {
+ call.cancel();
+ }
+ });
+ subscriber.onSubscribe(subscription);
+
+ try {
+ Response response = call.execute();
+ if (!subscription.isUnsubscribed()) {
+ if (response.isSuccess()) {
+ subscriber.onCompleted();
+ } else {
+ subscriber.onError(new HttpException(response));
+ }
+ }
+ } catch (Throwable t) {
+ Exceptions.throwIfFatal(t);
+ if (!subscription.isUnsubscribed()) {
+ subscriber.onError(t);
+ }
+ }
+ }
+ }
+}
diff --git a/retrofit-adapters/rxjava/src/main/java/retrofit2/adapter/rxjava/RxJavaCallAdapterFactory.java b/retrofit-adapters/rxjava/src/main/java/retrofit2/adapter/rxjava/RxJavaCallAdapterFactory.java
index f4b60209a7..ecbdc8a533 100644
--- a/retrofit-adapters/rxjava/src/main/java/retrofit2/adapter/rxjava/RxJavaCallAdapterFactory.java
+++ b/retrofit-adapters/rxjava/src/main/java/retrofit2/adapter/rxjava/RxJavaCallAdapterFactory.java
@@ -15,9 +15,6 @@
*/
package retrofit2.adapter.rxjava;
-import java.lang.annotation.Annotation;
-import java.lang.reflect.ParameterizedType;
-import java.lang.reflect.Type;
import retrofit2.Call;
import retrofit2.CallAdapter;
import retrofit2.Response;
@@ -29,6 +26,10 @@
import rx.functions.Func1;
import rx.subscriptions.Subscriptions;
+import java.lang.annotation.Annotation;
+import java.lang.reflect.ParameterizedType;
+import java.lang.reflect.Type;
+
/**
* TODO docs
*/
@@ -46,20 +47,31 @@ private RxJavaCallAdapterFactory() {
@Override
public CallAdapter<?> get(Type returnType, Annotation[] annotations, Retrofit retrofit) {
Class<?> rawType = getRawType(returnType);
- boolean isSingle = "rx.Single".equals(rawType.getCanonicalName());
- if (rawType != Observable.class && !isSingle) {
+ final String canonicalName = rawType.getCanonicalName();
+ boolean isSingle = "rx.Single".equals(canonicalName);
+ boolean isCompletable = "rx.Completable".equals(canonicalName);
+ if (rawType != Observable.class && !isSingle && !isCompletable) {
return null;
}
- if (!(returnType instanceof ParameterizedType)) {
+ if (!isCompletable && !(returnType instanceof ParameterizedType)) {
String name = isSingle ? "Single" : "Observable";
throw new IllegalStateException(name + " return type must be parameterized"
+ " as " + name + "<Foo> or " + name + "<? extends Foo>");
}
+ if (isCompletable) {
+ // Add Completable-converter wrapper from a separate class. This defers classloading such that
+ // regular Observable operation can be leveraged without relying on this unstable RxJava API.
+ // Note that this has to be done separately since Completable doesn't have a parametrized
+ // type.
+ return CompletableHelper.makeCompletable();
+ }
+
CallAdapter<Observable<?>> callAdapter = getCallAdapter(returnType);
if (isSingle) {
// Add Single-converter wrapper from a separate class. This defers classloading such that
- // regular Observable operation can be leveraged without relying on this unstable RxJava API.
+ // regular Observable operation can be leveraged without relying on this unstable RxJava
+ // API.
return SingleHelper.makeSingle(callAdapter);
}
return callAdapter;
| diff --git a/retrofit-adapters/rxjava/src/test/java/retrofit2/adapter/rxjava/CompletableTest.java b/retrofit-adapters/rxjava/src/test/java/retrofit2/adapter/rxjava/CompletableTest.java
new file mode 100644
index 0000000000..f52b92ee33
--- /dev/null
+++ b/retrofit-adapters/rxjava/src/test/java/retrofit2/adapter/rxjava/CompletableTest.java
@@ -0,0 +1,80 @@
+/*
+ * Copyright (C) 2016 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 retrofit2.adapter.rxjava;
+
+import okhttp3.mockwebserver.MockResponse;
+import okhttp3.mockwebserver.MockWebServer;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import retrofit2.Retrofit;
+import retrofit2.http.GET;
+import rx.Completable;
+
+import java.io.IOException;
+
+import static okhttp3.mockwebserver.SocketPolicy.DISCONNECT_AFTER_REQUEST;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.Assert.fail;
+
+public final class CompletableTest {
+ @Rule
+ public final MockWebServer server = new MockWebServer();
+
+ interface Service {
+ @GET("/") Completable completable();
+ }
+
+ private Service service;
+
+ @Before public void setUp() {
+ Retrofit retrofit = new Retrofit.Builder()
+ .baseUrl(server.url("/"))
+ .addConverterFactory(new StringConverterFactory())
+ .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
+ .build();
+ service = retrofit.create(Service.class);
+ }
+
+ @Test public void completableSuccess200() {
+ server.enqueue(new MockResponse().setBody("Hi"));
+
+ service.completable().await();
+ }
+
+ @Test public void completableSuccess404() {
+ server.enqueue(new MockResponse().setResponseCode(404));
+
+ try {
+ service.completable().await();
+ fail();
+ } catch (RuntimeException e) {
+ Throwable cause = e.getCause();
+ assertThat(cause).isInstanceOf(HttpException.class).hasMessage("HTTP 404 Client Error");
+ }
+ }
+
+ @Test public void completableFailure() {
+ server.enqueue(new MockResponse().setSocketPolicy(DISCONNECT_AFTER_REQUEST));
+
+ try {
+ service.completable().await();
+ fail();
+ } catch (RuntimeException e) {
+ assertThat(e.getCause()).isInstanceOf(IOException.class);
+ }
+ }
+}
| val | val | 2016-02-09T17:35:02 | "2016-01-04T05:00:22Z" | ZacSweers | val |
square/retrofit/1600_1601 | square/retrofit | square/retrofit/1600 | square/retrofit/1601 | [
"keyword_pr_to_issue",
"timestamp(timedelta=0.0, similarity=0.9685647297980943)"
] | 9d6e1af1ea552e368be54b6b355f232b68d4750f | 4dd72f962a996c9de7ecbaaeee6a0c9feb1da975 | [
"The fix was in 3.1.0, actually. 3.1.2 is a bugfix for something completely\nunrelated .\n\nOn Sun, Feb 14, 2016, 10:18 PM Brad Leege [email protected] wrote:\n\n> Update Retrofit to use OkHttp 3.1.2 to address a Certificate Pinning\n> Vulnerability that was discovered\n> https://publicobject.com/2016/02/11/okhttp-certificate-pinning-vulnerability/\n> .\n> \n> —\n> Reply to this email directly or view it on GitHub\n> https://github.com/square/retrofit/issues/1600.\n"
] | [] | "2016-02-15T03:20:03Z" | [] | Update To OkHttp 3.1.2 | Update Retrofit to use OkHttp 3.1.2 to address a [Certificate Pinning Vulnerability that was discovered](https://publicobject.com/2016/02/11/okhttp-certificate-pinning-vulnerability/).
| [
"pom.xml"
] | [
"pom.xml"
] | [] | diff --git a/pom.xml b/pom.xml
index 846b9c6c7a..3b28746998 100644
--- a/pom.xml
+++ b/pom.xml
@@ -49,7 +49,7 @@
<!-- Dependencies -->
<android.version>4.1.1.4</android.version>
- <okhttp.version>3.1.1</okhttp.version>
+ <okhttp.version>3.1.2</okhttp.version>
<animal.sniffer.version>1.14</animal.sniffer.version>
<!-- Adapter Dependencies -->
| null | train | val | 2016-02-09T17:35:02 | "2016-02-15T03:18:52Z" | bleege | val |
square/retrofit/1592_1609 | square/retrofit | square/retrofit/1592 | square/retrofit/1609 | [
"timestamp(timedelta=7.0, similarity=0.9347780248724246)"
] | 691d99addf9a112f85c8fcc3f38b0ba29f3e6569 | 3fc3e7a35594f506e35c89be20eda3c78a7b2239 | [
"What are thoughts here?\nShould all adapters be lenient or not lenient?\nI suppose if you want only certain adapters to be lenient, you can easily make your own factory.\n",
"Definitely not be default\n\nOn Fri, Feb 12, 2016, 6:27 PM Eric Cochran [email protected] wrote:\n\n> What are thoughts here?\n> Should all adapters be lenient or not lenient?\n> I suppose if you want only certain adapters to be lenient, you can easily\n> make your own factory.\n> \n> —\n> Reply to this email directly or view it on GitHub\n> https://github.com/square/retrofit/issues/1592#issuecomment-183526800.\n",
"I think I'd do an asLenient() that returned a new lenient factory from an\nexisting one.\n\nOn Fri, Feb 12, 2016, 6:39 PM Jake Wharton [email protected] wrote:\n\n> Definitely not be default\n> \n> On Fri, Feb 12, 2016, 6:27 PM Eric Cochran [email protected]\n> wrote:\n> \n> > What are thoughts here?\n> > Should all adapters be lenient or not lenient?\n> > I suppose if you want only certain adapters to be lenient, you can easily\n> > make your own factory.\n> > \n> > —\n> > Reply to this email directly or view it on GitHub\n> > https://github.com/square/retrofit/issues/1592#issuecomment-183526800.\n",
"Right, not by default, but it will be a factory that makes all adapters lenient. I'm not sure if that's truly useful, but perhaps.\n",
"fb94144db40f8d403ba57799b61e9547cb349b34\n"
] | [
"This doesn't need to exist. Just call the constructor.\n",
"I would just delete this `if`. It'll never happen and even if it does it's not that big of a deal to create a new instance.\n"
] | "2016-02-18T03:40:54Z" | [] | MoshiConverterFactory should have a lenient option | https://github.com/square/moshi/issues/132
| [
"retrofit-converters/moshi/src/main/java/retrofit2/converter/moshi/MoshiConverterFactory.java"
] | [
"retrofit-converters/moshi/src/main/java/retrofit2/converter/moshi/MoshiConverterFactory.java"
] | [
"retrofit-converters/moshi/src/test/java/retrofit2/converter/moshi/MoshiConverterFactoryTest.java"
] | diff --git a/retrofit-converters/moshi/src/main/java/retrofit2/converter/moshi/MoshiConverterFactory.java b/retrofit-converters/moshi/src/main/java/retrofit2/converter/moshi/MoshiConverterFactory.java
index 1a98a78aa4..bf5a7bce69 100644
--- a/retrofit-converters/moshi/src/main/java/retrofit2/converter/moshi/MoshiConverterFactory.java
+++ b/retrofit-converters/moshi/src/main/java/retrofit2/converter/moshi/MoshiConverterFactory.java
@@ -40,20 +40,29 @@ public static MoshiConverterFactory create() {
/** Create an instance using {@code moshi} for conversion. */
public static MoshiConverterFactory create(Moshi moshi) {
- return new MoshiConverterFactory(moshi);
+ return new MoshiConverterFactory(moshi, false);
}
private final Moshi moshi;
+ private final boolean lenient;
- private MoshiConverterFactory(Moshi moshi) {
+ private MoshiConverterFactory(Moshi moshi, boolean lenient) {
if (moshi == null) throw new NullPointerException("moshi == null");
this.moshi = moshi;
+ this.lenient = lenient;
+ }
+
+ public MoshiConverterFactory asLenient() {
+ return new MoshiConverterFactory(moshi, true);
}
@Override
public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations,
Retrofit retrofit) {
JsonAdapter<?> adapter = moshi.adapter(type);
+ if (lenient) {
+ adapter = adapter.lenient();
+ }
return new MoshiResponseBodyConverter<>(adapter);
}
@@ -61,6 +70,9 @@ private MoshiConverterFactory(Moshi moshi) {
public Converter<?, RequestBody> requestBodyConverter(Type type,
Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
JsonAdapter<?> adapter = moshi.adapter(type);
+ if (lenient) {
+ adapter = adapter.lenient();
+ }
return new MoshiRequestBodyConverter<>(adapter);
}
}
| diff --git a/retrofit-converters/moshi/src/test/java/retrofit2/converter/moshi/MoshiConverterFactoryTest.java b/retrofit-converters/moshi/src/test/java/retrofit2/converter/moshi/MoshiConverterFactoryTest.java
index 2a85e58186..8583529fa4 100644
--- a/retrofit-converters/moshi/src/test/java/retrofit2/converter/moshi/MoshiConverterFactoryTest.java
+++ b/retrofit-converters/moshi/src/test/java/retrofit2/converter/moshi/MoshiConverterFactoryTest.java
@@ -30,11 +30,12 @@
import retrofit2.Call;
import retrofit2.Response;
import retrofit2.Retrofit;
-import retrofit2.converter.moshi.MoshiConverterFactory;
import retrofit2.http.Body;
import retrofit2.http.POST;
import static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.fail;
public final class MoshiConverterFactoryTest {
interface AnInterface {
@@ -85,16 +86,24 @@ interface Service {
@Rule public final MockWebServer server = new MockWebServer();
private Service service;
+ private Service serviceLenient;
@Before public void setUp() {
Moshi moshi = new Moshi.Builder()
.add(new AnInterfaceAdapter())
.build();
+ MoshiConverterFactory factory = MoshiConverterFactory.create(moshi);
+ MoshiConverterFactory factoryLenient = factory.asLenient();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(server.url("/"))
- .addConverterFactory(MoshiConverterFactory.create(moshi))
+ .addConverterFactory(factory)
+ .build();
+ Retrofit retrofitLenient = new Retrofit.Builder()
+ .baseUrl(server.url("/"))
+ .addConverterFactory(factoryLenient)
.build();
service = retrofit.create(Service.class);
+ serviceLenient = retrofitLenient.create(Service.class);
}
@Test public void anInterface() throws IOException, InterruptedException {
@@ -122,4 +131,28 @@ interface Service {
assertThat(request.getBody().readUtf8()).isEqualTo("{\"theName\":\"value\"}");
assertThat(request.getHeader("Content-Type")).isEqualTo("application/json; charset=UTF-8");
}
+
+ @Test public void asLenient() throws IOException, InterruptedException {
+ MockResponse malformedResponse = new MockResponse().setBody("{\"theName\":value}");
+
+ try {
+ server.enqueue(malformedResponse);
+ Call<AnImplementation> call = service.anImplementation(new AnImplementation("value"));
+ call.execute();
+ fail();
+ } catch (IOException e) {
+ assertEquals(e.getMessage(),
+ "Use JsonReader.setLenient(true) to accept malformed JSON at path $.theName");
+ }
+
+ server.enqueue(malformedResponse);
+ Call<AnImplementation> call = serviceLenient.anImplementation(new AnImplementation("value"));
+ Response<AnImplementation> response = call.execute();
+ AnImplementation body = response.body();
+ assertThat(body.theName).isEqualTo("value");
+
+ RecordedRequest request = server.takeRequest();
+ assertThat(request.getBody().readUtf8()).isEqualTo("{\"theName\":\"value\"}");
+ assertThat(request.getHeader("Content-Type")).isEqualTo("application/json; charset=UTF-8");
+ }
}
| train | val | 2016-02-18T04:52:15 | "2016-02-12T02:58:13Z" | swankjesse | val |
square/retrofit/1661_1662 | square/retrofit | square/retrofit/1661 | square/retrofit/1662 | [
"timestamp(timedelta=0.0, similarity=0.8973020220539903)"
] | 0104728017a5c1e2ac8d5fa474e70436f186dcdc | bf3c8b606664e5331f6e34cbc294bf96dcd209f5 | [
"There are no nullability annotations that are acceptable.\n"
] | [] | "2016-03-08T20:43:07Z" | [] | Call.enqueue with null parameter throws NullPointerException | `code Call.enqueue` should add a null check. If it can't accepts `null`parameter then it should be annotated with `@NotNull`
``` java
java.lang.NullPointerException: Attempt to invoke interface method 'void retrofit2.Callback.onResponse(retrofit2.Call, retrofit2.Response)' on a null object reference
at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run(ExecutorCallAdapterFactory.java:66)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6872)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)
```
| [
"retrofit-mock/src/main/java/retrofit2/mock/BehaviorCall.java",
"retrofit/src/main/java/retrofit2/ExecutorCallAdapterFactory.java",
"retrofit/src/main/java/retrofit2/OkHttpCall.java"
] | [
"retrofit-mock/src/main/java/retrofit2/mock/BehaviorCall.java",
"retrofit/src/main/java/retrofit2/ExecutorCallAdapterFactory.java",
"retrofit/src/main/java/retrofit2/OkHttpCall.java"
] | [] | diff --git a/retrofit-mock/src/main/java/retrofit2/mock/BehaviorCall.java b/retrofit-mock/src/main/java/retrofit2/mock/BehaviorCall.java
index ac10878fa9..cfc92c5f79 100644
--- a/retrofit-mock/src/main/java/retrofit2/mock/BehaviorCall.java
+++ b/retrofit-mock/src/main/java/retrofit2/mock/BehaviorCall.java
@@ -52,6 +52,8 @@ final class BehaviorCall<T> implements Call<T> {
}
@Override public void enqueue(final Callback<T> callback) {
+ if (callback == null) throw new NullPointerException("callback == null");
+
synchronized (this) {
if (executed) throw new IllegalStateException("Already executed");
executed = true;
diff --git a/retrofit/src/main/java/retrofit2/ExecutorCallAdapterFactory.java b/retrofit/src/main/java/retrofit2/ExecutorCallAdapterFactory.java
index 155dc528c5..95ecbf4b7e 100644
--- a/retrofit/src/main/java/retrofit2/ExecutorCallAdapterFactory.java
+++ b/retrofit/src/main/java/retrofit2/ExecutorCallAdapterFactory.java
@@ -55,6 +55,8 @@ static final class ExecutorCallbackCall<T> implements Call<T> {
}
@Override public void enqueue(final Callback<T> callback) {
+ if (callback == null) throw new NullPointerException("callback == null");
+
delegate.enqueue(new Callback<T>() {
@Override public void onResponse(final Call<T> call, final Response<T> response) {
callbackExecutor.execute(new Runnable() {
diff --git a/retrofit/src/main/java/retrofit2/OkHttpCall.java b/retrofit/src/main/java/retrofit2/OkHttpCall.java
index c793fecd55..5aa102db25 100644
--- a/retrofit/src/main/java/retrofit2/OkHttpCall.java
+++ b/retrofit/src/main/java/retrofit2/OkHttpCall.java
@@ -69,6 +69,8 @@ final class OkHttpCall<T> implements Call<T> {
}
@Override public void enqueue(final Callback<T> callback) {
+ if (callback == null) throw new NullPointerException("callback == null");
+
okhttp3.Call call;
Throwable failure;
| null | train | val | 2016-03-07T06:53:50 | "2016-03-08T20:39:41Z" | shaildyp | val |
square/retrofit/1710_1711 | square/retrofit | square/retrofit/1710 | square/retrofit/1711 | [
"timestamp(timedelta=0.0, similarity=0.8968148919460659)"
] | 011a89ee00e16d6e775b29fa4710718cc864baf8 | b50cf58ecb62438abfa19be0f406b8e59d0d0476 | [
"I'll have a look! We can probably provide a create method overload which\ntakes a registry.\n\nOn Sat, Apr 2, 2016, 12:28 PM vganin [email protected] wrote:\n\n> Hi, I'm trying to get protobuf object deserialized with Retrofit and\n> ProtoConverterFactory. The issue is that my message B is extension of\n> another message A like this:\n> \n> A.proto\n> \n> message A {\n> ...\n> }\n> \n> B.proto\n> \n> import \"A.proto\"\n> \n> message B {\n> ...\n> }\n> \n> extends A {\n> optional B b = 111;\n> }\n> \n> As it is known, to get extension, I have to register it first and then\n> parse the stream like this:\n> \n> ExtensionRegistry reg = RextensionRegistry.newInstance();\n> registry.add(BProtos.b);AProtos.A.parseFrom(stream, reg);\n> \n> But as I can see from source code, converter only calls parseFrom(stream)\n> and there are no hooks to attach ExtensionRegistry instance in the\n> process.\n> \n> Am I missing something?\n> \n> My issue is very similar to this one\n> http://stackoverflow.com/questions/21747336/protobuf-extension-registry-issue\n> \n> —\n> You are receiving this because you are subscribed to this thread.\n> Reply to this email directly or view it on GitHub\n> https://github.com/square/retrofit/issues/1710\n"
] | [] | "2016-04-02T17:58:55Z" | [] | Protobuf extension registry issue | Hi, I'm trying to get protobuf object deserialized with Retrofit and `ProtoConverterFactory`. The issue is that my message B is extension of another message A like this:
A.proto
```
message A {
...
}
```
B.proto
```
import "A.proto"
message B {
...
}
extends A {
optional B b = 111;
}
```
As it is known, to get extension, I have to register it first and then parse the stream like this:
``` java
ExtensionRegistry reg = RextensionRegistry.newInstance();
registry.add(BProtos.b);
AProtos.A.parseFrom(stream, reg);
```
But as I can see from source code, converter only calls `parseFrom(stream)` and there are no hooks to attach `ExtensionRegistry` instance in the process.
Am I missing something?
My issue is very similar to this one http://stackoverflow.com/questions/21747336/protobuf-extension-registry-issue
| [
"retrofit-converters/protobuf/src/main/java/retrofit2/converter/protobuf/ProtoConverterFactory.java",
"retrofit-converters/protobuf/src/main/java/retrofit2/converter/protobuf/ProtoResponseBodyConverter.java"
] | [
"retrofit-converters/protobuf/src/main/java/retrofit2/converter/protobuf/ProtoConverterFactory.java",
"retrofit-converters/protobuf/src/main/java/retrofit2/converter/protobuf/ProtoResponseBodyConverter.java"
] | [
"retrofit-converters/protobuf/src/test/java/retrofit2/converter/protobuf/PhoneProtos.java",
"retrofit-converters/protobuf/src/test/java/retrofit2/converter/protobuf/ProtoConverterFactoryTest.java",
"retrofit-converters/protobuf/src/test/protos/phone.proto"
] | diff --git a/retrofit-converters/protobuf/src/main/java/retrofit2/converter/protobuf/ProtoConverterFactory.java b/retrofit-converters/protobuf/src/main/java/retrofit2/converter/protobuf/ProtoConverterFactory.java
index aa4420c9d8..9b544eb0dd 100644
--- a/retrofit-converters/protobuf/src/main/java/retrofit2/converter/protobuf/ProtoConverterFactory.java
+++ b/retrofit-converters/protobuf/src/main/java/retrofit2/converter/protobuf/ProtoConverterFactory.java
@@ -15,6 +15,7 @@
*/
package retrofit2.converter.protobuf;
+import com.google.protobuf.ExtensionRegistryLite;
import com.google.protobuf.MessageLite;
import com.google.protobuf.Parser;
import java.lang.annotation.Annotation;
@@ -33,7 +34,18 @@
*/
public final class ProtoConverterFactory extends Converter.Factory {
public static ProtoConverterFactory create() {
- return new ProtoConverterFactory();
+ return new ProtoConverterFactory(null);
+ }
+
+ /** Create an instance which uses {@code registry} when deserializing. */
+ public static ProtoConverterFactory createWithRegistry(ExtensionRegistryLite registry) {
+ return new ProtoConverterFactory(registry);
+ }
+
+ private final ExtensionRegistryLite registry;
+
+ private ProtoConverterFactory(ExtensionRegistryLite registry) {
+ this.registry = registry;
}
@Override
@@ -56,7 +68,7 @@ public static ProtoConverterFactory create() {
throw new IllegalArgumentException(
"Found a protobuf message but " + c.getName() + " had no PARSER field.");
}
- return new ProtoResponseBodyConverter<>(parser);
+ return new ProtoResponseBodyConverter<>(parser, registry);
}
@Override
diff --git a/retrofit-converters/protobuf/src/main/java/retrofit2/converter/protobuf/ProtoResponseBodyConverter.java b/retrofit-converters/protobuf/src/main/java/retrofit2/converter/protobuf/ProtoResponseBodyConverter.java
index f2b78e1ded..3241994585 100644
--- a/retrofit-converters/protobuf/src/main/java/retrofit2/converter/protobuf/ProtoResponseBodyConverter.java
+++ b/retrofit-converters/protobuf/src/main/java/retrofit2/converter/protobuf/ProtoResponseBodyConverter.java
@@ -15,6 +15,7 @@
*/
package retrofit2.converter.protobuf;
+import com.google.protobuf.ExtensionRegistryLite;
import com.google.protobuf.InvalidProtocolBufferException;
import com.google.protobuf.MessageLite;
import com.google.protobuf.Parser;
@@ -25,14 +26,16 @@
final class ProtoResponseBodyConverter<T extends MessageLite>
implements Converter<ResponseBody, T> {
private final Parser<T> parser;
+ private final ExtensionRegistryLite registry;
- ProtoResponseBodyConverter(Parser<T> parser) {
+ ProtoResponseBodyConverter(Parser<T> parser, ExtensionRegistryLite registry) {
this.parser = parser;
+ this.registry = registry;
}
@Override public T convert(ResponseBody value) throws IOException {
try {
- return parser.parseFrom(value.byteStream());
+ return parser.parseFrom(value.byteStream(), registry);
} catch (InvalidProtocolBufferException e) {
throw new RuntimeException(e); // Despite extending IOException, this is data mismatch.
} finally {
| diff --git a/retrofit-converters/protobuf/src/test/java/retrofit2/converter/protobuf/PhoneProtos.java b/retrofit-converters/protobuf/src/test/java/retrofit2/converter/protobuf/PhoneProtos.java
index 69b41325b9..99d2bb2088 100644
--- a/retrofit-converters/protobuf/src/test/java/retrofit2/converter/protobuf/PhoneProtos.java
+++ b/retrofit-converters/protobuf/src/test/java/retrofit2/converter/protobuf/PhoneProtos.java
@@ -3,17 +3,17 @@
package retrofit2.converter.protobuf;
-import com.google.protobuf.AbstractMessage;
-
public final class PhoneProtos {
private PhoneProtos() {}
public static void registerAllExtensions(
com.google.protobuf.ExtensionRegistry registry) {
+ registry.add(retrofit2.converter.protobuf.PhoneProtos.voicemail);
}
- public interface PhoneOrBuilder
- extends com.google.protobuf.MessageOrBuilder {
+ public interface PhoneOrBuilder extends
+ // @@protoc_insertion_point(interface_extends:retrofit2.converter.protobuf.Phone)
+ com.google.protobuf.GeneratedMessage.
+ ExtendableMessageOrBuilder<Phone> {
- // optional string number = 1;
/**
* <code>optional string number = 1;</code>
*/
@@ -29,13 +29,15 @@ public interface PhoneOrBuilder
getNumberBytes();
}
/**
- * Protobuf type {@code retrofit2.Phone}
+ * Protobuf type {@code retrofit2.converter.protobuf.Phone}
*/
public static final class Phone extends
- com.google.protobuf.GeneratedMessage
- implements PhoneOrBuilder {
+ com.google.protobuf.GeneratedMessage.ExtendableMessage<
+ Phone> implements
+ // @@protoc_insertion_point(message_implements:retrofit2.converter.protobuf.Phone)
+ PhoneOrBuilder {
// Use Phone.newBuilder() to construct.
- private Phone(com.google.protobuf.GeneratedMessage.Builder<?> builder) {
+ private Phone(com.google.protobuf.GeneratedMessage.ExtendableBuilder<retrofit2.converter.protobuf.PhoneProtos.Phone, ?> builder) {
super(builder);
this.unknownFields = builder.getUnknownFields();
}
@@ -80,8 +82,9 @@ private Phone(
break;
}
case 10: {
+ com.google.protobuf.ByteString bs = input.readBytes();
bitField0_ |= 0x00000001;
- number_ = input.readBytes();
+ number_ = bs;
break;
}
}
@@ -98,14 +101,14 @@ private Phone(
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
- return PhoneProtos.internal_static_retrofit_Phone_descriptor;
+ return retrofit2.converter.protobuf.PhoneProtos.internal_static_retrofit2_converter_protobuf_Phone_descriptor;
}
protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
internalGetFieldAccessorTable() {
- return PhoneProtos.internal_static_retrofit_Phone_fieldAccessorTable
+ return retrofit2.converter.protobuf.PhoneProtos.internal_static_retrofit2_converter_protobuf_Phone_fieldAccessorTable
.ensureFieldAccessorsInitialized(
- PhoneProtos.Phone.class, PhoneProtos.Phone.Builder.class);
+ retrofit2.converter.protobuf.PhoneProtos.Phone.class, retrofit2.converter.protobuf.PhoneProtos.Phone.Builder.class);
}
public static com.google.protobuf.Parser<Phone> PARSER =
@@ -124,7 +127,6 @@ public com.google.protobuf.Parser<Phone> getParserForType() {
}
private int bitField0_;
- // optional string number = 1;
public static final int NUMBER_FIELD_NUMBER = 1;
private java.lang.Object number_;
/**
@@ -141,7 +143,7 @@ public java.lang.String getNumber() {
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
- com.google.protobuf.ByteString bs =
+ com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
@@ -157,7 +159,7 @@ public java.lang.String getNumber() {
getNumberBytes() {
java.lang.Object ref = number_;
if (ref instanceof java.lang.String) {
- com.google.protobuf.ByteString b =
+ com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
number_ = b;
@@ -173,8 +175,13 @@ private void initFields() {
private byte memoizedIsInitialized = -1;
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
- if (isInitialized != -1) return isInitialized == 1;
+ if (isInitialized == 1) return true;
+ if (isInitialized == 0) return false;
+ if (!extensionsAreInitialized()) {
+ memoizedIsInitialized = 0;
+ return false;
+ }
memoizedIsInitialized = 1;
return true;
}
@@ -182,9 +189,13 @@ public final boolean isInitialized() {
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
getSerializedSize();
+ com.google.protobuf.GeneratedMessage
+ .ExtendableMessage<retrofit2.converter.protobuf.PhoneProtos.Phone>.ExtensionWriter extensionWriter =
+ newExtensionWriter();
if (((bitField0_ & 0x00000001) == 0x00000001)) {
output.writeBytes(1, getNumberBytes());
}
+ extensionWriter.writeUntil(3, output);
getUnknownFields().writeTo(output);
}
@@ -198,6 +209,7 @@ public int getSerializedSize() {
size += com.google.protobuf.CodedOutputStream
.computeBytesSize(1, getNumberBytes());
}
+ size += extensionsSerializedSize();
size += getUnknownFields().getSerializedSize();
memoizedSerializedSize = size;
return size;
@@ -210,53 +222,53 @@ protected java.lang.Object writeReplace()
return super.writeReplace();
}
- public static PhoneProtos.Phone parseFrom(
+ public static retrofit2.converter.protobuf.PhoneProtos.Phone parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
- public static PhoneProtos.Phone parseFrom(
+ public static retrofit2.converter.protobuf.PhoneProtos.Phone parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
- public static PhoneProtos.Phone parseFrom(byte[] data)
+ public static retrofit2.converter.protobuf.PhoneProtos.Phone parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
- public static PhoneProtos.Phone parseFrom(
+ public static retrofit2.converter.protobuf.PhoneProtos.Phone parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
- public static PhoneProtos.Phone parseFrom(java.io.InputStream input)
+ public static retrofit2.converter.protobuf.PhoneProtos.Phone parseFrom(java.io.InputStream input)
throws java.io.IOException {
return PARSER.parseFrom(input);
}
- public static PhoneProtos.Phone parseFrom(
+ public static retrofit2.converter.protobuf.PhoneProtos.Phone parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return PARSER.parseFrom(input, extensionRegistry);
}
- public static PhoneProtos.Phone parseDelimitedFrom(java.io.InputStream input)
+ public static retrofit2.converter.protobuf.PhoneProtos.Phone parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return PARSER.parseDelimitedFrom(input);
}
- public static PhoneProtos.Phone parseDelimitedFrom(
+ public static retrofit2.converter.protobuf.PhoneProtos.Phone parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return PARSER.parseDelimitedFrom(input, extensionRegistry);
}
- public static PhoneProtos.Phone parseFrom(
+ public static retrofit2.converter.protobuf.PhoneProtos.Phone parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return PARSER.parseFrom(input);
}
- public static PhoneProtos.Phone parseFrom(
+ public static retrofit2.converter.protobuf.PhoneProtos.Phone parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
@@ -265,7 +277,7 @@ public static PhoneProtos.Phone parseFrom(
public static Builder newBuilder() { return Builder.create(); }
public Builder newBuilderForType() { return newBuilder(); }
- public static Builder newBuilder(PhoneProtos.Phone prototype) {
+ public static Builder newBuilder(retrofit2.converter.protobuf.PhoneProtos.Phone prototype) {
return newBuilder().mergeFrom(prototype);
}
public Builder toBuilder() { return newBuilder(this); }
@@ -277,21 +289,23 @@ protected Builder newBuilderForType(
return builder;
}
/**
- * Protobuf type {@code retrofit2.Phone}
+ * Protobuf type {@code retrofit2.converter.protobuf.Phone}
*/
public static final class Builder extends
- com.google.protobuf.GeneratedMessage.Builder<Builder>
- implements PhoneProtos.PhoneOrBuilder {
+ com.google.protobuf.GeneratedMessage.ExtendableBuilder<
+ retrofit2.converter.protobuf.PhoneProtos.Phone, Builder> implements
+ // @@protoc_insertion_point(builder_implements:retrofit2.converter.protobuf.Phone)
+ retrofit2.converter.protobuf.PhoneProtos.PhoneOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
- return PhoneProtos.internal_static_retrofit_Phone_descriptor;
+ return retrofit2.converter.protobuf.PhoneProtos.internal_static_retrofit2_converter_protobuf_Phone_descriptor;
}
protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
internalGetFieldAccessorTable() {
- return PhoneProtos.internal_static_retrofit_Phone_fieldAccessorTable
+ return retrofit2.converter.protobuf.PhoneProtos.internal_static_retrofit2_converter_protobuf_Phone_fieldAccessorTable
.ensureFieldAccessorsInitialized(
- PhoneProtos.Phone.class, PhoneProtos.Phone.Builder.class);
+ retrofit2.converter.protobuf.PhoneProtos.Phone.class, retrofit2.converter.protobuf.PhoneProtos.Phone.Builder.class);
}
// Construct using retrofit2.converter.protobuf.PhoneProtos.Phone.newBuilder()
@@ -325,23 +339,23 @@ public Builder clone() {
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
- return PhoneProtos.internal_static_retrofit_Phone_descriptor;
+ return retrofit2.converter.protobuf.PhoneProtos.internal_static_retrofit2_converter_protobuf_Phone_descriptor;
}
- public PhoneProtos.Phone getDefaultInstanceForType() {
- return PhoneProtos.Phone.getDefaultInstance();
+ public retrofit2.converter.protobuf.PhoneProtos.Phone getDefaultInstanceForType() {
+ return retrofit2.converter.protobuf.PhoneProtos.Phone.getDefaultInstance();
}
- public PhoneProtos.Phone build() {
- PhoneProtos.Phone result = buildPartial();
+ public retrofit2.converter.protobuf.PhoneProtos.Phone build() {
+ retrofit2.converter.protobuf.PhoneProtos.Phone result = buildPartial();
if (!result.isInitialized()) {
- throw AbstractMessage.Builder.newUninitializedMessageException(result);
+ throw newUninitializedMessageException(result);
}
return result;
}
- public PhoneProtos.Phone buildPartial() {
- PhoneProtos.Phone result = new PhoneProtos.Phone(this);
+ public retrofit2.converter.protobuf.PhoneProtos.Phone buildPartial() {
+ retrofit2.converter.protobuf.PhoneProtos.Phone result = new retrofit2.converter.protobuf.PhoneProtos.Phone(this);
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000001) == 0x00000001)) {
@@ -354,26 +368,31 @@ public PhoneProtos.Phone buildPartial() {
}
public Builder mergeFrom(com.google.protobuf.Message other) {
- if (other instanceof PhoneProtos.Phone) {
- return mergeFrom((PhoneProtos.Phone)other);
+ if (other instanceof retrofit2.converter.protobuf.PhoneProtos.Phone) {
+ return mergeFrom((retrofit2.converter.protobuf.PhoneProtos.Phone)other);
} else {
super.mergeFrom(other);
return this;
}
}
- public Builder mergeFrom(PhoneProtos.Phone other) {
- if (other == PhoneProtos.Phone.getDefaultInstance()) return this;
+ public Builder mergeFrom(retrofit2.converter.protobuf.PhoneProtos.Phone other) {
+ if (other == retrofit2.converter.protobuf.PhoneProtos.Phone.getDefaultInstance()) return this;
if (other.hasNumber()) {
bitField0_ |= 0x00000001;
number_ = other.number_;
onChanged();
}
+ this.mergeExtensionFields(other);
this.mergeUnknownFields(other.getUnknownFields());
return this;
}
public final boolean isInitialized() {
+ if (!extensionsAreInitialized()) {
+
+ return false;
+ }
return true;
}
@@ -381,11 +400,11 @@ public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
- PhoneProtos.Phone parsedMessage = null;
+ retrofit2.converter.protobuf.PhoneProtos.Phone parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
- parsedMessage = (PhoneProtos.Phone) e.getUnfinishedMessage();
+ parsedMessage = (retrofit2.converter.protobuf.PhoneProtos.Phone) e.getUnfinishedMessage();
throw e;
} finally {
if (parsedMessage != null) {
@@ -396,7 +415,6 @@ public Builder mergeFrom(
}
private int bitField0_;
- // optional string number = 1;
private java.lang.Object number_ = "";
/**
* <code>optional string number = 1;</code>
@@ -410,9 +428,12 @@ public boolean hasNumber() {
public java.lang.String getNumber() {
java.lang.Object ref = number_;
if (!(ref instanceof java.lang.String)) {
- java.lang.String s = ((com.google.protobuf.ByteString) ref)
- .toStringUtf8();
- number_ = s;
+ com.google.protobuf.ByteString bs =
+ (com.google.protobuf.ByteString) ref;
+ java.lang.String s = bs.toStringUtf8();
+ if (bs.isValidUtf8()) {
+ number_ = s;
+ }
return s;
} else {
return (java.lang.String) ref;
@@ -425,7 +446,7 @@ public java.lang.String getNumber() {
getNumberBytes() {
java.lang.Object ref = number_;
if (ref instanceof String) {
- com.google.protobuf.ByteString b =
+ com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
number_ = b;
@@ -470,7 +491,7 @@ public Builder setNumberBytes(
return this;
}
- // @@protoc_insertion_point(builder_scope:retrofit2.Phone)
+ // @@protoc_insertion_point(builder_scope:retrofit2.converter.protobuf.Phone)
}
static {
@@ -478,14 +499,25 @@ public Builder setNumberBytes(
defaultInstance.initFields();
}
- // @@protoc_insertion_point(class_scope:retrofit2.Phone)
+ // @@protoc_insertion_point(class_scope:retrofit2.converter.protobuf.Phone)
}
- private static com.google.protobuf.Descriptors.Descriptor
- internal_static_retrofit_Phone_descriptor;
+ public static final int VOICEMAIL_FIELD_NUMBER = 2;
+ /**
+ * <code>extend .retrofit2.converter.protobuf.Phone { ... }</code>
+ */
+ public static final
+ com.google.protobuf.GeneratedMessage.GeneratedExtension<
+ retrofit2.converter.protobuf.PhoneProtos.Phone,
+ java.lang.Boolean> voicemail = com.google.protobuf.GeneratedMessage
+ .newFileScopedGeneratedExtension(
+ java.lang.Boolean.class,
+ null);
+ private static final com.google.protobuf.Descriptors.Descriptor
+ internal_static_retrofit2_converter_protobuf_Phone_descriptor;
private static
com.google.protobuf.GeneratedMessage.FieldAccessorTable
- internal_static_retrofit_Phone_fieldAccessorTable;
+ internal_static_retrofit2_converter_protobuf_Phone_fieldAccessorTable;
public static com.google.protobuf.Descriptors.FileDescriptor
getDescriptor() {
@@ -495,28 +527,31 @@ public Builder setNumberBytes(
descriptor;
static {
java.lang.String[] descriptorData = {
- "\n\022protos/phone.proto\022\010retrofit\"\027\n\005Phone\022" +
- "\016\n\006number\030\001 \001(\tB!\n\022retrofit.converterB\013P" +
- "honeProtos"
+ "\n\022protos/phone.proto\022\034retrofit2.converte" +
+ "r.protobuf\"\035\n\005Phone\022\016\n\006number\030\001 \001(\t*\004\010\002\020" +
+ "\003:6\n\tvoicemail\022#.retrofit2.converter.pro" +
+ "tobuf.Phone\030\002 \001(\010B+\n\034retrofit2.converter" +
+ ".protobufB\013PhoneProtos"
};
com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner =
- new com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner() {
- public com.google.protobuf.ExtensionRegistry assignDescriptors(
- com.google.protobuf.Descriptors.FileDescriptor root) {
- descriptor = root;
- internal_static_retrofit_Phone_descriptor =
- getDescriptor().getMessageTypes().get(0);
- internal_static_retrofit_Phone_fieldAccessorTable = new
- com.google.protobuf.GeneratedMessage.FieldAccessorTable(
- internal_static_retrofit_Phone_descriptor,
- new java.lang.String[] { "Number", });
- return null;
- }
- };
+ new com.google.protobuf.Descriptors.FileDescriptor. InternalDescriptorAssigner() {
+ public com.google.protobuf.ExtensionRegistry assignDescriptors(
+ com.google.protobuf.Descriptors.FileDescriptor root) {
+ descriptor = root;
+ return null;
+ }
+ };
com.google.protobuf.Descriptors.FileDescriptor
.internalBuildGeneratedFileFrom(descriptorData,
new com.google.protobuf.Descriptors.FileDescriptor[] {
}, assigner);
+ internal_static_retrofit2_converter_protobuf_Phone_descriptor =
+ getDescriptor().getMessageTypes().get(0);
+ internal_static_retrofit2_converter_protobuf_Phone_fieldAccessorTable = new
+ com.google.protobuf.GeneratedMessage.FieldAccessorTable(
+ internal_static_retrofit2_converter_protobuf_Phone_descriptor,
+ new java.lang.String[] { "Number", });
+ voicemail.internalInit(descriptor.getExtensions().get(0));
}
// @@protoc_insertion_point(outer_class_scope)
diff --git a/retrofit-converters/protobuf/src/test/java/retrofit2/converter/protobuf/ProtoConverterFactoryTest.java b/retrofit-converters/protobuf/src/test/java/retrofit2/converter/protobuf/ProtoConverterFactoryTest.java
index f2ca958f47..5a585b21f3 100644
--- a/retrofit-converters/protobuf/src/test/java/retrofit2/converter/protobuf/ProtoConverterFactoryTest.java
+++ b/retrofit-converters/protobuf/src/test/java/retrofit2/converter/protobuf/ProtoConverterFactoryTest.java
@@ -15,6 +15,7 @@
*/
package retrofit2.converter.protobuf;
+import com.google.protobuf.ExtensionRegistry;
import com.google.protobuf.InvalidProtocolBufferException;
import java.io.IOException;
import java.util.List;
@@ -44,10 +45,14 @@ interface Service {
@GET("/") Call<String> wrongClass();
@GET("/") Call<List<String>> wrongType();
}
+ interface ServiceWithRegistry {
+ @GET("/") Call<Phone> get();
+ }
@Rule public final MockWebServer server = new MockWebServer();
private Service service;
+ private ServiceWithRegistry serviceWithRegistry;
@Before public void setUp() {
Retrofit retrofit = new Retrofit.Builder()
@@ -55,6 +60,14 @@ interface Service {
.addConverterFactory(ProtoConverterFactory.create())
.build();
service = retrofit.create(Service.class);
+
+ ExtensionRegistry registry = ExtensionRegistry.newInstance();
+ PhoneProtos.registerAllExtensions(registry);
+ Retrofit retrofitWithRegistry = new Retrofit.Builder()
+ .baseUrl(server.url("/"))
+ .addConverterFactory(ProtoConverterFactory.createWithRegistry(registry))
+ .build();
+ serviceWithRegistry = retrofitWithRegistry.create(ServiceWithRegistry.class);
}
@Test public void serializeAndDeserialize() throws IOException, InterruptedException {
@@ -80,6 +93,17 @@ interface Service {
assertThat(body.hasNumber()).isFalse();
}
+ @Test public void deserializeUsesRegistry() throws IOException {
+ ByteString encoded = ByteString.decodeBase64("Cg4oNTE5KSA4NjctNTMwORAB");
+ server.enqueue(new MockResponse().setBody(new Buffer().write(encoded)));
+
+ Call<Phone> call = serviceWithRegistry.get();
+ Response<Phone> response = call.execute();
+ Phone body = response.body();
+ assertThat(body.getNumber()).isEqualTo("(519) 867-5309");
+ assertThat(body.getExtension(PhoneProtos.voicemail)).isEqualTo(true);
+ }
+
@Test public void deserializeWrongClass() throws IOException {
ByteString encoded = ByteString.decodeBase64("Cg4oNTE5KSA4NjctNTMwOQ==");
server.enqueue(new MockResponse().setBody(new Buffer().write(encoded)));
diff --git a/retrofit-converters/protobuf/src/test/protos/phone.proto b/retrofit-converters/protobuf/src/test/protos/phone.proto
index 69876668b4..02e4b9268f 100644
--- a/retrofit-converters/protobuf/src/test/protos/phone.proto
+++ b/retrofit-converters/protobuf/src/test/protos/phone.proto
@@ -1,8 +1,14 @@
package retrofit2.converter.protobuf;
-option java_package = "retrofit2";
+option java_package = "retrofit2.converter.protobuf";
option java_outer_classname = "PhoneProtos";
message Phone {
optional string number = 1;
+
+ extensions 2;
+}
+
+extend Phone {
+ optional bool voicemail = 2;
}
| test | val | 2016-03-31T05:04:09 | "2016-04-02T16:28:14Z" | vganin | val |
square/retrofit/1716_1718 | square/retrofit | square/retrofit/1716 | square/retrofit/1718 | [
"keyword_pr_to_issue"
] | d03c87f6066c005c3336ebd8cbc85ec983dfc6d2 | 471a12ee7ef0d16f370a6f3366507246ff0f7251 | [] | [] | "2016-04-05T15:13:57Z" | [] | Cloning a call leads to callback being invoked off the main thread | I have to retry a call in the callback after it failed. As mentioned in various places, you can do so by cloning the Call<T> and enqueuing (or executing) it again. Problem is, that cloned callback is not invoked on the main thread (which I need for doing UI stuff).
I played around with other/new callbacks, starting a completely new call, etc. Only when I clone the call the callback is invoked off the main thread.
Using Retrofit 2.0.1
Was confimred by at least one other user:
[Stackoverflow topic](http://stackoverflow.com/questions/36407237/cloning-a-call-leads-to-callback-being-called-off-the-main-thread)
``` java
public static abstract class MyCallback<T> implements Callback<T> {
@Override
public void onResponse(Call<T> call, retrofit2.Response<T> response) {
Timber.d("is this the main thread %b", Looper.myLooper() == Looper.getMainLooper());
if (response.isSuccessful()) {
//success handling
} else {
if (response.code() == 406) {
// remedy reason for failure
call.clone().enqueue(MyCallback.this);
}
}
}
@Override
public void onFailure(Call<T> call, Throwable t) {
Timber.e("onFailure %s", t.getMessage());
}
}
```
Gives:
```
is this the main thread true
is this the main thread false
is this the main thread false
is this the main thread false
is this the main thread false
[looping]
```
| [
"retrofit/src/main/java/retrofit2/ExecutorCallAdapterFactory.java"
] | [
"retrofit/src/main/java/retrofit2/ExecutorCallAdapterFactory.java"
] | [
"retrofit/src/test/java/retrofit2/ExecutorCallAdapterFactoryTest.java"
] | diff --git a/retrofit/src/main/java/retrofit2/ExecutorCallAdapterFactory.java b/retrofit/src/main/java/retrofit2/ExecutorCallAdapterFactory.java
index 95ecbf4b7e..0c44243c6f 100644
--- a/retrofit/src/main/java/retrofit2/ExecutorCallAdapterFactory.java
+++ b/retrofit/src/main/java/retrofit2/ExecutorCallAdapterFactory.java
@@ -58,23 +58,23 @@ static final class ExecutorCallbackCall<T> implements Call<T> {
if (callback == null) throw new NullPointerException("callback == null");
delegate.enqueue(new Callback<T>() {
- @Override public void onResponse(final Call<T> call, final Response<T> response) {
+ @Override public void onResponse(Call<T> call, final Response<T> response) {
callbackExecutor.execute(new Runnable() {
@Override public void run() {
if (delegate.isCanceled()) {
// Emulate OkHttp's behavior of throwing/delivering an IOException on cancellation.
- callback.onFailure(call, new IOException("Canceled"));
+ callback.onFailure(ExecutorCallbackCall.this, new IOException("Canceled"));
} else {
- callback.onResponse(call, response);
+ callback.onResponse(ExecutorCallbackCall.this, response);
}
}
});
}
- @Override public void onFailure(final Call<T> call, final Throwable t) {
+ @Override public void onFailure(Call<T> call, final Throwable t) {
callbackExecutor.execute(new Runnable() {
@Override public void run() {
- callback.onFailure(call, t);
+ callback.onFailure(ExecutorCallbackCall.this, t);
}
});
}
| diff --git a/retrofit/src/test/java/retrofit2/ExecutorCallAdapterFactoryTest.java b/retrofit/src/test/java/retrofit2/ExecutorCallAdapterFactoryTest.java
index ba45b5fe67..24b8710529 100644
--- a/retrofit/src/test/java/retrofit2/ExecutorCallAdapterFactoryTest.java
+++ b/retrofit/src/test/java/retrofit2/ExecutorCallAdapterFactoryTest.java
@@ -94,7 +94,7 @@ public final class ExecutorCallAdapterFactoryTest {
Call<String> call = (Call<String>) adapter.adapt(originalCall);
call.enqueue(callback);
verify(callbackExecutor).execute(any(Runnable.class));
- verify(callback).onResponse(originalCall, response);
+ verify(callback).onResponse(call, response);
}
@Test public void adaptedCallEnqueueUsesExecutorForFailureCallback() {
@@ -111,7 +111,7 @@ public final class ExecutorCallAdapterFactoryTest {
call.enqueue(callback);
verify(callbackExecutor).execute(any(Runnable.class));
verifyNoMoreInteractions(callbackExecutor);
- verify(callback).onFailure(originalCall, throwable);
+ verify(callback).onFailure(call, throwable);
verifyNoMoreInteractions(callback);
}
| val | val | 2016-04-03T16:33:13 | "2016-04-05T10:36:29Z" | TillSimon | val |
square/retrofit/1740_1743 | square/retrofit | square/retrofit/1740 | square/retrofit/1743 | [
"timestamp(timedelta=67182.0, similarity=0.850899462607937)"
] | d04f3a50e41ca01d22f370ac4f332f6ddf4ba9fe | 6f9b7161f3447feb16a0cee6c389a18532102915 | [
"### Read the official document\n\n[]()http://square.github.io/retrofit/\n\n> CONVERTERS\n> \n> By default, Retrofit can only deserialize HTTP bodies into OkHttp's ResponseBody type and it can only accept its RequestBody type for @Body.\n> \n> Converters can be added to support other types. Six sibling modules adapt popular serialization libraries for your convenience.\n> \n> Gson: com.squareup.retrofit2:converter-gson\n> Jackson: com.squareup.retrofit2:converter-jackson\n> Moshi: com.squareup.retrofit2:converter-moshi\n> Protobuf: com.squareup.retrofit2:converter-protobuf\n> Wire: com.squareup.retrofit2:converter-wire\n> Simple XML: com.squareup.retrofit2:converter-simplexml\n> Scalars (primitives, boxed, and String): com.squareup.retrofit2:converter-scalars\n\n### About Serializing and Deserializing Generic Types:\n\nAssumed, Serializing and Deserializing json data with Gson\n[](url)https://github.com/google/gson/blob/master/UserGuide.md#TOC-Serializing-and-Deserializing-Generic-Types\n",
"@yy197133 \nIt seams that you are not reading the retrofit document carefully. Always look at the official document/example before ask any questions;\n\n```\nI don't know how to add gson convertor to retrofit2.0?\n```\n\nUse com.squareup.retrofit2:converter-gson mentioned above;\n\n```\ndata is generic (private T data;)\n```\n\nData is absolutely ok to be different for each API response, it‘s nothing to do with generic, you'd better specify the detail data structure for each response. You can define base response class with data to be generic\n",
"Seems like this was answered. Additionally there's a `samples/` folder which has some example usages that include Gson. Feel free to direct specific questions to StackOverflow with the 'retrofit' tag in the future.\n"
] | [] | "2016-04-15T09:01:59Z" | [] | How can I add convertor to retrofit 2.0 with a generic gson? | my server json like this:
{code:
msg:
data:{}
}
in POJO, data is generic (private T data;),I know how to parse,but I don't know how to add gson convertor to retrofit2.0?
| [
"pom.xml",
"retrofit-converters/pom.xml"
] | [
"pom.xml",
"retrofit-converters/fastjson/README.md",
"retrofit-converters/fastjson/pom.xml",
"retrofit-converters/fastjson/src/main/java/retrofit2/converter/fastjson/FastJsonConverterFactory.java",
"retrofit-converters/fastjson/src/main/java/retrofit2/converter/fastjson/FastJsonRequestBodyConverter.java",
"retrofit-converters/fastjson/src/main/java/retrofit2/converter/fastjson/FastJsonResponseBodyConverter.java",
"retrofit-converters/pom.xml"
] | [
"retrofit-converters/fastjson/src/test/java/retrofit2/converter/fastjson/FastJsonConverterFactoryTest.java"
] | diff --git a/pom.xml b/pom.xml
index b99efb76b1..9336f3a3df 100644
--- a/pom.xml
+++ b/pom.xml
@@ -56,6 +56,7 @@
<rxjava.version>1.1.1</rxjava.version>
<!-- Converter Dependencies -->
+ <fastjson.version>1.2.8</fastjson.version>
<gson.version>2.6.1</gson.version>
<protobuf.version>2.6.1</protobuf.version>
<jackson.version>2.7.2</jackson.version>
@@ -115,6 +116,11 @@
<artifactId>okhttp</artifactId>
<version>${okhttp.version}</version>
</dependency>
+ <dependency>
+ <groupId>com.alibaba</groupId>
+ <artifactId>fastjson</artifactId>
+ <version>${fastjson.version}</version>
+ </dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
diff --git a/retrofit-converters/fastjson/README.md b/retrofit-converters/fastjson/README.md
new file mode 100644
index 0000000000..238b51e36c
--- /dev/null
+++ b/retrofit-converters/fastjson/README.md
@@ -0,0 +1,6 @@
+FastJson Converter
+==============
+
+A `Converter` which uses [FastJson][1] for serialization to and from JSON.
+
+ [1]: https://github.com/alibaba/fastjson
diff --git a/retrofit-converters/fastjson/pom.xml b/retrofit-converters/fastjson/pom.xml
new file mode 100644
index 0000000000..25cb8cc306
--- /dev/null
+++ b/retrofit-converters/fastjson/pom.xml
@@ -0,0 +1,44 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+
+ <parent>
+ <groupId>com.squareup.retrofit2</groupId>
+ <artifactId>retrofit-converters</artifactId>
+ <version>2.0.3-SNAPSHOT</version>
+ <relativePath>../pom.xml</relativePath>
+ </parent>
+
+ <artifactId>converter-fastjson</artifactId>
+ <name>Converter: FastJson</name>
+
+ <dependencies>
+ <dependency>
+ <groupId>${project.groupId}</groupId>
+ <artifactId>retrofit</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>com.alibaba</groupId>
+ <artifactId>fastjson</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>com.squareup.okhttp3</groupId>
+ <artifactId>mockwebserver</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.assertj</groupId>
+ <artifactId>assertj-core</artifactId>
+ <scope>test</scope>
+ </dependency>
+ </dependencies>
+
+</project>
\ No newline at end of file
diff --git a/retrofit-converters/fastjson/src/main/java/retrofit2/converter/fastjson/FastJsonConverterFactory.java b/retrofit-converters/fastjson/src/main/java/retrofit2/converter/fastjson/FastJsonConverterFactory.java
new file mode 100644
index 0000000000..9ed0f2b391
--- /dev/null
+++ b/retrofit-converters/fastjson/src/main/java/retrofit2/converter/fastjson/FastJsonConverterFactory.java
@@ -0,0 +1,100 @@
+package retrofit2.converter.fastjson;
+
+import com.alibaba.fastjson.JSON;
+import com.alibaba.fastjson.parser.Feature;
+import com.alibaba.fastjson.parser.ParserConfig;
+import com.alibaba.fastjson.parser.deserializer.ParseProcess;
+import com.alibaba.fastjson.serializer.SerializeConfig;
+import com.alibaba.fastjson.serializer.SerializerFeature;
+import okhttp3.RequestBody;
+import okhttp3.ResponseBody;
+import retrofit2.Converter;
+import retrofit2.Retrofit;
+
+import java.lang.annotation.Annotation;
+import java.lang.reflect.Type;
+
+
+/**
+ * A {@linkplain Converter.Factory converter} which uses FastJson for JSON.
+ * <p>
+ * Because FastJson is so flexible in the types it supports, this converter assumes that it can handle
+ * all types. If you are mixing JSON serialization with something else (such as protocol buffers),
+ * you must {@linkplain Retrofit.Builder#addConverterFactory(Converter.Factory) add this instance}
+ * last to allow the other converters a chance to see their types.
+ */
+public class FastJsonConverterFactory extends Converter.Factory {
+
+ private ParserConfig mParserConfig = ParserConfig.getGlobalInstance();
+ private int mFeatureValues = JSON.DEFAULT_PARSER_FEATURE;
+ private Feature[] mFeatures;
+
+ private SerializeConfig mSerializeConfig;
+ private SerializerFeature[] mSerializerFeatures;
+
+ /**
+ * Create an default instance for conversion. Encoding to JSON and
+ * decoding from JSON (when no charset is specified by a header) will use UTF-8.
+ */
+ public static FastJsonConverterFactory create() {
+ return new FastJsonConverterFactory();
+ }
+
+ private FastJsonConverterFactory() {
+ }
+
+ @Override
+ public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
+ return new FastJsonResponseBodyConverter<>(type, mParserConfig, mFeatureValues, mFeatures);
+ }
+
+ @Override
+ public Converter<?, RequestBody> requestBodyConverter(Type type, Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
+ return new FastJsonRequestBodyConverter<>(mSerializeConfig, mSerializerFeatures);
+ }
+
+ public ParserConfig getParserConfig() {
+ return mParserConfig;
+ }
+
+ public FastJsonConverterFactory setParserConfig(ParserConfig config) {
+ this.mParserConfig = config;
+ return this;
+ }
+
+ public int getParserFeatureValues() {
+ return mFeatureValues;
+ }
+
+ public FastJsonConverterFactory setParserFeatureValues(int featureValues) {
+ this.mFeatureValues = featureValues;
+ return this;
+ }
+
+ public Feature[] getParserFeatures() {
+ return mFeatures;
+ }
+
+ public FastJsonConverterFactory setParserFeatures(Feature[] features) {
+ this.mFeatures = features;
+ return this;
+ }
+
+ public SerializeConfig getSerializeConfig() {
+ return mSerializeConfig;
+ }
+
+ public FastJsonConverterFactory setSerializeConfig(SerializeConfig serializeConfig) {
+ this.mSerializeConfig = serializeConfig;
+ return this;
+ }
+
+ public SerializerFeature[] getSerializerFeatures() {
+ return mSerializerFeatures;
+ }
+
+ public FastJsonConverterFactory setSerializerFeatures(SerializerFeature[] serializerFeatures) {
+ this.mSerializerFeatures = serializerFeatures;
+ return this;
+ }
+}
diff --git a/retrofit-converters/fastjson/src/main/java/retrofit2/converter/fastjson/FastJsonRequestBodyConverter.java b/retrofit-converters/fastjson/src/main/java/retrofit2/converter/fastjson/FastJsonRequestBodyConverter.java
new file mode 100644
index 0000000000..8432de8ffd
--- /dev/null
+++ b/retrofit-converters/fastjson/src/main/java/retrofit2/converter/fastjson/FastJsonRequestBodyConverter.java
@@ -0,0 +1,40 @@
+package retrofit2.converter.fastjson;
+
+import com.alibaba.fastjson.JSON;
+import com.alibaba.fastjson.serializer.SerializeConfig;
+import com.alibaba.fastjson.serializer.SerializerFeature;
+import okhttp3.MediaType;
+import okhttp3.RequestBody;
+import retrofit2.Converter;
+
+import java.io.IOException;
+
+final class FastJsonRequestBodyConverter<T> implements Converter<T, RequestBody> {
+ private static final MediaType MEDIA_TYPE = MediaType.parse("application/json; charset=UTF-8");
+ private SerializeConfig mSerializeConfig;
+ private SerializerFeature[] mSerializerFeatures;
+
+ FastJsonRequestBodyConverter(SerializeConfig config, SerializerFeature... features) {
+ mSerializeConfig = config;
+ mSerializerFeatures = features;
+ }
+
+ @Override
+ public RequestBody convert(T value) throws IOException {
+ byte[] content;
+ if (mSerializeConfig != null) {
+ if (mSerializerFeatures != null) {
+ content = JSON.toJSONBytes(value, mSerializeConfig, mSerializerFeatures);
+ } else {
+ content = JSON.toJSONBytes(value, mSerializeConfig);
+ }
+ } else {
+ if (mSerializerFeatures != null) {
+ content = JSON.toJSONBytes(value, mSerializerFeatures);
+ } else {
+ content = JSON.toJSONBytes(value);
+ }
+ }
+ return RequestBody.create(MEDIA_TYPE, content);
+ }
+}
diff --git a/retrofit-converters/fastjson/src/main/java/retrofit2/converter/fastjson/FastJsonResponseBodyConverter.java b/retrofit-converters/fastjson/src/main/java/retrofit2/converter/fastjson/FastJsonResponseBodyConverter.java
new file mode 100644
index 0000000000..193112ba44
--- /dev/null
+++ b/retrofit-converters/fastjson/src/main/java/retrofit2/converter/fastjson/FastJsonResponseBodyConverter.java
@@ -0,0 +1,40 @@
+package retrofit2.converter.fastjson;
+
+import com.alibaba.fastjson.JSON;
+import com.alibaba.fastjson.parser.Feature;
+import com.alibaba.fastjson.parser.ParserConfig;
+import com.alibaba.fastjson.parser.deserializer.ParseProcess;
+import okhttp3.ResponseBody;
+import retrofit2.Converter;
+
+import java.io.IOException;
+import java.lang.reflect.Type;
+
+final class FastJsonResponseBodyConverter<T> implements Converter<ResponseBody, T> {
+
+ private static final Feature[] EMPTY_SERIALIZER_FEATURES = new Feature[0];
+
+ private Type mType;
+
+ private ParserConfig mConfig;
+ private int mFeatureValues;
+ private Feature[] mFeatures;
+
+ FastJsonResponseBodyConverter(Type type, ParserConfig config, int featureValues,
+ Feature... features) {
+ mType = type;
+ mConfig = config;
+ mFeatureValues = featureValues;
+ mFeatures = features;
+ }
+
+ @Override
+ public T convert(ResponseBody value) throws IOException {
+ try {
+ return JSON.parseObject(value.string(), mType, mConfig, mFeatureValues,
+ mFeatures != null ? mFeatures : EMPTY_SERIALIZER_FEATURES);
+ } finally {
+ value.close();
+ }
+ }
+}
diff --git a/retrofit-converters/pom.xml b/retrofit-converters/pom.xml
index 87b1463cc2..b4c89fb8b7 100644
--- a/retrofit-converters/pom.xml
+++ b/retrofit-converters/pom.xml
@@ -22,5 +22,6 @@
<module>simplexml</module>
<module>scalars</module>
<module>moshi</module>
+ <module>fastjson</module>
</modules>
</project>
| diff --git a/retrofit-converters/fastjson/src/test/java/retrofit2/converter/fastjson/FastJsonConverterFactoryTest.java b/retrofit-converters/fastjson/src/test/java/retrofit2/converter/fastjson/FastJsonConverterFactoryTest.java
new file mode 100644
index 0000000000..8d1a245a14
--- /dev/null
+++ b/retrofit-converters/fastjson/src/test/java/retrofit2/converter/fastjson/FastJsonConverterFactoryTest.java
@@ -0,0 +1,116 @@
+package retrofit2.converter.fastjson;
+
+
+import com.alibaba.fastjson.annotation.JSONField;
+import com.alibaba.fastjson.parser.DefaultJSONParser;
+import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer;
+import com.alibaba.fastjson.serializer.JSONSerializer;
+import com.alibaba.fastjson.serializer.ObjectSerializer;
+import com.alibaba.fastjson.serializer.SerializeWriter;
+import okhttp3.mockwebserver.MockResponse;
+import okhttp3.mockwebserver.MockWebServer;
+import okhttp3.mockwebserver.RecordedRequest;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import retrofit2.Call;
+import retrofit2.Response;
+import retrofit2.Retrofit;
+import retrofit2.http.Body;
+import retrofit2.http.POST;
+
+import java.io.IOException;
+import java.lang.reflect.Type;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+public class FastJsonConverterFactoryTest {
+ interface AnInterface {
+ @JSONField(name = "name")
+ String getName();
+ @JSONField(name = "name")
+ void setName(String name);
+ }
+
+ static class AnImplementation implements AnInterface {
+
+ @JSONField(name = "name")
+ private String theName;
+
+ AnImplementation() {
+ }
+
+ AnImplementation(String name) {
+ theName = name;
+ }
+
+ @JSONField(name = "name")
+ @Override public String getName() {
+ return theName;
+ }
+
+ @JSONField(name = "name")
+ @Override
+ public void setName(String name) {
+ theName = name;
+ }
+ }
+
+ interface Service {
+ @POST("/")
+ Call<AnImplementation> anImplementation(@Body AnImplementation impl);
+ @POST("/") Call<AnInterface> anInterface(@Body AnInterface impl);
+ }
+
+ @Rule
+ public final MockWebServer server = new MockWebServer();
+
+ private Service service;
+
+ @Before
+ public void setUp() {
+ Retrofit retrofit = new Retrofit.Builder()
+ .baseUrl(server.url("/"))
+ .addConverterFactory(FastJsonConverterFactory.create())
+ .build();
+ service = retrofit.create(Service.class);
+ }
+
+ @Test
+ public void anInterface() throws IOException, InterruptedException {
+ server.enqueue(new MockResponse().setBody("{\"name\":\"value\"}"));
+
+ Call<AnInterface> call = service.anInterface(new AnImplementation("value"));
+ Response<AnInterface> response = call.execute();
+ AnInterface body = response.body();
+ assertThat(body.getName()).isEqualTo("value");
+
+ RecordedRequest request = server.takeRequest();
+ assertThat(request.getBody().readUtf8()).isEqualTo("{\"name\":\"value\"}");
+ assertThat(request.getHeader("Content-Type")).isEqualTo("application/json; charset=UTF-8");
+ }
+
+ @Test public void anImplementation() throws IOException, InterruptedException {
+ server.enqueue(new MockResponse().setBody("{\"theName\":\"value\"}"));
+
+ Call<AnImplementation> call = service.anImplementation(new AnImplementation("value"));
+ Response<AnImplementation> response = call.execute();
+ AnImplementation body = response.body();
+ assertThat(body.theName).isNull();
+
+ RecordedRequest request = server.takeRequest();
+ assertThat(request.getBody().readUtf8()).isEqualTo("{\"name\":\"value\"}");
+ assertThat(request.getHeader("Content-Type")).isEqualTo("application/json; charset=UTF-8");
+ }
+
+ @Test public void serializeUsesConfiguration() throws IOException, InterruptedException {
+ server.enqueue(new MockResponse().setBody("{}"));
+
+ service.anImplementation(new AnImplementation(null)).execute();
+
+ RecordedRequest request = server.takeRequest();
+ assertThat(request.getBody().readUtf8()).isEqualTo("{}"); // Null value was not serialized.
+ assertThat(request.getHeader("Content-Type")).isEqualTo("application/json; charset=UTF-8");
+ }
+
+}
| train | val | 2016-04-15T02:23:13 | "2016-04-14T02:41:07Z" | yy197133 | val |
square/retrofit/1740_1744 | square/retrofit | square/retrofit/1740 | square/retrofit/1744 | [
"timestamp(timedelta=124.0, similarity=0.850899462607937)"
] | d04f3a50e41ca01d22f370ac4f332f6ddf4ba9fe | 8d642abe5a8319769c918e18e4f4a7a427f28638 | [
"### Read the official document\n\n[]()http://square.github.io/retrofit/\n\n> CONVERTERS\n> \n> By default, Retrofit can only deserialize HTTP bodies into OkHttp's ResponseBody type and it can only accept its RequestBody type for @Body.\n> \n> Converters can be added to support other types. Six sibling modules adapt popular serialization libraries for your convenience.\n> \n> Gson: com.squareup.retrofit2:converter-gson\n> Jackson: com.squareup.retrofit2:converter-jackson\n> Moshi: com.squareup.retrofit2:converter-moshi\n> Protobuf: com.squareup.retrofit2:converter-protobuf\n> Wire: com.squareup.retrofit2:converter-wire\n> Simple XML: com.squareup.retrofit2:converter-simplexml\n> Scalars (primitives, boxed, and String): com.squareup.retrofit2:converter-scalars\n\n### About Serializing and Deserializing Generic Types:\n\nAssumed, Serializing and Deserializing json data with Gson\n[](url)https://github.com/google/gson/blob/master/UserGuide.md#TOC-Serializing-and-Deserializing-Generic-Types\n",
"@yy197133 \nIt seams that you are not reading the retrofit document carefully. Always look at the official document/example before ask any questions;\n\n```\nI don't know how to add gson convertor to retrofit2.0?\n```\n\nUse com.squareup.retrofit2:converter-gson mentioned above;\n\n```\ndata is generic (private T data;)\n```\n\nData is absolutely ok to be different for each API response, it‘s nothing to do with generic, you'd better specify the detail data structure for each response. You can define base response class with data to be generic\n",
"Seems like this was answered. Additionally there's a `samples/` folder which has some example usages that include Gson. Feel free to direct specific questions to StackOverflow with the 'retrofit' tag in the future.\n"
] | [] | "2016-04-15T09:33:12Z" | [] | How can I add convertor to retrofit 2.0 with a generic gson? | my server json like this:
{code:
msg:
data:{}
}
in POJO, data is generic (private T data;),I know how to parse,but I don't know how to add gson convertor to retrofit2.0?
| [
"pom.xml",
"retrofit-converters/pom.xml"
] | [
"pom.xml",
"retrofit-converters/fastjson/README.md",
"retrofit-converters/fastjson/pom.xml",
"retrofit-converters/fastjson/src/main/java/retrofit2/converter/fastjson/FastJsonConverterFactory.java",
"retrofit-converters/fastjson/src/main/java/retrofit2/converter/fastjson/FastJsonRequestBodyConverter.java",
"retrofit-converters/fastjson/src/main/java/retrofit2/converter/fastjson/FastJsonResponseBodyConverter.java",
"retrofit-converters/pom.xml"
] | [
"retrofit-converters/fastjson/src/test/java/retrofit2/converter/fastjson/FastJsonConverterFactoryTest.java"
] | diff --git a/pom.xml b/pom.xml
index b99efb76b1..9336f3a3df 100644
--- a/pom.xml
+++ b/pom.xml
@@ -56,6 +56,7 @@
<rxjava.version>1.1.1</rxjava.version>
<!-- Converter Dependencies -->
+ <fastjson.version>1.2.8</fastjson.version>
<gson.version>2.6.1</gson.version>
<protobuf.version>2.6.1</protobuf.version>
<jackson.version>2.7.2</jackson.version>
@@ -115,6 +116,11 @@
<artifactId>okhttp</artifactId>
<version>${okhttp.version}</version>
</dependency>
+ <dependency>
+ <groupId>com.alibaba</groupId>
+ <artifactId>fastjson</artifactId>
+ <version>${fastjson.version}</version>
+ </dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
diff --git a/retrofit-converters/fastjson/README.md b/retrofit-converters/fastjson/README.md
new file mode 100644
index 0000000000..238b51e36c
--- /dev/null
+++ b/retrofit-converters/fastjson/README.md
@@ -0,0 +1,6 @@
+FastJson Converter
+==============
+
+A `Converter` which uses [FastJson][1] for serialization to and from JSON.
+
+ [1]: https://github.com/alibaba/fastjson
diff --git a/retrofit-converters/fastjson/pom.xml b/retrofit-converters/fastjson/pom.xml
new file mode 100644
index 0000000000..25cb8cc306
--- /dev/null
+++ b/retrofit-converters/fastjson/pom.xml
@@ -0,0 +1,44 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+
+ <parent>
+ <groupId>com.squareup.retrofit2</groupId>
+ <artifactId>retrofit-converters</artifactId>
+ <version>2.0.3-SNAPSHOT</version>
+ <relativePath>../pom.xml</relativePath>
+ </parent>
+
+ <artifactId>converter-fastjson</artifactId>
+ <name>Converter: FastJson</name>
+
+ <dependencies>
+ <dependency>
+ <groupId>${project.groupId}</groupId>
+ <artifactId>retrofit</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>com.alibaba</groupId>
+ <artifactId>fastjson</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>com.squareup.okhttp3</groupId>
+ <artifactId>mockwebserver</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.assertj</groupId>
+ <artifactId>assertj-core</artifactId>
+ <scope>test</scope>
+ </dependency>
+ </dependencies>
+
+</project>
\ No newline at end of file
diff --git a/retrofit-converters/fastjson/src/main/java/retrofit2/converter/fastjson/FastJsonConverterFactory.java b/retrofit-converters/fastjson/src/main/java/retrofit2/converter/fastjson/FastJsonConverterFactory.java
new file mode 100644
index 0000000000..ad1abebfd7
--- /dev/null
+++ b/retrofit-converters/fastjson/src/main/java/retrofit2/converter/fastjson/FastJsonConverterFactory.java
@@ -0,0 +1,101 @@
+package retrofit2.converter.fastjson;
+
+import com.alibaba.fastjson.JSON;
+import com.alibaba.fastjson.parser.Feature;
+import com.alibaba.fastjson.parser.ParserConfig;
+import com.alibaba.fastjson.serializer.SerializeConfig;
+import com.alibaba.fastjson.serializer.SerializerFeature;
+import okhttp3.RequestBody;
+import okhttp3.ResponseBody;
+import retrofit2.Converter;
+import retrofit2.Retrofit;
+
+import java.lang.annotation.Annotation;
+import java.lang.reflect.Type;
+
+
+/**
+ * A {@linkplain Converter.Factory converter} which uses FastJson for JSON.
+ * <p>
+ * Because FastJson is so flexible in the types it supports, this converter assumes that it can
+ * handle all types. If you are mixing JSON serialization with something else (such as protocol
+ * buffers), you must {@linkplain Retrofit.Builder#addConverterFactory(Converter.Factory) add
+ * this instance} last to allow the other converters a chance to see their types.
+ */
+public class FastJsonConverterFactory extends Converter.Factory {
+
+ private ParserConfig mParserConfig = ParserConfig.getGlobalInstance();
+ private int featureValues = JSON.DEFAULT_PARSER_FEATURE;
+ private Feature[] features;
+
+ private SerializeConfig serializeConfig;
+ private SerializerFeature[] serializerFeatures;
+
+ /**
+ * Create an default instance for conversion. Encoding to JSON and
+ * decoding from JSON (when no charset is specified by a header) will use UTF-8.
+ */
+ public static FastJsonConverterFactory create() {
+ return new FastJsonConverterFactory();
+ }
+
+ private FastJsonConverterFactory() {
+ }
+
+ @Override
+ public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations,
+ Retrofit retrofit) {
+ return new FastJsonResponseBodyConverter<>(type, mParserConfig, featureValues, features);
+ }
+
+ @Override
+ public Converter<?, RequestBody> requestBodyConverter(Type type,
+ Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
+ return new FastJsonRequestBodyConverter<>(serializeConfig, serializerFeatures);
+ }
+
+ public ParserConfig getParserConfig() {
+ return mParserConfig;
+ }
+
+ public FastJsonConverterFactory setParserConfig(ParserConfig config) {
+ this.mParserConfig = config;
+ return this;
+ }
+
+ public int getParserFeatureValues() {
+ return featureValues;
+ }
+
+ public FastJsonConverterFactory setParserFeatureValues(int featureValues) {
+ this.featureValues = featureValues;
+ return this;
+ }
+
+ public Feature[] getParserFeatures() {
+ return features;
+ }
+
+ public FastJsonConverterFactory setParserFeatures(Feature[] features) {
+ this.features = features;
+ return this;
+ }
+
+ public SerializeConfig getSerializeConfig() {
+ return serializeConfig;
+ }
+
+ public FastJsonConverterFactory setSerializeConfig(SerializeConfig serializeConfig) {
+ this.serializeConfig = serializeConfig;
+ return this;
+ }
+
+ public SerializerFeature[] getSerializerFeatures() {
+ return serializerFeatures;
+ }
+
+ public FastJsonConverterFactory setSerializerFeatures(SerializerFeature[] features) {
+ this.serializerFeatures = features;
+ return this;
+ }
+}
diff --git a/retrofit-converters/fastjson/src/main/java/retrofit2/converter/fastjson/FastJsonRequestBodyConverter.java b/retrofit-converters/fastjson/src/main/java/retrofit2/converter/fastjson/FastJsonRequestBodyConverter.java
new file mode 100644
index 0000000000..b21e36266a
--- /dev/null
+++ b/retrofit-converters/fastjson/src/main/java/retrofit2/converter/fastjson/FastJsonRequestBodyConverter.java
@@ -0,0 +1,40 @@
+package retrofit2.converter.fastjson;
+
+import com.alibaba.fastjson.JSON;
+import com.alibaba.fastjson.serializer.SerializeConfig;
+import com.alibaba.fastjson.serializer.SerializerFeature;
+import okhttp3.MediaType;
+import okhttp3.RequestBody;
+import retrofit2.Converter;
+
+import java.io.IOException;
+
+final class FastJsonRequestBodyConverter<T> implements Converter<T, RequestBody> {
+ private static final MediaType MEDIA_TYPE = MediaType.parse("application/json; charset=UTF-8");
+ private SerializeConfig serializeConfig;
+ private SerializerFeature[] serializerFeatures;
+
+ FastJsonRequestBodyConverter(SerializeConfig config, SerializerFeature... features) {
+ serializeConfig = config;
+ serializerFeatures = features;
+ }
+
+ @Override
+ public RequestBody convert(T value) throws IOException {
+ byte[] content;
+ if (serializeConfig != null) {
+ if (serializerFeatures != null) {
+ content = JSON.toJSONBytes(value, serializeConfig, serializerFeatures);
+ } else {
+ content = JSON.toJSONBytes(value, serializeConfig);
+ }
+ } else {
+ if (serializerFeatures != null) {
+ content = JSON.toJSONBytes(value, serializerFeatures);
+ } else {
+ content = JSON.toJSONBytes(value);
+ }
+ }
+ return RequestBody.create(MEDIA_TYPE, content);
+ }
+}
diff --git a/retrofit-converters/fastjson/src/main/java/retrofit2/converter/fastjson/FastJsonResponseBodyConverter.java b/retrofit-converters/fastjson/src/main/java/retrofit2/converter/fastjson/FastJsonResponseBodyConverter.java
new file mode 100644
index 0000000000..c965b73613
--- /dev/null
+++ b/retrofit-converters/fastjson/src/main/java/retrofit2/converter/fastjson/FastJsonResponseBodyConverter.java
@@ -0,0 +1,39 @@
+package retrofit2.converter.fastjson;
+
+import com.alibaba.fastjson.JSON;
+import com.alibaba.fastjson.parser.Feature;
+import com.alibaba.fastjson.parser.ParserConfig;
+import okhttp3.ResponseBody;
+import retrofit2.Converter;
+
+import java.io.IOException;
+import java.lang.reflect.Type;
+
+final class FastJsonResponseBodyConverter<T> implements Converter<ResponseBody, T> {
+
+ private static final Feature[] EMPTY_SERIALIZER_FEATURES = new Feature[0];
+
+ private Type mType;
+
+ private ParserConfig config;
+ private int featureValues;
+ private Feature[] features;
+
+ FastJsonResponseBodyConverter(Type type, ParserConfig config, int featureValues,
+ Feature... features) {
+ mType = type;
+ this.config = config;
+ this.featureValues = featureValues;
+ this.features = features;
+ }
+
+ @Override
+ public T convert(ResponseBody value) throws IOException {
+ try {
+ return JSON.parseObject(value.string(), mType, config, featureValues,
+ features != null ? features : EMPTY_SERIALIZER_FEATURES);
+ } finally {
+ value.close();
+ }
+ }
+}
diff --git a/retrofit-converters/pom.xml b/retrofit-converters/pom.xml
index 87b1463cc2..b4c89fb8b7 100644
--- a/retrofit-converters/pom.xml
+++ b/retrofit-converters/pom.xml
@@ -22,5 +22,6 @@
<module>simplexml</module>
<module>scalars</module>
<module>moshi</module>
+ <module>fastjson</module>
</modules>
</project>
| diff --git a/retrofit-converters/fastjson/src/test/java/retrofit2/converter/fastjson/FastJsonConverterFactoryTest.java b/retrofit-converters/fastjson/src/test/java/retrofit2/converter/fastjson/FastJsonConverterFactoryTest.java
new file mode 100644
index 0000000000..6467992d8f
--- /dev/null
+++ b/retrofit-converters/fastjson/src/test/java/retrofit2/converter/fastjson/FastJsonConverterFactoryTest.java
@@ -0,0 +1,116 @@
+package retrofit2.converter.fastjson;
+
+
+import com.alibaba.fastjson.annotation.JSONField;
+import com.alibaba.fastjson.parser.DefaultJSONParser;
+import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer;
+import com.alibaba.fastjson.serializer.JSONSerializer;
+import com.alibaba.fastjson.serializer.ObjectSerializer;
+import com.alibaba.fastjson.serializer.SerializeWriter;
+import okhttp3.mockwebserver.MockResponse;
+import okhttp3.mockwebserver.MockWebServer;
+import okhttp3.mockwebserver.RecordedRequest;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import retrofit2.Call;
+import retrofit2.Response;
+import retrofit2.Retrofit;
+import retrofit2.http.Body;
+import retrofit2.http.POST;
+
+import java.io.IOException;
+import java.lang.reflect.Type;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+public class FastJsonConverterFactoryTest {
+ interface AnInterface {
+ @JSONField(name = "name")
+ String getName();
+ @JSONField(name = "name")
+ void setName(String name);
+ }
+
+ static class AnImplementation implements AnInterface {
+
+ @JSONField(name = "name")
+ private String theName;
+
+ AnImplementation() {
+ }
+
+ AnImplementation(String name) {
+ theName = name;
+ }
+
+ @JSONField(name = "name")
+ @Override public String getName() {
+ return theName;
+ }
+
+ @JSONField(name = "name")
+ @Override
+ public void setName(String name) {
+ theName = name;
+ }
+ }
+
+ interface Service {
+ @POST("/")
+ Call<AnImplementation> anImplementation(@Body AnImplementation impl);
+ @POST("/") Call<AnInterface> anInterface(@Body AnInterface impl);
+ }
+
+ @Rule
+ public final MockWebServer server = new MockWebServer();
+
+ private Service service;
+
+ @Before
+ public void setUp() {
+ Retrofit retrofit = new Retrofit.Builder()
+ .baseUrl(server.url("/"))
+ .addConverterFactory(FastJsonConverterFactory.create())
+ .build();
+ service = retrofit.create(Service.class);
+ }
+
+ @Test
+ public void anInterface() throws IOException, InterruptedException {
+ server.enqueue(new MockResponse().setBody("{\"name\":\"value\"}"));
+
+ Call<AnInterface> call = service.anInterface(new AnImplementation("value"));
+ Response<AnInterface> response = call.execute();
+ AnInterface body = response.body();
+ assertThat(body.getName()).isEqualTo("value");
+
+ RecordedRequest request = server.takeRequest();
+ assertThat(request.getBody().readUtf8()).isEqualTo("{\"name\":\"value\"}");
+ assertThat(request.getHeader("Content-Type")).isEqualTo("application/json; charset=UTF-8");
+ }
+
+ @Test public void anImplementation() throws IOException, InterruptedException {
+ server.enqueue(new MockResponse().setBody("{\"theName\":\"value\"}"));
+
+ Call<AnImplementation> call = service.anImplementation(new AnImplementation("value"));
+ Response<AnImplementation> response = call.execute();
+ AnImplementation body = response.body();
+ assertThat(body.theName).isNull();
+
+ RecordedRequest request = server.takeRequest();
+ assertThat(request.getBody().readUtf8()).isEqualTo("{\"name\":\"value\"}");
+ assertThat(request.getHeader("Content-Type")).isEqualTo("application/json; charset=UTF-8");
+ }
+
+ @Test public void serializeUsesConfiguration() throws IOException, InterruptedException {
+ server.enqueue(new MockResponse().setBody("{}"));
+
+ service.anImplementation(new AnImplementation(null)).execute();
+
+ RecordedRequest request = server.takeRequest();
+ assertThat(request.getBody().readUtf8()).isEqualTo("{}"); // Null value was not serialized.
+ assertThat(request.getHeader("Content-Type")).isEqualTo("application/json; charset=UTF-8");
+ }
+
+}
| val | val | 2016-04-15T02:23:13 | "2016-04-14T02:41:07Z" | yy197133 | val |
square/retrofit/1736_1751 | square/retrofit | square/retrofit/1736 | square/retrofit/1751 | [
"timestamp(timedelta=13.0, similarity=0.8906381814558909)"
] | d04f3a50e41ca01d22f370ac4f332f6ddf4ba9fe | f8e23078874975c7e9de7f53bad5425b946c36d3 | [
"I'm not opposed to `@HeadersMap`.\n",
"Merged as adfe99884bfc01dd3a1164a768fef96d6550208b.\n",
"Thanks, @JakeWharton \n"
] | [
"We cannot depend on Guava\n",
"Oh okay. Should we have our own `MultiMap`? Or should we support `Map<String, Collection<?>>` instead?\n",
"Just ignore that case for now, we're going to look into it as part of #626. \n",
"Sure, thanks!\n",
"This is false, but I suspect this is copy/paste from other map annotations so I'll fix them all once this is merged.\n"
] | "2016-04-20T16:07:39Z" | [
"Enhancement"
] | Add @HeadersMap | **> First:**
``` java
public interface ApiService {
@Headers({
"User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.110 Safari/537.36",
"Accept: text/html,text/plain,application/json",
"Accept-Language: zh-cn,zh,en-US,en",
"Accept: text/html,text/plain,application/json",
"Accept-Language: zh-cn,zh,en-US,en",
"Accept-Charset: utf-8,GB2312",
"Connection: keep-alive"
})
@GET("Api-{module}-{method}")
Call<TokenEntity> asyncGet(@Path("module") String pModule, @Path("method") String pMethod, @QueryMap Map<String, String> pParameterOptions);
}
```
"Headers" modify to "HeaderMap" easy reading
**> Second:**
This feature is exist or implement new feature?
``` java
private static class SingletonHolder {
private static final OkHttpClient S_CLIENT;
private static final Retrofit.Builder S_BUILDER;
static {
OkHttpClient.Builder nClientBuilder = new OkHttpClient.Builder();
/* 连接超时2分钟 */
nClientBuilder.connectTimeout(2 * 60 * 1000, TimeUnit.MILLISECONDS);
/* 数据读取超时10分钟 */
nClientBuilder.readTimeout(10 * 60 * 1000, TimeUnit.MILLISECONDS);
/* 数据上传超时10分钟 */
nClientBuilder.writeTimeout(10 * 60 * 1000, TimeUnit.MILLISECONDS);
/* 连接失败后尝试重新连接 */
nClientBuilder.retryOnConnectionFailure(true);
S_CLIENT = nClientBuilder.build();
/* Retrofit结合OkHttpClient*/
S_BUILDER = new Retrofit.Builder();
S_BUILDER.baseUrl("http://ybirds.lp/").addConverterFactory(GsonConverterFactory.create()).validateEagerly(true).client(S_CLIENT);
}
}
public static Retrofit.Builder getRetrofitBuilder(){
return SingletonHolder.S_BUILDER;
}
public interface ApiService {
@GET("Api-{module}-{method}")
<T> Call<T> asyncGet(@Path("module") String pModule, @Path("method") String pMethod);
}
Retrofit nRetrofit = getRetrofitBuilder().build();
ApiService nApiService = nRetrofit.create(ApiService.class);
Map<String, String> nParameters = new HashMap<>();
nParameters.put("appid","9CA630FF6AA2EE3E99");
Call<TokenEntity> nTokenCall = nApiService.asyncGet("Token", "getToken", nParameters);
// ------------------------------------
Call<UserInfoEntity> nTokenCall = nApiService.asyncGet("user", "getUserInfo", nParameters);
// and so on
```
| [
"retrofit/src/main/java/retrofit2/Converter.java",
"retrofit/src/main/java/retrofit2/ParameterHandler.java",
"retrofit/src/main/java/retrofit2/ServiceMethod.java",
"retrofit/src/main/java/retrofit2/http/Header.java",
"retrofit/src/main/java/retrofit2/http/Headers.java"
] | [
"retrofit/src/main/java/retrofit2/Converter.java",
"retrofit/src/main/java/retrofit2/ParameterHandler.java",
"retrofit/src/main/java/retrofit2/ServiceMethod.java",
"retrofit/src/main/java/retrofit2/http/Header.java",
"retrofit/src/main/java/retrofit2/http/HeaderMap.java",
"retrofit/src/main/java/retrofit2/http/Headers.java"
] | [
"retrofit/src/test/java/retrofit2/RequestBuilderTest.java"
] | diff --git a/retrofit/src/main/java/retrofit2/Converter.java b/retrofit/src/main/java/retrofit2/Converter.java
index 9fd8eddafa..604bcf0864 100644
--- a/retrofit/src/main/java/retrofit2/Converter.java
+++ b/retrofit/src/main/java/retrofit2/Converter.java
@@ -66,8 +66,8 @@ public Converter<?, RequestBody> requestBodyConverter(Type type,
* Returns a {@link Converter} for converting {@code type} to a {@link String}, or null if
* {@code type} cannot be handled by this factory. This is used to create converters for types
* specified by {@link Field @Field}, {@link FieldMap @FieldMap} values,
- * {@link Header @Header}, {@link Path @Path}, {@link Query @Query}, and
- * {@link QueryMap @QueryMap} values.
+ * {@link Header @Header}, {@link HeaderMap @HeaderMap}, {@link Path @Path},
+ * {@link Query @Query}, and {@link QueryMap @QueryMap} values.
*/
public Converter<?, String> stringConverter(Type type, Annotation[] annotations,
Retrofit retrofit) {
diff --git a/retrofit/src/main/java/retrofit2/ParameterHandler.java b/retrofit/src/main/java/retrofit2/ParameterHandler.java
index 38e21e5598..3221790357 100644
--- a/retrofit/src/main/java/retrofit2/ParameterHandler.java
+++ b/retrofit/src/main/java/retrofit2/ParameterHandler.java
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2015 Square, Inc.
+ * Copyright (C) 2015-2016 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -18,6 +18,7 @@
import java.io.IOException;
import java.lang.reflect.Array;
import java.util.Map;
+
import okhttp3.Headers;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
@@ -139,6 +140,33 @@ static final class QueryMap<T> extends ParameterHandler<Map<String, T>> {
}
}
+ static final class HeaderMap<T> extends ParameterHandler<Map<String, T>> {
+ private final Converter<T, String> valueConverter;
+
+ HeaderMap(Converter<T, String> valueConverter) {
+ this.valueConverter = valueConverter;
+ }
+
+ @Override void apply(RequestBuilder builder, Map<String, T> value) throws IOException {
+ if (value == null) {
+ throw new IllegalArgumentException("Header map was null.");
+ }
+
+ for (Map.Entry<String, T> entry : value.entrySet()) {
+ String headerName = entry.getKey();
+ if (headerName == null) {
+ throw new IllegalArgumentException("Header map contained null key.");
+ }
+ T headerValue = entry.getValue();
+ if (headerValue == null) {
+ throw new IllegalArgumentException(
+ "Header map contained null value for key '" + headerName + "'.");
+ }
+ builder.addHeader(headerName, valueConverter.convert(headerValue));
+ }
+ }
+ }
+
static final class Field<T> extends ParameterHandler<T> {
private final String name;
private final Converter<T, String> valueConverter;
diff --git a/retrofit/src/main/java/retrofit2/ServiceMethod.java b/retrofit/src/main/java/retrofit2/ServiceMethod.java
index a055688599..c9ab874efd 100644
--- a/retrofit/src/main/java/retrofit2/ServiceMethod.java
+++ b/retrofit/src/main/java/retrofit2/ServiceMethod.java
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2015 Square, Inc.
+ * Copyright (C) 2015-2016 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -26,6 +26,7 @@
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
+
import okhttp3.Headers;
import okhttp3.HttpUrl;
import okhttp3.MediaType;
@@ -42,6 +43,7 @@
import retrofit2.http.HEAD;
import retrofit2.http.HTTP;
import retrofit2.http.Header;
+import retrofit2.http.HeaderMap;
import retrofit2.http.Multipart;
import retrofit2.http.OPTIONS;
import retrofit2.http.PATCH;
@@ -471,6 +473,26 @@ private ParameterHandler<?> parseParameterAnnotation(
return new ParameterHandler.Header<>(name, converter);
}
+ } else if (annotation instanceof HeaderMap) {
+ Class<?> rawParameterType = Utils.getRawType(type);
+ if (!Map.class.isAssignableFrom(rawParameterType)) {
+ throw parameterError(p, "@HeaderMap parameter type must be Map.");
+ }
+ Type mapType = Utils.getSupertype(type, rawParameterType, Map.class);
+ if (!(mapType instanceof ParameterizedType)) {
+ throw parameterError(p, "Map must include generic types (e.g., Map<String, String>)");
+ }
+ ParameterizedType parameterizedType = (ParameterizedType) mapType;
+ Type keyType = Utils.getParameterUpperBound(0, parameterizedType);
+ if (String.class != keyType) {
+ throw parameterError(p, "@HeaderMap keys must be of type String: " + keyType);
+ }
+ Type valueType = Utils.getParameterUpperBound(1, parameterizedType);
+ Converter<?, String> valueConverter =
+ retrofit.stringConverter(valueType, annotations);
+
+ return new ParameterHandler.HeaderMap<>(valueConverter);
+
} else if (annotation instanceof Field) {
if (!isFormEncoded) {
throw parameterError(p, "@Field parameters can only be used with form encoding.");
diff --git a/retrofit/src/main/java/retrofit2/http/Header.java b/retrofit/src/main/java/retrofit2/http/Header.java
index 8ce5cb8d05..b8f7a70ea0 100644
--- a/retrofit/src/main/java/retrofit2/http/Header.java
+++ b/retrofit/src/main/java/retrofit2/http/Header.java
@@ -33,6 +33,9 @@
* <p>
* <strong>Note:</strong> Headers do not overwrite each other. All headers with the same name will
* be included in the request.
+ *
+ * @see Headers
+ * @see HeaderMap
*/
@Documented
@Retention(RUNTIME)
diff --git a/retrofit/src/main/java/retrofit2/http/HeaderMap.java b/retrofit/src/main/java/retrofit2/http/HeaderMap.java
new file mode 100644
index 0000000000..aa1facd399
--- /dev/null
+++ b/retrofit/src/main/java/retrofit2/http/HeaderMap.java
@@ -0,0 +1,51 @@
+/*
+ * Copyright (C) 2016 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 retrofit2.http;
+
+import static java.lang.annotation.ElementType.PARAMETER;
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+
+import java.lang.annotation.Documented;
+import java.lang.annotation.Retention;
+import java.lang.annotation.Target;
+import java.util.Map;
+
+/**
+ * Adds headers specified in the {@link Map}.
+ * <p>
+ * Values are converted to strings using {@link String#valueOf(Object)}.
+ * <p>
+ * Simple Example:
+ * <pre>
+ * @GET("/search")
+ * void list(@HeaderMap Map<String, String> headers);
+ *
+ * ...
+ *
+ * // The following call yields /search with headers
+ * // Accept: text/plain and Accept-Charset: utf-8
+ * foo.list(ImmutableMap.of("Accept", "text/plain", "Accept-Charset", "utf-8"));
+ * </pre>
+ *
+ * @see Header
+ * @see Headers
+ */
+@Documented
+@Target(PARAMETER)
+@Retention(RUNTIME)
+public @interface HeaderMap {
+
+}
diff --git a/retrofit/src/main/java/retrofit2/http/Headers.java b/retrofit/src/main/java/retrofit2/http/Headers.java
index 8b2adea1a1..b360f3ec3d 100644
--- a/retrofit/src/main/java/retrofit2/http/Headers.java
+++ b/retrofit/src/main/java/retrofit2/http/Headers.java
@@ -38,6 +38,9 @@
* </code></pre>
* <strong>Note:</strong> Headers do not overwrite each other. All headers with the same name will
* be included in the request.
+ *
+ * @see Header
+ * @see HeaderMap
*/
@Documented
@Target(METHOD)
| diff --git a/retrofit/src/test/java/retrofit2/RequestBuilderTest.java b/retrofit/src/test/java/retrofit2/RequestBuilderTest.java
index 65595b9180..3621343aba 100644
--- a/retrofit/src/test/java/retrofit2/RequestBuilderTest.java
+++ b/retrofit/src/test/java/retrofit2/RequestBuilderTest.java
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2013 Square, Inc.
+ * Copyright (C) 2013-2016 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -35,6 +35,7 @@
import okio.Buffer;
import org.junit.Ignore;
import org.junit.Test;
+
import retrofit2.helpers.ToStringConverterFactory;
import retrofit2.http.Body;
import retrofit2.http.DELETE;
@@ -45,6 +46,7 @@
import retrofit2.http.HEAD;
import retrofit2.http.HTTP;
import retrofit2.http.Header;
+import retrofit2.http.HeaderMap;
import retrofit2.http.Headers;
import retrofit2.http.Multipart;
import retrofit2.http.OPTIONS;
@@ -531,6 +533,119 @@ Call<ResponseBody> method(@QueryMap Map<String, String> a) {
}
}
+ @Test public void getWithHeaderMap() {
+ class Example {
+ @GET("/search")
+ Call<ResponseBody> method(@HeaderMap Map<String, Object> headers) {
+ return null;
+ }
+ }
+
+ Map<String, Object> headers = new LinkedHashMap<>();
+ headers.put("Accept", "text/plain");
+ headers.put("Accept-Charset", "utf-8");
+
+ Request request = buildRequest(Example.class, headers);
+ assertThat(request.method()).isEqualTo("GET");
+ assertThat(request.url().toString()).isEqualTo("http://example.com/search");
+ assertThat(request.body()).isNull();
+ assertThat(request.headers().size()).isEqualTo(2);
+ assertThat(request.header("Accept")).isEqualTo("text/plain");
+ assertThat(request.header("Accept-Charset")).isEqualTo("utf-8");
+ }
+
+ @Test public void headerMapMustBeAMap() {
+ class Example {
+ @GET("/")
+ Call<ResponseBody> method(@HeaderMap List<String> headers) {
+ return null;
+ }
+ }
+ try {
+ buildRequest(Example.class);
+ fail();
+ } catch (IllegalArgumentException e) {
+ assertThat(e).hasMessage(
+ "@HeaderMap parameter type must be Map. (parameter #1)\n for method Example.method");
+ }
+ }
+
+ @Test public void headerMapSupportsSubclasses() {
+ class Foo extends HashMap<String, String> {
+ }
+
+ class Example {
+ @GET("/search")
+ Call<ResponseBody> method(@HeaderMap Foo headers) {
+ return null;
+ }
+ }
+
+ Foo headers = new Foo();
+ headers.put("Accept", "text/plain");
+
+ Request request = buildRequest(Example.class, headers);
+ assertThat(request.url().toString()).isEqualTo("http://example.com/search");
+ assertThat(request.headers().size()).isEqualTo(1);
+ assertThat(request.header("Accept")).isEqualTo("text/plain");
+ }
+
+ @Test public void headerMapRejectsNull() {
+ class Example {
+ @GET("/")
+ Call<ResponseBody> method(@HeaderMap Map<String, String> headers) {
+ return null;
+ }
+ }
+
+ try {
+ buildRequest(Example.class, (Map<String, String>) null);
+ fail();
+ } catch (IllegalArgumentException e) {
+ assertThat(e).hasMessage("Header map was null.");
+ }
+ }
+
+ @Test public void headerMapRejectsNullKeys() {
+ class Example {
+ @GET("/")
+ Call<ResponseBody> method(@HeaderMap Map<String, String> headers) {
+ return null;
+ }
+ }
+
+ Map<String, String> headers = new LinkedHashMap<>();
+ headers.put("Accept", "text/plain");
+ headers.put(null, "utf-8");
+
+ try {
+ buildRequest(Example.class, headers);
+ fail();
+ } catch (IllegalArgumentException e) {
+ assertThat(e).hasMessage("Header map contained null key.");
+ }
+ }
+
+ @Test public void headerMapRejectsNullValues() {
+ class Example {
+ @GET("/")
+ Call<ResponseBody> method(@HeaderMap Map<String, String> headers) {
+ return null;
+ }
+ }
+
+ Map<String, String> headers = new LinkedHashMap<>();
+ headers.put("Accept", "text/plain");
+ headers.put("Accept-Charset", null);
+
+ try {
+ buildRequest(Example.class, headers);
+ fail();
+ } catch (IllegalArgumentException e) {
+ assertThat(e).hasMessage("Header map contained null value for key 'Accept-Charset'.");
+ }
+ }
+
@Test public void twoBodies() {
class Example {
@PUT("/") //
| train | val | 2016-04-15T02:23:13 | "2016-04-13T08:11:50Z" | artshell | val |
square/retrofit/1876_1882 | square/retrofit | square/retrofit/1876 | square/retrofit/1882 | [
"timestamp(timedelta=0.0, similarity=0.8465718613260184)"
] | 5febe68b3c812a25f60d16e8faa74e39e87528a7 | 9f00bd309afb7898b68362466d56bf9783d02cfe | [
"i found the default BuildInConverters,its stringConverter will intercept the request which type is String.\n\n```\n@Override public Converter<?, String> stringConverter(Type type, Annotation[] annotations,Retrofit retrofit) {\n if (type == String.class) {\n return StringConverter.INSTANCE;\n }\n return null;\n}\n```\n\nso i change the type of the parameter,like this\n\npublic interface API {\n @FormUrlEncoded\n @POST(\"login.do?os=\" + ConstantValue.OS + \"&version=\" + ConstantValue.VERSION)\n Observable<LoginInfo> login(@Field(\"cmd\") JsonObject params);\n}\n\nthen my custom Converter work.\n\nnote:\ni do not know weather the way I encrypt the request is ok.. \ncan I change the default Converter ,not change my type to let it can use my custom converter . \n",
"The built-in converter is added last so any user-supplied converters should always take precedence.\n",
"Looks like we don't call the string converter when the type is already string. This is potentially problematic if you have annotations on the parameter with which you want to modify the value. Let me look at relaxing this restriction.\n",
"thank you very much @JakeWharton @swankjesse \n",
"@iacky 后来你是怎么处理的呢?求解"
] | [
"This is unrelated... it just looks nicer.\n",
"Did the IDE tell you to re-format this and you just accidentally pressed yes :curious_face: ?\n",
"🍩\n"
] | "2016-06-26T05:52:34Z" | [
"Enhancement"
] | retrofit2.BuildInConverters$StringConverter let me confused | I am so confused,when send request like this
public interface API {
@FormUrlEncoded
@POST("login.do?os=" + ConstantValue.OS + "&version=" + ConstantValue.VERSION)
Observable<LoginInfo> login(@Field("cmd") String params);
}
the method of my custom Converter stringConverter method do not work.. (to encrypt request)
retrofit2.BuildInConvert$StringConverter is first before mine execute.. help~please~
retrofit version 2.1.0 @
| [
"retrofit/src/main/java/retrofit2/BuiltInConverters.java"
] | [
"retrofit/src/main/java/retrofit2/BuiltInConverters.java"
] | [
"retrofit/src/test/java/retrofit2/RetrofitTest.java"
] | diff --git a/retrofit/src/main/java/retrofit2/BuiltInConverters.java b/retrofit/src/main/java/retrofit2/BuiltInConverters.java
index d580c00fb1..f729383a31 100644
--- a/retrofit/src/main/java/retrofit2/BuiltInConverters.java
+++ b/retrofit/src/main/java/retrofit2/BuiltInConverters.java
@@ -27,10 +27,9 @@ final class BuiltInConverters extends Converter.Factory {
public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations,
Retrofit retrofit) {
if (type == ResponseBody.class) {
- if (Utils.isAnnotationPresent(annotations, Streaming.class)) {
- return StreamingResponseBodyConverter.INSTANCE;
- }
- return BufferingResponseBodyConverter.INSTANCE;
+ return Utils.isAnnotationPresent(annotations, Streaming.class)
+ ? StreamingResponseBodyConverter.INSTANCE
+ : BufferingResponseBodyConverter.INSTANCE;
}
if (type == Void.class) {
return VoidResponseBodyConverter.INSTANCE;
@@ -47,22 +46,6 @@ public Converter<?, RequestBody> requestBodyConverter(Type type,
return null;
}
- @Override public Converter<?, String> stringConverter(Type type, Annotation[] annotations,
- Retrofit retrofit) {
- if (type == String.class) {
- return StringConverter.INSTANCE;
- }
- return null;
- }
-
- static final class StringConverter implements Converter<String, String> {
- static final StringConverter INSTANCE = new StringConverter();
-
- @Override public String convert(String value) throws IOException {
- return value;
- }
- }
-
static final class VoidResponseBodyConverter implements Converter<ResponseBody, Void> {
static final VoidResponseBodyConverter INSTANCE = new VoidResponseBodyConverter();
| diff --git a/retrofit/src/test/java/retrofit2/RetrofitTest.java b/retrofit/src/test/java/retrofit2/RetrofitTest.java
index 9c17cab429..41036c9877 100644
--- a/retrofit/src/test/java/retrofit2/RetrofitTest.java
+++ b/retrofit/src/test/java/retrofit2/RetrofitTest.java
@@ -399,11 +399,13 @@ class MyConverterFactory extends Converter.Factory {
assertThat(annotations).hasAtLeastOneElementOfType(Annotated.Foo.class);
}
- @Test public void stringConverterNotCalledForString() {
+ @Test public void stringConverterCalledForString() {
+ final AtomicBoolean factoryCalled = new AtomicBoolean();
class MyConverterFactory extends Converter.Factory {
@Override public Converter<?, String> stringConverter(Type type, Annotation[] annotations,
Retrofit retrofit) {
- throw new AssertionError();
+ factoryCalled.set(true);
+ return null;
}
}
Retrofit retrofit = new Retrofit.Builder()
@@ -413,7 +415,7 @@ class MyConverterFactory extends Converter.Factory {
CallMethod service = retrofit.create(CallMethod.class);
Call<ResponseBody> call = service.queryString(null);
assertThat(call).isNotNull();
- // We also implicitly assert the above factory was not called as it would have thrown.
+ assertThat(factoryCalled.get()).isTrue();
}
@Test public void stringConverterReturningNullResultsInDefault() {
| test | val | 2016-06-23T03:07:29 | "2016-06-23T06:50:35Z" | iacky | val |
square/retrofit/1821_1953 | square/retrofit | square/retrofit/1821 | square/retrofit/1953 | [
"timestamp(timedelta=0.0, similarity=0.9230674544220068)"
] | c0bef604924007b5bcebf221ea626e4b7807c18b | e52a4d74106c03891c286d388bcfdb06af656837 | [
"We've been waiting for the API to stabilize since we don't support\npre-release versions.\n\nOn Fri, May 27, 2016 at 7:21 AM Xboy [email protected] wrote:\n\n> @JakeWharton https://github.com/JakeWharton\n> Hi Wharton,\n> Retrofit is really a delightful networking framework for android. But we\n> have recently found “ProtoConverterFactory” is not support ProtoBuf 3.0. So\n> we want to know when you can update the ProtoConverter.\n> \n> Thank you very much.\n> \n> —\n> You are receiving this because you were mentioned.\n> Reply to this email directly, view it on GitHub\n> https://github.com/square/retrofit/issues/1821, or mute the thread\n> https://github.com/notifications/unsubscribe/AAEEEdrgPaKY5Ix_tA_JSvniUyvP8XyUks5qFtO5gaJpZM4IoaPT\n> .\n",
"Yes, please. I'm waiting for it too.\n\n@brilliance-boy \nMeanwhile, I'm using [this workaround](https://gist.github.com/fabriciointerama/22178fe28528bd2919a02f171680ca13).\n",
"@fabriciointerama @brilliance-boy @JakeWharton \n\nHello All, \n\ncan you please give me some example how we can use protobuf in retrofit - i tried but its failed with some error , let me give you sample of my implementation on that.\n\ni hope you guys will help me. \n\nApiInterface.java\n\n```\npublic interface ApiInterface {\n @GET\n Call<CommonProto.Country> makeGetRequest(@Url String url);\n}\n```\n\nApiClient.java\n\n```\npublic class ApiClient {\n\n public static final String BASE_URL = \"**************************\";\n\n private static Retrofit retrofit = null;\n\n\n public static Retrofit getClient() {\n if (retrofit==null) {\n retrofit = new Retrofit.Builder()\n .baseUrl(BASE_URL)\n .addConverterFactory(Proto3ConverterFactory.create())\n .build();\n }\n return retrofit;\n }\n\n}\n\n```\n\nMainActivity.java\n\n```\nApiInterface apiService =\n ApiClient.getClient().create(ApiInterface.class);\n\nCall<CommonProto.Country> call = apiService.makeGetRequest(\"Services/CountryServices/GetAllCountry\");\n\n call.enqueue(new Callback<CommonProto.Country>() {\n @Override\n public void onResponse(Call<CommonProto.Country> call, Response<CommonProto.Country> response) {\n String bodyString = null;\n try {\n Log.e(\"RETROFIT ::::::: \", String.valueOf(response.body())+\"TEST\");\n } catch (Exception e) {\n Log.e(\"RETROFIT ERROR ::::::: \", e.getMessage()+\"TEST\");\n e.printStackTrace();\n }\n\n }\n\n @Override\n public void onFailure(Call<CommonProto.Country> call, Throwable t) {\n // Log error here since request failed\n Log.e(TAG, t.toString());\n }\n }\n\n ); \n```\n\nwhen i run this way i got the error \njava.lang.RuntimeException: com.google.protobuf.InvalidProtocolBufferException: Protocol message tag had invalid wire type.\n\nI have attached the Proto File with this message please find the attachment.\n\n[CommonProto.java.zip](https://github.com/square/retrofit/files/390594/CommonProto.java.zip)\n[CommonProto.proto.zip](https://github.com/square/retrofit/files/390593/CommonProto.proto.zip)\n\nPlease let me know how to do this GET Req and also i was Struggling with POST Req.\n\nThanks In advance , \nMadhav\n",
"I'd be interested to hear how the current protobuf converter wasn't working with 3.0, because in all my tests it works fine. In any case, we've updated it.\n"
] | [
"pedantic: if it’s an InvocationTargetException, falling back doesn’t seem right\n",
"Rethrow the cause? It should never happen.\n"
] | "2016-08-03T04:11:04Z" | [
"Enhancement"
] | Support protobuf 3.0 when released. | @JakeWharton
Hi Wharton,
Retrofit is really a delightful networking framework for android. But we have recently found “ProtoConverterFactory” is not support ProtoBuf 3.0. So we want to know when you can update the ProtoConverter.
Thank you very much.
| [
"pom.xml",
"retrofit-converters/protobuf/src/main/java/retrofit2/converter/protobuf/ProtoConverterFactory.java"
] | [
"pom.xml",
"retrofit-converters/protobuf/src/main/java/retrofit2/converter/protobuf/ProtoConverterFactory.java"
] | [
"retrofit-converters/protobuf/src/test/java/retrofit2/converter/protobuf/FallbackParserFinderTest.java",
"retrofit-converters/protobuf/src/test/java/retrofit2/converter/protobuf/PhoneProtos.java"
] | diff --git a/pom.xml b/pom.xml
index b898d124cb..d9818fc1e2 100644
--- a/pom.xml
+++ b/pom.xml
@@ -57,7 +57,7 @@
<!-- Converter Dependencies -->
<gson.version>2.7</gson.version>
- <protobuf.version>2.6.1</protobuf.version>
+ <protobuf.version>3.0.0</protobuf.version>
<jackson.version>2.7.2</jackson.version>
<wire.version>2.2.0</wire.version>
<simplexml.version>2.7.1</simplexml.version>
diff --git a/retrofit-converters/protobuf/src/main/java/retrofit2/converter/protobuf/ProtoConverterFactory.java b/retrofit-converters/protobuf/src/main/java/retrofit2/converter/protobuf/ProtoConverterFactory.java
index 9b544eb0dd..ec2aac4529 100644
--- a/retrofit-converters/protobuf/src/main/java/retrofit2/converter/protobuf/ProtoConverterFactory.java
+++ b/retrofit-converters/protobuf/src/main/java/retrofit2/converter/protobuf/ProtoConverterFactory.java
@@ -20,6 +20,8 @@
import com.google.protobuf.Parser;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
import java.lang.reflect.Type;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
@@ -61,12 +63,22 @@ private ProtoConverterFactory(ExtensionRegistryLite registry) {
Parser<MessageLite> parser;
try {
- Field field = c.getDeclaredField("PARSER");
+ Method method = c.getDeclaredMethod("parser");
//noinspection unchecked
- parser = (Parser<MessageLite>) field.get(null);
- } catch (NoSuchFieldException | IllegalAccessException e) {
- throw new IllegalArgumentException(
- "Found a protobuf message but " + c.getName() + " had no PARSER field.");
+ parser = (Parser<MessageLite>) method.invoke(null);
+ } catch (InvocationTargetException e) {
+ throw new RuntimeException(e.getCause());
+ } catch (NoSuchMethodException | IllegalAccessException ignored) {
+ // If the method is missing, fall back to original static field for pre-3.0 support.
+ try {
+ Field field = c.getDeclaredField("PARSER");
+ //noinspection unchecked
+ parser = (Parser<MessageLite>) field.get(null);
+ } catch (NoSuchFieldException | IllegalAccessException e) {
+ throw new IllegalArgumentException("Found a protobuf message but "
+ + c.getName()
+ + " had no parser() method or PARSER field.");
+ }
}
return new ProtoResponseBodyConverter<>(parser, registry);
}
| diff --git a/retrofit-converters/protobuf/src/test/java/retrofit2/converter/protobuf/FallbackParserFinderTest.java b/retrofit-converters/protobuf/src/test/java/retrofit2/converter/protobuf/FallbackParserFinderTest.java
new file mode 100644
index 0000000000..b37ab55bc3
--- /dev/null
+++ b/retrofit-converters/protobuf/src/test/java/retrofit2/converter/protobuf/FallbackParserFinderTest.java
@@ -0,0 +1,42 @@
+/*
+ * Copyright (C) 2016 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 retrofit2.converter.protobuf;
+
+import com.google.protobuf.MessageLite;
+import com.google.protobuf.Parser;
+import java.lang.annotation.Annotation;
+import okhttp3.ResponseBody;
+import org.junit.Test;
+import retrofit2.Converter;
+import retrofit2.Retrofit;
+import retrofit2.converter.protobuf.PhoneProtos.Phone;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+public final class FallbackParserFinderTest {
+ @Test public void converterFactoryFallsBackToParserField() {
+ Retrofit retrofit = new Retrofit.Builder().baseUrl("http://localhost/").build();
+ ProtoConverterFactory factory = ProtoConverterFactory.create();
+ Converter<ResponseBody, ?> converter =
+ factory.responseBodyConverter(FakePhone.class, new Annotation[0], retrofit);
+ assertThat(converter).isNotNull();
+ }
+
+ @SuppressWarnings("unused") // Used reflectively.
+ public static abstract class FakePhone implements MessageLite {
+ public static final Parser<Phone> PARSER = Phone.parser();
+ }
+}
diff --git a/retrofit-converters/protobuf/src/test/java/retrofit2/converter/protobuf/PhoneProtos.java b/retrofit-converters/protobuf/src/test/java/retrofit2/converter/protobuf/PhoneProtos.java
index 99d2bb2088..3ad1bb0f6d 100644
--- a/retrofit-converters/protobuf/src/test/java/retrofit2/converter/protobuf/PhoneProtos.java
+++ b/retrofit-converters/protobuf/src/test/java/retrofit2/converter/protobuf/PhoneProtos.java
@@ -6,9 +6,15 @@
public final class PhoneProtos {
private PhoneProtos() {}
public static void registerAllExtensions(
- com.google.protobuf.ExtensionRegistry registry) {
+ com.google.protobuf.ExtensionRegistryLite registry) {
registry.add(retrofit2.converter.protobuf.PhoneProtos.voicemail);
}
+
+ public static void registerAllExtensions(
+ com.google.protobuf.ExtensionRegistry registry) {
+ registerAllExtensions(
+ (com.google.protobuf.ExtensionRegistryLite) registry);
+ }
public interface PhoneOrBuilder extends
// @@protoc_insertion_point(interface_extends:retrofit2.converter.protobuf.Phone)
com.google.protobuf.GeneratedMessage.
@@ -31,7 +37,7 @@ public interface PhoneOrBuilder extends
/**
* Protobuf type {@code retrofit2.converter.protobuf.Phone}
*/
- public static final class Phone extends
+ public static final class Phone extends
com.google.protobuf.GeneratedMessage.ExtendableMessage<
Phone> implements
// @@protoc_insertion_point(message_implements:retrofit2.converter.protobuf.Phone)
@@ -39,30 +45,21 @@ public static final class Phone extends
// Use Phone.newBuilder() to construct.
private Phone(com.google.protobuf.GeneratedMessage.ExtendableBuilder<retrofit2.converter.protobuf.PhoneProtos.Phone, ?> builder) {
super(builder);
- this.unknownFields = builder.getUnknownFields();
}
- private Phone(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); }
-
- private static final Phone defaultInstance;
- public static Phone getDefaultInstance() {
- return defaultInstance;
- }
-
- public Phone getDefaultInstanceForType() {
- return defaultInstance;
+ private Phone() {
+ number_ = "";
}
- private final com.google.protobuf.UnknownFieldSet unknownFields;
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet
- getUnknownFields() {
+ getUnknownFields() {
return this.unknownFields;
}
private Phone(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
- initFields();
+ this();
int mutable_bitField0_ = 0;
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder();
@@ -93,7 +90,7 @@ private Phone(
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(
- e.getMessage()).setUnfinishedMessage(this);
+ e).setUnfinishedMessage(this);
} finally {
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
@@ -111,24 +108,9 @@ private Phone(
retrofit2.converter.protobuf.PhoneProtos.Phone.class, retrofit2.converter.protobuf.PhoneProtos.Phone.Builder.class);
}
- public static com.google.protobuf.Parser<Phone> PARSER =
- new com.google.protobuf.AbstractParser<Phone>() {
- public Phone parsePartialFrom(
- com.google.protobuf.CodedInputStream input,
- com.google.protobuf.ExtensionRegistryLite extensionRegistry)
- throws com.google.protobuf.InvalidProtocolBufferException {
- return new Phone(input, extensionRegistry);
- }
- };
-
- @java.lang.Override
- public com.google.protobuf.Parser<Phone> getParserForType() {
- return PARSER;
- }
-
private int bitField0_;
public static final int NUMBER_FIELD_NUMBER = 1;
- private java.lang.Object number_;
+ private volatile java.lang.Object number_;
/**
* <code>optional string number = 1;</code>
*/
@@ -169,9 +151,6 @@ public java.lang.String getNumber() {
}
}
- private void initFields() {
- number_ = "";
- }
private byte memoizedIsInitialized = -1;
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
@@ -188,38 +167,68 @@ public final boolean isInitialized() {
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
- getSerializedSize();
com.google.protobuf.GeneratedMessage
- .ExtendableMessage<retrofit2.converter.protobuf.PhoneProtos.Phone>.ExtensionWriter extensionWriter =
- newExtensionWriter();
+ .ExtendableMessage<retrofit2.converter.protobuf.PhoneProtos.Phone>.ExtensionWriter
+ extensionWriter = newExtensionWriter();
if (((bitField0_ & 0x00000001) == 0x00000001)) {
- output.writeBytes(1, getNumberBytes());
+ com.google.protobuf.GeneratedMessage.writeString(output, 1, number_);
}
extensionWriter.writeUntil(3, output);
- getUnknownFields().writeTo(output);
+ unknownFields.writeTo(output);
}
- private int memoizedSerializedSize = -1;
public int getSerializedSize() {
- int size = memoizedSerializedSize;
+ int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (((bitField0_ & 0x00000001) == 0x00000001)) {
- size += com.google.protobuf.CodedOutputStream
- .computeBytesSize(1, getNumberBytes());
+ size += com.google.protobuf.GeneratedMessage.computeStringSize(1, number_);
}
size += extensionsSerializedSize();
- size += getUnknownFields().getSerializedSize();
- memoizedSerializedSize = size;
+ size += unknownFields.getSerializedSize();
+ memoizedSize = size;
return size;
}
private static final long serialVersionUID = 0L;
@java.lang.Override
- protected java.lang.Object writeReplace()
- throws java.io.ObjectStreamException {
- return super.writeReplace();
+ public boolean equals(final java.lang.Object obj) {
+ if (obj == this) {
+ return true;
+ }
+ if (!(obj instanceof retrofit2.converter.protobuf.PhoneProtos.Phone)) {
+ return super.equals(obj);
+ }
+ retrofit2.converter.protobuf.PhoneProtos.Phone other = (retrofit2.converter.protobuf.PhoneProtos.Phone) obj;
+
+ boolean result = true;
+ result = result && (hasNumber() == other.hasNumber());
+ if (hasNumber()) {
+ result = result && getNumber()
+ .equals(other.getNumber());
+ }
+ result = result && unknownFields.equals(other.unknownFields);
+ result = result &&
+ getExtensionFields().equals(other.getExtensionFields());
+ return result;
+ }
+
+ @java.lang.Override
+ public int hashCode() {
+ if (memoizedHashCode != 0) {
+ return memoizedHashCode;
+ }
+ int hash = 41;
+ hash = (19 * hash) + getDescriptorForType().hashCode();
+ if (hasNumber()) {
+ hash = (37 * hash) + NUMBER_FIELD_NUMBER;
+ hash = (53 * hash) + getNumber().hashCode();
+ }
+ hash = hashFields(hash, getExtensionFields());
+ hash = (29 * hash) + unknownFields.hashCode();
+ memoizedHashCode = hash;
+ return hash;
}
public static retrofit2.converter.protobuf.PhoneProtos.Phone parseFrom(
@@ -245,42 +254,53 @@ public static retrofit2.converter.protobuf.PhoneProtos.Phone parseFrom(
}
public static retrofit2.converter.protobuf.PhoneProtos.Phone parseFrom(java.io.InputStream input)
throws java.io.IOException {
- return PARSER.parseFrom(input);
+ return com.google.protobuf.GeneratedMessage
+ .parseWithIOException(PARSER, input);
}
public static retrofit2.converter.protobuf.PhoneProtos.Phone parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
- return PARSER.parseFrom(input, extensionRegistry);
+ return com.google.protobuf.GeneratedMessage
+ .parseWithIOException(PARSER, input, extensionRegistry);
}
public static retrofit2.converter.protobuf.PhoneProtos.Phone parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
- return PARSER.parseDelimitedFrom(input);
+ return com.google.protobuf.GeneratedMessage
+ .parseDelimitedWithIOException(PARSER, input);
}
public static retrofit2.converter.protobuf.PhoneProtos.Phone parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
- return PARSER.parseDelimitedFrom(input, extensionRegistry);
+ return com.google.protobuf.GeneratedMessage
+ .parseDelimitedWithIOException(PARSER, input, extensionRegistry);
}
public static retrofit2.converter.protobuf.PhoneProtos.Phone parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
- return PARSER.parseFrom(input);
+ return com.google.protobuf.GeneratedMessage
+ .parseWithIOException(PARSER, input);
}
public static retrofit2.converter.protobuf.PhoneProtos.Phone parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
- return PARSER.parseFrom(input, extensionRegistry);
+ return com.google.protobuf.GeneratedMessage
+ .parseWithIOException(PARSER, input, extensionRegistry);
}
- public static Builder newBuilder() { return Builder.create(); }
public Builder newBuilderForType() { return newBuilder(); }
+ public static Builder newBuilder() {
+ return DEFAULT_INSTANCE.toBuilder();
+ }
public static Builder newBuilder(retrofit2.converter.protobuf.PhoneProtos.Phone prototype) {
- return newBuilder().mergeFrom(prototype);
+ return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
+ }
+ public Builder toBuilder() {
+ return this == DEFAULT_INSTANCE
+ ? new Builder() : new Builder().mergeFrom(this);
}
- public Builder toBuilder() { return newBuilder(this); }
@java.lang.Override
protected Builder newBuilderForType(
@@ -322,10 +342,6 @@ private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) {
}
}
- private static Builder create() {
- return new Builder();
- }
-
public Builder clear() {
super.clear();
number_ = "";
@@ -333,10 +349,6 @@ public Builder clear() {
return this;
}
- public Builder clone() {
- return create().mergeFrom(buildPartial());
- }
-
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return retrofit2.converter.protobuf.PhoneProtos.internal_static_retrofit2_converter_protobuf_Phone_descriptor;
@@ -367,6 +379,55 @@ public retrofit2.converter.protobuf.PhoneProtos.Phone buildPartial() {
return result;
}
+ public Builder clone() {
+ return (Builder) super.clone();
+ }
+ public Builder setField(
+ com.google.protobuf.Descriptors.FieldDescriptor field,
+ Object value) {
+ return (Builder) super.setField(field, value);
+ }
+ public Builder clearField(
+ com.google.protobuf.Descriptors.FieldDescriptor field) {
+ return (Builder) super.clearField(field);
+ }
+ public Builder clearOneof(
+ com.google.protobuf.Descriptors.OneofDescriptor oneof) {
+ return (Builder) super.clearOneof(oneof);
+ }
+ public Builder setRepeatedField(
+ com.google.protobuf.Descriptors.FieldDescriptor field,
+ int index, Object value) {
+ return (Builder) super.setRepeatedField(field, index, value);
+ }
+ public Builder addRepeatedField(
+ com.google.protobuf.Descriptors.FieldDescriptor field,
+ Object value) {
+ return (Builder) super.addRepeatedField(field, value);
+ }
+ public <Type> Builder setExtension(
+ com.google.protobuf.GeneratedMessage.GeneratedExtension<
+ retrofit2.converter.protobuf.PhoneProtos.Phone, Type> extension,
+ Type value) {
+ return (Builder) super.setExtension(extension, value);
+ }
+ public <Type> Builder setExtension(
+ com.google.protobuf.GeneratedMessage.GeneratedExtension<
+ retrofit2.converter.protobuf.PhoneProtos.Phone, java.util.List<Type>> extension,
+ int index, Type value) {
+ return (Builder) super.setExtension(extension, index, value);
+ }
+ public <Type> Builder addExtension(
+ com.google.protobuf.GeneratedMessage.GeneratedExtension<
+ retrofit2.converter.protobuf.PhoneProtos.Phone, java.util.List<Type>> extension,
+ Type value) {
+ return (Builder) super.addExtension(extension, value);
+ }
+ public <Type> Builder clearExtension(
+ com.google.protobuf.GeneratedMessage.GeneratedExtension<
+ retrofit2.converter.protobuf.PhoneProtos.Phone, ?> extension) {
+ return (Builder) super.clearExtension(extension);
+ }
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof retrofit2.converter.protobuf.PhoneProtos.Phone) {
return mergeFrom((retrofit2.converter.protobuf.PhoneProtos.Phone)other);
@@ -384,13 +445,13 @@ public Builder mergeFrom(retrofit2.converter.protobuf.PhoneProtos.Phone other) {
onChanged();
}
this.mergeExtensionFields(other);
- this.mergeUnknownFields(other.getUnknownFields());
+ this.mergeUnknownFields(other.unknownFields);
+ onChanged();
return this;
}
public final boolean isInitialized() {
if (!extensionsAreInitialized()) {
-
return false;
}
return true;
@@ -405,7 +466,7 @@ public Builder mergeFrom(
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (retrofit2.converter.protobuf.PhoneProtos.Phone) e.getUnfinishedMessage();
- throw e;
+ throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
@@ -490,16 +551,53 @@ public Builder setNumberBytes(
onChanged();
return this;
}
+ public final Builder setUnknownFields(
+ final com.google.protobuf.UnknownFieldSet unknownFields) {
+ return super.setUnknownFields(unknownFields);
+ }
+
+ public final Builder mergeUnknownFields(
+ final com.google.protobuf.UnknownFieldSet unknownFields) {
+ return super.mergeUnknownFields(unknownFields);
+ }
+
// @@protoc_insertion_point(builder_scope:retrofit2.converter.protobuf.Phone)
}
+ // @@protoc_insertion_point(class_scope:retrofit2.converter.protobuf.Phone)
+ private static final retrofit2.converter.protobuf.PhoneProtos.Phone DEFAULT_INSTANCE;
static {
- defaultInstance = new Phone(true);
- defaultInstance.initFields();
+ DEFAULT_INSTANCE = new retrofit2.converter.protobuf.PhoneProtos.Phone();
+ }
+
+ public static retrofit2.converter.protobuf.PhoneProtos.Phone getDefaultInstance() {
+ return DEFAULT_INSTANCE;
+ }
+
+ @java.lang.Deprecated public static final com.google.protobuf.Parser<Phone>
+ PARSER = new com.google.protobuf.AbstractParser<Phone>() {
+ public Phone parsePartialFrom(
+ com.google.protobuf.CodedInputStream input,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws com.google.protobuf.InvalidProtocolBufferException {
+ return new Phone(input, extensionRegistry);
+ }
+ };
+
+ public static com.google.protobuf.Parser<Phone> parser() {
+ return PARSER;
+ }
+
+ @java.lang.Override
+ public com.google.protobuf.Parser<Phone> getParserForType() {
+ return PARSER;
+ }
+
+ public retrofit2.converter.protobuf.PhoneProtos.Phone getDefaultInstanceForType() {
+ return DEFAULT_INSTANCE;
}
- // @@protoc_insertion_point(class_scope:retrofit2.converter.protobuf.Phone)
}
public static final int VOICEMAIL_FIELD_NUMBER = 2;
@@ -515,7 +613,7 @@ public Builder setNumberBytes(
null);
private static final com.google.protobuf.Descriptors.Descriptor
internal_static_retrofit2_converter_protobuf_Phone_descriptor;
- private static
+ private static final
com.google.protobuf.GeneratedMessage.FieldAccessorTable
internal_static_retrofit2_converter_protobuf_Phone_fieldAccessorTable;
@@ -523,7 +621,7 @@ public Builder setNumberBytes(
getDescriptor() {
return descriptor;
}
- private static com.google.protobuf.Descriptors.FileDescriptor
+ private static com.google.protobuf.Descriptors.FileDescriptor
descriptor;
static {
java.lang.String[] descriptorData = {
| train | val | 2016-08-02T17:06:56 | "2016-05-27T11:21:28Z" | xboy-im | val |
square/retrofit/1973_2018 | square/retrofit | square/retrofit/1973 | square/retrofit/2018 | [
"timestamp(timedelta=0.0, similarity=0.8759188829121922)"
] | a2765946d54572f133606a932eddb53b015606e0 | 31c82e8bd96d9ec7ef4782157c6dcc742351ff00 | [
"Yep. Since Moshi doesn't have any top-level configuration around this we'll provide options on the converter.\n"
] | [] | "2016-09-17T22:20:20Z" | [
"Enhancement"
] | Allow to serialize nulls in moshi request body converter | Hi!
Seems like there is an issue in Moshi converter. Would be nice to be able control writters serializeNulls property when using Moshi converter.
Sincerely,
Roman
| [
"retrofit-converters/moshi/src/main/java/retrofit2/converter/moshi/MoshiConverterFactory.java",
"retrofit-converters/moshi/src/main/java/retrofit2/converter/moshi/MoshiRequestBodyConverter.java"
] | [
"retrofit-converters/moshi/src/main/java/retrofit2/converter/moshi/MoshiConverterFactory.java",
"retrofit-converters/moshi/src/main/java/retrofit2/converter/moshi/MoshiRequestBodyConverter.java"
] | [
"retrofit-converters/moshi/src/test/java/retrofit2/converter/moshi/MoshiConverterFactoryTest.java"
] | diff --git a/retrofit-converters/moshi/src/main/java/retrofit2/converter/moshi/MoshiConverterFactory.java b/retrofit-converters/moshi/src/main/java/retrofit2/converter/moshi/MoshiConverterFactory.java
index d566c3044c..60e5f1bfd8 100644
--- a/retrofit-converters/moshi/src/main/java/retrofit2/converter/moshi/MoshiConverterFactory.java
+++ b/retrofit-converters/moshi/src/main/java/retrofit2/converter/moshi/MoshiConverterFactory.java
@@ -50,21 +50,28 @@ public static MoshiConverterFactory create() {
/** Create an instance using {@code moshi} for conversion. */
public static MoshiConverterFactory create(Moshi moshi) {
- return new MoshiConverterFactory(moshi, false);
+ if (moshi == null) throw new NullPointerException("moshi == null");
+ return new MoshiConverterFactory(moshi, false, false);
}
private final Moshi moshi;
private final boolean lenient;
+ private final boolean serializeNulls;
- private MoshiConverterFactory(Moshi moshi, boolean lenient) {
- if (moshi == null) throw new NullPointerException("moshi == null");
+ private MoshiConverterFactory(Moshi moshi, boolean lenient, boolean serializeNulls) {
this.moshi = moshi;
this.lenient = lenient;
+ this.serializeNulls = serializeNulls;
}
/** Return a new factory which uses {@linkplain JsonAdapter#lenient() lenient} adapters. */
public MoshiConverterFactory asLenient() {
- return new MoshiConverterFactory(moshi, true);
+ return new MoshiConverterFactory(moshi, true, serializeNulls);
+ }
+
+ /** Return a new factory which includes null values into the serialized JSON. */
+ public MoshiConverterFactory withNullSerialization() {
+ return new MoshiConverterFactory(moshi, lenient, true);
}
@Override
@@ -84,7 +91,7 @@ public Converter<?, RequestBody> requestBodyConverter(Type type,
if (lenient) {
adapter = adapter.lenient();
}
- return new MoshiRequestBodyConverter<>(adapter);
+ return new MoshiRequestBodyConverter<>(adapter, serializeNulls);
}
private static Set<? extends Annotation> jsonAnnotations(Annotation[] annotations) {
diff --git a/retrofit-converters/moshi/src/main/java/retrofit2/converter/moshi/MoshiRequestBodyConverter.java b/retrofit-converters/moshi/src/main/java/retrofit2/converter/moshi/MoshiRequestBodyConverter.java
index ac3d095d35..5e59b17fed 100644
--- a/retrofit-converters/moshi/src/main/java/retrofit2/converter/moshi/MoshiRequestBodyConverter.java
+++ b/retrofit-converters/moshi/src/main/java/retrofit2/converter/moshi/MoshiRequestBodyConverter.java
@@ -16,6 +16,7 @@
package retrofit2.converter.moshi;
import com.squareup.moshi.JsonAdapter;
+import com.squareup.moshi.JsonWriter;
import java.io.IOException;
import okhttp3.MediaType;
import okhttp3.RequestBody;
@@ -26,14 +27,18 @@ final class MoshiRequestBodyConverter<T> implements Converter<T, RequestBody> {
private static final MediaType MEDIA_TYPE = MediaType.parse("application/json; charset=UTF-8");
private final JsonAdapter<T> adapter;
+ private final boolean serializeNulls;
- MoshiRequestBodyConverter(JsonAdapter<T> adapter) {
+ MoshiRequestBodyConverter(JsonAdapter<T> adapter, boolean serializeNulls) {
this.adapter = adapter;
+ this.serializeNulls = serializeNulls;
}
@Override public RequestBody convert(T value) throws IOException {
Buffer buffer = new Buffer();
- adapter.toJson(buffer, value);
+ JsonWriter writer = JsonWriter.of(buffer);
+ writer.setSerializeNulls(serializeNulls);
+ adapter.toJson(writer, value);
return RequestBody.create(MEDIA_TYPE, buffer.readByteString());
}
}
| diff --git a/retrofit-converters/moshi/src/test/java/retrofit2/converter/moshi/MoshiConverterFactoryTest.java b/retrofit-converters/moshi/src/test/java/retrofit2/converter/moshi/MoshiConverterFactoryTest.java
index 3b902d1d8c..d22c372678 100644
--- a/retrofit-converters/moshi/src/test/java/retrofit2/converter/moshi/MoshiConverterFactoryTest.java
+++ b/retrofit-converters/moshi/src/test/java/retrofit2/converter/moshi/MoshiConverterFactoryTest.java
@@ -119,6 +119,7 @@ interface Service {
private Service service;
private Service serviceLenient;
+ private Service serviceNulls;
@Before public void setUp() {
Moshi moshi = new Moshi.Builder()
@@ -137,6 +138,7 @@ interface Service {
.build();
MoshiConverterFactory factory = MoshiConverterFactory.create(moshi);
MoshiConverterFactory factoryLenient = factory.asLenient();
+ MoshiConverterFactory factoryNulls = factory.withNullSerialization();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(server.url("/"))
.addConverterFactory(factory)
@@ -145,8 +147,13 @@ interface Service {
.baseUrl(server.url("/"))
.addConverterFactory(factoryLenient)
.build();
+ Retrofit retrofitNulls = new Retrofit.Builder()
+ .baseUrl(server.url("/"))
+ .addConverterFactory(factoryNulls)
+ .build();
service = retrofit.create(Service.class);
serviceLenient = retrofitLenient.create(Service.class);
+ serviceNulls = retrofitNulls.create(Service.class);
}
@Test public void anInterface() throws IOException, InterruptedException {
@@ -207,6 +214,14 @@ interface Service {
assertThat(body.theName).isEqualTo("value");
}
+ @Test public void withNulls() throws IOException, InterruptedException {
+ server.enqueue(new MockResponse().setBody("{}"));
+
+ Call<AnImplementation> call = serviceNulls.anImplementation(new AnImplementation(null));
+ call.execute();
+ assertEquals("{\"theName\":null}", server.takeRequest().getBody().readUtf8());
+ }
+
@Test public void utf8BomSkipped() throws IOException {
Buffer responseBody = new Buffer()
.write(ByteString.decodeHex("EFBBBF"))
| train | val | 2016-09-01T19:52:20 | "2016-08-13T20:43:08Z" | romatroskin | val |
square/retrofit/2037_2038 | square/retrofit | square/retrofit/2037 | square/retrofit/2038 | [
"timestamp(timedelta=40.0, similarity=0.9739437454754193)"
] | 78b049143b5129b6d802b14c69f900b4089da33c | 3792f558944980689bd8889ed1d26d0f05a5a71f | [
"This can be accomplished with:\r\n```java\r\npublic final class FileBodyConverter implements Converter<File, RequestBody> {\r\n public static final Converter.Factory FACTORY = new Factory() {\r\n @Override public Converter<?, RequestBody> requestBodyConverter(Type type,\r\n Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {\r\n return File.class.equals(type) ? new FileBodyConverter() : null;\r\n }\r\n }\r\n \r\n @Override public RequestBody convert(File value) throws IOException {\r\n return RequestBody.create(null, value);\r\n }\r\n}\r\n```\r\nand since it's unclear what content-type to use for a `File` I don't want to ship a general version of this."
] | [] | "2016-10-01T19:11:50Z" | [] | Explicit usage of File objects in @Multipart methods with @Part and @PartMap | I want to use File object explicitly in Retrofit interfaces without manually creating `MultipartBody.Part`. It should be available in single parameters with `@Part` and `@PartMap` annotations.
Example :
```
public interface FileService {
@Multipart
@POST("/upload")
Call<ResponseBody> sendFile(@Part("file") File fileToSend);
}
```
I will provide a pull request with tests and implementation.
| [
"retrofit/src/main/java/retrofit2/ParameterHandler.java",
"retrofit/src/main/java/retrofit2/ServiceMethod.java"
] | [
"retrofit/src/main/java/retrofit2/ParameterHandler.java",
"retrofit/src/main/java/retrofit2/ServiceMethod.java"
] | [
"retrofit/src/test/java/retrofit2/RequestBuilderTest.java"
] | diff --git a/retrofit/src/main/java/retrofit2/ParameterHandler.java b/retrofit/src/main/java/retrofit2/ParameterHandler.java
index c332fad501..fbdde7380c 100644
--- a/retrofit/src/main/java/retrofit2/ParameterHandler.java
+++ b/retrofit/src/main/java/retrofit2/ParameterHandler.java
@@ -15,6 +15,7 @@
*/
package retrofit2;
+import java.io.File;
import java.io.IOException;
import java.lang.reflect.Array;
import java.util.Map;
@@ -247,15 +248,27 @@ private RawPart() {
}
}
- static final class PartMap<T> extends ParameterHandler<Map<String, T>> {
- private final Converter<T, RequestBody> valueConverter;
- private final String transferEncoding;
+ static final class FilePart extends ParameterHandler<File> {
+ private final String name;
- PartMap(Converter<T, RequestBody> valueConverter, String transferEncoding) {
- this.valueConverter = valueConverter;
- this.transferEncoding = transferEncoding;
+ FilePart(String name) {
+ this.name = name;
+ }
+
+ @Override void apply(RequestBuilder builder, File value) throws IOException {
+ apply(builder, name, value);
}
+ static void apply(RequestBuilder builder, String name, File value) {
+ if (value != null) { // Skip null values.
+ builder.addPart(MultipartBody.Part.createFormData(name,
+ value.getName(),
+ RequestBody.create(null, value)));
+ }
+ }
+ }
+
+ abstract static class BasePartMap<T> extends ParameterHandler<Map<String, T>> {
@Override void apply(RequestBuilder builder, Map<String, T> value) throws IOException {
if (value == null) {
throw new IllegalArgumentException("Part map was null.");
@@ -271,13 +284,36 @@ static final class PartMap<T> extends ParameterHandler<Map<String, T>> {
throw new IllegalArgumentException(
"Part map contained null value for key '" + entryKey + "'.");
}
+ applyEntry(builder, entryKey, entryValue);
+ }
+ }
- Headers headers = Headers.of(
- "Content-Disposition", "form-data; name=\"" + entryKey + "\"",
- "Content-Transfer-Encoding", transferEncoding);
+ abstract void applyEntry(RequestBuilder builder, String key, T value) throws IOException;
+ }
- builder.addPart(headers, valueConverter.convert(entryValue));
- }
+ static final class FilePartMap extends BasePartMap<File> {
+ static final FilePartMap INSTANCE = new FilePartMap();
+
+ @Override void applyEntry(RequestBuilder builder, String key, File value) throws IOException {
+ FilePart.apply(builder, key, value);
+ }
+ }
+
+ static final class PartMap<T> extends BasePartMap<T> {
+ private final Converter<T, RequestBody> valueConverter;
+ private final String transferEncoding;
+
+ PartMap(Converter<T, RequestBody> valueConverter, String transferEncoding) {
+ this.valueConverter = valueConverter;
+ this.transferEncoding = transferEncoding;
+ }
+
+ @Override void applyEntry(RequestBuilder builder, String key, T value) throws IOException {
+ Headers headers = Headers.of(
+ "Content-Disposition", "form-data; name=\"" + key + "\"",
+ "Content-Transfer-Encoding", transferEncoding);
+
+ builder.addPart(headers, valueConverter.convert(value));
}
}
diff --git a/retrofit/src/main/java/retrofit2/ServiceMethod.java b/retrofit/src/main/java/retrofit2/ServiceMethod.java
index 3a4325a7ef..8e82ae1e2a 100644
--- a/retrofit/src/main/java/retrofit2/ServiceMethod.java
+++ b/retrofit/src/main/java/retrofit2/ServiceMethod.java
@@ -15,6 +15,7 @@
*/
package retrofit2;
+import java.io.File;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
@@ -589,6 +590,8 @@ private ParameterHandler<?> parseParameterAnnotation(
return ParameterHandler.RawPart.INSTANCE.array();
} else if (MultipartBody.Part.class.isAssignableFrom(rawParameterType)) {
return ParameterHandler.RawPart.INSTANCE;
+ } else if (File.class.isAssignableFrom(rawParameterType)) {
+ throw parameterError(p, "File parts must have defined name.");
} else {
throw parameterError(p,
"@Part annotation must supply a name or use MultipartBody.Part parameter type.");
@@ -626,6 +629,8 @@ private ParameterHandler<?> parseParameterAnnotation(
} else if (MultipartBody.Part.class.isAssignableFrom(rawParameterType)) {
throw parameterError(p, "@Part parameters using the MultipartBody.Part must not "
+ "include a part name in the annotation.");
+ } else if (File.class.isAssignableFrom(rawParameterType)) {
+ return new ParameterHandler.FilePart(partName);
} else {
Converter<?, RequestBody> converter =
retrofit.requestBodyConverter(type, annotations, methodAnnotations);
@@ -658,6 +663,9 @@ private ParameterHandler<?> parseParameterAnnotation(
throw parameterError(p, "@PartMap values cannot be MultipartBody.Part. "
+ "Use @Part List<Part> or a different value type instead.");
}
+ if (File.class.isAssignableFrom(Utils.getRawType(valueType))) {
+ return ParameterHandler.FilePartMap.INSTANCE;
+ }
Converter<?, RequestBody> valueConverter =
retrofit.requestBodyConverter(valueType, annotations, methodAnnotations);
| diff --git a/retrofit/src/test/java/retrofit2/RequestBuilderTest.java b/retrofit/src/test/java/retrofit2/RequestBuilderTest.java
index 0f3b5ebe66..6a1a9ee032 100644
--- a/retrofit/src/test/java/retrofit2/RequestBuilderTest.java
+++ b/retrofit/src/test/java/retrofit2/RequestBuilderTest.java
@@ -15,6 +15,7 @@
*/
package retrofit2;
+import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.math.BigInteger;
@@ -2071,6 +2072,82 @@ Call<ResponseBody> method(@Part("ping") RequestBody ping) {
}
}
+ @Test public void multipartWithFileContents() throws IOException {
+ class Example {
+ @Multipart
+ @POST("/foo/bar/")
+ Call<ResponseBody> method(@Part("filepart") File content) { return null; }
+ }
+
+ File multipartFile = File.createTempFile("multipartFileTest", ".txt");
+
+ Request request = buildRequest(Example.class, multipartFile);
+ RequestBody body = request.body();
+ Buffer buffer = new Buffer();
+ body.writeTo(buffer);
+ String bodyString = buffer.readUtf8();
+
+ assertThat(bodyString)
+ .contains("name=\"filepart\"; filename=\"" + multipartFile.getName() + "\"");
+ }
+
+ @Test public void multipartMapWithFiles() throws IOException {
+ class Example {
+ @Multipart
+ @POST("/foo/bar")
+ Call<ResponseBody> method(@PartMap Map<String, File> files) { return null; }
+ }
+
+ Map<String, File> fileMap = new HashMap<>(3);
+ fileMap.put("file[0]", File.createTempFile("multipartFileTest", ".txt"));
+ fileMap.put("file[1]", File.createTempFile("multipartFileTest", ".txt"));
+ fileMap.put("file[2]", File.createTempFile("multipartFileTest", ".txt"));
+
+ Request request = buildRequest(Example.class, fileMap);
+ RequestBody body = request.body();
+ Buffer buffer = new Buffer();
+ body.writeTo(buffer);
+ String bodyString = buffer.readUtf8();
+
+ assertThat(bodyString)
+ .contains("name=\"file[0]\"; filename=\"" + fileMap.get("file[0]").getName() + "\"")
+ .contains("name=\"file[1]\"; filename=\"" + fileMap.get("file[1]").getName() + "\"")
+ .contains("name=\"file[2]\"; filename=\"" + fileMap.get("file[2]").getName() + "\"");
+ }
+
+ @Test public void multipartFileContentsNullValue() throws IOException {
+ class Example {
+ @Multipart
+ @POST("/foo/bar/")
+ Call<ResponseBody> method(@Part("text") String text, @Part("filepart") File content) { return null; }
+ }
+
+ Request request = buildRequest(Example.class, "param", (File) null);
+ RequestBody body = request.body();
+ Buffer buffer = new Buffer();
+ body.writeTo(buffer);
+ String bodyString = buffer.readUtf8();
+
+ assertThat(bodyString)
+ .contains("name=\"text\"")
+ .doesNotContain("name=\"filepart\"");
+ }
+
+ @Test public void multipartFileContentsWithoutPartName() {
+ class Example {
+ @Multipart
+ @POST("/foo/bar/")
+ Call<ResponseBody> method(@Part File content) { return null; }
+ }
+
+ try {
+ buildRequest(Example.class, null);
+ fail();
+ } catch (IllegalArgumentException e) {
+ assertThat(e.getMessage()).isEqualTo("File parts must have defined name. (parameter #1)\n for method Example.method");
+ }
+ }
+
@Test public void simpleFormEncoded() {
class Example {
@FormUrlEncoded //
| val | val | 2016-09-20T18:35:49 | "2016-10-01T19:10:45Z" | urbanpawel90 | val |
square/retrofit/2054_2056 | square/retrofit | square/retrofit/2054 | square/retrofit/2056 | [
"timestamp(timedelta=0.0, similarity=0.9312923084130892)"
] | 32ace0894882a98f56cd509fee1bcc7dff804347 | 2060a1911fbc47966ad1af746c21252ce4827418 | [
"Why do you need it?\n\nOn Wed, Oct 19, 2016, 8:22 PM Jared Burrows [email protected]\nwrote:\n\n> Can we add newBuilder builder similar to Okhttp3 (see here\n> https://github.com/square/okhttp/blob/master/okhttp/src/main/java/okhttp3/OkHttpClient.java#L390)\n> to Retrofit.Builder?\n> \n> —\n> You are receiving this because you are subscribed to this thread.\n> Reply to this email directly, view it on GitHub\n> https://github.com/square/retrofit/issues/2054, or mute the thread\n> https://github.com/notifications/unsubscribe-auth/AAEEEXlDnSQ3DS4w7Zeo3ts1VrbzYEFNks5q1rRSgaJpZM4KbmNw\n> .\n",
"The same reason it is availble in OkHttp3.\n\nFor instance:\n\n```\n// Some Client\nOkHttpClient client = new OkHttpClient.Builder()\n .addInterceptor(new HttpLoggingInterceptor()\n .setLevel(HttpLoggingInterceptor.Level.BODY))\n .cache(cache)\n .build();\n\n// Some client 2\nOkHttpClient client2 = client.newBuilder()\n .connectTimeout(CLIENT_TIME_OUT, TimeUnit.SECONDS)\n .writeTimeout(CLIENT_TIME_OUT, TimeUnit.SECONDS)\n .readTimeout(CLIENT_TIME_OUT, TimeUnit.SECONDS)\n .build();\n```\n\nI can reuse the existing builder to create another client and change some the existing parameters. I would like to be able to do the same with Retrofit 2.\n",
"I know what it's function is, but what specifically would you use it for?\nUnlike OkHttpClient the Retrofit instance is much more dumb and\nnecessitates something like this much less. So actual motivations are much\nmore compelling than theoretical ones (which is why it's currently absent).\n\nOn Wed, Oct 19, 2016 at 8:47 PM Jared Burrows [email protected]\nwrote:\n\n> The same reason it is availble in OkHttp3.\n> \n> For instance:\n> \n> // Some Client\n> OkHttpClient client = new OkHttpClient.Builder()\n> .addInterceptor(new HttpLoggingInterceptor()\n> .setLevel(HttpLoggingInterceptor.Level.BODY))\n> .cache(cache)\n> .build();\n> \n> // Some client 2\n> OkHttpClient client2 = client.newBuilder().connectTimeout(CLIENT_TIME_OUT, TimeUnit.SECONDS)\n> .writeTimeout(CLIENT_TIME_OUT, TimeUnit.SECONDS)\n> .readTimeout(CLIENT_TIME_OUT, TimeUnit.SECONDS)\n> .build();\n> \n> I can reuse the existing builder to create another client and change some\n> the existing parameters. I would like to be able to do the same with\n> Retrofit 2.\n> \n> —\n> You are receiving this because you commented.\n> \n> Reply to this email directly, view it on GitHub\n> https://github.com/square/retrofit/issues/2054#issuecomment-254980927,\n> or mute the thread\n> https://github.com/notifications/unsubscribe-auth/AAEEER5uY1QdYgzRJg0ABd44T6NKFRVmks5q1ro7gaJpZM4KbmNw\n> .\n",
"It would be nice to easily call `newBuilder` and pass in the url from the Okhttp mockserver for testing. But in general, it would be nice to change some the existing parameters.\n",
"U can hold one Retrofit.Builder instance, then you can create different Retrofit instance with this builder.\nlike this:\nRetrofit.Builder builder = Retrofit.Builder()\n .addConverterFactory(GsonConverterFactory.create())\n .addCallAdapterFactory(RxJavaCallAdapterFactory.create())\n .client(okHttpClient);\nRetrofit retrofit1 = builder\n .baseUrl(\"xxx\")\n .build();\n\nRetrofit retrofit2 = builder\n .baseUrl(\"xxxxx\")\n .build();\nDo you mean this?\n",
"@ly85206559 That is what I am doing now. I do not want to pass `Retrofit.Builder`. It would be nice to pass `Retrofit` as a parameter. With `OkHttp3`, you can call `newBuilder()` on `OkHttpClient`.\n"
] | [
"All lists should use `addAll` and not retain these unmodifiable references.\n",
"What's a \"rest adapter\"?!? I don't think we want any of this doc. Unlike OkHttp, this isn't something we expect many to do (seeing as we haven't had the ability for Retrofit's 5 years of existence).\n",
"Good eye.\n"
] | "2016-10-22T03:00:22Z" | [] | [Request] Add "newBuilder" to Retrofit class | Can we add `newBuilder` builder similar to Okhttp3 (see [here](https://github.com/square/okhttp/blob/master/okhttp/src/main/java/okhttp3/OkHttpClient.java#L390)) to `Retrofit.Builder`?
I would like to change the URL of an already created builder.
| [
"retrofit/src/main/java/retrofit2/Retrofit.java"
] | [
"retrofit/src/main/java/retrofit2/Retrofit.java"
] | [
"retrofit/src/test/java/retrofit2/RetrofitTest.java"
] | diff --git a/retrofit/src/main/java/retrofit2/Retrofit.java b/retrofit/src/main/java/retrofit2/Retrofit.java
index 9ee1116d50..2cea88098f 100644
--- a/retrofit/src/main/java/retrofit2/Retrofit.java
+++ b/retrofit/src/main/java/retrofit2/Retrofit.java
@@ -59,16 +59,18 @@
public final class Retrofit {
private final Map<Method, ServiceMethod<?, ?>> serviceMethodCache = new ConcurrentHashMap<>();
- private final okhttp3.Call.Factory callFactory;
- private final HttpUrl baseUrl;
- private final List<Converter.Factory> converterFactories;
- private final List<CallAdapter.Factory> adapterFactories;
- private final Executor callbackExecutor;
- private final boolean validateEagerly;
-
- Retrofit(okhttp3.Call.Factory callFactory, HttpUrl baseUrl,
+ final Platform platform;
+ final okhttp3.Call.Factory callFactory;
+ final HttpUrl baseUrl;
+ final List<Converter.Factory> converterFactories;
+ final List<CallAdapter.Factory> adapterFactories;
+ final Executor callbackExecutor;
+ final boolean validateEagerly;
+
+ Retrofit(Platform platform, okhttp3.Call.Factory callFactory, HttpUrl baseUrl,
List<Converter.Factory> converterFactories, List<CallAdapter.Factory> adapterFactories,
Executor callbackExecutor, boolean validateEagerly) {
+ this.platform = platform;
this.callFactory = callFactory;
this.baseUrl = baseUrl;
this.converterFactories = unmodifiableList(converterFactories); // Defensive copy at call site.
@@ -379,6 +381,10 @@ public Executor callbackExecutor() {
return callbackExecutor;
}
+ public Builder newBuilder() {
+ return new Builder(this);
+ }
+
/**
* Build a new {@link Retrofit}.
* <p>
@@ -386,13 +392,13 @@ public Executor callbackExecutor() {
* are optional.
*/
public static final class Builder {
- private Platform platform;
- private okhttp3.Call.Factory callFactory;
- private HttpUrl baseUrl;
- private List<Converter.Factory> converterFactories = new ArrayList<>();
- private List<CallAdapter.Factory> adapterFactories = new ArrayList<>();
- private Executor callbackExecutor;
- private boolean validateEagerly;
+ Platform platform;
+ okhttp3.Call.Factory callFactory;
+ HttpUrl baseUrl;
+ List<Converter.Factory> converterFactories = new ArrayList<>();
+ List<CallAdapter.Factory> adapterFactories = new ArrayList<>();
+ Executor callbackExecutor;
+ boolean validateEagerly;
Builder(Platform platform) {
this.platform = platform;
@@ -405,6 +411,16 @@ public Builder() {
this(Platform.get());
}
+ public Builder(Retrofit retrofit) {
+ this.platform = retrofit.platform;
+ this.callFactory = retrofit.callFactory;
+ this.baseUrl = retrofit.baseUrl;
+ this.converterFactories.addAll(retrofit.converterFactories);
+ this.adapterFactories.addAll(retrofit.adapterFactories);
+ this.callbackExecutor = retrofit.callbackExecutor;
+ this.validateEagerly = retrofit.validateEagerly;
+ }
+
/**
* The HTTP client used for requests.
* <p>
@@ -562,7 +578,7 @@ public Retrofit build() {
// Make a defensive copy of the converters.
List<Converter.Factory> converterFactories = new ArrayList<>(this.converterFactories);
- return new Retrofit(callFactory, baseUrl, converterFactories, adapterFactories,
+ return new Retrofit(platform, callFactory, baseUrl, converterFactories, adapterFactories,
callbackExecutor, validateEagerly);
}
}
| diff --git a/retrofit/src/test/java/retrofit2/RetrofitTest.java b/retrofit/src/test/java/retrofit2/RetrofitTest.java
index 885394bfc0..b54cf598fe 100644
--- a/retrofit/src/test/java/retrofit2/RetrofitTest.java
+++ b/retrofit/src/test/java/retrofit2/RetrofitTest.java
@@ -54,6 +54,8 @@
import static okhttp3.mockwebserver.SocketPolicy.DISCONNECT_AT_START;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.Matchers.any;
@@ -140,6 +142,39 @@ interface MutableParameters {
}
}
+ @Test public void cloneSharesStatefulInstances() {
+ CallAdapter.Factory callAdapter = mock(CallAdapter.Factory.class);
+ Converter.Factory converter = mock(Converter.Factory.class);
+ Executor executor = mock(Executor.class);
+ okhttp3.Call.Factory call = mock(okhttp3.Call.Factory.class);
+ OkHttpClient client = mock(OkHttpClient.class);
+
+ Retrofit retrofit = new Retrofit.Builder()
+ .addCallAdapterFactory(callAdapter)
+ .addConverterFactory(converter)
+ .baseUrl(server.url("/"))
+ .callbackExecutor(executor)
+ .callFactory(call)
+ .client(client)
+ .build();
+
+ // Values should be non-null.
+ Retrofit a = retrofit.newBuilder().build();
+ assertNotNull(a.callAdapterFactories().get(0));
+ assertNotNull(a.converterFactories().get(0));
+ assertNotNull(a.baseUrl());
+ assertNotNull(a.callbackExecutor());
+ assertNotNull(a.callFactory());
+
+ // Multiple clients share the instances.
+ Retrofit b = retrofit.newBuilder().build();
+ assertSame(a.callAdapterFactories().get(0), b.callAdapterFactories().get(0));
+ assertSame(a.converterFactories().get(0), b.converterFactories().get(0));
+ assertSame(a.baseUrl(), b.baseUrl());
+ assertSame(a.callbackExecutor(), b.callbackExecutor());
+ assertSame(a.callFactory(), b.callFactory());
+ }
+
@Test public void responseTypeCannotBeRetrofitResponse() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(server.url("/"))
| train | val | 2016-10-15T23:16:27 | "2016-10-20T00:22:39Z" | jaredsburrows | val |
square/retrofit/2102_2103 | square/retrofit | square/retrofit/2102 | square/retrofit/2103 | [
"timestamp(timedelta=0.0, similarity=0.9190210928500488)"
] | 777b520523ceb85e8d2aba1b4964352d1ed1c35c | f331e3b7bdbc7c3332a63c569871b4db976d0ba7 | [
"Submitted pull request #2103.",
"Any idea how I can look to see what classes from Android are included? We tend to like class lookups since they offer better insight into the capabilities of the enclosing VM rather than inspecting properties.\r\n\r\nOr, more specifically, if we switched to checking for `android.os.Looper` would the same problem occur?",
"You would have to write a plugin and try to lookup the class you are considering to see if it throws. Even if it does not throw, I recommend against this approach because JetBrains / Google may choose to expose additional classes over time; there is no guarantee. In my experience the safest way to achieve what you want is to ask the JVM (e.g. properties) which is much more stable.",
"For feature detection inside a platform we've traditionally favored the opposite. But detection of the platform itself might mean needing to look at properties.\r\n\r\n@swankjesse?",
"Curious – what if we instead of probing for `Build` we could probe for `Looper`? If that works it might mean we end up with the right behavior on Android, Java, Android Studio and Robolectric.",
"Hello, this issue is still blocking us to use retrofit in any environment that has android classes on classpath. Are there any plans to fix it?\r\nusing JVM properties will be way smarter way to find Platform.\r\n\r\nAlso it would be nice to give opportunity to user to provide platform. This will provide valid workaround for any usecase. For example just do System.getProperty(\"retrofit.platform\")as first line and if property is provided create appropriate Platform, if not use default logic. This will allow lib clients to specify Platform if needed.\r\n\r\nThanks,\r\n-Alex",
"Hey @JakeWharton / @swankjesse, are there any updates here? I'm running into an identical issue (plugin development for JetBrains IntelliJ) which is preventing me from using retrofit.\r\n\r\nIt looks like there hasn't been any movement on the PR (#2103) that @baron1405 submitted over a year ago.\r\n\r\n**Edit:** Something like @akazancev is suggesting would work; if a system property is set, use the property, otherwise default to existing logic. :)\r\n\r\nLooking forward to your thoughts!\r\n\r\nBest,\r\nChris",
"@swankjesse do you have any updates on this?\r\nThanks,\r\n-Alex"
] | [
"This seems like enough of an indicator where we don't even need to bother with the `Class.forName` check?\r\n\r\n@swankjesse thoughts?",
"Looks like `Dalvik` value will be there forever, even on ART it's `Dalvik` and `java.vm.version` can be used to distinguish between Dalvik/ART/etc https://developer.android.com/guide/practices/verifying-apps-art.html#GC_Migration\r\n\r\nWould be great to apply this to OkHttp and RxJava if you'll decide to remove class lookup.",
"Will it work if we look for `android.os.Looper` instead? Seems like if that class is present then we should have Android behavior",
"BTW you can replace the forName check for Java 8 by using the `java.class.version` property. Any value >= 52 is Java 8 or newer.",
"I am concerned that attempting to load any Android class runs the risk of undesirable consequences especially in an IDE environment. Case in point is the android.os.Builder class was not on the classpath in the IDEA 2016.2 version of the Android Support plugin but has appeared on the classpath in the 2016.3 version. In other words, it is impossible to predict what Google and JetBrains will expose either intentionally or accidentally. A property based approach would be the safest. ",
"True. It also affects our ability to test this behavior since the Android classes are on the classpath but aren't actually usable."
] | "2016-12-01T22:22:09Z" | [
"Enhancement"
] | NPE when retrofit used by IntelliJ IDEA plugin | What kind of issue is this?
- [ ] Question. This issue tracker is not the place for questions. If you want to ask how to do
something, or to understand why something isn't working the way you expect it to, use Stack
Overflow. https://stackoverflow.com/questions/tagged/retrofit
- [X ] Bug report. If you’ve found a bug, spend the time to write a failing test. Bugs with tests
get fixed. Here’s an example: https://gist.github.com/swankjesse/6608b4713ad80988cdc9
- [ ] Feature Request. Start by telling us what problem you’re trying to solve. Often a solution
already exists! Don’t send pull requests to implement new features without first getting our
support. Sometimes we leave features out on purpose to keep the project small.
We are developing a plugin for IntelliJ IDEA Ultimate. The plugin uses retrofit for communication with a service. The plugin is crashing due to a NullPointerException resulting from retrofit's platform detection getting confused by the presence of an Android class on the IntelliJ IDEA classpath. The class is present due to IntelliJ's bundled Android Support plugin. The stack trace is:
```
2016-11-30 14:30:27,654 [ 7389] ERROR - plication.impl.ApplicationImpl - null
java.lang.ExceptionInInitializerError
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:264)
at retrofit2.Platform.findPlatform(Platform.java:37)
at retrofit2.Platform.<clinit>(Platform.java:29)
at retrofit2.Retrofit$Builder.<init>(Retrofit.java:402)
...
at com.intellij.openapi.application.impl.ApplicationImpl$3.call(ApplicationImpl.java:331)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.NullPointerException
at android.os.SystemProperties_Delegate.native_get(SystemProperties_Delegate.java:44)
at android.os.SystemProperties.native_get(SystemProperties.java)
at android.os.SystemProperties.get(SystemProperties.java:64)
at android.os.Build.getString(Build.java:819)
at android.os.Build.<clinit>(Build.java:39)
... 13 more
```
The relevant portion of the retrofit code is from the Platform class:
```java
private static Platform findPlatform() {
try {
Class.forName("android.os.Build");
if (Build.VERSION.SDK_INT != 0) {
return new Android();
}
} catch (ClassNotFoundException ignored) {
}
try {
Class.forName("java.util.Optional");
return new Java8();
} catch (ClassNotFoundException ignored) {
}
return new Platform();
}
```
The environment is RedHat Linux 6.6 running IntelliJ IDEA Ultimate 2016.3. That version of IntelliJ comes bundled with the Android Support plugin version 10.2.2. | [
"retrofit/src/main/java/retrofit2/Platform.java"
] | [
"retrofit/src/main/java/retrofit2/Platform.java"
] | [] | diff --git a/retrofit/src/main/java/retrofit2/Platform.java b/retrofit/src/main/java/retrofit2/Platform.java
index ad9cf533c7..5340c7f80b 100644
--- a/retrofit/src/main/java/retrofit2/Platform.java
+++ b/retrofit/src/main/java/retrofit2/Platform.java
@@ -32,12 +32,14 @@ static Platform get() {
}
private static Platform findPlatform() {
- try {
- Class.forName("android.os.Build");
- if (Build.VERSION.SDK_INT != 0) {
- return new Android();
+ if ("Dalvik".equals(System.getProperty("java.vm.name"))) {
+ try {
+ Class.forName("android.os.Build");
+ if (Build.VERSION.SDK_INT != 0) {
+ return new Android();
+ }
+ } catch (ClassNotFoundException ignored) {
}
- } catch (ClassNotFoundException ignored) {
}
try {
Class.forName("java.util.Optional");
| null | test | val | 2016-11-22T19:45:19 | "2016-12-01T17:58:02Z" | baron1405 | val |
square/retrofit/2132_2172 | square/retrofit | square/retrofit/2132 | square/retrofit/2172 | [
"timestamp(timedelta=0.0, similarity=0.8995889538586805)"
] | 4ec773178f8a992f9750ec4e7a57d2839530a075 | 77a65b7b1d852ef1fa2d19cab78ea831069b6fd0 | [] | [
"The only new code in this PR is this `Callback` implementation. Everything else was here previously."
] | "2017-01-30T03:55:29Z" | [] | Evaluate adding createAsync() to the RxJava adapters. | This would use `enqueue` instead of `execute` to defer threading to OkHttp's `Dispatcher` instead of blocking a scheduler (or application) thread. This would allow re-using 90% of the built-in machinery around things like type parsing, `Result`/body handling, etc. | [
"retrofit-adapters/rxjava/src/main/java/retrofit2/adapter/rxjava/CallOnSubscribe.java",
"retrofit-adapters/rxjava/src/main/java/retrofit2/adapter/rxjava/RxJavaCallAdapter.java",
"retrofit-adapters/rxjava/src/main/java/retrofit2/adapter/rxjava/RxJavaCallAdapterFactory.java"
] | [
"retrofit-adapters/rxjava/src/main/java/retrofit2/adapter/rxjava/CallArbiter.java",
"retrofit-adapters/rxjava/src/main/java/retrofit2/adapter/rxjava/CallEnqueueOnSubscribe.java",
"retrofit-adapters/rxjava/src/main/java/retrofit2/adapter/rxjava/CallExecuteOnSubscribe.java",
"retrofit-adapters/rxjava/src/main/java/retrofit2/adapter/rxjava/RxJavaCallAdapter.java",
"retrofit-adapters/rxjava/src/main/java/retrofit2/adapter/rxjava/RxJavaCallAdapterFactory.java"
] | [
"retrofit-adapters/rxjava/src/test/java/retrofit2/adapter/rxjava/AsyncTest.java"
] | diff --git a/retrofit-adapters/rxjava/src/main/java/retrofit2/adapter/rxjava/CallArbiter.java b/retrofit-adapters/rxjava/src/main/java/retrofit2/adapter/rxjava/CallArbiter.java
new file mode 100644
index 0000000000..34b0b004a5
--- /dev/null
+++ b/retrofit-adapters/rxjava/src/main/java/retrofit2/adapter/rxjava/CallArbiter.java
@@ -0,0 +1,149 @@
+/*
+ * Copyright (C) 2016 Jake Wharton
+ *
+ * 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 retrofit2.adapter.rxjava;
+
+import java.util.concurrent.atomic.AtomicInteger;
+import retrofit2.Call;
+import retrofit2.Response;
+import rx.Producer;
+import rx.Subscriber;
+import rx.Subscription;
+import rx.exceptions.CompositeException;
+import rx.exceptions.Exceptions;
+import rx.plugins.RxJavaPlugins;
+
+final class CallArbiter<T> extends AtomicInteger implements Subscription, Producer {
+ private static final int STATE_WAITING = 0;
+ private static final int STATE_REQUESTED = 1;
+ private static final int STATE_HAS_RESPONSE = 2;
+ private static final int STATE_TERMINATED = 3;
+
+ private final Call<T> call;
+ private final Subscriber<? super Response<T>> subscriber;
+
+ private volatile Response<T> response;
+
+ CallArbiter(Call<T> call, Subscriber<? super Response<T>> subscriber) {
+ super(STATE_WAITING);
+
+ this.call = call;
+ this.subscriber = subscriber;
+ }
+
+ @Override public void unsubscribe() {
+ call.cancel();
+ }
+
+ @Override public boolean isUnsubscribed() {
+ return call.isCanceled();
+ }
+
+ @Override public void request(long amount) {
+ if (amount == 0) {
+ return;
+ }
+ while (true) {
+ int state = get();
+ switch (state) {
+ case STATE_WAITING:
+ if (compareAndSet(STATE_WAITING, STATE_REQUESTED)) {
+ return;
+ }
+ break; // State transition failed. Try again.
+
+ case STATE_HAS_RESPONSE:
+ if (compareAndSet(STATE_HAS_RESPONSE, STATE_TERMINATED)) {
+ deliverResponse(response);
+ return;
+ }
+ break; // State transition failed. Try again.
+
+ case STATE_REQUESTED:
+ case STATE_TERMINATED:
+ return; // Nothing to do.
+
+ default:
+ throw new IllegalStateException("Unknown state: " + state);
+ }
+ }
+ }
+
+ void emitResponse(Response<T> response) {
+ while (true) {
+ int state = get();
+ switch (state) {
+ case STATE_WAITING:
+ this.response = response;
+ if (compareAndSet(STATE_WAITING, STATE_HAS_RESPONSE)) {
+ return;
+ }
+ break; // State transition failed. Try again.
+
+ case STATE_REQUESTED:
+ if (compareAndSet(STATE_REQUESTED, STATE_TERMINATED)) {
+ deliverResponse(response);
+ return;
+ }
+ break; // State transition failed. Try again.
+
+ case STATE_HAS_RESPONSE:
+ case STATE_TERMINATED:
+ throw new AssertionError();
+
+ default:
+ throw new IllegalStateException("Unknown state: " + state);
+ }
+ }
+ }
+
+ private void deliverResponse(Response<T> response) {
+ try {
+ if (!isUnsubscribed()) {
+ subscriber.onNext(response);
+ }
+ } catch (Throwable t) {
+ Exceptions.throwIfFatal(t);
+ try {
+ subscriber.onError(t);
+ } catch (Throwable inner) {
+ Exceptions.throwIfFatal(inner);
+ CompositeException composite = new CompositeException(t, inner);
+ RxJavaPlugins.getInstance().getErrorHandler().handleError(composite);
+ }
+ return;
+ }
+ try {
+ subscriber.onCompleted();
+ } catch (Throwable t) {
+ Exceptions.throwIfFatal(t);
+ RxJavaPlugins.getInstance().getErrorHandler().handleError(t);
+ }
+ }
+
+ void emitError(Throwable t) {
+ set(STATE_TERMINATED);
+
+ if (!isUnsubscribed()) {
+ try {
+ subscriber.onError(t);
+ } catch (Throwable inner) {
+ Exceptions.throwIfFatal(inner);
+ CompositeException composite = new CompositeException(t, inner);
+ RxJavaPlugins.getInstance().getErrorHandler().handleError(composite);
+ }
+ }
+ }
+}
diff --git a/retrofit-adapters/rxjava/src/main/java/retrofit2/adapter/rxjava/CallEnqueueOnSubscribe.java b/retrofit-adapters/rxjava/src/main/java/retrofit2/adapter/rxjava/CallEnqueueOnSubscribe.java
new file mode 100644
index 0000000000..7dcf917c39
--- /dev/null
+++ b/retrofit-adapters/rxjava/src/main/java/retrofit2/adapter/rxjava/CallEnqueueOnSubscribe.java
@@ -0,0 +1,50 @@
+/*
+ * Copyright (C) 2016 Jake Wharton
+ *
+ * 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 retrofit2.adapter.rxjava;
+
+import retrofit2.Call;
+import retrofit2.Callback;
+import retrofit2.Response;
+import rx.Observable.OnSubscribe;
+import rx.Subscriber;
+import rx.exceptions.Exceptions;
+
+final class CallEnqueueOnSubscribe<T> implements OnSubscribe<Response<T>> {
+ private final Call<T> originalCall;
+
+ CallEnqueueOnSubscribe(Call<T> originalCall) {
+ this.originalCall = originalCall;
+ }
+
+ @Override public void call(Subscriber<? super Response<T>> subscriber) {
+ // Since Call is a one-shot type, clone it for each new subscriber.
+ Call<T> call = originalCall.clone();
+ final CallArbiter<T> arbiter = new CallArbiter<>(call, subscriber);
+ subscriber.add(arbiter);
+ subscriber.setProducer(arbiter);
+
+ call.enqueue(new Callback<T>() {
+ @Override public void onResponse(Call<T> call, Response<T> response) {
+ arbiter.emitResponse(response);
+ }
+
+ @Override public void onFailure(Call<T> call, Throwable t) {
+ Exceptions.throwIfFatal(t);
+ arbiter.emitError(t);
+ }
+ });
+ }
+}
diff --git a/retrofit-adapters/rxjava/src/main/java/retrofit2/adapter/rxjava/CallExecuteOnSubscribe.java b/retrofit-adapters/rxjava/src/main/java/retrofit2/adapter/rxjava/CallExecuteOnSubscribe.java
new file mode 100644
index 0000000000..593770aa77
--- /dev/null
+++ b/retrofit-adapters/rxjava/src/main/java/retrofit2/adapter/rxjava/CallExecuteOnSubscribe.java
@@ -0,0 +1,48 @@
+/*
+ * Copyright (C) 2016 Jake Wharton
+ *
+ * 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 retrofit2.adapter.rxjava;
+
+import retrofit2.Call;
+import retrofit2.Response;
+import rx.Observable.OnSubscribe;
+import rx.Subscriber;
+import rx.exceptions.Exceptions;
+
+final class CallExecuteOnSubscribe<T> implements OnSubscribe<Response<T>> {
+ private final Call<T> originalCall;
+
+ CallExecuteOnSubscribe(Call<T> originalCall) {
+ this.originalCall = originalCall;
+ }
+
+ @Override public void call(Subscriber<? super Response<T>> subscriber) {
+ // Since Call is a one-shot type, clone it for each new subscriber.
+ Call<T> call = originalCall.clone();
+ CallArbiter<T> arbiter = new CallArbiter<>(call, subscriber);
+ subscriber.add(arbiter);
+ subscriber.setProducer(arbiter);
+
+ Response<T> response;
+ try {
+ response = call.execute();
+ } catch (Throwable t) {
+ Exceptions.throwIfFatal(t);
+ arbiter.emitError(t);
+ return;
+ }
+ arbiter.emitResponse(response);
+ }
+}
diff --git a/retrofit-adapters/rxjava/src/main/java/retrofit2/adapter/rxjava/CallOnSubscribe.java b/retrofit-adapters/rxjava/src/main/java/retrofit2/adapter/rxjava/CallOnSubscribe.java
deleted file mode 100644
index 7e0f53969c..0000000000
--- a/retrofit-adapters/rxjava/src/main/java/retrofit2/adapter/rxjava/CallOnSubscribe.java
+++ /dev/null
@@ -1,176 +0,0 @@
-/*
- * Copyright (C) 2016 Jake Wharton
- *
- * 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 retrofit2.adapter.rxjava;
-
-import java.util.concurrent.atomic.AtomicInteger;
-import retrofit2.Call;
-import retrofit2.Response;
-import rx.Observable.OnSubscribe;
-import rx.Producer;
-import rx.Subscriber;
-import rx.Subscription;
-import rx.exceptions.CompositeException;
-import rx.exceptions.Exceptions;
-import rx.plugins.RxJavaPlugins;
-
-final class CallOnSubscribe<T> implements OnSubscribe<Response<T>> {
- private final Call<T> originalCall;
-
- CallOnSubscribe(Call<T> originalCall) {
- this.originalCall = originalCall;
- }
-
- @Override public void call(Subscriber<? super Response<T>> subscriber) {
- // Since Call is a one-shot type, clone it for each new subscriber.
- Call<T> call = originalCall.clone();
- CallArbiter<T> arbiter = new CallArbiter<>(call, subscriber);
- subscriber.add(arbiter);
- subscriber.setProducer(arbiter);
-
- Response<T> response;
- try {
- response = call.execute();
- } catch (Throwable t) {
- Exceptions.throwIfFatal(t);
- arbiter.emitError(t);
- return;
- }
- arbiter.emitResponse(response);
- }
-
- static final class CallArbiter<T> extends AtomicInteger implements Subscription, Producer {
- private static final int STATE_WAITING = 0;
- private static final int STATE_REQUESTED = 1;
- private static final int STATE_HAS_RESPONSE = 2;
- private static final int STATE_TERMINATED = 3;
-
- private final Call<T> call;
- private final Subscriber<? super Response<T>> subscriber;
-
- private volatile Response<T> response;
-
- CallArbiter(Call<T> call, Subscriber<? super Response<T>> subscriber) {
- super(STATE_WAITING);
-
- this.call = call;
- this.subscriber = subscriber;
- }
-
- @Override public void unsubscribe() {
- call.cancel();
- }
-
- @Override public boolean isUnsubscribed() {
- return call.isCanceled();
- }
-
- @Override public void request(long amount) {
- if (amount == 0) {
- return;
- }
- while (true) {
- int state = get();
- switch (state) {
- case STATE_WAITING:
- if (compareAndSet(STATE_WAITING, STATE_REQUESTED)) {
- return;
- }
- break; // State transition failed. Try again.
-
- case STATE_HAS_RESPONSE:
- if (compareAndSet(STATE_HAS_RESPONSE, STATE_TERMINATED)) {
- deliverResponse(response);
- return;
- }
- break; // State transition failed. Try again.
-
- case STATE_REQUESTED:
- case STATE_TERMINATED:
- return; // Nothing to do.
-
- default:
- throw new IllegalStateException("Unknown state: " + state);
- }
- }
- }
-
- void emitResponse(Response<T> response) {
- while (true) {
- int state = get();
- switch (state) {
- case STATE_WAITING:
- this.response = response;
- if (compareAndSet(STATE_WAITING, STATE_HAS_RESPONSE)) {
- return;
- }
- break; // State transition failed. Try again.
-
- case STATE_REQUESTED:
- if (compareAndSet(STATE_REQUESTED, STATE_TERMINATED)) {
- deliverResponse(response);
- return;
- }
- break; // State transition failed. Try again.
-
- case STATE_HAS_RESPONSE:
- case STATE_TERMINATED:
- throw new AssertionError();
-
- default:
- throw new IllegalStateException("Unknown state: " + state);
- }
- }
- }
-
- private void deliverResponse(Response<T> response) {
- try {
- if (!isUnsubscribed()) {
- subscriber.onNext(response);
- }
- } catch (Throwable t) {
- Exceptions.throwIfFatal(t);
- try {
- subscriber.onError(t);
- } catch (Throwable inner) {
- Exceptions.throwIfFatal(inner);
- CompositeException composite = new CompositeException(t, inner);
- RxJavaPlugins.getInstance().getErrorHandler().handleError(composite);
- }
- return;
- }
- try {
- subscriber.onCompleted();
- } catch (Throwable t) {
- Exceptions.throwIfFatal(t);
- RxJavaPlugins.getInstance().getErrorHandler().handleError(t);
- }
- }
-
- void emitError(Throwable t) {
- set(STATE_TERMINATED);
-
- if (!isUnsubscribed()) {
- try {
- subscriber.onError(t);
- } catch (Throwable inner) {
- Exceptions.throwIfFatal(inner);
- CompositeException composite = new CompositeException(t, inner);
- RxJavaPlugins.getInstance().getErrorHandler().handleError(composite);
- }
- }
- }
- }
-}
diff --git a/retrofit-adapters/rxjava/src/main/java/retrofit2/adapter/rxjava/RxJavaCallAdapter.java b/retrofit-adapters/rxjava/src/main/java/retrofit2/adapter/rxjava/RxJavaCallAdapter.java
index 8d8f3776a2..f14c47181a 100644
--- a/retrofit-adapters/rxjava/src/main/java/retrofit2/adapter/rxjava/RxJavaCallAdapter.java
+++ b/retrofit-adapters/rxjava/src/main/java/retrofit2/adapter/rxjava/RxJavaCallAdapter.java
@@ -26,15 +26,17 @@
final class RxJavaCallAdapter<R> implements CallAdapter<R, Object> {
private final Type responseType;
private final Scheduler scheduler;
+ private final boolean isAsync;
private final boolean isResult;
private final boolean isBody;
private final boolean isSingle;
private final boolean isCompletable;
- RxJavaCallAdapter(Type responseType, Scheduler scheduler, boolean isResult, boolean isBody,
- boolean isSingle, boolean isCompletable) {
+ RxJavaCallAdapter(Type responseType, Scheduler scheduler, boolean isAsync, boolean isResult,
+ boolean isBody, boolean isSingle, boolean isCompletable) {
this.responseType = responseType;
this.scheduler = scheduler;
+ this.isAsync = isAsync;
this.isResult = isResult;
this.isBody = isBody;
this.isSingle = isSingle;
@@ -46,7 +48,9 @@ final class RxJavaCallAdapter<R> implements CallAdapter<R, Object> {
}
@Override public Object adapt(Call<R> call) {
- OnSubscribe<Response<R>> callFunc = new CallOnSubscribe<>(call);
+ OnSubscribe<Response<R>> callFunc = isAsync
+ ? new CallEnqueueOnSubscribe<>(call)
+ : new CallExecuteOnSubscribe<>(call);
OnSubscribe<?> func;
if (isResult) {
diff --git a/retrofit-adapters/rxjava/src/main/java/retrofit2/adapter/rxjava/RxJavaCallAdapterFactory.java b/retrofit-adapters/rxjava/src/main/java/retrofit2/adapter/rxjava/RxJavaCallAdapterFactory.java
index 2834516791..184750d059 100644
--- a/retrofit-adapters/rxjava/src/main/java/retrofit2/adapter/rxjava/RxJavaCallAdapterFactory.java
+++ b/retrofit-adapters/rxjava/src/main/java/retrofit2/adapter/rxjava/RxJavaCallAdapterFactory.java
@@ -61,7 +61,15 @@ public final class RxJavaCallAdapterFactory extends CallAdapter.Factory {
* by default.
*/
public static RxJavaCallAdapterFactory create() {
- return new RxJavaCallAdapterFactory(null);
+ return new RxJavaCallAdapterFactory(null, false);
+ }
+
+ /**
+ * Returns an instance which creates asynchronous observables. Applying
+ * {@link Observable#subscribeOn} has no effect on stream types created by this factory.
+ */
+ public static RxJavaCallAdapterFactory createAsync() {
+ return new RxJavaCallAdapterFactory(null, true);
}
/**
@@ -70,13 +78,15 @@ public static RxJavaCallAdapterFactory create() {
*/
public static RxJavaCallAdapterFactory createWithScheduler(Scheduler scheduler) {
if (scheduler == null) throw new NullPointerException("scheduler == null");
- return new RxJavaCallAdapterFactory(scheduler);
+ return new RxJavaCallAdapterFactory(scheduler, false);
}
private final Scheduler scheduler;
+ private final boolean isAsync;
- private RxJavaCallAdapterFactory(Scheduler scheduler) {
+ private RxJavaCallAdapterFactory(Scheduler scheduler, boolean isAsync) {
this.scheduler = scheduler;
+ this.isAsync = isAsync;
}
@Override
@@ -89,7 +99,7 @@ private RxJavaCallAdapterFactory(Scheduler scheduler) {
}
if (isCompletable) {
- return new RxJavaCallAdapter(Void.class, scheduler, false, true, false, true);
+ return new RxJavaCallAdapter(Void.class, scheduler, isAsync, false, true, false, true);
}
boolean isResult = false;
@@ -121,6 +131,7 @@ private RxJavaCallAdapterFactory(Scheduler scheduler) {
isBody = true;
}
- return new RxJavaCallAdapter(responseType, scheduler, isResult, isBody, isSingle, false);
+ return new RxJavaCallAdapter(responseType, scheduler, isAsync, isResult, isBody, isSingle,
+ false);
}
}
| diff --git a/retrofit-adapters/rxjava/src/test/java/retrofit2/adapter/rxjava/AsyncTest.java b/retrofit-adapters/rxjava/src/test/java/retrofit2/adapter/rxjava/AsyncTest.java
new file mode 100644
index 0000000000..2c27037693
--- /dev/null
+++ b/retrofit-adapters/rxjava/src/test/java/retrofit2/adapter/rxjava/AsyncTest.java
@@ -0,0 +1,143 @@
+/*
+ * Copyright (C) 2017 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 retrofit2.adapter.rxjava;
+
+import java.io.IOException;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.atomic.AtomicReference;
+import okhttp3.mockwebserver.MockResponse;
+import okhttp3.mockwebserver.MockWebServer;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.TestRule;
+import retrofit2.Retrofit;
+import retrofit2.http.GET;
+import rx.Completable;
+import rx.exceptions.CompositeException;
+import rx.exceptions.Exceptions;
+import rx.observers.AsyncCompletableSubscriber;
+import rx.observers.TestSubscriber;
+import rx.plugins.RxJavaErrorHandler;
+import rx.plugins.RxJavaPlugins;
+
+import static java.util.concurrent.TimeUnit.SECONDS;
+import static okhttp3.mockwebserver.SocketPolicy.DISCONNECT_AFTER_REQUEST;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.Assert.assertFalse;
+
+public final class AsyncTest {
+ @Rule public final MockWebServer server = new MockWebServer();
+ @Rule public final TestRule pluginsReset = new RxJavaPluginsResetRule();
+
+ interface Service {
+ @GET("/") Completable completable();
+ }
+
+ private Service service;
+ @Before public void setUp() {
+ Retrofit retrofit = new Retrofit.Builder()
+ .baseUrl(server.url("/"))
+ .addCallAdapterFactory(RxJavaCallAdapterFactory.createAsync())
+ .build();
+ service = retrofit.create(Service.class);
+ }
+
+ @Test public void success() throws InterruptedException {
+ TestSubscriber<Void> subscriber = new TestSubscriber<>();
+ service.completable().subscribe(subscriber);
+ assertFalse(subscriber.awaitValueCount(1, 1, SECONDS));
+
+ server.enqueue(new MockResponse());
+ subscriber.awaitTerminalEvent(1, SECONDS);
+ subscriber.assertCompleted();
+ }
+
+
+ @Test public void failure() throws InterruptedException {
+ TestSubscriber<Void> subscriber = new TestSubscriber<>();
+ service.completable().subscribe(subscriber);
+ assertFalse(subscriber.awaitValueCount(1, 1, SECONDS));
+
+ server.enqueue(new MockResponse().setSocketPolicy(DISCONNECT_AFTER_REQUEST));
+ subscriber.awaitTerminalEvent(1, SECONDS);
+ subscriber.assertError(IOException.class);
+ }
+
+ @Test public void throwingInOnCompleteDeliveredToPlugin() throws InterruptedException {
+ server.enqueue(new MockResponse());
+
+ final CountDownLatch latch = new CountDownLatch(1);
+ final AtomicReference<Throwable> errorRef = new AtomicReference<>();
+ RxJavaPlugins.getInstance().registerErrorHandler(new RxJavaErrorHandler() {
+ @Override public void handleError(Throwable throwable) {
+ if (!errorRef.compareAndSet(null, throwable)) {
+ throw Exceptions.propagate(throwable); // Don't swallow secondary errors!
+ }
+ latch.countDown();
+ }
+ });
+
+ final TestSubscriber<Void> subscriber = new TestSubscriber<>();
+ final RuntimeException e = new RuntimeException();
+ service.completable().unsafeSubscribe(new AsyncCompletableSubscriber() {
+ @Override public void onCompleted() {
+ throw e;
+ }
+
+ @Override public void onError(Throwable t) {
+ subscriber.onError(t);
+ }
+ });
+
+ latch.await(1, SECONDS);
+ assertThat(errorRef.get()).isSameAs(e);
+ }
+
+ @Test public void bodyThrowingInOnErrorDeliveredToPlugin() throws InterruptedException {
+ server.enqueue(new MockResponse().setResponseCode(404));
+
+ final CountDownLatch latch = new CountDownLatch(1);
+ final AtomicReference<Throwable> pluginRef = new AtomicReference<>();
+ RxJavaPlugins.getInstance().registerErrorHandler(new RxJavaErrorHandler() {
+ @Override public void handleError(Throwable throwable) {
+ if (!pluginRef.compareAndSet(null, throwable)) {
+ throw Exceptions.propagate(throwable); // Don't swallow secondary errors!
+ }
+ latch.countDown();
+ }
+ });
+
+ final TestSubscriber<Void> subscriber = new TestSubscriber<>();
+ final RuntimeException e = new RuntimeException();
+ final AtomicReference<Throwable> errorRef = new AtomicReference<>();
+ service.completable().unsafeSubscribe(new AsyncCompletableSubscriber() {
+ @Override public void onCompleted() {
+ subscriber.onCompleted();
+ }
+
+ @Override public void onError(Throwable t) {
+ errorRef.set(t);
+ throw e;
+ }
+ });
+
+ latch.await(1, SECONDS);
+ //noinspection ThrowableResultOfMethodCallIgnored
+ CompositeException composite = (CompositeException) pluginRef.get();
+ assertThat(composite.getExceptions()).containsExactly(errorRef.get(), e);
+ }
+}
| train | val | 2017-01-30T04:31:26 | "2016-12-21T19:29:32Z" | JakeWharton | val |
square/retrofit/1864_2172 | square/retrofit | square/retrofit/1864 | square/retrofit/2172 | [
"timestamp(timedelta=120.0, similarity=0.848334570472823)"
] | 4ec773178f8a992f9750ec4e7a57d2839530a075 | 77a65b7b1d852ef1fa2d19cab78ea831069b6fd0 | [
"Transformer is a good idea.\n\nOn Sat, Jun 18, 2016, 3:28 PM tsuijten [email protected] wrote:\n\n> I'd like to have all Single's returned by the RxJavaCallAdapterFactory to\n> be have this: .observeOn(AndroidSchedulers.mainThread())\n> \n> I think it would be nice if we could also pass a scheduler to the\n> RxJavaCallAdapterFactory which allows to achieve always observing on the\n> Android main thread.\n> \n> Or even better, the ability to pass a Transformer to\n> RxJavaCallAdapterFactory (which will use compose) so you can transform\n> the Observable before it's returned.\n> \n> I you feel this is a good idea I'm happy to help with a PR.\n> \n> —\n> You are receiving this because you are subscribed to this thread.\n> Reply to this email directly, view it on GitHub\n> https://github.com/square/retrofit/issues/1864, or mute the thread\n> https://github.com/notifications/unsubscribe/AAEEEeyYBo7k3LsMgRDV5lqQt_plCnMpks5qNEbmgaJpZM4I5BEE\n> .\n",
"Unfortunately Single and Completeable have different Transformer types so\nthere is no single way to apply functionality for all three.\n\nAs a workaround for now you can write a CallAdapter.Factory which delegates\nto the real implementation for creating Observable types and then it would\napply observeOn.\n\nOn Sat, Jun 18, 2016 at 10:00 PM Jake Wharton [email protected] wrote:\n\n> Transformer is a good idea.\n> \n> On Sat, Jun 18, 2016, 3:28 PM tsuijten [email protected] wrote:\n> \n> > I'd like to have all Single's returned by the RxJavaCallAdapterFactory\n> > to be have this: .observeOn(AndroidSchedulers.mainThread())\n> > \n> > I think it would be nice if we could also pass a scheduler to the\n> > RxJavaCallAdapterFactory which allows to achieve always observing on the\n> > Android main thread.\n> > \n> > Or even better, the ability to pass a Transformer to\n> > RxJavaCallAdapterFactory (which will use compose) so you can transform\n> > the Observable before it's returned.\n> > \n> > I you feel this is a good idea I'm happy to help with a PR.\n> > \n> > —\n> > You are receiving this because you are subscribed to this thread.\n> > Reply to this email directly, view it on GitHub\n> > https://github.com/square/retrofit/issues/1864, or mute the thread\n> > https://github.com/notifications/unsubscribe/AAEEEeyYBo7k3LsMgRDV5lqQt_plCnMpks5qNEbmgaJpZM4I5BEE\n> > .\n",
"I created a PR with a custom transformer which transforms Observable and Completable separately. #1865\n",
"I added a sample to show how to use CallAdapter composition to alter the created observables such as adding operators like `observeOn` in https://github.com/square/retrofit/pull/2092"
] | [
"The only new code in this PR is this `Callback` implementation. Everything else was here previously."
] | "2017-01-30T03:55:29Z" | [] | Ability to compose RxJavaCallAdapterFactory (in order to observe on Android main thread) | I'd like to have all `Single`'s returned by the `RxJavaCallAdapterFactory` to have this: `.observeOn(AndroidSchedulers.mainThread())` applied to it
I think it would be nice if we could also pass a scheduler to the `RxJavaCallAdapterFactory` which allows always observing on the Android main thread.
Or even better, the ability to pass a `Transformer` to `RxJavaCallAdapterFactory` (which will use `compose`) so you can transform the Observable before it's returned. Of course when using a `Transformer` you don't want the type of a Observable to be changed...
If you feel this is a good idea I'm happy to help with a PR.
| [
"retrofit-adapters/rxjava/src/main/java/retrofit2/adapter/rxjava/CallOnSubscribe.java",
"retrofit-adapters/rxjava/src/main/java/retrofit2/adapter/rxjava/RxJavaCallAdapter.java",
"retrofit-adapters/rxjava/src/main/java/retrofit2/adapter/rxjava/RxJavaCallAdapterFactory.java"
] | [
"retrofit-adapters/rxjava/src/main/java/retrofit2/adapter/rxjava/CallArbiter.java",
"retrofit-adapters/rxjava/src/main/java/retrofit2/adapter/rxjava/CallEnqueueOnSubscribe.java",
"retrofit-adapters/rxjava/src/main/java/retrofit2/adapter/rxjava/CallExecuteOnSubscribe.java",
"retrofit-adapters/rxjava/src/main/java/retrofit2/adapter/rxjava/RxJavaCallAdapter.java",
"retrofit-adapters/rxjava/src/main/java/retrofit2/adapter/rxjava/RxJavaCallAdapterFactory.java"
] | [
"retrofit-adapters/rxjava/src/test/java/retrofit2/adapter/rxjava/AsyncTest.java"
] | diff --git a/retrofit-adapters/rxjava/src/main/java/retrofit2/adapter/rxjava/CallArbiter.java b/retrofit-adapters/rxjava/src/main/java/retrofit2/adapter/rxjava/CallArbiter.java
new file mode 100644
index 0000000000..34b0b004a5
--- /dev/null
+++ b/retrofit-adapters/rxjava/src/main/java/retrofit2/adapter/rxjava/CallArbiter.java
@@ -0,0 +1,149 @@
+/*
+ * Copyright (C) 2016 Jake Wharton
+ *
+ * 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 retrofit2.adapter.rxjava;
+
+import java.util.concurrent.atomic.AtomicInteger;
+import retrofit2.Call;
+import retrofit2.Response;
+import rx.Producer;
+import rx.Subscriber;
+import rx.Subscription;
+import rx.exceptions.CompositeException;
+import rx.exceptions.Exceptions;
+import rx.plugins.RxJavaPlugins;
+
+final class CallArbiter<T> extends AtomicInteger implements Subscription, Producer {
+ private static final int STATE_WAITING = 0;
+ private static final int STATE_REQUESTED = 1;
+ private static final int STATE_HAS_RESPONSE = 2;
+ private static final int STATE_TERMINATED = 3;
+
+ private final Call<T> call;
+ private final Subscriber<? super Response<T>> subscriber;
+
+ private volatile Response<T> response;
+
+ CallArbiter(Call<T> call, Subscriber<? super Response<T>> subscriber) {
+ super(STATE_WAITING);
+
+ this.call = call;
+ this.subscriber = subscriber;
+ }
+
+ @Override public void unsubscribe() {
+ call.cancel();
+ }
+
+ @Override public boolean isUnsubscribed() {
+ return call.isCanceled();
+ }
+
+ @Override public void request(long amount) {
+ if (amount == 0) {
+ return;
+ }
+ while (true) {
+ int state = get();
+ switch (state) {
+ case STATE_WAITING:
+ if (compareAndSet(STATE_WAITING, STATE_REQUESTED)) {
+ return;
+ }
+ break; // State transition failed. Try again.
+
+ case STATE_HAS_RESPONSE:
+ if (compareAndSet(STATE_HAS_RESPONSE, STATE_TERMINATED)) {
+ deliverResponse(response);
+ return;
+ }
+ break; // State transition failed. Try again.
+
+ case STATE_REQUESTED:
+ case STATE_TERMINATED:
+ return; // Nothing to do.
+
+ default:
+ throw new IllegalStateException("Unknown state: " + state);
+ }
+ }
+ }
+
+ void emitResponse(Response<T> response) {
+ while (true) {
+ int state = get();
+ switch (state) {
+ case STATE_WAITING:
+ this.response = response;
+ if (compareAndSet(STATE_WAITING, STATE_HAS_RESPONSE)) {
+ return;
+ }
+ break; // State transition failed. Try again.
+
+ case STATE_REQUESTED:
+ if (compareAndSet(STATE_REQUESTED, STATE_TERMINATED)) {
+ deliverResponse(response);
+ return;
+ }
+ break; // State transition failed. Try again.
+
+ case STATE_HAS_RESPONSE:
+ case STATE_TERMINATED:
+ throw new AssertionError();
+
+ default:
+ throw new IllegalStateException("Unknown state: " + state);
+ }
+ }
+ }
+
+ private void deliverResponse(Response<T> response) {
+ try {
+ if (!isUnsubscribed()) {
+ subscriber.onNext(response);
+ }
+ } catch (Throwable t) {
+ Exceptions.throwIfFatal(t);
+ try {
+ subscriber.onError(t);
+ } catch (Throwable inner) {
+ Exceptions.throwIfFatal(inner);
+ CompositeException composite = new CompositeException(t, inner);
+ RxJavaPlugins.getInstance().getErrorHandler().handleError(composite);
+ }
+ return;
+ }
+ try {
+ subscriber.onCompleted();
+ } catch (Throwable t) {
+ Exceptions.throwIfFatal(t);
+ RxJavaPlugins.getInstance().getErrorHandler().handleError(t);
+ }
+ }
+
+ void emitError(Throwable t) {
+ set(STATE_TERMINATED);
+
+ if (!isUnsubscribed()) {
+ try {
+ subscriber.onError(t);
+ } catch (Throwable inner) {
+ Exceptions.throwIfFatal(inner);
+ CompositeException composite = new CompositeException(t, inner);
+ RxJavaPlugins.getInstance().getErrorHandler().handleError(composite);
+ }
+ }
+ }
+}
diff --git a/retrofit-adapters/rxjava/src/main/java/retrofit2/adapter/rxjava/CallEnqueueOnSubscribe.java b/retrofit-adapters/rxjava/src/main/java/retrofit2/adapter/rxjava/CallEnqueueOnSubscribe.java
new file mode 100644
index 0000000000..7dcf917c39
--- /dev/null
+++ b/retrofit-adapters/rxjava/src/main/java/retrofit2/adapter/rxjava/CallEnqueueOnSubscribe.java
@@ -0,0 +1,50 @@
+/*
+ * Copyright (C) 2016 Jake Wharton
+ *
+ * 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 retrofit2.adapter.rxjava;
+
+import retrofit2.Call;
+import retrofit2.Callback;
+import retrofit2.Response;
+import rx.Observable.OnSubscribe;
+import rx.Subscriber;
+import rx.exceptions.Exceptions;
+
+final class CallEnqueueOnSubscribe<T> implements OnSubscribe<Response<T>> {
+ private final Call<T> originalCall;
+
+ CallEnqueueOnSubscribe(Call<T> originalCall) {
+ this.originalCall = originalCall;
+ }
+
+ @Override public void call(Subscriber<? super Response<T>> subscriber) {
+ // Since Call is a one-shot type, clone it for each new subscriber.
+ Call<T> call = originalCall.clone();
+ final CallArbiter<T> arbiter = new CallArbiter<>(call, subscriber);
+ subscriber.add(arbiter);
+ subscriber.setProducer(arbiter);
+
+ call.enqueue(new Callback<T>() {
+ @Override public void onResponse(Call<T> call, Response<T> response) {
+ arbiter.emitResponse(response);
+ }
+
+ @Override public void onFailure(Call<T> call, Throwable t) {
+ Exceptions.throwIfFatal(t);
+ arbiter.emitError(t);
+ }
+ });
+ }
+}
diff --git a/retrofit-adapters/rxjava/src/main/java/retrofit2/adapter/rxjava/CallExecuteOnSubscribe.java b/retrofit-adapters/rxjava/src/main/java/retrofit2/adapter/rxjava/CallExecuteOnSubscribe.java
new file mode 100644
index 0000000000..593770aa77
--- /dev/null
+++ b/retrofit-adapters/rxjava/src/main/java/retrofit2/adapter/rxjava/CallExecuteOnSubscribe.java
@@ -0,0 +1,48 @@
+/*
+ * Copyright (C) 2016 Jake Wharton
+ *
+ * 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 retrofit2.adapter.rxjava;
+
+import retrofit2.Call;
+import retrofit2.Response;
+import rx.Observable.OnSubscribe;
+import rx.Subscriber;
+import rx.exceptions.Exceptions;
+
+final class CallExecuteOnSubscribe<T> implements OnSubscribe<Response<T>> {
+ private final Call<T> originalCall;
+
+ CallExecuteOnSubscribe(Call<T> originalCall) {
+ this.originalCall = originalCall;
+ }
+
+ @Override public void call(Subscriber<? super Response<T>> subscriber) {
+ // Since Call is a one-shot type, clone it for each new subscriber.
+ Call<T> call = originalCall.clone();
+ CallArbiter<T> arbiter = new CallArbiter<>(call, subscriber);
+ subscriber.add(arbiter);
+ subscriber.setProducer(arbiter);
+
+ Response<T> response;
+ try {
+ response = call.execute();
+ } catch (Throwable t) {
+ Exceptions.throwIfFatal(t);
+ arbiter.emitError(t);
+ return;
+ }
+ arbiter.emitResponse(response);
+ }
+}
diff --git a/retrofit-adapters/rxjava/src/main/java/retrofit2/adapter/rxjava/CallOnSubscribe.java b/retrofit-adapters/rxjava/src/main/java/retrofit2/adapter/rxjava/CallOnSubscribe.java
deleted file mode 100644
index 7e0f53969c..0000000000
--- a/retrofit-adapters/rxjava/src/main/java/retrofit2/adapter/rxjava/CallOnSubscribe.java
+++ /dev/null
@@ -1,176 +0,0 @@
-/*
- * Copyright (C) 2016 Jake Wharton
- *
- * 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 retrofit2.adapter.rxjava;
-
-import java.util.concurrent.atomic.AtomicInteger;
-import retrofit2.Call;
-import retrofit2.Response;
-import rx.Observable.OnSubscribe;
-import rx.Producer;
-import rx.Subscriber;
-import rx.Subscription;
-import rx.exceptions.CompositeException;
-import rx.exceptions.Exceptions;
-import rx.plugins.RxJavaPlugins;
-
-final class CallOnSubscribe<T> implements OnSubscribe<Response<T>> {
- private final Call<T> originalCall;
-
- CallOnSubscribe(Call<T> originalCall) {
- this.originalCall = originalCall;
- }
-
- @Override public void call(Subscriber<? super Response<T>> subscriber) {
- // Since Call is a one-shot type, clone it for each new subscriber.
- Call<T> call = originalCall.clone();
- CallArbiter<T> arbiter = new CallArbiter<>(call, subscriber);
- subscriber.add(arbiter);
- subscriber.setProducer(arbiter);
-
- Response<T> response;
- try {
- response = call.execute();
- } catch (Throwable t) {
- Exceptions.throwIfFatal(t);
- arbiter.emitError(t);
- return;
- }
- arbiter.emitResponse(response);
- }
-
- static final class CallArbiter<T> extends AtomicInteger implements Subscription, Producer {
- private static final int STATE_WAITING = 0;
- private static final int STATE_REQUESTED = 1;
- private static final int STATE_HAS_RESPONSE = 2;
- private static final int STATE_TERMINATED = 3;
-
- private final Call<T> call;
- private final Subscriber<? super Response<T>> subscriber;
-
- private volatile Response<T> response;
-
- CallArbiter(Call<T> call, Subscriber<? super Response<T>> subscriber) {
- super(STATE_WAITING);
-
- this.call = call;
- this.subscriber = subscriber;
- }
-
- @Override public void unsubscribe() {
- call.cancel();
- }
-
- @Override public boolean isUnsubscribed() {
- return call.isCanceled();
- }
-
- @Override public void request(long amount) {
- if (amount == 0) {
- return;
- }
- while (true) {
- int state = get();
- switch (state) {
- case STATE_WAITING:
- if (compareAndSet(STATE_WAITING, STATE_REQUESTED)) {
- return;
- }
- break; // State transition failed. Try again.
-
- case STATE_HAS_RESPONSE:
- if (compareAndSet(STATE_HAS_RESPONSE, STATE_TERMINATED)) {
- deliverResponse(response);
- return;
- }
- break; // State transition failed. Try again.
-
- case STATE_REQUESTED:
- case STATE_TERMINATED:
- return; // Nothing to do.
-
- default:
- throw new IllegalStateException("Unknown state: " + state);
- }
- }
- }
-
- void emitResponse(Response<T> response) {
- while (true) {
- int state = get();
- switch (state) {
- case STATE_WAITING:
- this.response = response;
- if (compareAndSet(STATE_WAITING, STATE_HAS_RESPONSE)) {
- return;
- }
- break; // State transition failed. Try again.
-
- case STATE_REQUESTED:
- if (compareAndSet(STATE_REQUESTED, STATE_TERMINATED)) {
- deliverResponse(response);
- return;
- }
- break; // State transition failed. Try again.
-
- case STATE_HAS_RESPONSE:
- case STATE_TERMINATED:
- throw new AssertionError();
-
- default:
- throw new IllegalStateException("Unknown state: " + state);
- }
- }
- }
-
- private void deliverResponse(Response<T> response) {
- try {
- if (!isUnsubscribed()) {
- subscriber.onNext(response);
- }
- } catch (Throwable t) {
- Exceptions.throwIfFatal(t);
- try {
- subscriber.onError(t);
- } catch (Throwable inner) {
- Exceptions.throwIfFatal(inner);
- CompositeException composite = new CompositeException(t, inner);
- RxJavaPlugins.getInstance().getErrorHandler().handleError(composite);
- }
- return;
- }
- try {
- subscriber.onCompleted();
- } catch (Throwable t) {
- Exceptions.throwIfFatal(t);
- RxJavaPlugins.getInstance().getErrorHandler().handleError(t);
- }
- }
-
- void emitError(Throwable t) {
- set(STATE_TERMINATED);
-
- if (!isUnsubscribed()) {
- try {
- subscriber.onError(t);
- } catch (Throwable inner) {
- Exceptions.throwIfFatal(inner);
- CompositeException composite = new CompositeException(t, inner);
- RxJavaPlugins.getInstance().getErrorHandler().handleError(composite);
- }
- }
- }
- }
-}
diff --git a/retrofit-adapters/rxjava/src/main/java/retrofit2/adapter/rxjava/RxJavaCallAdapter.java b/retrofit-adapters/rxjava/src/main/java/retrofit2/adapter/rxjava/RxJavaCallAdapter.java
index 8d8f3776a2..f14c47181a 100644
--- a/retrofit-adapters/rxjava/src/main/java/retrofit2/adapter/rxjava/RxJavaCallAdapter.java
+++ b/retrofit-adapters/rxjava/src/main/java/retrofit2/adapter/rxjava/RxJavaCallAdapter.java
@@ -26,15 +26,17 @@
final class RxJavaCallAdapter<R> implements CallAdapter<R, Object> {
private final Type responseType;
private final Scheduler scheduler;
+ private final boolean isAsync;
private final boolean isResult;
private final boolean isBody;
private final boolean isSingle;
private final boolean isCompletable;
- RxJavaCallAdapter(Type responseType, Scheduler scheduler, boolean isResult, boolean isBody,
- boolean isSingle, boolean isCompletable) {
+ RxJavaCallAdapter(Type responseType, Scheduler scheduler, boolean isAsync, boolean isResult,
+ boolean isBody, boolean isSingle, boolean isCompletable) {
this.responseType = responseType;
this.scheduler = scheduler;
+ this.isAsync = isAsync;
this.isResult = isResult;
this.isBody = isBody;
this.isSingle = isSingle;
@@ -46,7 +48,9 @@ final class RxJavaCallAdapter<R> implements CallAdapter<R, Object> {
}
@Override public Object adapt(Call<R> call) {
- OnSubscribe<Response<R>> callFunc = new CallOnSubscribe<>(call);
+ OnSubscribe<Response<R>> callFunc = isAsync
+ ? new CallEnqueueOnSubscribe<>(call)
+ : new CallExecuteOnSubscribe<>(call);
OnSubscribe<?> func;
if (isResult) {
diff --git a/retrofit-adapters/rxjava/src/main/java/retrofit2/adapter/rxjava/RxJavaCallAdapterFactory.java b/retrofit-adapters/rxjava/src/main/java/retrofit2/adapter/rxjava/RxJavaCallAdapterFactory.java
index 2834516791..184750d059 100644
--- a/retrofit-adapters/rxjava/src/main/java/retrofit2/adapter/rxjava/RxJavaCallAdapterFactory.java
+++ b/retrofit-adapters/rxjava/src/main/java/retrofit2/adapter/rxjava/RxJavaCallAdapterFactory.java
@@ -61,7 +61,15 @@ public final class RxJavaCallAdapterFactory extends CallAdapter.Factory {
* by default.
*/
public static RxJavaCallAdapterFactory create() {
- return new RxJavaCallAdapterFactory(null);
+ return new RxJavaCallAdapterFactory(null, false);
+ }
+
+ /**
+ * Returns an instance which creates asynchronous observables. Applying
+ * {@link Observable#subscribeOn} has no effect on stream types created by this factory.
+ */
+ public static RxJavaCallAdapterFactory createAsync() {
+ return new RxJavaCallAdapterFactory(null, true);
}
/**
@@ -70,13 +78,15 @@ public static RxJavaCallAdapterFactory create() {
*/
public static RxJavaCallAdapterFactory createWithScheduler(Scheduler scheduler) {
if (scheduler == null) throw new NullPointerException("scheduler == null");
- return new RxJavaCallAdapterFactory(scheduler);
+ return new RxJavaCallAdapterFactory(scheduler, false);
}
private final Scheduler scheduler;
+ private final boolean isAsync;
- private RxJavaCallAdapterFactory(Scheduler scheduler) {
+ private RxJavaCallAdapterFactory(Scheduler scheduler, boolean isAsync) {
this.scheduler = scheduler;
+ this.isAsync = isAsync;
}
@Override
@@ -89,7 +99,7 @@ private RxJavaCallAdapterFactory(Scheduler scheduler) {
}
if (isCompletable) {
- return new RxJavaCallAdapter(Void.class, scheduler, false, true, false, true);
+ return new RxJavaCallAdapter(Void.class, scheduler, isAsync, false, true, false, true);
}
boolean isResult = false;
@@ -121,6 +131,7 @@ private RxJavaCallAdapterFactory(Scheduler scheduler) {
isBody = true;
}
- return new RxJavaCallAdapter(responseType, scheduler, isResult, isBody, isSingle, false);
+ return new RxJavaCallAdapter(responseType, scheduler, isAsync, isResult, isBody, isSingle,
+ false);
}
}
| diff --git a/retrofit-adapters/rxjava/src/test/java/retrofit2/adapter/rxjava/AsyncTest.java b/retrofit-adapters/rxjava/src/test/java/retrofit2/adapter/rxjava/AsyncTest.java
new file mode 100644
index 0000000000..2c27037693
--- /dev/null
+++ b/retrofit-adapters/rxjava/src/test/java/retrofit2/adapter/rxjava/AsyncTest.java
@@ -0,0 +1,143 @@
+/*
+ * Copyright (C) 2017 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 retrofit2.adapter.rxjava;
+
+import java.io.IOException;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.atomic.AtomicReference;
+import okhttp3.mockwebserver.MockResponse;
+import okhttp3.mockwebserver.MockWebServer;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.TestRule;
+import retrofit2.Retrofit;
+import retrofit2.http.GET;
+import rx.Completable;
+import rx.exceptions.CompositeException;
+import rx.exceptions.Exceptions;
+import rx.observers.AsyncCompletableSubscriber;
+import rx.observers.TestSubscriber;
+import rx.plugins.RxJavaErrorHandler;
+import rx.plugins.RxJavaPlugins;
+
+import static java.util.concurrent.TimeUnit.SECONDS;
+import static okhttp3.mockwebserver.SocketPolicy.DISCONNECT_AFTER_REQUEST;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.Assert.assertFalse;
+
+public final class AsyncTest {
+ @Rule public final MockWebServer server = new MockWebServer();
+ @Rule public final TestRule pluginsReset = new RxJavaPluginsResetRule();
+
+ interface Service {
+ @GET("/") Completable completable();
+ }
+
+ private Service service;
+ @Before public void setUp() {
+ Retrofit retrofit = new Retrofit.Builder()
+ .baseUrl(server.url("/"))
+ .addCallAdapterFactory(RxJavaCallAdapterFactory.createAsync())
+ .build();
+ service = retrofit.create(Service.class);
+ }
+
+ @Test public void success() throws InterruptedException {
+ TestSubscriber<Void> subscriber = new TestSubscriber<>();
+ service.completable().subscribe(subscriber);
+ assertFalse(subscriber.awaitValueCount(1, 1, SECONDS));
+
+ server.enqueue(new MockResponse());
+ subscriber.awaitTerminalEvent(1, SECONDS);
+ subscriber.assertCompleted();
+ }
+
+
+ @Test public void failure() throws InterruptedException {
+ TestSubscriber<Void> subscriber = new TestSubscriber<>();
+ service.completable().subscribe(subscriber);
+ assertFalse(subscriber.awaitValueCount(1, 1, SECONDS));
+
+ server.enqueue(new MockResponse().setSocketPolicy(DISCONNECT_AFTER_REQUEST));
+ subscriber.awaitTerminalEvent(1, SECONDS);
+ subscriber.assertError(IOException.class);
+ }
+
+ @Test public void throwingInOnCompleteDeliveredToPlugin() throws InterruptedException {
+ server.enqueue(new MockResponse());
+
+ final CountDownLatch latch = new CountDownLatch(1);
+ final AtomicReference<Throwable> errorRef = new AtomicReference<>();
+ RxJavaPlugins.getInstance().registerErrorHandler(new RxJavaErrorHandler() {
+ @Override public void handleError(Throwable throwable) {
+ if (!errorRef.compareAndSet(null, throwable)) {
+ throw Exceptions.propagate(throwable); // Don't swallow secondary errors!
+ }
+ latch.countDown();
+ }
+ });
+
+ final TestSubscriber<Void> subscriber = new TestSubscriber<>();
+ final RuntimeException e = new RuntimeException();
+ service.completable().unsafeSubscribe(new AsyncCompletableSubscriber() {
+ @Override public void onCompleted() {
+ throw e;
+ }
+
+ @Override public void onError(Throwable t) {
+ subscriber.onError(t);
+ }
+ });
+
+ latch.await(1, SECONDS);
+ assertThat(errorRef.get()).isSameAs(e);
+ }
+
+ @Test public void bodyThrowingInOnErrorDeliveredToPlugin() throws InterruptedException {
+ server.enqueue(new MockResponse().setResponseCode(404));
+
+ final CountDownLatch latch = new CountDownLatch(1);
+ final AtomicReference<Throwable> pluginRef = new AtomicReference<>();
+ RxJavaPlugins.getInstance().registerErrorHandler(new RxJavaErrorHandler() {
+ @Override public void handleError(Throwable throwable) {
+ if (!pluginRef.compareAndSet(null, throwable)) {
+ throw Exceptions.propagate(throwable); // Don't swallow secondary errors!
+ }
+ latch.countDown();
+ }
+ });
+
+ final TestSubscriber<Void> subscriber = new TestSubscriber<>();
+ final RuntimeException e = new RuntimeException();
+ final AtomicReference<Throwable> errorRef = new AtomicReference<>();
+ service.completable().unsafeSubscribe(new AsyncCompletableSubscriber() {
+ @Override public void onCompleted() {
+ subscriber.onCompleted();
+ }
+
+ @Override public void onError(Throwable t) {
+ errorRef.set(t);
+ throw e;
+ }
+ });
+
+ latch.await(1, SECONDS);
+ //noinspection ThrowableResultOfMethodCallIgnored
+ CompositeException composite = (CompositeException) pluginRef.get();
+ assertThat(composite.getExceptions()).containsExactly(errorRef.get(), e);
+ }
+}
| train | val | 2017-01-30T04:31:26 | "2016-06-18T19:28:36Z" | tsuijten | val |
square/retrofit/2171_2188 | square/retrofit | square/retrofit/2171 | square/retrofit/2188 | [
"timestamp(timedelta=0.0, similarity=0.9716822098759192)"
] | 8dfc7b8ff00ab64126ac86f205bf74b686e8c6ed | 9f2ea471e572f6596c482d23edcfeee0d861b959 | [] | [
"Useless, but other methods do the same, and it's best for symmetry here, I believe."
] | "2017-02-05T00:27:43Z" | [
"Blocked"
] | Use Moshi's JsonAdapter.serializeNulls() method. | Once it's released.
https://github.com/square/moshi/pull/238 | [
"pom.xml",
"retrofit-converters/moshi/src/main/java/retrofit2/converter/moshi/MoshiConverterFactory.java",
"retrofit-converters/moshi/src/main/java/retrofit2/converter/moshi/MoshiRequestBodyConverter.java"
] | [
"pom.xml",
"retrofit-converters/moshi/src/main/java/retrofit2/converter/moshi/MoshiConverterFactory.java",
"retrofit-converters/moshi/src/main/java/retrofit2/converter/moshi/MoshiRequestBodyConverter.java"
] | [] | diff --git a/pom.xml b/pom.xml
index a2309e1769..4dd4aa6ab7 100644
--- a/pom.xml
+++ b/pom.xml
@@ -63,7 +63,7 @@
<jackson.version>2.7.2</jackson.version>
<wire.version>2.2.0</wire.version>
<simplexml.version>2.7.1</simplexml.version>
- <moshi.version>1.3.0</moshi.version>
+ <moshi.version>1.4.0</moshi.version>
<!-- Sample Dependencies -->
<jsoup.version>1.7.3</jsoup.version>
diff --git a/retrofit-converters/moshi/src/main/java/retrofit2/converter/moshi/MoshiConverterFactory.java b/retrofit-converters/moshi/src/main/java/retrofit2/converter/moshi/MoshiConverterFactory.java
index 0b95d19518..311d76d0dc 100644
--- a/retrofit-converters/moshi/src/main/java/retrofit2/converter/moshi/MoshiConverterFactory.java
+++ b/retrofit-converters/moshi/src/main/java/retrofit2/converter/moshi/MoshiConverterFactory.java
@@ -94,6 +94,9 @@ public MoshiConverterFactory withNullSerialization() {
if (failOnUnknown) {
adapter = adapter.failOnUnknown();
}
+ if (serializeNulls) {
+ adapter = adapter.serializeNulls();
+ }
return new MoshiResponseBodyConverter<>(adapter);
}
@@ -106,7 +109,10 @@ public MoshiConverterFactory withNullSerialization() {
if (failOnUnknown) {
adapter = adapter.failOnUnknown();
}
- return new MoshiRequestBodyConverter<>(adapter, serializeNulls);
+ if (serializeNulls) {
+ adapter = adapter.serializeNulls();
+ }
+ return new MoshiRequestBodyConverter<>(adapter);
}
private static Set<? extends Annotation> jsonAnnotations(Annotation[] annotations) {
diff --git a/retrofit-converters/moshi/src/main/java/retrofit2/converter/moshi/MoshiRequestBodyConverter.java b/retrofit-converters/moshi/src/main/java/retrofit2/converter/moshi/MoshiRequestBodyConverter.java
index 5e59b17fed..edbcf243e5 100644
--- a/retrofit-converters/moshi/src/main/java/retrofit2/converter/moshi/MoshiRequestBodyConverter.java
+++ b/retrofit-converters/moshi/src/main/java/retrofit2/converter/moshi/MoshiRequestBodyConverter.java
@@ -27,17 +27,14 @@ final class MoshiRequestBodyConverter<T> implements Converter<T, RequestBody> {
private static final MediaType MEDIA_TYPE = MediaType.parse("application/json; charset=UTF-8");
private final JsonAdapter<T> adapter;
- private final boolean serializeNulls;
- MoshiRequestBodyConverter(JsonAdapter<T> adapter, boolean serializeNulls) {
+ MoshiRequestBodyConverter(JsonAdapter<T> adapter) {
this.adapter = adapter;
- this.serializeNulls = serializeNulls;
}
@Override public RequestBody convert(T value) throws IOException {
Buffer buffer = new Buffer();
JsonWriter writer = JsonWriter.of(buffer);
- writer.setSerializeNulls(serializeNulls);
adapter.toJson(writer, value);
return RequestBody.create(MEDIA_TYPE, buffer.readByteString());
}
| null | val | test | 2017-01-31T21:00:59 | "2017-01-30T03:26:22Z" | JakeWharton | val |
square/retrofit/2194_2196 | square/retrofit | square/retrofit/2194 | square/retrofit/2196 | [
"timestamp(timedelta=0.0, similarity=0.8520825379521623)"
] | 78e0cd85451bef91d4803964e26bc406649e1e7e | 3a9d4b77c60e3dfe3a98e0a74a59371014cad7ab | [] | [
"I suppose this could have been final, and the deprecated types could have delegated to this.\r\nprobably not worth those extra lines, though.",
"2017 ?",
"Probably can’t compose because `catch` clauses are expecting a specific type.",
"Not actually a new type. Copied from one of the adapters."
] | "2017-02-13T22:18:27Z" | [
"Enhancement"
] | Promote HttpException to core artifact. | Change adapter implementations to be deprecated but extend it. | [
"retrofit-adapters/guava/src/main/java/retrofit2/adapter/guava/GuavaCallAdapterFactory.java",
"retrofit-adapters/guava/src/main/java/retrofit2/adapter/guava/HttpException.java",
"retrofit-adapters/java8/src/main/java/retrofit2/adapter/java8/HttpException.java",
"retrofit-adapters/java8/src/main/java/retrofit2/adapter/java8/Java8CallAdapterFactory.java",
"retrofit-adapters/rxjava/src/main/java/retrofit2/adapter/rxjava/HttpException.java",
"retrofit-adapters/rxjava/src/main/java/retrofit2/adapter/rxjava/RxJavaCallAdapterFactory.java",
"retrofit-adapters/rxjava2/src/main/java/retrofit2/adapter/rxjava2/HttpException.java",
"retrofit-adapters/rxjava2/src/main/java/retrofit2/adapter/rxjava2/RxJava2CallAdapterFactory.java"
] | [
"retrofit-adapters/guava/src/main/java/retrofit2/adapter/guava/GuavaCallAdapterFactory.java",
"retrofit-adapters/guava/src/main/java/retrofit2/adapter/guava/HttpException.java",
"retrofit-adapters/java8/src/main/java/retrofit2/adapter/java8/HttpException.java",
"retrofit-adapters/java8/src/main/java/retrofit2/adapter/java8/Java8CallAdapterFactory.java",
"retrofit-adapters/rxjava/src/main/java/retrofit2/adapter/rxjava/HttpException.java",
"retrofit-adapters/rxjava/src/main/java/retrofit2/adapter/rxjava/RxJavaCallAdapterFactory.java",
"retrofit-adapters/rxjava2/src/main/java/retrofit2/adapter/rxjava2/HttpException.java",
"retrofit-adapters/rxjava2/src/main/java/retrofit2/adapter/rxjava2/RxJava2CallAdapterFactory.java",
"retrofit/src/main/java/retrofit2/HttpException.java"
] | [
"retrofit-adapters/guava/src/test/java/retrofit2/adapter/guava/ListenableFutureTest.java",
"retrofit-adapters/java8/src/test/java/retrofit2/adapter/java8/CompletableFutureTest.java",
"retrofit-adapters/rxjava/src/test/java/retrofit2/adapter/rxjava/CompletableTest.java",
"retrofit-adapters/rxjava/src/test/java/retrofit2/adapter/rxjava/ObservableTest.java",
"retrofit-adapters/rxjava/src/test/java/retrofit2/adapter/rxjava/SingleTest.java",
"retrofit-adapters/rxjava2/src/test/java/retrofit2/adapter/rxjava2/CompletableTest.java",
"retrofit-adapters/rxjava2/src/test/java/retrofit2/adapter/rxjava2/FlowableTest.java",
"retrofit-adapters/rxjava2/src/test/java/retrofit2/adapter/rxjava2/MaybeTest.java",
"retrofit-adapters/rxjava2/src/test/java/retrofit2/adapter/rxjava2/ObservableTest.java",
"retrofit-adapters/rxjava2/src/test/java/retrofit2/adapter/rxjava2/SingleTest.java",
"retrofit/src/test/java/retrofit2/HttpExceptionTest.java"
] | diff --git a/retrofit-adapters/guava/src/main/java/retrofit2/adapter/guava/GuavaCallAdapterFactory.java b/retrofit-adapters/guava/src/main/java/retrofit2/adapter/guava/GuavaCallAdapterFactory.java
index b3624fc3aa..64dd0f5ad5 100644
--- a/retrofit-adapters/guava/src/main/java/retrofit2/adapter/guava/GuavaCallAdapterFactory.java
+++ b/retrofit-adapters/guava/src/main/java/retrofit2/adapter/guava/GuavaCallAdapterFactory.java
@@ -41,8 +41,8 @@
* There are two configurations supported for the {@code ListenableFuture} type parameter:
* <ul>
* <li>Direct body (e.g., {@code ListenableFuture<User>}) returns the deserialized body for 2XX
- * responses, sets {@link HttpException} errors for non-2XX responses, and sets {@link IOException}
- * for network errors.</li>
+ * responses, sets {@link retrofit2.HttpException HttpException} errors for non-2XX responses, and
+ * sets {@link IOException} for network errors.</li>
* <li>Response wrapped body (e.g., {@code ListenableFuture<Response<User>>}) returns a
* {@link Response} object for all HTTP responses and sets {@link IOException} for network
* errors</li>
diff --git a/retrofit-adapters/guava/src/main/java/retrofit2/adapter/guava/HttpException.java b/retrofit-adapters/guava/src/main/java/retrofit2/adapter/guava/HttpException.java
index f18a819554..4eb780eaa1 100644
--- a/retrofit-adapters/guava/src/main/java/retrofit2/adapter/guava/HttpException.java
+++ b/retrofit-adapters/guava/src/main/java/retrofit2/adapter/guava/HttpException.java
@@ -17,33 +17,10 @@
import retrofit2.Response;
-/** Exception for an unexpected, non-2xx HTTP response. */
-public final class HttpException extends Exception {
- private final int code;
- private final String message;
- private final transient Response<?> response;
-
+/** @deprecated Use {@link retrofit2.HttpException}. */
+@Deprecated
+public final class HttpException extends retrofit2.HttpException {
public HttpException(Response<?> response) {
- super("HTTP " + response.code() + " " + response.message());
- this.code = response.code();
- this.message = response.message();
- this.response = response;
- }
-
- /** HTTP status code. */
- public int code() {
- return code;
- }
-
- /** HTTP status message. */
- public String message() {
- return message;
- }
-
- /**
- * The full HTTP response. This may be null if the exception was serialized.
- */
- public Response<?> response() {
- return response;
+ super(response);
}
}
diff --git a/retrofit-adapters/java8/src/main/java/retrofit2/adapter/java8/HttpException.java b/retrofit-adapters/java8/src/main/java/retrofit2/adapter/java8/HttpException.java
index 022fa9848e..c2d29cbbbe 100644
--- a/retrofit-adapters/java8/src/main/java/retrofit2/adapter/java8/HttpException.java
+++ b/retrofit-adapters/java8/src/main/java/retrofit2/adapter/java8/HttpException.java
@@ -17,33 +17,10 @@
import retrofit2.Response;
-/** Exception for an unexpected, non-2xx HTTP response. */
-public final class HttpException extends Exception {
- private final int code;
- private final String message;
- private final transient Response<?> response;
-
+/** @deprecated Use {@link retrofit2.HttpException}. */
+@Deprecated
+public final class HttpException extends retrofit2.HttpException {
public HttpException(Response<?> response) {
- super("HTTP " + response.code() + " " + response.message());
- this.code = response.code();
- this.message = response.message();
- this.response = response;
- }
-
- /** HTTP status code. */
- public int code() {
- return code;
- }
-
- /** HTTP status message. */
- public String message() {
- return message;
- }
-
- /**
- * The full HTTP response. This may be null if the exception was serialized.
- */
- public Response<?> response() {
- return response;
+ super(response);
}
}
diff --git a/retrofit-adapters/java8/src/main/java/retrofit2/adapter/java8/Java8CallAdapterFactory.java b/retrofit-adapters/java8/src/main/java/retrofit2/adapter/java8/Java8CallAdapterFactory.java
index fd905475d3..35b79f1a3c 100644
--- a/retrofit-adapters/java8/src/main/java/retrofit2/adapter/java8/Java8CallAdapterFactory.java
+++ b/retrofit-adapters/java8/src/main/java/retrofit2/adapter/java8/Java8CallAdapterFactory.java
@@ -40,8 +40,8 @@
* There are two configurations supported for the {@code CompletableFuture} type parameter:
* <ul>
* <li>Direct body (e.g., {@code CompletableFuture<User>}) returns the deserialized body for 2XX
- * responses, sets {@link HttpException} errors for non-2XX responses, and sets {@link IOException}
- * for network errors.</li>
+ * responses, sets {@link retrofit2.HttpException HttpException} errors for non-2XX responses, and
+ * sets {@link IOException} for network errors.</li>
* <li>Response wrapped body (e.g., {@code CompletableFuture<Response<User>>}) returns a
* {@link Response} object for all HTTP responses and sets {@link IOException} for network
* errors</li>
diff --git a/retrofit-adapters/rxjava/src/main/java/retrofit2/adapter/rxjava/HttpException.java b/retrofit-adapters/rxjava/src/main/java/retrofit2/adapter/rxjava/HttpException.java
index 2e501e1216..c81ad938e6 100644
--- a/retrofit-adapters/rxjava/src/main/java/retrofit2/adapter/rxjava/HttpException.java
+++ b/retrofit-adapters/rxjava/src/main/java/retrofit2/adapter/rxjava/HttpException.java
@@ -2,38 +2,10 @@
import retrofit2.Response;
-/** Exception for an unexpected, non-2xx HTTP response. */
-public final class HttpException extends Exception {
- private static String getMessage(Response<?> response) {
- if (response == null) throw new NullPointerException("response == null");
- return "HTTP " + response.code() + " " + response.message();
- }
-
- private final int code;
- private final String message;
- private final transient Response<?> response;
-
+/** @deprecated Use {@link retrofit2.HttpException}. */
+@Deprecated
+public final class HttpException extends retrofit2.HttpException {
public HttpException(Response<?> response) {
- super(getMessage(response));
- this.code = response.code();
- this.message = response.message();
- this.response = response;
- }
-
- /** HTTP status code. */
- public int code() {
- return code;
- }
-
- /** HTTP status message. */
- public String message() {
- return message;
- }
-
- /**
- * The full HTTP response. This may be null if the exception was serialized.
- */
- public Response<?> response() {
- return response;
+ super(response);
}
}
diff --git a/retrofit-adapters/rxjava/src/main/java/retrofit2/adapter/rxjava/RxJavaCallAdapterFactory.java b/retrofit-adapters/rxjava/src/main/java/retrofit2/adapter/rxjava/RxJavaCallAdapterFactory.java
index 184750d059..ee297ad303 100644
--- a/retrofit-adapters/rxjava/src/main/java/retrofit2/adapter/rxjava/RxJavaCallAdapterFactory.java
+++ b/retrofit-adapters/rxjava/src/main/java/retrofit2/adapter/rxjava/RxJavaCallAdapterFactory.java
@@ -20,6 +20,7 @@
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import retrofit2.CallAdapter;
+import retrofit2.HttpException;
import retrofit2.Response;
import retrofit2.Retrofit;
import rx.Completable;
diff --git a/retrofit-adapters/rxjava2/src/main/java/retrofit2/adapter/rxjava2/HttpException.java b/retrofit-adapters/rxjava2/src/main/java/retrofit2/adapter/rxjava2/HttpException.java
index d612b9d5af..6e282e583d 100644
--- a/retrofit-adapters/rxjava2/src/main/java/retrofit2/adapter/rxjava2/HttpException.java
+++ b/retrofit-adapters/rxjava2/src/main/java/retrofit2/adapter/rxjava2/HttpException.java
@@ -17,38 +17,10 @@
import retrofit2.Response;
-/** Exception for an unexpected, non-2xx HTTP response. */
-public final class HttpException extends Exception {
- private static String getMessage(Response<?> response) {
- if (response == null) throw new NullPointerException("response == null");
- return "HTTP " + response.code() + " " + response.message();
- }
-
- private final int code;
- private final String message;
- private final transient Response<?> response;
-
+/** @deprecated Use {@link retrofit2.HttpException}. */
+@Deprecated
+public final class HttpException extends retrofit2.HttpException {
public HttpException(Response<?> response) {
- super(getMessage(response));
- this.code = response.code();
- this.message = response.message();
- this.response = response;
- }
-
- /** HTTP status code. */
- public int code() {
- return code;
- }
-
- /** HTTP status message. */
- public String message() {
- return message;
- }
-
- /**
- * The full HTTP response. This may be null if the exception was serialized.
- */
- public Response<?> response() {
- return response;
+ super(response);
}
}
diff --git a/retrofit-adapters/rxjava2/src/main/java/retrofit2/adapter/rxjava2/RxJava2CallAdapterFactory.java b/retrofit-adapters/rxjava2/src/main/java/retrofit2/adapter/rxjava2/RxJava2CallAdapterFactory.java
index dfe4b317b7..e4b685999d 100644
--- a/retrofit-adapters/rxjava2/src/main/java/retrofit2/adapter/rxjava2/RxJava2CallAdapterFactory.java
+++ b/retrofit-adapters/rxjava2/src/main/java/retrofit2/adapter/rxjava2/RxJava2CallAdapterFactory.java
@@ -26,6 +26,7 @@
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import retrofit2.CallAdapter;
+import retrofit2.HttpException;
import retrofit2.Response;
import retrofit2.Retrofit;
diff --git a/retrofit/src/main/java/retrofit2/HttpException.java b/retrofit/src/main/java/retrofit2/HttpException.java
new file mode 100644
index 0000000000..0018948edb
--- /dev/null
+++ b/retrofit/src/main/java/retrofit2/HttpException.java
@@ -0,0 +1,52 @@
+/*
+ * Copyright (C) 2016 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 retrofit2;
+
+/** Exception for an unexpected, non-2xx HTTP response. */
+public class HttpException extends Exception {
+ private static String getMessage(Response<?> response) {
+ if (response == null) throw new NullPointerException("response == null");
+ return "HTTP " + response.code() + " " + response.message();
+ }
+
+ private final int code;
+ private final String message;
+ private final transient Response<?> response;
+
+ public HttpException(Response<?> response) {
+ super(getMessage(response));
+ this.code = response.code();
+ this.message = response.message();
+ this.response = response;
+ }
+
+ /** HTTP status code. */
+ public int code() {
+ return code;
+ }
+
+ /** HTTP status message. */
+ public String message() {
+ return message;
+ }
+
+ /**
+ * The full HTTP response. This may be null if the exception was serialized.
+ */
+ public Response<?> response() {
+ return response;
+ }
+}
| diff --git a/retrofit-adapters/guava/src/test/java/retrofit2/adapter/guava/ListenableFutureTest.java b/retrofit-adapters/guava/src/test/java/retrofit2/adapter/guava/ListenableFutureTest.java
index fb3ccb3da2..f3ceeca624 100644
--- a/retrofit-adapters/guava/src/test/java/retrofit2/adapter/guava/ListenableFutureTest.java
+++ b/retrofit-adapters/guava/src/test/java/retrofit2/adapter/guava/ListenableFutureTest.java
@@ -65,7 +65,9 @@ interface Service {
future.get();
fail();
} catch (ExecutionException e) {
- assertThat(e.getCause()).isInstanceOf(HttpException.class)
+ assertThat(e.getCause())
+ .isInstanceOf(HttpException.class) // Required for backwards compatibility.
+ .isInstanceOf(retrofit2.HttpException.class)
.hasMessage("HTTP 404 Client Error");
}
}
diff --git a/retrofit-adapters/java8/src/test/java/retrofit2/adapter/java8/CompletableFutureTest.java b/retrofit-adapters/java8/src/test/java/retrofit2/adapter/java8/CompletableFutureTest.java
index d4a00a1dc6..ee06a31eb4 100644
--- a/retrofit-adapters/java8/src/test/java/retrofit2/adapter/java8/CompletableFutureTest.java
+++ b/retrofit-adapters/java8/src/test/java/retrofit2/adapter/java8/CompletableFutureTest.java
@@ -65,7 +65,9 @@ interface Service {
future.get();
fail();
} catch (ExecutionException e) {
- assertThat(e.getCause()).isInstanceOf(HttpException.class)
+ assertThat(e.getCause())
+ .isInstanceOf(HttpException.class) // Required for backwards compatibility.
+ .isInstanceOf(retrofit2.HttpException.class)
.hasMessage("HTTP 404 Client Error");
}
}
diff --git a/retrofit-adapters/rxjava/src/test/java/retrofit2/adapter/rxjava/CompletableTest.java b/retrofit-adapters/rxjava/src/test/java/retrofit2/adapter/rxjava/CompletableTest.java
index b10ab34aff..3d84b39f22 100644
--- a/retrofit-adapters/rxjava/src/test/java/retrofit2/adapter/rxjava/CompletableTest.java
+++ b/retrofit-adapters/rxjava/src/test/java/retrofit2/adapter/rxjava/CompletableTest.java
@@ -60,6 +60,7 @@ interface Service {
RecordingSubscriber<Void> subscriber = subscriberRule.create();
service.completable().unsafeSubscribe(subscriber);
+ // Required for backwards compatibility.
subscriber.assertError(HttpException.class, "HTTP 404 Client Error");
}
diff --git a/retrofit-adapters/rxjava/src/test/java/retrofit2/adapter/rxjava/ObservableTest.java b/retrofit-adapters/rxjava/src/test/java/retrofit2/adapter/rxjava/ObservableTest.java
index 53dcc07709..4a8d8652f2 100644
--- a/retrofit-adapters/rxjava/src/test/java/retrofit2/adapter/rxjava/ObservableTest.java
+++ b/retrofit-adapters/rxjava/src/test/java/retrofit2/adapter/rxjava/ObservableTest.java
@@ -65,6 +65,7 @@ interface Service {
RecordingSubscriber<String> subscriber = subscriberRule.create();
service.body().unsafeSubscribe(subscriber);
+ // Required for backwards compatibility.
subscriber.assertError(HttpException.class, "HTTP 404 Client Error");
}
diff --git a/retrofit-adapters/rxjava/src/test/java/retrofit2/adapter/rxjava/SingleTest.java b/retrofit-adapters/rxjava/src/test/java/retrofit2/adapter/rxjava/SingleTest.java
index c4c35ab457..babd05c73a 100644
--- a/retrofit-adapters/rxjava/src/test/java/retrofit2/adapter/rxjava/SingleTest.java
+++ b/retrofit-adapters/rxjava/src/test/java/retrofit2/adapter/rxjava/SingleTest.java
@@ -65,6 +65,7 @@ interface Service {
RecordingSubscriber<String> subscriber = subscriberRule.create();
service.body().unsafeSubscribe(subscriber);
+ // Required for backwards compatibility.
subscriber.assertError(HttpException.class, "HTTP 404 Client Error");
}
diff --git a/retrofit-adapters/rxjava2/src/test/java/retrofit2/adapter/rxjava2/CompletableTest.java b/retrofit-adapters/rxjava2/src/test/java/retrofit2/adapter/rxjava2/CompletableTest.java
index 64fb3870ae..999cf31bde 100644
--- a/retrofit-adapters/rxjava2/src/test/java/retrofit2/adapter/rxjava2/CompletableTest.java
+++ b/retrofit-adapters/rxjava2/src/test/java/retrofit2/adapter/rxjava2/CompletableTest.java
@@ -59,6 +59,7 @@ interface Service {
RecordingCompletableObserver observer = observerRule.create();
service.completable().subscribe(observer);
+ // Required for backwards compatibility.
observer.assertError(HttpException.class, "HTTP 404 Client Error");
}
diff --git a/retrofit-adapters/rxjava2/src/test/java/retrofit2/adapter/rxjava2/FlowableTest.java b/retrofit-adapters/rxjava2/src/test/java/retrofit2/adapter/rxjava2/FlowableTest.java
index 042b8028dc..22efcee2bf 100644
--- a/retrofit-adapters/rxjava2/src/test/java/retrofit2/adapter/rxjava2/FlowableTest.java
+++ b/retrofit-adapters/rxjava2/src/test/java/retrofit2/adapter/rxjava2/FlowableTest.java
@@ -63,6 +63,7 @@ interface Service {
RecordingSubscriber<String> subscriber = subscriberRule.create();
service.body().subscribe(subscriber);
+ // Required for backwards compatibility.
subscriber.assertError(HttpException.class, "HTTP 404 Client Error");
}
diff --git a/retrofit-adapters/rxjava2/src/test/java/retrofit2/adapter/rxjava2/HttpExceptionTest.java b/retrofit-adapters/rxjava2/src/test/java/retrofit2/adapter/rxjava2/HttpExceptionTest.java
deleted file mode 100644
index da781ffd05..0000000000
--- a/retrofit-adapters/rxjava2/src/test/java/retrofit2/adapter/rxjava2/HttpExceptionTest.java
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
- * Copyright (C) 2016 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 retrofit2.adapter.rxjava2;
-
-import org.junit.Test;
-import retrofit2.Response;
-
-import static org.assertj.core.api.Assertions.assertThat;
-import static org.junit.Assert.fail;
-
-public final class HttpExceptionTest {
- @Test public void response() {
- Response<String> response = Response.success("Hi");
- HttpException exception = new HttpException(response);
- assertThat(exception.code()).isEqualTo(200);
- assertThat(exception.message()).isEqualTo("OK");
- assertThat(exception.response()).isSameAs(response);
- }
-
- @Test public void nullResponseThrows() {
- try {
- new HttpException(null);
- fail();
- } catch (NullPointerException e) {
- assertThat(e).hasMessage("response == null");
- }
- }
-}
diff --git a/retrofit-adapters/rxjava2/src/test/java/retrofit2/adapter/rxjava2/MaybeTest.java b/retrofit-adapters/rxjava2/src/test/java/retrofit2/adapter/rxjava2/MaybeTest.java
index d5eda7d9ec..21f69c68aa 100644
--- a/retrofit-adapters/rxjava2/src/test/java/retrofit2/adapter/rxjava2/MaybeTest.java
+++ b/retrofit-adapters/rxjava2/src/test/java/retrofit2/adapter/rxjava2/MaybeTest.java
@@ -64,6 +64,7 @@ interface Service {
RecordingMaybeObserver<String> observer = observerRule.create();
service.body().subscribe(observer);
+ // Required for backwards compatibility.
observer.assertError(HttpException.class, "HTTP 404 Client Error");
}
diff --git a/retrofit-adapters/rxjava2/src/test/java/retrofit2/adapter/rxjava2/ObservableTest.java b/retrofit-adapters/rxjava2/src/test/java/retrofit2/adapter/rxjava2/ObservableTest.java
index be8f5c31a6..e421c16526 100644
--- a/retrofit-adapters/rxjava2/src/test/java/retrofit2/adapter/rxjava2/ObservableTest.java
+++ b/retrofit-adapters/rxjava2/src/test/java/retrofit2/adapter/rxjava2/ObservableTest.java
@@ -63,6 +63,7 @@ interface Service {
RecordingObserver<String> observer = observerRule.create();
service.body().subscribe(observer);
+ // Required for backwards compatibility.
observer.assertError(HttpException.class, "HTTP 404 Client Error");
}
diff --git a/retrofit-adapters/rxjava2/src/test/java/retrofit2/adapter/rxjava2/SingleTest.java b/retrofit-adapters/rxjava2/src/test/java/retrofit2/adapter/rxjava2/SingleTest.java
index 9ebe67e94e..dba2dd62aa 100644
--- a/retrofit-adapters/rxjava2/src/test/java/retrofit2/adapter/rxjava2/SingleTest.java
+++ b/retrofit-adapters/rxjava2/src/test/java/retrofit2/adapter/rxjava2/SingleTest.java
@@ -63,6 +63,7 @@ interface Service {
RecordingSingleObserver<String> observer = observerRule.create();
service.body().subscribe(observer);
+ // Required for backwards compatibility.
observer.assertError(HttpException.class, "HTTP 404 Client Error");
}
diff --git a/retrofit-adapters/rxjava/src/test/java/retrofit2/adapter/rxjava/HttpExceptionTest.java b/retrofit/src/test/java/retrofit2/HttpExceptionTest.java
similarity index 95%
rename from retrofit-adapters/rxjava/src/test/java/retrofit2/adapter/rxjava/HttpExceptionTest.java
rename to retrofit/src/test/java/retrofit2/HttpExceptionTest.java
index 2e77f06c16..37fa3722c4 100644
--- a/retrofit-adapters/rxjava/src/test/java/retrofit2/adapter/rxjava/HttpExceptionTest.java
+++ b/retrofit/src/test/java/retrofit2/HttpExceptionTest.java
@@ -13,10 +13,9 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package retrofit2.adapter.rxjava;
+package retrofit2;
import org.junit.Test;
-import retrofit2.Response;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;
| train | test | 2017-02-11T04:17:08 | "2017-02-11T05:57:04Z" | JakeWharton | val |
square/retrofit/2716_2721 | square/retrofit | square/retrofit/2716 | square/retrofit/2721 | [
"keyword_pr_to_issue"
] | 329a9fda122f29a40f49482d421f260bf148ee83 | 5c2f505a974d84763b3c2279128351b8a73a3e2d | [
"Seems fine to me. PR?",
"👍 \r\n\r\nWhenever custom Observable type is instantiated, it should go through `RxJavaPlugins.onAssembly()`",
"https://github.com/square/retrofit/pull/2721 thx for the quick consideration folks!"
] | [
"Hm, I thought only custom observable instantiation will be wrapped:\r\n\r\n```java\r\nObservable<Response<R>> responseObservable = RxJavaPlugins.onAssembly(isAsync\r\n ? new CallEnqueueObservable<>(call)\r\n : new CallExecuteObservable<>(call));\r\n```\r\n\r\n```java\r\nif (isResult) {\r\n observable = RxJavaPlugins.onAssembly(new ResultObservable<>(responseObservable));\r\n} else if (isBody) {\r\n observable = RxJavaPlugins.onAssembly(new BodyObservable<>(responseObservable));\r\n} else {\r\n observable = responseObservable;\r\n}\r\n```\r\n\r\nCurrent implementation is not bad, but:\r\n\r\n- As far as I see stactrace won't point to specific lines where `CallEnqueueObservable`/`CallExecuteObservable`/`ResultObservable`/`BodyObservable` got intantiated but will only point to line 87 where it can be hard to figure which branch of code was executed and what is the original observable type if `subscribeOn` was applied\r\n- Wrapping happens after potential `subscribeOn`. Retrofit Observable types are package-private which means that reflecting on their internals is not part of public api provided by Retrofit, however it seems legal to check for `package` of the Observable type to apply some custom behavior. Since wrapping happens after `subscribeOn`, type information gets hidden.",
"I've made a branch with more fine-grained wrapping that we can turn into PR if you want \r\n\r\nhttps://github.com/square/retrofit/compare/master...artem-zinnatullin:az/rxjava-adapter-onAssembly-fix?expand=1"
] | "2018-03-28T14:23:35Z" | [] | Facilitate trace propagation with RxJava2 | What kind of issue is this?
- [x] Feature Request. Start by telling us what problem you’re trying to solve. Often a solution
already exists! Don’t send pull requests to implement new features without first getting our
support. Sometimes we leave features out on purpose to keep the project small.
I'm trying to help get tracing working for retrofit. For example, continuing an incoming trace during an retrofit outbound request (including but not limited to SLF4J propagation).
I looked at similar tech https://github.com/akaita/RxJava2Debug and assembly hooks look quite good for this. I started testing and noticed everything works nicely, except when the result type is Observable. That's because observable types are returned as-is:
```java
final class RxJava2CallAdapter<R> implements CallAdapter<R, Object> {
--snip--
if (isCompletable) {
return observable.ignoreElements(); // .ignoreElements indirectly calls RxJavaPlugins.onAssembly
}
return observable; // returned with no hooks
}
```
I understand that a custom adapter could do this, but wondering if we could make it default to use the hook on plain observable.
ex.
```java
final class RxJava2CallAdapter<R> implements CallAdapter<R, Object> {
--snip--
if (isCompletable) {
return observable.ignoreElements();
}
return RxJavaPlugins.onAssembly(observable);
}
```
Open to other ideas to make this drop-in | [
"retrofit-adapters/rxjava2/src/main/java/retrofit2/adapter/rxjava2/RxJava2CallAdapter.java"
] | [
"retrofit-adapters/rxjava2/src/main/java/retrofit2/adapter/rxjava2/RxJava2CallAdapter.java"
] | [
"retrofit-adapters/rxjava2/src/test/java/retrofit2/adapter/rxjava2/ObservableTest.java"
] | diff --git a/retrofit-adapters/rxjava2/src/main/java/retrofit2/adapter/rxjava2/RxJava2CallAdapter.java b/retrofit-adapters/rxjava2/src/main/java/retrofit2/adapter/rxjava2/RxJava2CallAdapter.java
index eccd30da36..254f921ad5 100644
--- a/retrofit-adapters/rxjava2/src/main/java/retrofit2/adapter/rxjava2/RxJava2CallAdapter.java
+++ b/retrofit-adapters/rxjava2/src/main/java/retrofit2/adapter/rxjava2/RxJava2CallAdapter.java
@@ -18,6 +18,7 @@
import io.reactivex.BackpressureStrategy;
import io.reactivex.Observable;
import io.reactivex.Scheduler;
+import io.reactivex.plugins.RxJavaPlugins;
import java.lang.reflect.Type;
import javax.annotation.Nullable;
import retrofit2.Call;
@@ -83,6 +84,6 @@ final class RxJava2CallAdapter<R> implements CallAdapter<R, Object> {
if (isCompletable) {
return observable.ignoreElements();
}
- return observable;
+ return RxJavaPlugins.onAssembly(observable);
}
}
| diff --git a/retrofit-adapters/rxjava2/src/test/java/retrofit2/adapter/rxjava2/ObservableTest.java b/retrofit-adapters/rxjava2/src/test/java/retrofit2/adapter/rxjava2/ObservableTest.java
index e421c16526..23c20f77e3 100644
--- a/retrofit-adapters/rxjava2/src/test/java/retrofit2/adapter/rxjava2/ObservableTest.java
+++ b/retrofit-adapters/rxjava2/src/test/java/retrofit2/adapter/rxjava2/ObservableTest.java
@@ -16,6 +16,8 @@
package retrofit2.adapter.rxjava2;
import io.reactivex.Observable;
+import io.reactivex.functions.Function;
+import io.reactivex.plugins.RxJavaPlugins;
import java.io.IOException;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
@@ -133,4 +135,18 @@ interface Service {
assertThat(result.error()).isInstanceOf(IOException.class);
observer.assertComplete();
}
+
+ @Test public void observableAssembly() {
+ try {
+ final Observable<String> justMe = Observable.just("me");
+ RxJavaPlugins.setOnObservableAssembly(new Function<Observable, Observable>() {
+ @Override public Observable apply(Observable f) {
+ return justMe;
+ }
+ });
+ assertThat(service.body()).isEqualTo(justMe);
+ } finally {
+ RxJavaPlugins.reset();
+ }
+ }
}
| val | test | 2018-03-27T16:33:32 | "2018-03-27T07:26:57Z" | codefromthecrypt | val |
square/retrofit/2845_2849 | square/retrofit | square/retrofit/2845 | square/retrofit/2849 | [
"keyword_pr_to_issue"
] | 4a048cc03f5a851b64d9726098df49b5fa4130c6 | 5e957e41458a1f3e3450446db892c54732eaba6d | [
"`@Url` must be first. We have a test which enforces this invariant. I'll look into why it doesn't work here.",
"Thanks, set @Url as the first parameter, it's working for me."
] | [] | "2018-08-10T01:31:46Z" | [
"Bug"
] | Check for @Url as the first parameter doesn't work on Kotlin | I set @Url default value in function with last param,like this:
```
@GET
fun batch(@HeaderMap header: Map<String, String>, @QueryMap param: Map<String, String>, @Url url: String = "http://xxx.xxx./xxx"): Flowable<Result>
```
and the log:
```
java.lang.NullPointerException: Attempt to invoke virtual method 'okhttp3.HttpUrl$Builder okhttp3.HttpUrl$Builder.addQueryParameter(java.lang.String, java.lang.String)' on a null object reference
at retrofit2.RequestBuilder.addQueryParam(RequestBuilder.java:162)
at retrofit2.ParameterHandler$QueryMap.apply(ParameterHandler.java:176)
at retrofit2.ParameterHandler$QueryMap.apply(ParameterHandler.java:139)
at retrofit2.ServiceMethod.toCall(ServiceMethod.java:110)
at retrofit2.OkHttpCall.createRawCall(OkHttpCall.java:184)
at retrofit2.OkHttpCall.execute(OkHttpCall.java:167)
at retrofit2.adapter.rxjava2.CallExecuteObservable.subscribeActual(CallExecuteObservable.java:42)
at io.reactivex.Observable.subscribe(Observable.java:12051)
at retrofit2.adapter.rxjava2.BodyObservable.subscribeActual(BodyObservable.java:34)
at io.reactivex.Observable.subscribe(Observable.java:12051)
at io.reactivex.internal.operators.flowable.FlowableFromObservable.subscribeActual(FlowableFromObservable.java:29)
at io.reactivex.Flowable.subscribe(Flowable.java:14349)
at io.reactivex.internal.operators.flowable.FlowableOnBackpressureLatest.subscribeActual(FlowableOnBackpressureLatest.java:32)
at io.reactivex.Flowable.subscribe(Flowable.java:14349)
at io.reactivex.Flowable.subscribe(Flowable.java:14295)
at io.reactivex.internal.operators.flowable.FlowableSubscribeOn$SubscribeOnSubscriber.run(FlowableSubscribeOn.java:82)
at io.reactivex.internal.schedulers.ScheduledRunnable.run(ScheduledRunnable.java:66)
at io.reactivex.internal.schedulers.ScheduledRunnable.call(ScheduledRunnable.java:57)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:301)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
at java.lang.Thread.run(Thread.java:764)
```
| [
"retrofit/src/main/java/retrofit2/RequestFactory.java"
] | [
"retrofit/src/main/java/retrofit2/RequestFactory.java"
] | [
"retrofit/src/test/java/retrofit2/RequestFactoryTest.java"
] | diff --git a/retrofit/src/main/java/retrofit2/RequestFactory.java b/retrofit/src/main/java/retrofit2/RequestFactory.java
index c6098b2a93..ee7cdba415 100644
--- a/retrofit/src/main/java/retrofit2/RequestFactory.java
+++ b/retrofit/src/main/java/retrofit2/RequestFactory.java
@@ -127,6 +127,8 @@ static final class Builder {
boolean gotBody;
boolean gotPath;
boolean gotQuery;
+ boolean gotQueryName;
+ boolean gotQueryMap;
boolean gotUrl;
String httpMethod;
boolean hasBody;
@@ -322,7 +324,13 @@ private ParameterHandler<?> parseParameterAnnotation(
throw parameterError(method, p, "@Path parameters may not be used with @Url.");
}
if (gotQuery) {
- throw parameterError(method, p, "A @Url parameter must not come after a @Query");
+ throw parameterError(method, p, "A @Url parameter must not come after a @Query.");
+ }
+ if (gotQueryName) {
+ throw parameterError(method, p, "A @Url parameter must not come after a @QueryName.");
+ }
+ if (gotQueryMap) {
+ throw parameterError(method, p, "A @Url parameter must not come after a @QueryMap.");
}
if (relativeUrl != null) {
throw parameterError(method, p, "@Url cannot be used with @%s URL", httpMethod);
@@ -344,6 +352,12 @@ private ParameterHandler<?> parseParameterAnnotation(
if (gotQuery) {
throw parameterError(method, p, "A @Path parameter must not come after a @Query.");
}
+ if (gotQueryName) {
+ throw parameterError(method, p, "A @Path parameter must not come after a @QueryName.");
+ }
+ if (gotQueryMap) {
+ throw parameterError(method, p, "A @Path parameter must not come after a @QueryMap.");
+ }
if (gotUrl) {
throw parameterError(method, p, "@Path parameters may not be used with @Url.");
}
@@ -395,7 +409,7 @@ private ParameterHandler<?> parseParameterAnnotation(
boolean encoded = query.encoded();
Class<?> rawParameterType = Utils.getRawType(type);
- gotQuery = true;
+ gotQueryName = true;
if (Iterable.class.isAssignableFrom(rawParameterType)) {
if (!(type instanceof ParameterizedType)) {
throw parameterError(method, p, rawParameterType.getSimpleName()
@@ -421,6 +435,7 @@ private ParameterHandler<?> parseParameterAnnotation(
} else if (annotation instanceof QueryMap) {
Class<?> rawParameterType = Utils.getRawType(type);
+ gotQueryMap = true;
if (!Map.class.isAssignableFrom(rawParameterType)) {
throw parameterError(method, p, "@QueryMap parameter type must be Map.");
}
| diff --git a/retrofit/src/test/java/retrofit2/RequestFactoryTest.java b/retrofit/src/test/java/retrofit2/RequestFactoryTest.java
index cfee28e19f..97d178677a 100644
--- a/retrofit/src/test/java/retrofit2/RequestFactoryTest.java
+++ b/retrofit/src/test/java/retrofit2/RequestFactoryTest.java
@@ -1005,6 +1005,40 @@ Call<ResponseBody> method(@Query("kit") String kit, @Path("ping") String ping) {
}
}
+ @Test public void getWithQueryNameThenPathThrows() {
+ class Example {
+ @GET("/foo/bar/{ping}/") //
+ Call<ResponseBody> method(@QueryName String kit, @Path("ping") String ping) {
+ throw new AssertionError();
+ }
+ }
+
+ try {
+ buildRequest(Example.class, "kat", "pong");
+ fail();
+ } catch (IllegalArgumentException e) {
+ assertThat(e).hasMessage("A @Path parameter must not come after a @QueryName. (parameter #2)\n"
+ + " for method Example.method");
+ }
+ }
+
+ @Test public void getWithQueryMapThenPathThrows() {
+ class Example {
+ @GET("/foo/bar/{ping}/") //
+ Call<ResponseBody> method(@QueryMap Map<String, String> queries, @Path("ping") String ping) {
+ throw new AssertionError();
+ }
+ }
+
+ try {
+ buildRequest(Example.class, Collections.singletonMap("kit", "kat"), "pong");
+ fail();
+ } catch (IllegalArgumentException e) {
+ assertThat(e).hasMessage("A @Path parameter must not come after a @QueryMap. (parameter #2)\n"
+ + " for method Example.method");
+ }
+ }
+
@Test public void getWithPathAndQueryQuestionMarkParam() {
class Example {
@GET("/foo/bar/{ping}/") //
@@ -1444,7 +1478,41 @@ Call<ResponseBody> method(@Query("hey") String hey, @Url Object url) {
buildRequest(Example.class, "hey", "foo/bar/");
fail();
} catch (IllegalArgumentException e) {
- assertThat(e).hasMessage("A @Url parameter must not come after a @Query (parameter #2)\n"
+ assertThat(e).hasMessage("A @Url parameter must not come after a @Query. (parameter #2)\n"
+ + " for method Example.method");
+ }
+ }
+
+ @Test public void getWithQueryNameThenUrlThrows() {
+ class Example {
+ @GET
+ Call<ResponseBody> method(@QueryName String name, @Url String url) {
+ throw new AssertionError();
+ }
+ }
+
+ try {
+ buildRequest(Example.class, Collections.singletonMap("kit", "kat"), "foo/bar/");
+ fail();
+ } catch (IllegalArgumentException e) {
+ assertThat(e).hasMessage("A @Url parameter must not come after a @QueryName. (parameter #2)\n"
+ + " for method Example.method");
+ }
+ }
+
+ @Test public void getWithQueryMapThenUrlThrows() {
+ class Example {
+ @GET
+ Call<ResponseBody> method(@QueryMap Map<String, String> queries, @Url String url) {
+ throw new AssertionError();
+ }
+ }
+
+ try {
+ buildRequest(Example.class, Collections.singletonMap("kit", "kat"), "foo/bar/");
+ fail();
+ } catch (IllegalArgumentException e) {
+ assertThat(e).hasMessage("A @Url parameter must not come after a @QueryMap. (parameter #2)\n"
+ " for method Example.method");
}
}
| train | test | 2018-07-28T23:19:28 | "2018-08-08T07:30:30Z" | MarkMjw | val |
square/retrofit/2032_2981 | square/retrofit | square/retrofit/2032 | square/retrofit/2981 | [
"keyword_pr_to_issue"
] | ee72ada9bb9d227f133786a866606c019c349064 | ac566e1abd3fee77d8d588a2cd97c5056d330d2c | [
"Should be easy to fix. Can you paste the exception?\n\nOn Wed, Sep 28, 2016 at 1:30 PM mdeluisi [email protected] wrote:\n\n> Retrofit 2.1.0 currently throws an exception building a client\n> implementation proxy if the interface has static methods.\n> \n> —\n> You are receiving this because you are subscribed to this thread.\n> Reply to this email directly, view it on GitHub\n> https://github.com/square/retrofit/issues/2032, or mute the thread\n> https://github.com/notifications/unsubscribe-auth/AAEEEWF0EQ4Jqo4NpmX2h_F2R-6gYDqQks5quqQqgaJpZM4KJGFG\n> .\n",
"static method is declared as the following in the interface:\n\n`\nstatic TalendClientBuilder builder() {\n return TalendClientBuilder.create();\n}\n`\nException:\nCaused by: java.lang.IllegalArgumentException: Could not locate call adapter for class com.corp.talend.client.v1.api.TalendClientBuilder.\n Tried:\n- retrofit2.DefaultCallAdapterFactory\n at retrofit2.Retrofit.nextCallAdapter(Retrofit.java:237) ~[retrofit-2.1.0.jar:?]\n at retrofit2.Retrofit.callAdapter(Retrofit.java:201) ~[retrofit-2.1.0.jar:?]\n at retrofit2.ServiceMethod$Builder.createCallAdapter(ServiceMethod.java:232) ~[retrofit-2.1.0.jar:?]\n at retrofit2.ServiceMethod$Builder.build(ServiceMethod.java:160) ~[retrofit-2.1.0.jar:?]\n at retrofit2.Retrofit.loadServiceMethod(Retrofit.java:166) ~[retrofit-2.1.0.jar:?]\n at retrofit2.Retrofit.eagerlyValidateMethods(Retrofit.java:156) ~[retrofit-2.1.0.jar:?]\n at retrofit2.Retrofit.create(Retrofit.java:130) ~[retrofit-2.1.0.jar:?]\n ...\n",
"Looks like the issue is in Retrofit.eagerlyValidateMethods method. It should probably just bypass the validation if the method is static. If I disable eager validation the create() call works fine and a proxy is created.\n",
"I don't see this failing locally. Are you sure you defined the method as static?\n",
"Did you enable eager validation in your test? Yea, I declared it exactly like my example posted above.\n",
"I was able to reproduce an issue related to this: https://github.com/bnorm/retrofit/blob/bnorm.1030.static_method/retrofit-adapters/java8/src/test/java/retrofit2/adapter/java8/Java8StaticMethodsTest.java\r\n\r\nI can open a pull-request with this failing unit test if that is helpful.\r\n\r\nAlso, I would be happy to contribute a fix. Should just be adding `&& (method.getModifiers() & Modifier.STATIC) != Modifier.STATIC` to the `Retrofit.eagerlyValidateMethods` method either directly or through `Platform`."
] | [
"Let me know if you want this removed. It's weird to be calling a static method on an instance, but technically legal. This at least keeps that behavior",
"Is this line reachable in test cases? I assume it won’t be dispatched this way",
"Yeah I don't think this can happen. The only case I can think of is if a virtual method was made static without recompiling the caller. But even then I would expect the VM to intervene.",
"done f1fbbda",
"Can you move this to a separate test class? I don't want to conflate the two things being tested here together.",
"fbf8d3c\r\n\r\nLeft the var name fix in the original though as an opportunistic fix",
"Is the condition reachable?",
"Ahh, this happens during reflection, not invocation. Works for me."
] | "2018-12-03T20:52:38Z" | [
"Needs Info"
] | Support for Java8 interface static methods | Retrofit 2.1.0 currently throws an exception building a client implementation proxy if the interface has static methods.
| [
"retrofit/src/main/java/retrofit2/Retrofit.java"
] | [
"retrofit/src/main/java/retrofit2/Retrofit.java"
] | [
"retrofit/src/test/java/retrofit2/Java8DefaultMethodsTest.java",
"retrofit/src/test/java/retrofit2/Java8DefaultStaticMethodsInValidationTest.java"
] | diff --git a/retrofit/src/main/java/retrofit2/Retrofit.java b/retrofit/src/main/java/retrofit2/Retrofit.java
index a9040f8b3a..5d0ad8957a 100644
--- a/retrofit/src/main/java/retrofit2/Retrofit.java
+++ b/retrofit/src/main/java/retrofit2/Retrofit.java
@@ -18,6 +18,7 @@
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
+import java.lang.reflect.Modifier;
import java.lang.reflect.Proxy;
import java.lang.reflect.Type;
import java.util.ArrayList;
@@ -152,7 +153,7 @@ public <T> T create(final Class<T> service) {
private void eagerlyValidateMethods(Class<?> service) {
Platform platform = Platform.get();
for (Method method : service.getDeclaredMethods()) {
- if (!platform.isDefaultMethod(method)) {
+ if (!platform.isDefaultMethod(method) && !Modifier.isStatic(method.getModifiers())) {
loadServiceMethod(method);
}
}
| diff --git a/retrofit/src/test/java/retrofit2/Java8DefaultMethodsTest.java b/retrofit/src/test/java/retrofit2/Java8DefaultMethodsTest.java
index 8333969c65..501c909e48 100644
--- a/retrofit/src/test/java/retrofit2/Java8DefaultMethodsTest.java
+++ b/retrofit/src/test/java/retrofit2/Java8DefaultMethodsTest.java
@@ -39,7 +39,7 @@ public final class Java8DefaultMethodsTest {
//
// Response<String> response = example.user().execute();
// assertThat(response.body()).isEqualTo("Hi");
- // Response<String> response = example.user("hi").execute();
- // assertThat(response.body()).isEqualTo("Hi");
+ // Response<String> response2 = example.user("Hi").execute();
+ // assertThat(response2.body()).isEqualTo("Hi");
//}
}
diff --git a/retrofit/src/test/java/retrofit2/Java8DefaultStaticMethodsInValidationTest.java b/retrofit/src/test/java/retrofit2/Java8DefaultStaticMethodsInValidationTest.java
new file mode 100644
index 0000000000..bc2521d5a3
--- /dev/null
+++ b/retrofit/src/test/java/retrofit2/Java8DefaultStaticMethodsInValidationTest.java
@@ -0,0 +1,42 @@
+/*
+ * Copyright (C) 2016 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 retrofit2;
+
+// TODO this test doesn't play nice in the IDE because it relies on Java 8 language features.
+public final class Java8DefaultStaticMethodsInValidationTest {
+ //@Rule public final MockWebServer server = new MockWebServer();
+ //
+ //interface Example {
+ // @GET("/") Call<String> user(@Query("name") String name);
+ //
+ // default Call<String> user() {
+ // return user("hey");
+ // }
+ //
+ // static String staticMethod() {
+ // return "Hi";
+ // }
+ //}
+ //
+ //@Test public void test() throws IOException {
+ // Retrofit retrofit = new Retrofit.Builder()
+ // .baseUrl(server.url("/"))
+ // .addConverterFactory(new ToStringConverterFactory())
+ // .validateEagerly(true)
+ // .build();
+ // Example example = retrofit.create(Example.class);
+ //}
+}
| train | test | 2018-11-24T19:51:42 | "2016-09-28T17:30:17Z" | mdeluisi | val |
square/retrofit/2991_2993 | square/retrofit | square/retrofit/2991 | square/retrofit/2993 | [
"keyword_pr_to_issue"
] | ee72ada9bb9d227f133786a866606c019c349064 | b093109fb753d77b8fc42667c378bd9e5565273f | [
"We can update, sure, but we don't do releases for updating converter\ndependencies. If you need a newer version the consumer should specify it.\n\nOn Tue, Dec 18, 2018, 11:07 AM dGhlb3ds <[email protected] wrote:\n\n> Snyk analysis flags up security vulnerabilities in\n> com.squareup.retrofit2:converter-jackson:2.5.0 due to the dependency on\n> com.fasterxml.jackson.core:[email protected]\n>\n> https://snyk.io/vuln/SNYK-JAVA-COMFASTERXMLJACKSONCORE-72451\n>\n> Could you please upgrade to [email protected]?\n>\n> —\n> You are receiving this because you are subscribed to this thread.\n> Reply to this email directly, view it on GitHub\n> <https://github.com/square/retrofit/issues/2991>, or mute the thread\n> <https://github.com/notifications/unsubscribe-auth/AAEEEQHAhV1oM95KCdnnLVJ2IUgxciCkks5u6RKngaJpZM4ZYmmM>\n> .\n>\n",
"How does the consumer specify the newer version ? ",
"They declare it explicitly as a dependency and their dependency tool will\nresolve the newer version. Basically the same as how you declare any other\ndependency.\n\nOn Fri, Feb 15, 2019, 3:16 AM pavankumarvvijapur <[email protected]\nwrote:\n\n> How does the consumer specify the newer version ?\n>\n> —\n> You are receiving this because you commented.\n>\n>\n> Reply to this email directly, view it on GitHub\n> <https://github.com/square/retrofit/issues/2991#issuecomment-463947736>,\n> or mute the thread\n> <https://github.com/notifications/unsubscribe-auth/AAEEEYNVGNNO8M58UENlY2PVFkHCBTDAks5vNmzYgaJpZM4ZYmmM>\n> .\n>\n"
] | [] | "2018-12-19T16:11:44Z" | [] | Deserialisation of untrusted data in jackson-databind [,2.9.7) | Snyk analysis flags up security vulnerabilities in com.squareup.retrofit2:converter-jackson:2.5.0 due to the dependency on com.fasterxml.jackson.core:[email protected]
https://snyk.io/vuln/SNYK-JAVA-COMFASTERXMLJACKSONCORE-72451
Could you please upgrade to [email protected]? | [
"pom.xml"
] | [
"pom.xml"
] | [] | diff --git a/pom.xml b/pom.xml
index 85a3ceebfe..d1ac09dba3 100644
--- a/pom.xml
+++ b/pom.xml
@@ -62,7 +62,7 @@
<!-- Converter Dependencies -->
<gson.version>2.8.2</gson.version>
<protobuf.version>3.0.0</protobuf.version>
- <jackson.version>2.9.4</jackson.version>
+ <jackson.version>2.9.8</jackson.version>
<wire.version>2.2.0</wire.version>
<simplexml.version>2.7.1</simplexml.version>
<moshi.version>1.5.0</moshi.version>
| null | train | test | 2018-11-24T19:51:42 | "2018-12-18T16:07:00Z" | dGhlb3ds | val |
square/retrofit/2983_3011 | square/retrofit | square/retrofit/2983 | square/retrofit/3011 | [
"keyword_pr_to_issue"
] | eb844dc3ad004b81a79c226e0c23708ba7a805ea | 92b819ba92ef00f607c2a17c3c8858c2494895ff | [] | [] | "2019-01-22T20:10:59Z" | [
"Bug"
] | HttpException.response() should be marked w/ @Nullable | What kind of issue is this?
- [x] Bug report
Code for that method in Retrofit2 2.5 is:
```
/**
* The full HTTP response. This may be null if the exception was serialized.
*/
public Response<?> response() {
return response;
}
``` | [
"retrofit/src/main/java/retrofit2/HttpException.java"
] | [
"retrofit/src/main/java/retrofit2/HttpException.java"
] | [] | diff --git a/retrofit/src/main/java/retrofit2/HttpException.java b/retrofit/src/main/java/retrofit2/HttpException.java
index c01f97dfe8..f53e76e782 100644
--- a/retrofit/src/main/java/retrofit2/HttpException.java
+++ b/retrofit/src/main/java/retrofit2/HttpException.java
@@ -15,6 +15,8 @@
*/
package retrofit2;
+import javax.annotation.Nullable;
+
import static retrofit2.Utils.checkNotNull;
/** Exception for an unexpected, non-2xx HTTP response. */
@@ -48,7 +50,7 @@ public String message() {
/**
* The full HTTP response. This may be null if the exception was serialized.
*/
- public Response<?> response() {
+ public @Nullable Response<?> response() {
return response;
}
}
| null | train | test | 2019-01-22T21:05:24 | "2018-12-06T15:13:10Z" | kenyee | val |
square/retrofit/3034_3035 | square/retrofit | square/retrofit/3034 | square/retrofit/3035 | [
"keyword_pr_to_issue"
] | 8839c4fc4e859e458296400123a6bb97a0985283 | c2b930c9c74c185d8dbc1742b0fedede29aaf6be | [
"nice. i'll update the post tonight to note the fix in ExceptionCatchingResponseBody."
] | [] | "2019-02-20T15:41:42Z" | [] | ExceptionCatchingResponseBody shouldn’t create new BufferedSource instances | Subsequent calls to `source()` should return the same instance.
http://blog.nightlynexus.com/where-did-my-responsebody-data-go/
FYI @NightlyNexus ! | [
"retrofit/src/main/java/retrofit2/OkHttpCall.java"
] | [
"retrofit/src/main/java/retrofit2/OkHttpCall.java"
] | [
"retrofit/src/test/java/retrofit2/CallTest.java",
"retrofit/src/test/java/retrofit2/TestingUtils.java"
] | diff --git a/retrofit/src/main/java/retrofit2/OkHttpCall.java b/retrofit/src/main/java/retrofit2/OkHttpCall.java
index 6de7e957b6..a5b5b9237b 100644
--- a/retrofit/src/main/java/retrofit2/OkHttpCall.java
+++ b/retrofit/src/main/java/retrofit2/OkHttpCall.java
@@ -277,10 +277,21 @@ static final class NoContentResponseBody extends ResponseBody {
static final class ExceptionCatchingResponseBody extends ResponseBody {
private final ResponseBody delegate;
+ private final BufferedSource delegateSource;
@Nullable IOException thrownException;
ExceptionCatchingResponseBody(ResponseBody delegate) {
this.delegate = delegate;
+ this.delegateSource = Okio.buffer(new ForwardingSource(delegate.source()) {
+ @Override public long read(Buffer sink, long byteCount) throws IOException {
+ try {
+ return super.read(sink, byteCount);
+ } catch (IOException e) {
+ thrownException = e;
+ throw e;
+ }
+ }
+ });
}
@Override public MediaType contentType() {
@@ -292,16 +303,7 @@ static final class ExceptionCatchingResponseBody extends ResponseBody {
}
@Override public BufferedSource source() {
- return Okio.buffer(new ForwardingSource(delegate.source()) {
- @Override public long read(Buffer sink, long byteCount) throws IOException {
- try {
- return super.read(sink, byteCount);
- } catch (IOException e) {
- thrownException = e;
- throw e;
- }
- }
- });
+ return delegateSource;
}
@Override public void close() {
| diff --git a/retrofit/src/test/java/retrofit2/CallTest.java b/retrofit/src/test/java/retrofit2/CallTest.java
index aa9b882d8d..4f579034f5 100644
--- a/retrofit/src/test/java/retrofit2/CallTest.java
+++ b/retrofit/src/test/java/retrofit2/CallTest.java
@@ -49,6 +49,7 @@
import static org.junit.Assert.fail;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verifyNoMoreInteractions;
+import static retrofit2.TestingUtils.repeat;
public final class CallTest {
@Rule public final MockWebServer server = new MockWebServer();
@@ -421,6 +422,31 @@ public Converter<?, RequestBody> requestBodyConverter(Type type,
verifyNoMoreInteractions(converter);
}
+ @Test public void converterBodyDoesNotLeakContentInIntermediateBuffers() throws IOException {
+ Retrofit retrofit = new Retrofit.Builder()
+ .baseUrl(server.url("/"))
+ .addConverterFactory(new Converter.Factory() {
+ @Override public Converter<ResponseBody, ?> responseBodyConverter(Type type,
+ Annotation[] annotations, Retrofit retrofit) {
+ return new Converter<ResponseBody, String>() {
+ @Override public String convert(ResponseBody value) throws IOException {
+ String prefix = value.source().readUtf8(2);
+ value.source().skip(20_000 - 4);
+ String suffix = value.source().readUtf8();
+ return prefix + suffix;
+ }
+ };
+ }
+ })
+ .build();
+ Service example = retrofit.create(Service.class);
+
+ server.enqueue(new MockResponse().setBody(repeat('a', 10_000) + repeat('b', 10_000)));
+
+ Response<String> response = example.getString().execute();
+ assertThat(response.body()).isEqualTo("aabb");
+ }
+
@Test public void executeCallOnce() throws IOException {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(server.url("/"))
diff --git a/retrofit/src/test/java/retrofit2/TestingUtils.java b/retrofit/src/test/java/retrofit2/TestingUtils.java
index 3847509ea5..f68b724cf7 100644
--- a/retrofit/src/test/java/retrofit2/TestingUtils.java
+++ b/retrofit/src/test/java/retrofit2/TestingUtils.java
@@ -16,13 +16,20 @@
package retrofit2;
import java.lang.reflect.Method;
+import java.util.Arrays;
-public final class TestingUtils {
- public static Method onlyMethod(Class c) {
+final class TestingUtils {
+ static Method onlyMethod(Class c) {
Method[] declaredMethods = c.getDeclaredMethods();
if (declaredMethods.length == 1) {
return declaredMethods[0];
}
throw new IllegalArgumentException("More than one method declared.");
}
+
+ static String repeat(char c, int times) {
+ char[] cs = new char[times];
+ Arrays.fill(cs, c);
+ return new String(cs);
+ }
}
| train | test | 2019-02-16T13:21:06 | "2019-02-20T14:04:14Z" | swankjesse | val |
square/retrofit/2966_3338 | square/retrofit | square/retrofit/2966 | square/retrofit/3338 | [
"keyword_pr_to_issue"
] | ff448cf65b3086701cdac3158a19535341231b6f | 206c860d0a728b4f6960d731e6e3e7cf5e099f52 | [
"You don't actually have to do what you described to get per-service timeouts. There's two ways this can be done currently:\r\n\r\n 1. Add a `@Headers` annotation with a synthetic header that specifies the timeout value on the service method. Read and strip the header in an interceptor. Update the timeout on the `chain` based on the header value before calling `chain.proceed`.\r\n\r\n 2. Add a custom `@Timeout` annotation on the service method. ~In an interceptor, read the `Invocation.class` tag instance from the `Call` object and adjust the timeout on the `chain` before calling `chain.proceed`.~ In a delegating `CallAdapter.Factory`, read the annotation and create a `CallAdapter` which applies the timeout. See https://github.com/square/retrofit/issues/2982#issuecomment-456608496\r\n\r\nI'm not sure if we want to add static (i.e., annotation-based) and/or dynamic (i.e., parameter-based) timeouts. I'll have to think about it! And additional use cases are welcome.",
"now when I think about it, I'm not even sure if `okhttp3.Call.timeout()` will help me.\r\n\r\nsince I have a `OkHttpClient` with `X` ms connect & `Y` ms read timeouts, will `Call.timeout((X + Y) * 2)` have any effect? Need to try that one out",
"Suggestion 2 didn't work above, but this should: https://github.com/square/retrofit/issues/2982#issuecomment-456608496",
"I think we can do like this.\r\n```java\r\n @Retention(RetentionPolicy.RUNTIME)\r\n @Target(ElementType.METHOD)\r\n public @interface Timeout {\r\n int value();\r\n\r\n TimeUnit unit();\r\n }\r\n\r\n public interface ApiService {\r\n @Timeout(value = 100, unit = TimeUnit.MILLISECONDS)\r\n @GET(\"something\")\r\n retrofit2.Call<String> getSomething();\r\n }\r\n\r\npublic class CallFactoryProxy implements Call.Factory {\r\n\r\n protected final Call.Factory delegate;\r\n\r\n public CallFactoryProxy(Call.Factory delegate) {\r\n Utils.checkNotNull(delegate, \"delegate==null\");\r\n this.delegate = delegate;\r\n }\r\n\r\n @Override\r\n public Call newCall(Request request) {\r\n Call call = delegate.newCall(request);\r\n Invocation tag = request.tag(Invocation.class);\r\n Method method = tag.method();\r\n Timeout timeout = method.getAnnotation(Timeout.class);\r\n if (timeout != null) {\r\n call.timeout().timeout(timeout.value(), timeout.unit());\r\n }\r\n return call;\r\n }\r\n}\r\n // create retrofit\r\n OkHttpClient client = new OkHttpClient.Builder()\r\n .build();\r\n Retrofit retrofit = new Retrofit.Builder()\r\n .baseUrl(\"https://xxxxx.com/\")\r\n .callFactory(new CallFactoryProxy(client))\r\n .addConverterFactory(GsonConverterFactory.create())\r\n .build();\r\n\r\n```",
"or dynamic you can use `@Header` or ` @Tag` and parse it from `newCall(Request request)` "
] | [
"Needs to be synchronized. Concurrent invocations can return different instances or see partial state.\r\n\r\nI hope error-prone catches this because of the `@GuardedBy`...",
"It did. Whew."
] | "2020-03-18T18:49:35Z" | [
"Feature"
] | Support okhttp3.Call.timeout() | https://github.com/square/okhttp/blob/c273b3be385383842e44d25d6b7ca137ff6b1076/okhttp/src/main/java/okhttp3/Call.java#L84-L91
I have one endpoint in the retrofit `interface` that needs an increased timeout. Currently I have to create a modified `OkHttpClient`, and then create an additional `interface` with an endpoint that needs the increased timeout.
It would be great to have annotation for that | [
"retrofit-mock/src/main/java/retrofit2/mock/BehaviorCall.java",
"retrofit-mock/src/main/java/retrofit2/mock/Calls.java",
"retrofit/src/main/java/retrofit2/Call.java",
"retrofit/src/main/java/retrofit2/DefaultCallAdapterFactory.java",
"retrofit/src/main/java/retrofit2/OkHttpCall.java"
] | [
"retrofit-mock/src/main/java/retrofit2/mock/BehaviorCall.java",
"retrofit-mock/src/main/java/retrofit2/mock/Calls.java",
"retrofit/src/main/java/retrofit2/Call.java",
"retrofit/src/main/java/retrofit2/DefaultCallAdapterFactory.java",
"retrofit/src/main/java/retrofit2/OkHttpCall.java"
] | [
"retrofit/src/test/java/retrofit2/CallTest.java",
"retrofit/src/test/java/retrofit2/DefaultCallAdapterFactoryTest.java"
] | diff --git a/retrofit-mock/src/main/java/retrofit2/mock/BehaviorCall.java b/retrofit-mock/src/main/java/retrofit2/mock/BehaviorCall.java
index a41664876c..d333d0f09b 100644
--- a/retrofit-mock/src/main/java/retrofit2/mock/BehaviorCall.java
+++ b/retrofit-mock/src/main/java/retrofit2/mock/BehaviorCall.java
@@ -23,6 +23,7 @@
import javax.annotation.Nullable;
import javax.annotation.concurrent.GuardedBy;
import okhttp3.Request;
+import okio.Timeout;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
@@ -54,6 +55,10 @@ final class BehaviorCall<T> implements Call<T> {
return delegate.request();
}
+ @Override public Timeout timeout() {
+ return delegate.timeout();
+ }
+
@SuppressWarnings("ConstantConditions") // Guarding public API nullability.
@Override public void enqueue(final Callback<T> callback) {
if (callback == null) throw new NullPointerException("callback == null");
diff --git a/retrofit-mock/src/main/java/retrofit2/mock/Calls.java b/retrofit-mock/src/main/java/retrofit2/mock/Calls.java
index 65d3afd4af..1670e62ae8 100644
--- a/retrofit-mock/src/main/java/retrofit2/mock/Calls.java
+++ b/retrofit-mock/src/main/java/retrofit2/mock/Calls.java
@@ -20,6 +20,7 @@
import java.util.concurrent.atomic.AtomicBoolean;
import javax.annotation.Nullable;
import okhttp3.Request;
+import okio.Timeout;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
@@ -136,6 +137,10 @@ private static <T extends Throwable> T sneakyThrow2(Throwable t) throws T {
.url("http://localhost")
.build();
}
+
+ @Override public Timeout timeout() {
+ return Timeout.NONE;
+ }
}
static final class DeferredCall<T> implements Call<T> {
@@ -186,5 +191,9 @@ private synchronized Call<T> getDelegate() {
@Override public Request request() {
return getDelegate().request();
}
+
+ @Override public Timeout timeout() {
+ return getDelegate().timeout();
+ }
}
}
diff --git a/retrofit/src/main/java/retrofit2/Call.java b/retrofit/src/main/java/retrofit2/Call.java
index 171d9e0c41..bb861fbaa7 100644
--- a/retrofit/src/main/java/retrofit2/Call.java
+++ b/retrofit/src/main/java/retrofit2/Call.java
@@ -16,7 +16,9 @@
package retrofit2;
import java.io.IOException;
+import okhttp3.OkHttpClient;
import okhttp3.Request;
+import okio.Timeout;
/**
* An invocation of a Retrofit method that sends a request to a webserver and returns a response.
@@ -70,4 +72,11 @@ public interface Call<T> extends Cloneable {
/** The original HTTP request. */
Request request();
+
+ /**
+ * Returns a timeout that spans the entire call: resolving DNS, connecting, writing the request
+ * body, server processing, and reading the response body. If the call requires redirects or
+ * retries all must complete within one timeout period.
+ */
+ Timeout timeout();
}
diff --git a/retrofit/src/main/java/retrofit2/DefaultCallAdapterFactory.java b/retrofit/src/main/java/retrofit2/DefaultCallAdapterFactory.java
index e7a9c3b5f7..ab22274bff 100644
--- a/retrofit/src/main/java/retrofit2/DefaultCallAdapterFactory.java
+++ b/retrofit/src/main/java/retrofit2/DefaultCallAdapterFactory.java
@@ -23,6 +23,7 @@
import java.util.concurrent.Executor;
import javax.annotation.Nullable;
import okhttp3.Request;
+import okio.Timeout;
final class DefaultCallAdapterFactory extends CallAdapter.Factory {
private final @Nullable Executor callbackExecutor;
@@ -113,5 +114,9 @@ static final class ExecutorCallbackCall<T> implements Call<T> {
@Override public Request request() {
return delegate.request();
}
+
+ @Override public Timeout timeout() {
+ return delegate.timeout();
+ }
}
}
diff --git a/retrofit/src/main/java/retrofit2/OkHttpCall.java b/retrofit/src/main/java/retrofit2/OkHttpCall.java
index cc348a6602..10f27da97a 100644
--- a/retrofit/src/main/java/retrofit2/OkHttpCall.java
+++ b/retrofit/src/main/java/retrofit2/OkHttpCall.java
@@ -26,6 +26,7 @@
import okio.BufferedSource;
import okio.ForwardingSource;
import okio.Okio;
+import okio.Timeout;
import static retrofit2.Utils.throwIfFatal;
@@ -58,28 +59,48 @@ final class OkHttpCall<T> implements Call<T> {
}
@Override public synchronized Request request() {
- okhttp3.Call call = rawCall;
- if (call != null) {
- return call.request();
+ try {
+ return getRawCall().request();
+ } catch (IOException e) {
+ throw new RuntimeException("Unable to create request.", e);
+ }
+ }
+
+ @Override public synchronized Timeout timeout() {
+ try {
+ return getRawCall().timeout();
+ } catch (IOException e) {
+ throw new RuntimeException("Unable to create call.", e);
}
+ }
+
+ /**
+ * Returns the raw call, initializing it if necessary. Throws if initializing the raw call throws,
+ * or has thrown in previous attempts to create it.
+ */
+ @GuardedBy("this")
+ private okhttp3.Call getRawCall() throws IOException {
+ okhttp3.Call call = rawCall;
+ if (call != null) return call;
+
+ // Re-throw previous failures if this isn't the first attempt.
if (creationFailure != null) {
if (creationFailure instanceof IOException) {
- throw new RuntimeException("Unable to create request.", creationFailure);
+ throw (IOException) creationFailure;
} else if (creationFailure instanceof RuntimeException) {
throw (RuntimeException) creationFailure;
} else {
throw (Error) creationFailure;
}
}
+
+ // Create and remember either the success or the failure.
try {
- return (rawCall = createRawCall()).request();
- } catch (RuntimeException | Error e) {
+ return rawCall = createRawCall();
+ } catch (RuntimeException | Error | IOException e) {
throwIfFatal(e); // Do not assign a fatal error to creationFailure.
creationFailure = e;
throw e;
- } catch (IOException e) {
- creationFailure = e;
- throw new RuntimeException("Unable to create request.", e);
}
}
@@ -159,26 +180,7 @@ private void callFailure(Throwable e) {
if (executed) throw new IllegalStateException("Already executed.");
executed = true;
- if (creationFailure != null) {
- if (creationFailure instanceof IOException) {
- throw (IOException) creationFailure;
- } else if (creationFailure instanceof RuntimeException) {
- throw (RuntimeException) creationFailure;
- } else {
- throw (Error) creationFailure;
- }
- }
-
- call = rawCall;
- if (call == null) {
- try {
- call = rawCall = createRawCall();
- } catch (IOException | RuntimeException | Error e) {
- throwIfFatal(e); // Do not assign a fatal error to creationFailure.
- creationFailure = e;
- throw e;
- }
- }
+ call = getRawCall();
}
if (canceled) {
| diff --git a/retrofit/src/test/java/retrofit2/CallTest.java b/retrofit/src/test/java/retrofit2/CallTest.java
index f347189efe..2e13db5c66 100644
--- a/retrofit/src/test/java/retrofit2/CallTest.java
+++ b/retrofit/src/test/java/retrofit2/CallTest.java
@@ -16,9 +16,11 @@
package retrofit2;
import java.io.IOException;
+import java.io.InterruptedIOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
@@ -1248,4 +1250,58 @@ public Converter<ResponseBody, String> responseBodyConverter(Type type,
}
assertThat(writeCount.get()).isEqualTo(2);
}
+
+ @Test public void timeoutExceeded() throws IOException {
+ Retrofit retrofit = new Retrofit.Builder()
+ .baseUrl(server.url("/"))
+ .addConverterFactory(new ToStringConverterFactory())
+ .build();
+ Service example = retrofit.create(Service.class);
+
+ server.enqueue(new MockResponse()
+ .setHeadersDelay(500, TimeUnit.MILLISECONDS));
+
+ Call<String> call = example.getString();
+ call.timeout().timeout(100, TimeUnit.MILLISECONDS);
+ try {
+ call.execute();
+ fail();
+ } catch (InterruptedIOException expected) {
+ }
+ }
+
+ @Test public void deadlineExceeded() throws IOException {
+ Retrofit retrofit = new Retrofit.Builder()
+ .baseUrl(server.url("/"))
+ .addConverterFactory(new ToStringConverterFactory())
+ .build();
+ Service example = retrofit.create(Service.class);
+
+ server.enqueue(new MockResponse()
+ .setHeadersDelay(500, TimeUnit.MILLISECONDS));
+
+ Call<String> call = example.getString();
+ call.timeout().deadline(100, TimeUnit.MILLISECONDS);
+ try {
+ call.execute();
+ fail();
+ } catch (InterruptedIOException expected) {
+ }
+ }
+
+ @Test public void timeoutEnabledButNotExceeded() throws IOException {
+ Retrofit retrofit = new Retrofit.Builder()
+ .baseUrl(server.url("/"))
+ .addConverterFactory(new ToStringConverterFactory())
+ .build();
+ Service example = retrofit.create(Service.class);
+
+ server.enqueue(new MockResponse()
+ .setHeadersDelay(100, TimeUnit.MILLISECONDS));
+
+ Call<String> call = example.getString();
+ call.timeout().deadline(500, TimeUnit.MILLISECONDS);
+ Response<String> response = call.execute();
+ assertThat(response.isSuccessful()).isTrue();
+ }
}
diff --git a/retrofit/src/test/java/retrofit2/DefaultCallAdapterFactoryTest.java b/retrofit/src/test/java/retrofit2/DefaultCallAdapterFactoryTest.java
index 85182a469c..5d1e008479 100644
--- a/retrofit/src/test/java/retrofit2/DefaultCallAdapterFactoryTest.java
+++ b/retrofit/src/test/java/retrofit2/DefaultCallAdapterFactoryTest.java
@@ -22,6 +22,7 @@
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import okhttp3.Request;
+import okio.Timeout;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
@@ -130,5 +131,9 @@ static class EmptyCall implements Call<String> {
@Override public Request request() {
throw new UnsupportedOperationException();
}
+
+ @Override public Timeout timeout() {
+ return Timeout.NONE;
+ }
}
}
| test | test | 2020-03-12T19:00:27 | "2018-11-17T09:49:18Z" | meoyawn | val |
square/retrofit/3343_3344 | square/retrofit | square/retrofit/3343 | square/retrofit/3344 | [
"keyword_pr_to_issue"
] | 5876f05dd9e03cd9d073a9727c2806f65233b1c5 | 49aa9fe9ccb3addb7e4fbc17f0a96d0c584e9f6c | [
"Also worth mentioning that, the clean build didn't help, deleting the build folder inside my files didn't help.\r\n",
"Tested from Android 5.0 till 11, had to double-check and confirm that it breaks on Android 7.X and 7.X.X releases",
"The same error with Retrofit 2.8.0 on Android 7:\r\n```\r\nCaused by java.lang.NoClassDefFoundError: Failed resolution of: Ljava/lang/invoke/MethodHandles$Lookup;\r\n at retrofit2.Platform.<init> + 62(Platform.java:62)\r\n at retrofit2.Platform$Android.<init> + 115(Platform.java:115)\r\n at retrofit2.Platform.findPlatform + 44(Platform.java:44)\r\n at retrofit2.Platform.<clinit> + 34(Platform.java:34)\r\n at retrofit2.Platform.get + 37(Platform.java:37)\r\n at retrofit2.Retrofit$Builder.<init> + 430(Retrofit.java:430)\r\n at com.drakeet.purewriter.Retrofits.<clinit> + 45(Retrofits.java:45)\r\n at com.drakeet.purewriter.PureWriter$onCreate$1.run + 104(PureWriter.java:104)\r\n at io.reactivex.internal.operators.completable.CompletableFromAction.subscribeActual + 35(CompletableFromAction.java:35)\r\n at io.reactivex.Completable.subscribe + 2309(Completable.java:2309)\r\n at io.reactivex.internal.operators.completable.CompletableSubscribeOn$SubscribeOnObserver.run + 64(CompletableSubscribeOn.java:64)\r\n at io.reactivex.Scheduler$DisposeTask.run + 578(Scheduler.java:578)\r\n at io.reactivex.internal.schedulers.ScheduledRunnable.run + 66(ScheduledRunnable.java:66)\r\n at io.reactivex.internal.schedulers.ScheduledRunnable.call + 57(ScheduledRunnable.java:57)\r\n at java.util.concurrent.FutureTask.run + 237(FutureTask.java:237)\r\n at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run + 272(ScheduledThreadPoolExecutor.java:272)\r\n at java.util.concurrent.ThreadPoolExecutor.runWorker + 1133(ThreadPoolExecutor.java:1133)\r\n at java.util.concurrent.ThreadPoolExecutor$Worker.run + 607(ThreadPoolExecutor.java:607)\r\n at java.lang.Thread.run + 761(Thread.java:761)\r\n```\r\n\r\n![image](https://user-images.githubusercontent.com/5214214/77420609-51884b80-6e05-11ea-9ed6-b120b97dd798.png)\r\n\r\n@JakeWharton @swankjesse ",
"I see the same on Android 7.1.1:\r\n```\r\nFatal Exception: java.lang.NoClassDefFoundError: Failed resolution of: Ljava/lang/invoke/MethodHandles$Lookup;\r\n at retrofit2.Platform.<init>(Platform.java)\r\n at retrofit2.Platform$Android.<init>(Platform.java)\r\n at retrofit2.Platform.findPlatform(Platform.java)\r\n at retrofit2.Platform.<clinit>(Platform.java)\r\n at retrofit2.Platform.get(Platform.java)\r\n at retrofit2.Retrofit$Builder.<init>(Retrofit.java)\r\n at com.twitter.sdk.android.core.internal.oauth.OAuthService.<init>(OAuthService.java)\r\n at com.twitter.sdk.android.core.internal.oauth.OAuth2Service.<init>(OAuth2Service.java)\r\n at com.twitter.sdk.android.core.TwitterCore.createGuestSessionProvider(TwitterCore.java)\r\n at com.twitter.sdk.android.core.TwitterCore.getGuestSessionProvider(TwitterCore.java)\r\n at com.twitter.sdk.android.core.TwitterCore.addApiClient(TwitterCore.java)\r\n at com.twitter.sdk.android.core.TwitterCore.lambda$getInstance$0(TwitterCore.java)\r\n at com.twitter.sdk.android.core.-$$Lambda$TwitterCore$ltCfCYbT02qdRyGLE4y1z_Jg9Os.run(-.java)\r\n at java.util.concurrent.ThreadPoolExecutor.runWorker + 1133(ThreadPoolExecutor.java:1133)\r\n at java.util.concurrent.ThreadPoolExecutor$Worker.run + 607(ThreadPoolExecutor.java:607)\r\n at java.lang.Thread.run + 761(Thread.java:761)\r\n```",
"What is the fix for this? I've upgraded to Retrofit 2.9.0 and im still getting this crash for Android 7.X ... Using Java 1.8 and gradle plugin 3.6.1",
"> What is the fix for this? I've upgraded to Retrofit 2.9.0 and im still getting this crash for Android 7.X ... Using Java 1.8 and gradle plugin 3.6.1\r\n\r\nDid you update your retrofit adapters too?",
"> > What is the fix for this? I've upgraded to Retrofit 2.9.0 and im still getting this crash for Android 7.X ... Using Java 1.8 and gradle plugin 3.6.1\r\n> \r\n> Did you update your retrofit adapters too?\r\n\r\nI did.",
"> > > What is the fix for this? I've upgraded to Retrofit 2.9.0 and im still getting this crash for Android 7.X ... Using Java 1.8 and gradle plugin 3.6.1\r\n> > \r\n> > \r\n> > Did you update your retrofit adapters too?\r\n> \r\n> I did.\r\n\r\nI just tested it on Android 7.1.1\r\n\r\n```\r\ndef retrofit = \"2.9.0\"\r\n implementation \"com.squareup.retrofit2:converter-moshi:$retrofit\"\r\n implementation \"com.squareup.retrofit2:retrofit:$retrofit\"\r\n implementation \"com.squareup.retrofit2:adapter-rxjava3:$retrofit\"\r\n implementation \"com.squareup.retrofit2:converter-gson:$retrofit\"\r\n implementation 'com.squareup.okhttp3:logging-interceptor:4.7.2'\r\n```\r\n\r\nI didn't get any crash not with gson or rxjava3 adapter or moshi in this case\r\n\r\nTry to clean your project and re-build?\r\nInvalidate caches and restart?"
] | [
"25?"
] | "2020-03-24T20:01:54Z" | [] | Didn't find class "java.lang.invoke.MethodHandles$Lookup" | //retrofit
```
implementation 'com.squareup.retrofit2:converter-moshi:2.8.0'
implementation 'com.squareup.retrofit2:retrofit:2.8.0'
implementation 'com.squareup.retrofit2:adapter-rxjava2:2.8.0'
implementation 'com.squareup.retrofit2:converter-gson:2.8.0'
```
It doesn't work with either moshi either gson converters.
Gradle configured with
```
compileOptions {
sourceCompatibility = 1.8
targetCompatibility = 1.8
}
kotlinOptions {
jvmTarget = "1.8"
}
```
Also tried
```
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
```
What's the error?
> Caused by: java.lang.ClassNotFoundException: Didn't find class "java.lang.invoke.MethodHandles$Lookup"
It happens only on:
Android 7.0
Android 7.1.1
Android 7.1.2
Where does it print the stack trace?
https://github.com/square/retrofit/blob/master/retrofit/src/main/java/retrofit2/Platform.java
Line 62, 115, 44, 34, 37, 430
| [
"retrofit/src/main/java/retrofit2/Platform.java"
] | [
"retrofit/src/main/java/retrofit2/Platform.java"
] | [
"retrofit/src/test/java/retrofit2/DefaultMethodsAndroidTest.java",
"retrofit/src/test/java/retrofit2/DefaultMethodsTest.java"
] | diff --git a/retrofit/src/main/java/retrofit2/Platform.java b/retrofit/src/main/java/retrofit2/Platform.java
index 3da9a4d97c..edd944ad11 100644
--- a/retrofit/src/main/java/retrofit2/Platform.java
+++ b/retrofit/src/main/java/retrofit2/Platform.java
@@ -61,6 +61,9 @@ private static Platform findPlatform() {
// that ignores the visibility of the declaringClass.
lookupConstructor = Lookup.class.getDeclaredConstructor(Class.class, int.class);
lookupConstructor.setAccessible(true);
+ } catch (NoClassDefFoundError ignored) {
+ // Android API 24 or 25 where Lookup doesn't exist. Calling default methods on non-public
+ // interfaces will fail, but there's nothing we can do about it.
} catch (NoSuchMethodException ignored) {
// Assume JDK 14+ which contains a fix that allows a regular lookup to succeed.
// See https://bugs.openjdk.java.net/browse/JDK-8209005.
@@ -119,7 +122,16 @@ static final class Android extends Platform {
return new MainThreadExecutor();
}
- static class MainThreadExecutor implements Executor {
+ @Nullable @Override Object invokeDefaultMethod(Method method, Class<?> declaringClass,
+ Object object, @Nullable Object... args) throws Throwable {
+ if (Build.VERSION.SDK_INT < 26) {
+ throw new UnsupportedOperationException(
+ "Calling default methods on API 24 and 25 is not supported");
+ }
+ return super.invokeDefaultMethod(method, declaringClass, object, args);
+ }
+
+ static final class MainThreadExecutor implements Executor {
private final Handler handler = new Handler(Looper.getMainLooper());
@Override public void execute(Runnable r) {
| diff --git a/retrofit/src/test/java/retrofit2/DefaultMethodsAndroidTest.java b/retrofit/src/test/java/retrofit2/DefaultMethodsAndroidTest.java
new file mode 100644
index 0000000000..8a8357b170
--- /dev/null
+++ b/retrofit/src/test/java/retrofit2/DefaultMethodsAndroidTest.java
@@ -0,0 +1,99 @@
+/*
+ * Copyright (C) 2016 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 retrofit2;
+
+import java.io.IOException;
+import okhttp3.mockwebserver.MockResponse;
+import okhttp3.mockwebserver.MockWebServer;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.robolectric.RobolectricTestRunner;
+import org.robolectric.annotation.Config;
+import retrofit2.helpers.ToStringConverterFactory;
+import retrofit2.http.GET;
+import retrofit2.http.Query;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.Assert.fail;
+import static org.robolectric.annotation.Config.NEWEST_SDK;
+import static org.robolectric.annotation.Config.NONE;
+
+@RunWith(RobolectricTestRunner.class)
+@Config(sdk = NEWEST_SDK, manifest = NONE)
+public final class DefaultMethodsAndroidTest {
+ @Rule public final MockWebServer server = new MockWebServer();
+
+ interface Example {
+ @GET("/") Call<String> user(@Query("name") String name);
+
+ default Call<String> user() {
+ return user("hey");
+ }
+ }
+
+ @Config(sdk = 24)
+ @Test public void failsOnApi24() {
+ Retrofit retrofit = new Retrofit.Builder()
+ .baseUrl(server.url("/"))
+ .addConverterFactory(new ToStringConverterFactory())
+ .build();
+ Example example = retrofit.create(Example.class);
+
+ try {
+ example.user();
+ fail();
+ } catch (UnsupportedOperationException e) {
+ assertThat(e).hasMessage("Calling default methods on API 24 and 25 is not supported");
+ }
+ }
+
+ @Config(sdk = 25)
+ @Test public void failsOnApi25() {
+ Retrofit retrofit = new Retrofit.Builder()
+ .baseUrl(server.url("/"))
+ .addConverterFactory(new ToStringConverterFactory())
+ .build();
+ Example example = retrofit.create(Example.class);
+
+ try {
+ example.user();
+ fail();
+ } catch (UnsupportedOperationException e) {
+ assertThat(e).hasMessage("Calling default methods on API 24 and 25 is not supported");
+ }
+ }
+
+ /**
+ * Notably, this does not test that it works correctly on API 26+. Merely that the special casing
+ * of API 24/25 does not trigger.
+ */
+ @Test public void doesNotFailOnApi26() throws IOException {
+ server.enqueue(new MockResponse().setBody("Hi"));
+ server.enqueue(new MockResponse().setBody("Hi"));
+
+ Retrofit retrofit = new Retrofit.Builder()
+ .baseUrl(server.url("/"))
+ .addConverterFactory(new ToStringConverterFactory())
+ .build();
+ Example example = retrofit.create(Example.class);
+
+ Response<String> response = example.user().execute();
+ assertThat(response.body()).isEqualTo("Hi");
+ Response<String> response2 = example.user("Hi").execute();
+ assertThat(response2.body()).isEqualTo("Hi");
+ }
+}
diff --git a/retrofit/src/test/java/retrofit2/Java8DefaultMethodsTest.java b/retrofit/src/test/java/retrofit2/DefaultMethodsTest.java
similarity index 97%
rename from retrofit/src/test/java/retrofit2/Java8DefaultMethodsTest.java
rename to retrofit/src/test/java/retrofit2/DefaultMethodsTest.java
index fe101cae4b..fe01db903e 100644
--- a/retrofit/src/test/java/retrofit2/Java8DefaultMethodsTest.java
+++ b/retrofit/src/test/java/retrofit2/DefaultMethodsTest.java
@@ -26,7 +26,7 @@
import static org.assertj.core.api.Assertions.assertThat;
-public final class Java8DefaultMethodsTest {
+public final class DefaultMethodsTest {
@Rule public final MockWebServer server = new MockWebServer();
interface Example {
| train | test | 2020-03-23T19:17:52 | "2020-03-24T09:43:20Z" | FunkyMuse | val |
square/retrofit/3392_3393 | square/retrofit | square/retrofit/3392 | square/retrofit/3393 | [
"keyword_pr_to_issue"
] | c301cc8b42a7bd12c17572a716e3fc6394b95f66 | 2fe519b45d0906b1d34e991ea11d655e463044a6 | [] | [] | "2020-05-16T17:36:54Z" | [] | 2.9 snapshots ship with byte code level 58 | What kind of issue is this?
- [ ] Question. This issue tracker is not the place for questions. If you want to ask how to do
something, or to understand why something isn't working the way you expect it to, use Stack
Overflow. https://stackoverflow.com/questions/tagged/retrofit
- [x] Bug report. If you’ve found a bug, spend the time to write a failing test. Bugs with tests
get fixed. Here’s an example: https://gist.github.com/swankjesse/6608b4713ad80988cdc9
- [ ] Feature Request. Start by telling us what problem you’re trying to solve. Often a solution
already exists! Don’t send pull requests to implement new features without first getting our
support. Sometimes we leave features out on purpose to keep the project small.
```
➜ retrofit-2.8.1 javap -v retrofit2.Retrofit\$Builder|grep major
major version: 52
➜ retrofit-2.9.SNAPSPOT javap -v retrofit2.Retrofit\$Builder|grep major
major version: 58
```
Based on the ASG thread, looks like snapshots are shipping w/ Java 1.4 byte code unintentionally.
It would be nice to get them back to 52 so that i can use snapshot version :) | [
"build.gradle"
] | [
"build.gradle"
] | [] | diff --git a/build.gradle b/build.gradle
index d3dd0930dc..847eb2adc5 100644
--- a/build.gradle
+++ b/build.gradle
@@ -59,6 +59,12 @@ subprojects {
jcenter()
}
+ tasks.withType(JavaCompile).configureEach { task ->
+ task.options.encoding = 'UTF-8'
+ task.sourceCompatibility = JavaVersion.VERSION_1_8
+ task.targetCompatibility = JavaVersion.VERSION_1_8
+ }
+
// Error-prone only works on JDK 11 or older currently.
if (!Jvm.current().javaVersion.isJava12Compatible()) {
apply plugin: 'net.ltgt.errorprone'
@@ -69,10 +75,6 @@ subprojects {
}
tasks.withType(JavaCompile).configureEach { task ->
- task.options.encoding = 'UTF-8'
- task.sourceCompatibility = JavaVersion.VERSION_1_8
- task.targetCompatibility = JavaVersion.VERSION_1_8
-
task.options.errorprone {
excludedPaths = '.*/build/generated/source/proto/.*'
check('MissingFail', CheckSeverity.ERROR)
| null | train | test | 2020-05-16T04:38:35 | "2020-05-16T17:27:21Z" | yigit | val |
square/retrofit/3389_3394 | square/retrofit | square/retrofit/3389 | square/retrofit/3394 | [
"keyword_pr_to_issue"
] | 2fe519b45d0906b1d34e991ea11d655e463044a6 | 8e3843137902997c087bb62683a39e3bd21b1a58 | [
"Also, seems like this error surfaced before but I was not seeing it until 4.1.\r\nhttps://github.com/Microsoft/azure-tools-for-java/issues/363",
"😬 \r\n\r\nPresumably this is for layoutlib support? Sucks that it's not isolated into a classloader.\r\n\r\nRelated: #2102.",
"bug on studio:\r\nhttps://issuetracker.google.com/issues/156312959\r\n\r\nThis also seems to effect okhttp :( If there is some workaround, I would appreciate but i couldn't find since it runs on class initialization."
] | [] | "2020-05-17T21:11:03Z" | [] | Platform detection fails in Android Studio 4.1 Canary 8 | What kind of issue is this?
- [ ] Question. This issue tracker is not the place for questions. If you want to ask how to do
something, or to understand why something isn't working the way you expect it to, use Stack
Overflow. https://stackoverflow.com/questions/tagged/retrofit
- [x] Bug report. If you’ve found a bug, spend the time to write a failing test. Bugs with tests
get fixed. Here’s an example: https://gist.github.com/swankjesse/6608b4713ad80988cdc9
- [ ] Feature Request. Start by telling us what problem you’re trying to solve. Often a solution
already exists! Don’t send pull requests to implement new features without first getting our
support. Sometimes we leave features out on purpose to keep the project small.
I have an IntelliJ plugin that started crashing in AndroidStudio Canary 4.1.
full exception:
https://github.com/yigit/ArtifactFinder/issues/16
Seems like in 4.1, `Class.forName("android.os.Build") does not fail anymore and then eventually causes a different exception:
https://github.com/square/retrofit/blob/master/retrofit/src/main/java/retrofit2/Platform.java#L43
```
java.lang.UnsatisfiedLinkError: android.os.SystemProperties.native_get(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;
at android.os.SystemProperties.native_get(Native Method)
at android.os.SystemProperties.get(SystemProperties.java:129)
at android.os._Original_Build.getString(Build.java:1265)
at android.os._Original_Build.<clinit>(Build.java:51)
at android.os._Original_Build$VERSION.<clinit>(Build.java:229)
at android.os.Build$VERSION.<clinit>(Build.java:21)
at retrofit2.Platform.findPlatform(Platform.java:43)
```
I'm not sure why that class is available in studio but seems like detecting android platform based on the existence of that class is no more appropriate.
| [
"build.gradle"
] | [
"build.gradle"
] | [] | diff --git a/build.gradle b/build.gradle
index 847eb2adc5..ac2120773e 100644
--- a/build.gradle
+++ b/build.gradle
@@ -4,7 +4,7 @@ import org.gradle.internal.jvm.Jvm
buildscript {
ext.versions = [
'kotlin': '1.3.50',
- 'okhttp': '3.14.7',
+ 'okhttp': '3.14.9',
'protobuf': '3.10.0',
'jaxb': '2.3.1',
]
| null | train | test | 2020-05-16T19:52:23 | "2020-05-12T01:54:02Z" | yigit | val |
square/retrofit/3403_3411 | square/retrofit | square/retrofit/3403 | square/retrofit/3411 | [
"keyword_pr_to_issue"
] | 0e453000220e13d98979444dc452fd8ab1ee13ad | 921de4a239c100009d744009e2368092942fb13b | [
"Now standard Jackson binary format backends contains avro, cbor, protobuf and smile,the `JacksonConverterFactory ` can switch to binary format when the `ObjectMapper` support binary format data.please make a pull request.",
"Eclipse didn't like the project for some reason. I don't have time to investigate it right now. Anyone with working build/tests should have easy time implementing this.\r\n\r\nIn [JacksonResponseBodyConverter](https://github.com/square/retrofit/blob/master/retrofit-converters/jackson/src/main/java/retrofit2/converter/jackson/JacksonResponseBodyConverter.java), replace `value.charStream()` with `value.byteStream()`.\r\n\r\nIn [JacksonRequestBodyConverter](https://github.com/square/retrofit/blob/master/retrofit-converters/jackson/src/main/java/retrofit2/converter/jackson/JacksonRequestBodyConverter.java), turn `MEDIA_TYPE` into configurable parameter (passed from [JacksonConverterFactory](https://github.com/square/retrofit/blob/master/retrofit-converters/jackson/src/main/java/retrofit2/converter/jackson/JacksonConverterFactory.java)).\r\n\r\nAnd perhaps add a test case in [JacksonConverterFactoryTest](https://github.com/square/retrofit/blob/master/retrofit-converters/jackson/src/test/java/retrofit2/converter/jackson/JacksonConverterFactoryTest.java)."
] | [] | "2020-06-02T10:36:47Z" | [] | Support CBOR in JacksonConverterFactory | I am using [CBOR](http://cbor.io/) for request/response encoding. I am creating Jackson `ObjectMapper` with `CBORFactory` like this:
```java
ObjectMapper mapper = new ObjectMapper(new CBORFactory())
.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
```
I then tried to use the existing `JacksonConverterFactory` like this:
```java
Retrofit retrofit = new Retrofit.Builder()
.client(client)
.baseUrl("http://" + host + ":" + port + "/")
.addConverterFactory(JacksonConverterFactory.create(mapper))
.build();
```
But this failed with an exception, because `JacksonConverterFactory` insists on reading/writing documents as text while CBOR requires binary I/O.
I have implemented custom converter as a workaround. It would be nice to have CBOR supported simply by passing in custom `ObjectMapper`. Switching to binary I/O should have no negative impact on JSON serialization AFAIK. | [
"gradle/libs.versions.toml",
"retrofit-converters/jackson/build.gradle",
"retrofit-converters/jackson/src/main/java/retrofit2/converter/jackson/JacksonConverterFactory.java",
"retrofit-converters/jackson/src/main/java/retrofit2/converter/jackson/JacksonRequestBodyConverter.java",
"retrofit-converters/jackson/src/main/java/retrofit2/converter/jackson/JacksonResponseBodyConverter.java"
] | [
"gradle/libs.versions.toml",
"retrofit-converters/jackson/build.gradle",
"retrofit-converters/jackson/src/main/java/retrofit2/converter/jackson/JacksonConverterFactory.java",
"retrofit-converters/jackson/src/main/java/retrofit2/converter/jackson/JacksonRequestBodyConverter.java",
"retrofit-converters/jackson/src/main/java/retrofit2/converter/jackson/JacksonResponseBodyConverter.java"
] | [
"retrofit-converters/jackson/src/test/java/retrofit2/converter/jackson/JacksonCborConverterFactoryTest.java"
] | diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml
index 7dcf136962..7718c6b32b 100644
--- a/gradle/libs.versions.toml
+++ b/gradle/libs.versions.toml
@@ -20,6 +20,7 @@ robovm = "2.3.14"
kotlinx-serialization = "1.6.3"
autoService = "1.1.1"
incap = "1.0.0"
+jackson = "2.16.1"
[libraries]
androidPlugin = { module = "com.android.tools.build:gradle", version = "8.2.2" }
@@ -67,7 +68,8 @@ rxjava3 = { module = "io.reactivex.rxjava3:rxjava", version = "3.1.8" }
reactiveStreams = { module = "org.reactivestreams:reactive-streams", version = "1.0.4" }
scalaLibrary = { module = "org.scala-lang:scala-library", version = "2.13.12" }
gson = { module = "com.google.code.gson:gson", version = "2.10.1" }
-jacksonDatabind = { module = "com.fasterxml.jackson.core:jackson-databind", version = "2.16.1" }
+jacksonDatabind = { module = "com.fasterxml.jackson.core:jackson-databind", version.ref = "jackson" }
+jacksonDataformatCbor = { module = "com.fasterxml.jackson.dataformat:jackson-dataformat-cbor", version.ref = "jackson" }
jaxbApi = { module = "javax.xml.bind:jaxb-api", version = "2.3.1" }
jaxbImpl = { module = "org.glassfish.jaxb:jaxb-runtime", version = "4.0.4" }
jaxb3Api = { module = "jakarta.xml.bind:jakarta.xml.bind-api", version = "3.0.1" }
diff --git a/retrofit-converters/jackson/build.gradle b/retrofit-converters/jackson/build.gradle
index 1c6f7ec5bd..cbb4f49a3f 100644
--- a/retrofit-converters/jackson/build.gradle
+++ b/retrofit-converters/jackson/build.gradle
@@ -9,6 +9,7 @@ dependencies {
testImplementation libs.junit
testImplementation libs.truth
testImplementation libs.mockwebserver
+ testImplementation libs.jacksonDataformatCbor
}
jar {
diff --git a/retrofit-converters/jackson/src/main/java/retrofit2/converter/jackson/JacksonConverterFactory.java b/retrofit-converters/jackson/src/main/java/retrofit2/converter/jackson/JacksonConverterFactory.java
index afe395233f..0bf0b13556 100644
--- a/retrofit-converters/jackson/src/main/java/retrofit2/converter/jackson/JacksonConverterFactory.java
+++ b/retrofit-converters/jackson/src/main/java/retrofit2/converter/jackson/JacksonConverterFactory.java
@@ -21,6 +21,7 @@
import com.fasterxml.jackson.databind.ObjectWriter;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
+import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Converter;
@@ -35,22 +36,33 @@
* instance} last to allow the other converters a chance to see their types.
*/
public final class JacksonConverterFactory extends Converter.Factory {
+ private static final MediaType DEFAULT_MEDIA_TYPE =
+ MediaType.get("application/json; charset=UTF-8");
+
/** Create an instance using a default {@link ObjectMapper} instance for conversion. */
public static JacksonConverterFactory create() {
- return create(new ObjectMapper());
+ return new JacksonConverterFactory(new ObjectMapper(), DEFAULT_MEDIA_TYPE);
}
/** Create an instance using {@code mapper} for conversion. */
- @SuppressWarnings("ConstantConditions") // Guarding public API nullability.
public static JacksonConverterFactory create(ObjectMapper mapper) {
+ return create(mapper, DEFAULT_MEDIA_TYPE);
+ }
+
+ /** Create an instance using {@code mapper} and {@code mediaType} for conversion. */
+ @SuppressWarnings("ConstantConditions") // Guarding public API nullability.
+ public static JacksonConverterFactory create(ObjectMapper mapper, MediaType mediaType) {
if (mapper == null) throw new NullPointerException("mapper == null");
- return new JacksonConverterFactory(mapper);
+ if (mediaType == null) throw new NullPointerException("mediaType == null");
+ return new JacksonConverterFactory(mapper, mediaType);
}
private final ObjectMapper mapper;
+ private final MediaType mediaType;
- private JacksonConverterFactory(ObjectMapper mapper) {
+ private JacksonConverterFactory(ObjectMapper mapper, MediaType mediaType) {
this.mapper = mapper;
+ this.mediaType = mediaType;
}
@Override
@@ -69,6 +81,6 @@ public Converter<?, RequestBody> requestBodyConverter(
Retrofit retrofit) {
JavaType javaType = mapper.getTypeFactory().constructType(type);
ObjectWriter writer = mapper.writerFor(javaType);
- return new JacksonRequestBodyConverter<>(writer);
+ return new JacksonRequestBodyConverter<>(writer, mediaType);
}
}
diff --git a/retrofit-converters/jackson/src/main/java/retrofit2/converter/jackson/JacksonRequestBodyConverter.java b/retrofit-converters/jackson/src/main/java/retrofit2/converter/jackson/JacksonRequestBodyConverter.java
index 257067675a..fb1ceb74b7 100644
--- a/retrofit-converters/jackson/src/main/java/retrofit2/converter/jackson/JacksonRequestBodyConverter.java
+++ b/retrofit-converters/jackson/src/main/java/retrofit2/converter/jackson/JacksonRequestBodyConverter.java
@@ -22,17 +22,17 @@
import retrofit2.Converter;
final class JacksonRequestBodyConverter<T> implements Converter<T, RequestBody> {
- private static final MediaType MEDIA_TYPE = MediaType.get("application/json; charset=UTF-8");
-
private final ObjectWriter adapter;
+ private final MediaType mediaType;
- JacksonRequestBodyConverter(ObjectWriter adapter) {
+ JacksonRequestBodyConverter(ObjectWriter adapter, MediaType mediaType) {
this.adapter = adapter;
+ this.mediaType = mediaType;
}
@Override
public RequestBody convert(T value) throws IOException {
byte[] bytes = adapter.writeValueAsBytes(value);
- return RequestBody.create(MEDIA_TYPE, bytes);
+ return RequestBody.create(mediaType, bytes);
}
}
diff --git a/retrofit-converters/jackson/src/main/java/retrofit2/converter/jackson/JacksonResponseBodyConverter.java b/retrofit-converters/jackson/src/main/java/retrofit2/converter/jackson/JacksonResponseBodyConverter.java
index 0e733b35f0..0e8826e4f5 100644
--- a/retrofit-converters/jackson/src/main/java/retrofit2/converter/jackson/JacksonResponseBodyConverter.java
+++ b/retrofit-converters/jackson/src/main/java/retrofit2/converter/jackson/JacksonResponseBodyConverter.java
@@ -30,7 +30,7 @@ final class JacksonResponseBodyConverter<T> implements Converter<ResponseBody, T
@Override
public T convert(ResponseBody value) throws IOException {
try {
- return adapter.readValue(value.charStream());
+ return adapter.readValue(value.byteStream());
} finally {
value.close();
}
| diff --git a/retrofit-converters/jackson/src/test/java/retrofit2/converter/jackson/JacksonCborConverterFactoryTest.java b/retrofit-converters/jackson/src/test/java/retrofit2/converter/jackson/JacksonCborConverterFactoryTest.java
new file mode 100644
index 0000000000..66debe4dec
--- /dev/null
+++ b/retrofit-converters/jackson/src/test/java/retrofit2/converter/jackson/JacksonCborConverterFactoryTest.java
@@ -0,0 +1,83 @@
+/*
+ * Copyright (C) 2024 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 retrofit2.converter.jackson;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import com.fasterxml.jackson.dataformat.cbor.databind.CBORMapper;
+import java.io.IOException;
+import okhttp3.MediaType;
+import okhttp3.mockwebserver.MockResponse;
+import okhttp3.mockwebserver.MockWebServer;
+import okhttp3.mockwebserver.RecordedRequest;
+import okio.Buffer;
+import okio.ByteString;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import retrofit2.Call;
+import retrofit2.Response;
+import retrofit2.Retrofit;
+import retrofit2.http.Body;
+import retrofit2.http.POST;
+
+public class JacksonCborConverterFactoryTest {
+ static class IntWrapper {
+ public int value;
+
+ public IntWrapper(int v) {
+ value = v;
+ }
+
+ protected IntWrapper() {}
+ }
+
+ interface Service {
+ @POST("/")
+ Call<IntWrapper> post(@Body IntWrapper person);
+ }
+
+ @Rule public final MockWebServer server = new MockWebServer();
+
+ private Service service;
+
+ @Before
+ public void setUp() {
+ Retrofit retrofit =
+ new Retrofit.Builder()
+ .baseUrl(server.url("/"))
+ .addConverterFactory(
+ JacksonConverterFactory.create(new CBORMapper(), MediaType.get("application/cbor")))
+ .build();
+ service = retrofit.create(Service.class);
+ }
+
+ @Test
+ public void post() throws IOException, InterruptedException {
+ server.enqueue(
+ new MockResponse()
+ .setBody(new Buffer().write(ByteString.decodeHex("bf6576616c7565182aff"))));
+
+ Call<IntWrapper> call = service.post(new IntWrapper(12));
+ Response<IntWrapper> response = call.execute();
+ assertThat(response.body().value).isEqualTo(42);
+
+ RecordedRequest request = server.takeRequest();
+ assertThat(request.getBody().readByteString())
+ .isEqualTo(ByteString.decodeHex("bf6576616c75650cff"));
+ assertThat(request.getHeader("Content-Type")).isEqualTo("application/cbor");
+ }
+}
| train | test | 2024-02-21T05:18:50 | "2020-05-27T17:57:56Z" | robertvazan | val |
square/retrofit/3714_3715 | square/retrofit | square/retrofit/3714 | square/retrofit/3715 | [
"keyword_pr_to_issue"
] | 00ff27e6e1bee48774e80779052a62595da2d308 | 4910b3c5118e899f94ddcb53abed2315c17e16e2 | [] | [
"Our version of Kotlin is old enough that the stdlib isn't added by default. This is a hedge against future upgrades."
] | "2022-03-30T03:32:40Z" | [] | Run non-Kotlin tests in JVM without Kotlin stdlib/coroutines | This is already needed for our limited Kotlin support, but as it grows having all codepaths covered in a VM where the types are not present will be important.
Refs #3702 | [
"retrofit/build.gradle",
"retrofit/gradle.properties",
"settings.gradle"
] | [
"retrofit/build.gradle",
"retrofit/gradle.properties",
"settings.gradle"
] | [
"retrofit/kotlin-test/build.gradle",
"retrofit/kotlin-test/src/test/java/retrofit2/KotlinUnitTest.java"
] | diff --git a/retrofit/build.gradle b/retrofit/build.gradle
index 83acc0c330..8d425cf80a 100644
--- a/retrofit/build.gradle
+++ b/retrofit/build.gradle
@@ -17,8 +17,6 @@ dependencies {
testImplementation libs.assertj
testImplementation libs.guava
testImplementation libs.mockwebserver
- testImplementation libs.kotlinStdLib
- testImplementation libs.kotlinCoroutines
}
jar {
diff --git a/retrofit/gradle.properties b/retrofit/gradle.properties
index 774fe0fe97..f018996fb2 100644
--- a/retrofit/gradle.properties
+++ b/retrofit/gradle.properties
@@ -1,3 +1,5 @@
POM_ARTIFACT_ID=retrofit
POM_NAME=Retrofit
POM_DESCRIPTION=A type-safe HTTP client for Android and Java.
+
+kotlin.stdlib.default.dependency=false
diff --git a/settings.gradle b/settings.gradle
index f9c04c9998..efd5ab00ee 100644
--- a/settings.gradle
+++ b/settings.gradle
@@ -2,6 +2,7 @@ rootProject.name = 'retrofit-root'
include ':retrofit'
include ':retrofit:android-test'
+include ':retrofit:kotlin-test'
include ':retrofit:robovm-test'
include ':retrofit:test-helpers'
| diff --git a/retrofit/kotlin-test/build.gradle b/retrofit/kotlin-test/build.gradle
new file mode 100644
index 0000000000..b39ed4e17c
--- /dev/null
+++ b/retrofit/kotlin-test/build.gradle
@@ -0,0 +1,11 @@
+apply plugin: 'org.jetbrains.kotlin.jvm'
+
+dependencies {
+ testImplementation projects.retrofit
+ testImplementation projects.retrofit.testHelpers
+ testImplementation libs.junit
+ testImplementation libs.assertj
+ testImplementation libs.mockwebserver
+ testImplementation libs.kotlinStdLib
+ testImplementation libs.kotlinCoroutines
+}
diff --git a/retrofit/src/test/java/retrofit2/KotlinUnitTest.java b/retrofit/kotlin-test/src/test/java/retrofit2/KotlinUnitTest.java
similarity index 89%
rename from retrofit/src/test/java/retrofit2/KotlinUnitTest.java
rename to retrofit/kotlin-test/src/test/java/retrofit2/KotlinUnitTest.java
index 74216fe867..389441b166 100644
--- a/retrofit/src/test/java/retrofit2/KotlinUnitTest.java
+++ b/retrofit/kotlin-test/src/test/java/retrofit2/KotlinUnitTest.java
@@ -21,7 +21,6 @@
import kotlin.Unit;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
-import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import retrofit2.http.GET;
@@ -45,8 +44,4 @@ public void unitOnClasspath() throws IOException {
assertThat(response.isSuccessful()).isTrue();
assertThat(response.body()).isSameAs(Unit.INSTANCE);
}
-
- @Ignore("This is implicitly tested by integration tests of the adapters and converters")
- @Test
- public void unitMissingFromClasspath() {}
}
| train | test | 2022-03-30T09:26:27 | "2022-03-29T19:34:52Z" | JakeWharton | val |
square/retrofit/3691_3726 | square/retrofit | square/retrofit/3691 | square/retrofit/3726 | [
"keyword_pr_to_issue"
] | bcb7a72156ca81bba16f37e1413835e0c891b4ea | 6cd6f7d8287f73909614cb7300fcde05f5719750 | [
"You should never depend on Retrofit to provide a version of a library. Declare a sibling dependency on Gson with the version you desire and your build system will ensure the newer of the two is used. We also never make Retrofit releases simply to expose updated versions of our transitive dependencies."
] | [] | "2022-04-28T06:57:55Z" | [
"PR welcome"
] | Gson library has new version | Google has released an update regarding the gson library showing integers sometimes as decimals. I request this update to be imported | [
"gradle/libs.versions.toml"
] | [
"gradle/libs.versions.toml"
] | [] | diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml
index 350e2932c4..e20fbdbb37 100644
--- a/gradle/libs.versions.toml
+++ b/gradle/libs.versions.toml
@@ -48,7 +48,7 @@ rxjava2 = { module = "io.reactivex.rxjava2:rxjava", version = "2.2.21" }
rxjava3 = { module = "io.reactivex.rxjava3:rxjava", version = "3.1.1" }
reactiveStreams = { module = "org.reactivestreams:reactive-streams", version = "1.0.3" }
scalaLibrary = { module = "org.scala-lang:scala-library", version = "2.13.6" }
-gson = { module = "com.google.code.gson:gson", version = "2.8.9" }
+gson = { module = "com.google.code.gson:gson", version = "2.9.0" }
jacksonDatabind = { module = "com.fasterxml.jackson.core:jackson-databind", version = "2.12.4" }
jaxbApi = { module = "javax.xml.bind:jaxb-api", version.ref = "jaxb" }
jaxbImpl = { module = "org.glassfish.jaxb:jaxb-runtime", version.ref = "jaxb" }
| null | val | test | 2022-04-24T14:17:03 | "2022-02-10T14:24:18Z" | Bilecen | val |
square/retrofit/3730_3744 | square/retrofit | square/retrofit/3730 | square/retrofit/3744 | [
"keyword_pr_to_issue"
] | 27a9c5d41534ae825fca96320af52598376860ec | 0e453000220e13d98979444dc452fd8ab1ee13ad | [
"Are you asking for the actual instance or just the service class?",
"I am asking for the actual instance 🤔 (then the real service class can be deduced)",
"This is really easy to add, but I just want to make sure I understand completely what you want so I can try to balance it with any and all other options we have.\r\n\r\nSo are you basically would unsafe cast back to the `Sub` type in order to call this fallback function?",
"In my case, it would be called via reflection on the instance, but some other integration would require an unsafe cast, yes.",
"I think we'll add both the class and the instance.",
"soft bump ⬆️ @JakeWharton 😅",
"Just ran into another use case for this! This time for distinguishing the correct \"api\" subclass."
] | [
"Trying to maintain binary compatibility for anyone using this method by approximating the service class as `method.declaringClass` and instance as `null`.\r\n\r\nWould love to know if this is good enough or if its okay to break compatibility.",
"Didn't see another way of maintaining compatibility than making the `instance` nullable"
] | "2022-06-01T14:55:33Z" | [
"Enhancement",
"PR welcome"
] | Add Service instance to `Invocation` | What kind of issue is this?
- [ ] Question. This issue tracker is not the place for questions. If you want to ask how to do
something, or to understand why something isn't working the way you expect it to, use Stack
Overflow. https://stackoverflow.com/questions/tagged/retrofit
- [ ] Bug report. If you’ve found a bug, spend the time to write a failing test. Bugs with tests
get fixed. Here’s an example: https://gist.github.com/swankjesse/6608b4713ad80988cdc9
- [x] Feature Request. Start by telling us what problem you’re trying to solve. Often a solution
already exists! Don’t send pull requests to implement new features without first getting our
support. Sometimes we leave features out on purpose to keep the project small.
Since Retrofit supports service interface hierarchies, the `method()` & `arguments()` of the `Invocation` are no more sufficient to distinguish the invocation. A method might be declared in a super class with Retrofit annotations but the subclass is the interface which gets created.
```kt
interface Super {
@GET("/super") fun getSuper()
}
// This interface gets instantiated via Retrofit.create(Sub::class)
interface Sub: Super {
fun getSuperFallback(error: Throwable) { ... }
}
```
The primary use case right now is to be able to support/implement Resilience4j's CircuitBreaker fallback mechanism but there are [other library use cases](https://github.com/LianjiaTech/retrofit-spring-boot-starter/issues/109) and it might open the door to many others. | [
"retrofit/src/main/java/retrofit2/HttpServiceMethod.java",
"retrofit/src/main/java/retrofit2/Invocation.java",
"retrofit/src/main/java/retrofit2/KotlinExtensions.kt",
"retrofit/src/main/java/retrofit2/OkHttpCall.java",
"retrofit/src/main/java/retrofit2/RequestFactory.java",
"retrofit/src/main/java/retrofit2/Retrofit.java",
"retrofit/src/main/java/retrofit2/ServiceMethod.java",
"samples/src/main/java/com/example/retrofit/ErrorHandlingAdapter.java",
"samples/src/main/java/com/example/retrofit/InvocationMetrics.java"
] | [
"retrofit/src/main/java/retrofit2/HttpServiceMethod.java",
"retrofit/src/main/java/retrofit2/Invocation.java",
"retrofit/src/main/java/retrofit2/KotlinExtensions.kt",
"retrofit/src/main/java/retrofit2/OkHttpCall.java",
"retrofit/src/main/java/retrofit2/RequestFactory.java",
"retrofit/src/main/java/retrofit2/Retrofit.java",
"retrofit/src/main/java/retrofit2/ServiceMethod.java",
"samples/src/main/java/com/example/retrofit/ErrorHandlingAdapter.java",
"samples/src/main/java/com/example/retrofit/InvocationMetrics.java"
] | [
"retrofit/java-test/src/test/java/retrofit2/InvocationTest.java",
"retrofit/test-helpers/src/main/java/retrofit2/TestingUtils.java"
] | diff --git a/retrofit/src/main/java/retrofit2/HttpServiceMethod.java b/retrofit/src/main/java/retrofit2/HttpServiceMethod.java
index 38b7318a57..d285c0ae31 100644
--- a/retrofit/src/main/java/retrofit2/HttpServiceMethod.java
+++ b/retrofit/src/main/java/retrofit2/HttpServiceMethod.java
@@ -154,8 +154,9 @@ private static <ResponseT> Converter<ResponseBody, ResponseT> createResponseConv
}
@Override
- final @Nullable ReturnT invoke(Object[] args) {
- Call<ResponseT> call = new OkHttpCall<>(requestFactory, args, callFactory, responseConverter);
+ final @Nullable ReturnT invoke(Object instance, Object[] args) {
+ Call<ResponseT> call =
+ new OkHttpCall<>(requestFactory, instance, args, callFactory, responseConverter);
return adapt(call, args);
}
diff --git a/retrofit/src/main/java/retrofit2/Invocation.java b/retrofit/src/main/java/retrofit2/Invocation.java
index 84e50e089f..cd6d7a72f2 100644
--- a/retrofit/src/main/java/retrofit2/Invocation.java
+++ b/retrofit/src/main/java/retrofit2/Invocation.java
@@ -20,6 +20,7 @@
import java.util.Collections;
import java.util.List;
import java.util.Objects;
+import javax.annotation.Nullable;
/**
* A single invocation of a Retrofit service interface method. This class captures both the method
@@ -35,8 +36,9 @@
* Invocation invocation = request.tag(Invocation.class);
* if (invocation != null) {
* System.out.printf("%s.%s %s%n",
- * invocation.method().getDeclaringClass().getSimpleName(),
- * invocation.method().getName(), invocation.arguments());
+ * invocation.service().getSimpleName(),
+ * invocation.method().getName(),
+ * invocation.arguments());
* }
* return chain.proceed(request);
* }
@@ -49,21 +51,50 @@
* types for parameters!
*/
public final class Invocation {
+ public static <T> Invocation of(Class<T> service, T instance, Method method, List<?> arguments) {
+ Objects.requireNonNull(service, "service == null");
+ Objects.requireNonNull(instance, "instance == null");
+ Objects.requireNonNull(method, "method == null");
+ Objects.requireNonNull(arguments, "arguments == null");
+ return new Invocation(service, instance, method, new ArrayList<>(arguments)); // Defensive copy.
+ }
+
+ @Deprecated
public static Invocation of(Method method, List<?> arguments) {
Objects.requireNonNull(method, "method == null");
Objects.requireNonNull(arguments, "arguments == null");
- return new Invocation(method, new ArrayList<>(arguments)); // Defensive copy.
+ return new Invocation(
+ method.getDeclaringClass(), null, method, new ArrayList<>(arguments)); // Defensive copy.
}
+ private final Class<?> service;
+ @Nullable private final Object instance;
private final Method method;
private final List<?> arguments;
/** Trusted constructor assumes ownership of {@code arguments}. */
- Invocation(Method method, List<?> arguments) {
+ Invocation(Class<?> service, @Nullable Object instance, Method method, List<?> arguments) {
+ this.service = service;
+ this.instance = instance;
this.method = method;
this.arguments = Collections.unmodifiableList(arguments);
}
+ public Class<?> service() {
+ return service;
+ }
+
+ /**
+ * The instance of {@link #service}.
+ * <p>
+ * This will never be null when created by Retrofit. Null will only be returned when created
+ * by {@link #of(Method, List)}.
+ */
+ @Nullable
+ public Object instance() {
+ return instance;
+ }
+
public Method method() {
return method;
}
@@ -74,7 +105,6 @@ public List<?> arguments() {
@Override
public String toString() {
- return String.format(
- "%s.%s() %s", method.getDeclaringClass().getName(), method.getName(), arguments);
+ return String.format("%s.%s() %s", service.getName(), method.getName(), arguments);
}
}
diff --git a/retrofit/src/main/java/retrofit2/KotlinExtensions.kt b/retrofit/src/main/java/retrofit2/KotlinExtensions.kt
index 09b81b2628..2444c883ca 100644
--- a/retrofit/src/main/java/retrofit2/KotlinExtensions.kt
+++ b/retrofit/src/main/java/retrofit2/KotlinExtensions.kt
@@ -39,9 +39,10 @@ suspend fun <T : Any> Call<T>.await(): T {
val body = response.body()
if (body == null) {
val invocation = call.request().tag(Invocation::class.java)!!
+ val service = invocation.service()
val method = invocation.method()
val e = KotlinNullPointerException(
- "Response from ${method.declaringClass.name}.${method.name}" +
+ "Response from ${service.name}.${method.name}" +
" was null but response body type was declared as non-null",
)
continuation.resumeWithException(e)
diff --git a/retrofit/src/main/java/retrofit2/OkHttpCall.java b/retrofit/src/main/java/retrofit2/OkHttpCall.java
index 14c53521f7..ff67612263 100644
--- a/retrofit/src/main/java/retrofit2/OkHttpCall.java
+++ b/retrofit/src/main/java/retrofit2/OkHttpCall.java
@@ -32,6 +32,7 @@
final class OkHttpCall<T> implements Call<T> {
private final RequestFactory requestFactory;
+ private final Object instance;
private final Object[] args;
private final okhttp3.Call.Factory callFactory;
private final Converter<ResponseBody, T> responseConverter;
@@ -49,10 +50,12 @@ final class OkHttpCall<T> implements Call<T> {
OkHttpCall(
RequestFactory requestFactory,
+ Object instance,
Object[] args,
okhttp3.Call.Factory callFactory,
Converter<ResponseBody, T> responseConverter) {
this.requestFactory = requestFactory;
+ this.instance = instance;
this.args = args;
this.callFactory = callFactory;
this.responseConverter = responseConverter;
@@ -61,7 +64,7 @@ final class OkHttpCall<T> implements Call<T> {
@SuppressWarnings("CloneDoesntCallSuperClone") // We are a final type & this saves clearing state.
@Override
public OkHttpCall<T> clone() {
- return new OkHttpCall<>(requestFactory, args, callFactory, responseConverter);
+ return new OkHttpCall<>(requestFactory, instance, args, callFactory, responseConverter);
}
@Override
@@ -205,7 +208,7 @@ public Response<T> execute() throws IOException {
}
private okhttp3.Call createRawCall() throws IOException {
- okhttp3.Call call = callFactory.newCall(requestFactory.create(args));
+ okhttp3.Call call = callFactory.newCall(requestFactory.create(instance, args));
if (call == null) {
throw new NullPointerException("Call.Factory returned null.");
}
diff --git a/retrofit/src/main/java/retrofit2/RequestFactory.java b/retrofit/src/main/java/retrofit2/RequestFactory.java
index 52a4b1e6f0..6a30a99190 100644
--- a/retrofit/src/main/java/retrofit2/RequestFactory.java
+++ b/retrofit/src/main/java/retrofit2/RequestFactory.java
@@ -63,10 +63,11 @@
import retrofit2.http.Url;
final class RequestFactory {
- static RequestFactory parseAnnotations(Retrofit retrofit, Method method) {
- return new Builder(retrofit, method).build();
+ static RequestFactory parseAnnotations(Retrofit retrofit, Class<?> service, Method method) {
+ return new Builder(retrofit, service, method).build();
}
+ private final Class<?> service;
private final Method method;
private final HttpUrl baseUrl;
final String httpMethod;
@@ -80,6 +81,7 @@ static RequestFactory parseAnnotations(Retrofit retrofit, Method method) {
final boolean isKotlinSuspendFunction;
RequestFactory(Builder builder) {
+ service = builder.service;
method = builder.method;
baseUrl = builder.retrofit.baseUrl;
httpMethod = builder.httpMethod;
@@ -93,7 +95,7 @@ static RequestFactory parseAnnotations(Retrofit retrofit, Method method) {
isKotlinSuspendFunction = builder.isKotlinSuspendFunction;
}
- okhttp3.Request create(Object[] args) throws IOException {
+ okhttp3.Request create(@Nullable Object instance, Object[] args) throws IOException {
@SuppressWarnings("unchecked") // It is an error to invoke a method with the wrong arg types.
ParameterHandler<Object>[] handlers = (ParameterHandler<Object>[]) parameterHandlers;
@@ -129,7 +131,10 @@ okhttp3.Request create(Object[] args) throws IOException {
handlers[p].apply(requestBuilder, args[p]);
}
- return requestBuilder.get().tag(Invocation.class, new Invocation(method, argumentList)).build();
+ return requestBuilder
+ .get()
+ .tag(Invocation.class, new Invocation(service, instance, method, argumentList))
+ .build();
}
/**
@@ -144,6 +149,7 @@ static final class Builder {
private static final Pattern PARAM_NAME_REGEX = Pattern.compile(PARAM);
final Retrofit retrofit;
+ final Class<?> service;
final Method method;
final Annotation[] methodAnnotations;
final Annotation[][] parameterAnnotationsArray;
@@ -168,8 +174,9 @@ static final class Builder {
@Nullable ParameterHandler<?>[] parameterHandlers;
boolean isKotlinSuspendFunction;
- Builder(Retrofit retrofit, Method method) {
+ Builder(Retrofit retrofit, Class<?> service, Method method) {
this.retrofit = retrofit;
+ this.service = service;
this.method = method;
this.methodAnnotations = method.getAnnotations();
this.parameterTypes = method.getGenericParameterTypes();
diff --git a/retrofit/src/main/java/retrofit2/Retrofit.java b/retrofit/src/main/java/retrofit2/Retrofit.java
index a2b68f4d6d..c66f821251 100644
--- a/retrofit/src/main/java/retrofit2/Retrofit.java
+++ b/retrofit/src/main/java/retrofit2/Retrofit.java
@@ -174,7 +174,7 @@ public <T> T create(final Class<T> service) {
Reflection reflection = Platform.reflection;
return reflection.isDefaultMethod(method)
? reflection.invokeDefaultMethod(method, service, proxy, args)
- : loadServiceMethod(method).invoke(args);
+ : loadServiceMethod(service, method).invoke(proxy, args);
}
});
}
@@ -205,13 +205,13 @@ private void validateServiceInterface(Class<?> service) {
if (!reflection.isDefaultMethod(method)
&& !Modifier.isStatic(method.getModifiers())
&& !method.isSynthetic()) {
- loadServiceMethod(method);
+ loadServiceMethod(service, method);
}
}
}
}
- ServiceMethod<?> loadServiceMethod(Method method) {
+ ServiceMethod<?> loadServiceMethod(Class<?> service, Method method) {
// Note: Once we are minSdk 24 this whole method can be replaced by computeIfAbsent.
Object lookup = serviceMethodCache.get(method);
@@ -229,7 +229,7 @@ ServiceMethod<?> loadServiceMethod(Method method) {
if (lookup == null) {
// On successful lock insertion, perform the work and update the map before releasing.
// Other threads may be waiting on lock now and will expect the parsed model.
- ServiceMethod<Object> result = ServiceMethod.parseAnnotations(this, method);
+ ServiceMethod<Object> result = ServiceMethod.parseAnnotations(this, service, method);
serviceMethodCache.put(method, result);
return result;
}
diff --git a/retrofit/src/main/java/retrofit2/ServiceMethod.java b/retrofit/src/main/java/retrofit2/ServiceMethod.java
index ea4330ed63..f3117e1186 100644
--- a/retrofit/src/main/java/retrofit2/ServiceMethod.java
+++ b/retrofit/src/main/java/retrofit2/ServiceMethod.java
@@ -22,8 +22,8 @@
import javax.annotation.Nullable;
abstract class ServiceMethod<T> {
- static <T> ServiceMethod<T> parseAnnotations(Retrofit retrofit, Method method) {
- RequestFactory requestFactory = RequestFactory.parseAnnotations(retrofit, method);
+ static <T> ServiceMethod<T> parseAnnotations(Retrofit retrofit, Class<?> service, Method method) {
+ RequestFactory requestFactory = RequestFactory.parseAnnotations(retrofit, service, method);
Type returnType = method.getGenericReturnType();
if (Utils.hasUnresolvableType(returnType)) {
@@ -39,5 +39,5 @@ static <T> ServiceMethod<T> parseAnnotations(Retrofit retrofit, Method method) {
return HttpServiceMethod.parseAnnotations(retrofit, method, requestFactory);
}
- abstract @Nullable T invoke(Object[] args);
+ abstract @Nullable T invoke(Object instance, Object[] args);
}
diff --git a/samples/src/main/java/com/example/retrofit/ErrorHandlingAdapter.java b/samples/src/main/java/com/example/retrofit/ErrorHandlingAdapter.java
index 1c7fb0e1c7..afc7d329b4 100644
--- a/samples/src/main/java/com/example/retrofit/ErrorHandlingAdapter.java
+++ b/samples/src/main/java/com/example/retrofit/ErrorHandlingAdapter.java
@@ -125,8 +125,8 @@ public void enqueue(final MyCallback<T> callback) {
@Override
public void onResponse(Call<T> call, Response<T> response) {
// TODO if 'callbackExecutor' is not null, the 'callback' methods should be executed
- // on that executor by submitting a Runnable. This is left as an exercise for the
- // reader.
+ // on that executor by submitting a Runnable. This is left as an exercise for the
+ // reader.
int code = response.code();
if (code >= 200 && code < 300) {
@@ -145,8 +145,8 @@ public void onResponse(Call<T> call, Response<T> response) {
@Override
public void onFailure(Call<T> call, Throwable t) {
// TODO if 'callbackExecutor' is not null, the 'callback' methods should be executed
- // on that executor by submitting a Runnable. This is left as an exercise for the
- // reader.
+ // on that executor by submitting a Runnable. This is left as an exercise for the
+ // reader.
if (t instanceof IOException) {
callback.networkError((IOException) t);
diff --git a/samples/src/main/java/com/example/retrofit/InvocationMetrics.java b/samples/src/main/java/com/example/retrofit/InvocationMetrics.java
index a4d5d768af..0d491b76b6 100644
--- a/samples/src/main/java/com/example/retrofit/InvocationMetrics.java
+++ b/samples/src/main/java/com/example/retrofit/InvocationMetrics.java
@@ -55,7 +55,7 @@ public Response intercept(Chain chain) throws IOException {
if (invocation != null) {
System.out.printf(
"%s.%s %s HTTP %s (%.0f ms)%n",
- invocation.method().getDeclaringClass().getSimpleName(),
+ invocation.service().getSimpleName(),
invocation.method().getName(),
invocation.arguments(),
response.code(),
| diff --git a/retrofit/java-test/src/test/java/retrofit2/InvocationTest.java b/retrofit/java-test/src/test/java/retrofit2/InvocationTest.java
index 654d96fe3d..4fdebd0d4e 100644
--- a/retrofit/java-test/src/test/java/retrofit2/InvocationTest.java
+++ b/retrofit/java-test/src/test/java/retrofit2/InvocationTest.java
@@ -39,6 +39,8 @@ Call<ResponseBody> postMethod(
@Path("p1") String p1, @Query("p2") String p2, @Body RequestBody body);
}
+ interface ExampleSub extends Example {}
+
@Test
public void invocationObjectOnCallAndRequestTag() {
Retrofit retrofit =
@@ -58,10 +60,52 @@ public void invocationObjectOnCallAndRequestTag() {
assertThat(invocation.arguments()).isEqualTo(Arrays.asList("one", "two", requestBody));
}
+ @Test
+ public void invocationCorrectlyIdentifiesServiceMethodInvocation() {
+ Retrofit retrofit =
+ new Retrofit.Builder()
+ .baseUrl("http://example.com/")
+ .callFactory(new OkHttpClient())
+ .build();
+
+ ExampleSub example = retrofit.create(ExampleSub.class);
+ RequestBody requestBody = RequestBody.create(MediaType.get("text/plain"), "three");
+ Call<ResponseBody> call = example.postMethod("one", "two", requestBody);
+
+ Invocation invocation = call.request().tag(Invocation.class);
+ assertThat(invocation.service()).isEqualTo(ExampleSub.class);
+ assertThat(invocation.instance()).isSameInstanceAs(example);
+ assertThat(invocation.method().getName()).isEqualTo("postMethod");
+ assertThat(invocation.method().getDeclaringClass()).isEqualTo(Example.class);
+ assertThat(invocation.arguments()).isEqualTo(Arrays.asList("one", "two", requestBody));
+ }
+
+ @Test
+ public void nullService() {
+ try {
+ Invocation.of(
+ null, new Object(), Object.class.getDeclaredMethods()[0], Arrays.asList("one", "two"));
+ fail();
+ } catch (NullPointerException expected) {
+ assertThat(expected).hasMessageThat().isEqualTo("service == null");
+ }
+ }
+
+ @Test
+ public void nullInstance() {
+ try {
+ Invocation.of(
+ Object.class, null, Object.class.getDeclaredMethods()[0], Arrays.asList("one", "two"));
+ fail();
+ } catch (NullPointerException expected) {
+ assertThat(expected).hasMessageThat().isEqualTo("instance == null");
+ }
+ }
+
@Test
public void nullMethod() {
try {
- Invocation.of(null, Arrays.asList("one", "two"));
+ Invocation.of(Object.class, new Object(), null, Arrays.asList("one", "two"));
fail();
} catch (NullPointerException expected) {
assertThat(expected).hasMessageThat().isEqualTo("method == null");
@@ -70,6 +114,26 @@ public void nullMethod() {
@Test
public void nullArguments() {
+ try {
+ Invocation.of(Object.class, new Object(), Example.class.getDeclaredMethods()[0], null);
+ fail();
+ } catch (NullPointerException expected) {
+ assertThat(expected).hasMessageThat().isEqualTo("arguments == null");
+ }
+ }
+
+ @Test
+ public void deprecatedNullMethod() {
+ try {
+ Invocation.of(null, Arrays.asList("one", "two"));
+ fail();
+ } catch (NullPointerException expected) {
+ assertThat(expected).hasMessageThat().isEqualTo("method == null");
+ }
+ }
+
+ @Test
+ public void deprecatedNullArguments() {
try {
Invocation.of(Example.class.getDeclaredMethods()[0], null);
fail();
diff --git a/retrofit/test-helpers/src/main/java/retrofit2/TestingUtils.java b/retrofit/test-helpers/src/main/java/retrofit2/TestingUtils.java
index 703133ea87..912b138404 100644
--- a/retrofit/test-helpers/src/main/java/retrofit2/TestingUtils.java
+++ b/retrofit/test-helpers/src/main/java/retrofit2/TestingUtils.java
@@ -31,7 +31,7 @@ static <T> Request buildRequest(Class<T> cls, Retrofit.Builder builder, Object..
Method method = onlyMethod(cls);
try {
- return RequestFactory.parseAnnotations(retrofit, method).create(args);
+ return RequestFactory.parseAnnotations(retrofit, cls, method).create(null, args);
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
| test | test | 2024-02-21T02:07:58 | "2022-05-05T10:50:18Z" | efemoney | val |
square/retrofit/3863_3864 | square/retrofit | square/retrofit/3863 | square/retrofit/3864 | [
"keyword_pr_to_issue"
] | ab4654271aa782e481413e6d48dd6ed3bfe3135b | a4b81ed4ffc40a33c35bb466c4be707749b8c858 | [] | [
"```suggestion\r\n if (!platform.isDefaultMethod(method)\r\n && !Modifier.isStatic(method.getModifiers())\r\n && !method.isSynthetic()) {\r\n```"
] | "2023-03-15T13:51:17Z" | [] | service eager validation is failed when using jacoco | What kind of issue is this?
- [x] Bug report. If you’ve found a bug, spend the time to write a failing test. Bugs with tests
get fixed. Here’s an example: https://gist.github.com/swankjesse/6608b4713ad80988cdc9
Jacoco is a world famous code coverage tool . And it add $jacocoInit() method to interface in order to finish their job.
But it could cause Retrofit failed in eager service validation.
Should Retrofit eager validation ignore SYNTHETIC method in such scene ?
```
public final class Retrofit {
private void validateServiceInterface(Class<?> service) {
............
if (validateEagerly) {
Platform platform = Platform.get();
for (Method method : service.getDeclaredMethods()) {
if (!platform.isDefaultMethod(method) && !Modifier.isStatic(method.getModifiers())) {
loadServiceMethod(method);
}
}
}
...........
}
``` | [
"retrofit/src/main/java/retrofit2/Retrofit.java"
] | [
"retrofit/src/main/java/retrofit2/Retrofit.java"
] | [] | diff --git a/retrofit/src/main/java/retrofit2/Retrofit.java b/retrofit/src/main/java/retrofit2/Retrofit.java
index c5aa7dfb51..3390378db2 100644
--- a/retrofit/src/main/java/retrofit2/Retrofit.java
+++ b/retrofit/src/main/java/retrofit2/Retrofit.java
@@ -191,7 +191,9 @@ private void validateServiceInterface(Class<?> service) {
if (validateEagerly) {
Platform platform = Platform.get();
for (Method method : service.getDeclaredMethods()) {
- if (!platform.isDefaultMethod(method) && !Modifier.isStatic(method.getModifiers())) {
+ if (!platform.isDefaultMethod(method)
+ && !Modifier.isStatic(method.getModifiers())
+ && !method.isSynthetic()) {
loadServiceMethod(service, method);
}
}
| null | train | test | 2024-01-02T06:47:42 | "2023-03-15T08:47:07Z" | pkxiuluo | val |
square/retrofit/3774_3886 | square/retrofit | square/retrofit/3774 | square/retrofit/3886 | [
"keyword_issue_to_pr"
] | 7dae760ada4ab8fabfe81754eb3fca6d2371ce06 | 59d302aedce5edae4806efac57b630d4fe8c27db | [
"2.10.0-SNAPSHOT contains the [fix you're looking for](https://github.com/square/retrofit/pull/3596). Working fine for me with R8 full mode.",
"See https://github.com/square/retrofit/issues/3751#issuecomment-1192043644",
"Thank you!, both of you :)",
"UPDATE: The issue seems to be in AGP 7.2.2, not Retrofit. I have tried AGP 7.2 and 7.3 and both seem to be working fine with Retrofit with R8 full mode.\r\n\r\n---\r\n\r\nActually, this has started reoccurring in my case after I upgraded AGP from 7.0.4 to 7.2.2. Looks like 2.10.0-SNAPSHOT is missing a rule or two...\r\n\r\n```\r\n Caused by: java.lang.IllegalArgumentException: Unable to create call adapter for interface retrofit2.Call\r\n for method HttpBinService.get\r\n at retrofit2.Utils.methodError(Utils.java:55)\r\n at retrofit2.HttpServiceMethod.createCallAdapter(HttpServiceMethod.java:116)\r\n at retrofit2.HttpServiceMethod.parseAnnotations(HttpServiceMethod.java:67)\r\n at retrofit2.ServiceMethod.parseAnnotations(ServiceMethod.java:39)\r\n at retrofit2.Retrofit.loadServiceMethod(Retrofit.java:208)\r\n at retrofit2.Retrofit$1.invoke(Retrofit.java:166)\r\n at java.lang.reflect.Proxy.invoke(Proxy.java:1006)\r\n at $Proxy3.get(Unknown Source)\r\n at io.vibin.myapplication.MainActivity.onCreate(MainActivity.kt:45)\r\n at android.app.Activity.performCreate(Activity.java:8290)\r\n at android.app.Activity.performCreate(Activity.java:8269)\r\n at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1384)\r\n at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3657)\r\n ... 12 more\r\n Caused by: java.lang.IllegalArgumentException: Call return type must be parameterized as Call<Foo> or Call<? extends Foo>\r\n at retrofit2.DefaultCallAdapterFactory.get(DefaultCallAdapterFactory.java:42)\r\n at retrofit2.Retrofit.nextCallAdapter(Retrofit.java:259)\r\n at retrofit2.Retrofit.callAdapter(Retrofit.java:243)\r\n at retrofit2.HttpServiceMethod.createCallAdapter(HttpServiceMethod.java:114)\r\n ... 23 more\r\n```",
"I have added [the rules](https://github.com/square/retrofit/blob/master/retrofit/src/main/resources/META-INF/proguard/retrofit2.pro) to proguard and also followed [these](https://github.com/square/retrofit/issues/3751#issuecomment-1192043644), but even with AGP8 and R8 enabled with retrofit 2.9.0:\r\n```\r\nimplementation 'com.squareup.retrofit2:retrofit:2.9.0'\r\nimplementation 'com.squareup.retrofit2:converter-gson:2.9.0'\r\nimplementation 'com.squareup.retrofit2:adapter-rxjava3:2.9.0'\r\n```\r\n\r\nI get the following:\r\n```\r\nCaused by: java.lang.IllegalStateException: Observable return type must be parameterized as Observable<Foo> or Observable<? extends Foo>\r\nat retrofit2.adapter.rxjava3.RxJava3CallAdapterFactory.get(RxJava3CallAdapterFactory.java:123)\r\nat retrofit2.Retrofit.nextCallAdapter(Retrofit.java:253)\r\nat retrofit2.Retrofit.callAdapter(Retrofit.java:237)\r\nat retrofit2.HttpServiceMethod.createCallAdapter(HttpServiceMethod.java:114)\r\n```\r\n\r\nI have been fighting with this issue for quite a while and I would like to re-enable the code shrinking: can anyone help?",
"https://github.com/square/retrofit/blob/3770704de89233c1240699392baa7198d8b63bff/retrofit-adapters/rxjava3/src/main/resources/META-INF/proguard/retrofit2-rxjava3-adapter.pro#L1-L5",
"@Goooler Appreciated! Thanks!",
"See #3886 which fixes this in a general way rather than us playing whack-a-mole in each adapter jar.",
"> https://github.com/square/retrofit/blob/3770704de89233c1240699392baa7198d8b63bff/retrofit-adapters/rxjava3/src/main/resources/META-INF/proguard/retrofit2-rxjava3-adapter.pro#L1-L5\r\n\r\n\r\n\r\n> -keep,allowobfuscation,allowshrinking class io.reactivex.rxjava3.core.Flowable \r\n> -keep,allowobfuscation,allowshrinking class io.reactivex.rxjava3.core.Maybe \r\n> -keep,allowobfuscation,allowshrinking class io.reactivex.rxjava3.core.Observable \r\n> -keep,allowobfuscation,allowshrinking class io.reactivex.rxjava3.core.Single\r\n\r\nThanks, but after adding this I got an error in response: \r\n\"Unable to create instance of class m.b. Registering an InstanceCreator or a TypeAdapter for this type, or adding a no-args constructor may fix this problem.\"\r\n\r\nwith minify disabled I have no errors. ",
"That's Gson, not Retrofit.",
"> See #3886 which fixes this in a general way rather than us playing whack-a-mole in each adapter jar.\r\n\r\nWith AGP 8.0.2 this works with `Response<T>` but not with `Observable<Response<T>>`:\r\n```\r\njava.lang.IllegalArgumentException: Unable to create call adapter for io.reactivex.Observable<retrofit2.Response>\r\nCaused by: java.lang.IllegalStateException: Response must be parameterized as Response<Foo> or Response<? extends Foo>\r\n```",
"@JakeWharton #3910 fixes issue with `Observable<Response<T>>`.",
"It helped me:\r\n`-keep,allowobfuscation,allowshrinking class io.reactivex.Flowable\r\n-keep,allowobfuscation,allowshrinking class io.reactivex.Maybe\r\n-keep,allowobfuscation,allowshrinking class io.reactivex.Observable\r\n-keep,allowobfuscation,allowshrinking class io.reactivex.Single`"
] | [] | "2023-05-02T10:48:25Z" | [] | Crash with R8 full mode enabled with generics and Rx | Retrofit: 2.9.0
The crashing retrofit interface contains methods like these:
```
@FormUrlEncoded
@POST("token/oauth2")
fun clientCredentials(
@Field("client_id") clientId: String,
@Field("client_secret") clientSecret: String,
@Field("grant_type") @SupportedGrantType grantType: String = SupportedGrantType.CLIENT_CREDENTIALS
): Single<Response<JWTEnvelope>>
```
where JWTEnvelope is my own class:
```
@Keep // androidx.annotation
@JsonClass(generateAdapter = true)
data class JWTEnvelope(
@Json(name = "access_token")
val accessToken: String,
@Json(name = "token_type")
@SupportedTokenType
val tokenType: String,
@Json(name = "expires_in")
val expiresIn: Int,
@Json(name = "refresh_token")
val refreshToken: String? = null
)
```
I'm not sure if this is the same thing that is being discussed here https://github.com/square/retrofit/issues/3588.
But I have the `@Keep` annotation so this should work if the issue is the one described there, isn't it?
I get
```
java.lang.RuntimeException: Unable to start activity ComponentInfo{my.app/my.app.home.HomeActivity}: java.lang.IllegalArgumentException: Unable to create call adapter for class lj.u
[...]
Caused by: java.lang.IllegalArgumentException: Unable to create call adapter for class lj.u
for method j.a
at retrofit2.Utils.methodError(Utils.java:54)
at retrofit2.HttpServiceMethod.createCallAdapter(HttpServiceMethod.java:116)
at retrofit2.HttpServiceMethod.parseAnnotations(HttpServiceMethod.java:67)
at retrofit2.ServiceMethod.parseAnnotations(ServiceMethod.java:39)
at retrofit2.Retrofit.loadServiceMethod(Retrofit.java:202)
at retrofit2.Retrofit$1.invoke(Retrofit.java:160)
at java.lang.reflect.Proxy.invoke(Proxy.java:1006)
at $Proxy5.a(Unknown Source)
at my.app.auth.oauth2.OAuth2RestAPI$DefaultImpls.clientCredentials$default(OAuth2RestAPI.kt:18)
[...]
Caused by: java.lang.IllegalStateException: Single return type must be parameterized as Single<Foo> or Single<? extends Foo>
at retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory.get(RxJava2CallAdapterFactory.java:118)
at retrofit2.Retrofit.nextCallAdapter(Retrofit.java:253)
at retrofit2.Retrofit.callAdapter(Retrofit.java:237)
at retrofit2.HttpServiceMethod.createCallAdapter(HttpServiceMethod.java:114)
... 81 more
```
The Single class is the one that can't be mapped apparently: `io.reactivex.Single` -> `lj.u`.
Am I supposed to just keep every Single class? or **is there a better way?**
Thanks | [
"retrofit-adapters/guava/src/main/resources/META-INF/proguard/retrofit2-guava-adapter.pro",
"retrofit-adapters/rxjava/src/main/resources/META-INF/proguard/retrofit2-rxjava-adapter.pro",
"retrofit-adapters/rxjava2/src/main/resources/META-INF/proguard/retrofit2-rxjava2-adapter.pro",
"retrofit-adapters/rxjava3/src/main/resources/META-INF/proguard/retrofit2-rxjava3-adapter.pro",
"retrofit/src/main/resources/META-INF/proguard/retrofit2.pro"
] | [
"retrofit/src/main/resources/META-INF/proguard/retrofit2.pro"
] | [] | diff --git a/retrofit-adapters/guava/src/main/resources/META-INF/proguard/retrofit2-guava-adapter.pro b/retrofit-adapters/guava/src/main/resources/META-INF/proguard/retrofit2-guava-adapter.pro
deleted file mode 100644
index 603d49f0b4..0000000000
--- a/retrofit-adapters/guava/src/main/resources/META-INF/proguard/retrofit2-guava-adapter.pro
+++ /dev/null
@@ -1,2 +0,0 @@
-# Keep generic signature of ListenableFuture (R8 full mode strips signatures from non-kept items).
--keep,allowobfuscation,allowshrinking class com.google.common.util.concurrent.ListenableFuture
diff --git a/retrofit-adapters/rxjava/src/main/resources/META-INF/proguard/retrofit2-rxjava-adapter.pro b/retrofit-adapters/rxjava/src/main/resources/META-INF/proguard/retrofit2-rxjava-adapter.pro
deleted file mode 100644
index b85ad6ede4..0000000000
--- a/retrofit-adapters/rxjava/src/main/resources/META-INF/proguard/retrofit2-rxjava-adapter.pro
+++ /dev/null
@@ -1,3 +0,0 @@
-# Keep generic signature of RxJava (R8 full mode strips signatures from non-kept items).
--keep,allowobfuscation,allowshrinking class rx.Single
--keep,allowobfuscation,allowshrinking class rx.Observable
diff --git a/retrofit-adapters/rxjava2/src/main/resources/META-INF/proguard/retrofit2-rxjava2-adapter.pro b/retrofit-adapters/rxjava2/src/main/resources/META-INF/proguard/retrofit2-rxjava2-adapter.pro
deleted file mode 100644
index 3880063625..0000000000
--- a/retrofit-adapters/rxjava2/src/main/resources/META-INF/proguard/retrofit2-rxjava2-adapter.pro
+++ /dev/null
@@ -1,5 +0,0 @@
-# Keep generic signature of RxJava2 (R8 full mode strips signatures from non-kept items).
--keep,allowobfuscation,allowshrinking class io.reactivex.Flowable
--keep,allowobfuscation,allowshrinking class io.reactivex.Maybe
--keep,allowobfuscation,allowshrinking class io.reactivex.Observable
--keep,allowobfuscation,allowshrinking class io.reactivex.Single
diff --git a/retrofit-adapters/rxjava3/src/main/resources/META-INF/proguard/retrofit2-rxjava3-adapter.pro b/retrofit-adapters/rxjava3/src/main/resources/META-INF/proguard/retrofit2-rxjava3-adapter.pro
deleted file mode 100644
index ba96f6db81..0000000000
--- a/retrofit-adapters/rxjava3/src/main/resources/META-INF/proguard/retrofit2-rxjava3-adapter.pro
+++ /dev/null
@@ -1,5 +0,0 @@
-# Keep generic signature of RxJava3 (R8 full mode strips signatures from non-kept items).
--keep,allowobfuscation,allowshrinking class io.reactivex.rxjava3.core.Flowable
--keep,allowobfuscation,allowshrinking class io.reactivex.rxjava3.core.Maybe
--keep,allowobfuscation,allowshrinking class io.reactivex.rxjava3.core.Observable
--keep,allowobfuscation,allowshrinking class io.reactivex.rxjava3.core.Single
diff --git a/retrofit/src/main/resources/META-INF/proguard/retrofit2.pro b/retrofit/src/main/resources/META-INF/proguard/retrofit2.pro
index 9599746d30..f5b499fa55 100644
--- a/retrofit/src/main/resources/META-INF/proguard/retrofit2.pro
+++ b/retrofit/src/main/resources/META-INF/proguard/retrofit2.pro
@@ -35,11 +35,11 @@
-if interface * { @retrofit2.http.* <methods>; }
-keep,allowobfuscation interface * extends <1>
-# Keep generic signature of Call, Response (R8 full mode strips signatures from non-kept items).
--keep,allowobfuscation,allowshrinking interface retrofit2.Call
--keep,allowobfuscation,allowshrinking class retrofit2.Response
-
# With R8 full mode generic signatures are stripped for classes that are not
# kept. Suspend functions are wrapped in continuations where the type argument
# is used.
-keep,allowobfuscation,allowshrinking class kotlin.coroutines.Continuation
+
+# R8 full mode strips generic signatures from return types if not kept.
+-if interface * { @retrofit2.http.* public *** *(...); }
+-keep,allowoptimization,allowshrinking,allowobfuscation class <3>
| null | train | test | 2023-05-02T00:12:28 | "2022-09-22T16:30:32Z" | danielesegato | val |
square/retrofit/3804_3939 | square/retrofit | square/retrofit/3804 | square/retrofit/3939 | [
"keyword_pr_to_issue"
] | 58cc3c5dab07d51d0d16048e87bdc2ee932d2a2a | 2c1935663a00683574a138a8ef403e26a944a5d0 | [
" interface RepoService {\r\n @GET(\"search/repositories\")\r\n @Throws(DataException.DataNotFoundException::class)\r\n suspend fun searchRepos()\r\n }\r\n\r\nadd @Throws(DataException.DataNotFoundException::class) to function then the DataNotFoundException is declared \r\nso when exception is thrown to kotlin Coroutine,it won't be throw as UndeclaredThrowableException ",
"Is there a reason that you extend from `Throwable` instead of `Exception`?"
] | [] | "2023-08-15T13:53:49Z" | [
"Bug"
] | UndeclaredThrowableException when using single instance of Retrofit with non-IOException in custom CallAdapter | Retrofit crashes with `UndeclaredThrowableException` when single instance of Retrofit is used with custom adapter which returns non-`IOException`.
Simple code to reproduce. The code inside `while` loop will eventually fail.
```
private val service by lazy {
val client = OkHttpClient.Builder()
.build()
val retrofit = Retrofit.Builder()
.client(client)
.baseUrl("https://unresolved-host.com/")
.addCallAdapterFactory(RetrofitExceptionHandlerAdapterFactory())
.build()
retrofit.create(RepoService::class.java)
}
while (true) {
viewModelScope.launch {
try {
service.searchRepos()
} catch (e: DataException.DataNotFoundException) {
println("KOKO $e")
}
}
}
interface RepoService {
@GET("search/repositories")
suspend fun searchRepos()
}
sealed class DataException(override val cause: Throwable? = null): Throwable(cause) {
data class DataNotFoundException(override val cause: Throwable? = null): DataException(cause)
}
```
In custom adapter, instead of returning `IOException` I return `DataNotFoundException`( non-`IOException`) in `onFailure` method.
```
class RetrofitExceptionHandlerAdapterFactory: CallAdapter.Factory() {
override fun get(
returnType: Type, annotations: Array<Annotation>, retrofit: Retrofit
): CallAdapter<*, *>? {
// Validate Call
val typeCall = getRawType(returnType)
if (typeCall != Call::class.java)
return null
val responseType = getParameterUpperBound(0, returnType as ParameterizedType)
val responseTypeClass = getRawType(typeCall)
return RetrofitExceptionHandlerAdapter(responseType, responseTypeClass)
}
}
class RetrofitExceptionHandlerAdapter<T>(
private val responseType: Type,
private val responseTypeClass: Class<T>
) : CallAdapter<T, Call<T>> {
override fun responseType(): Type = responseType
private fun responseTypeClass(): Class<T> = responseTypeClass
override fun adapt(call: Call<T>): BodyCall<T> = BodyCall(call, responseTypeClass())
class BodyCall<T>(
private val delegate: Call<T>,
private val responseClass: Class<T>
) : Call<T> {
override fun enqueue(callback: Callback<T>) {
delegate.enqueue(
object : Callback<T> {
override fun onResponse(call: Call<T>, response: Response<T>) {
callback.onResponse(call, response)
}
override fun onFailure(call: Call<T>, t: Throwable) {
callback.onFailure(call, DataException.DataNotFoundException())
}
})
}
override fun isExecuted() = delegate.isExecuted
// Since suspend functions won't use this method, no need to implement
override fun execute(): Response<T> = throw NotImplementedError("Method not implemented")
override fun cancel() = delegate.cancel()
override fun isCanceled() = delegate.isCanceled
override fun clone(): Call<T> = BodyCall(delegate.clone(), responseClass)
override fun request(): Request = delegate.request()
override fun timeout(): Timeout = delegate.timeout()
}
}
```
**Solution:**
1. Either create new instance of retrofit on every call (which would not make sense)
2. Or inherit `DataNotFoundException` from `IOException` instead of `Throwable`
**Retrofit version:** `2.9.0` | [
"retrofit/src/main/java/retrofit2/HttpServiceMethod.java",
"retrofit/src/main/java/retrofit2/KotlinExtensions.kt"
] | [
"retrofit/src/main/java/retrofit2/HttpServiceMethod.java",
"retrofit/src/main/java/retrofit2/KotlinExtensions.kt"
] | [] | diff --git a/retrofit/src/main/java/retrofit2/HttpServiceMethod.java b/retrofit/src/main/java/retrofit2/HttpServiceMethod.java
index 2ca5c7f0ae..41758a9cd0 100644
--- a/retrofit/src/main/java/retrofit2/HttpServiceMethod.java
+++ b/retrofit/src/main/java/retrofit2/HttpServiceMethod.java
@@ -243,7 +243,10 @@ protected Object adapt(Call<ResponseT> call, Object[] args) {
} else {
return KotlinExtensions.await(call, continuation);
}
- } catch (Exception e) {
+ } catch (VirtualMachineError | ThreadDeath | LinkageError e) {
+ // Do not attempt to capture fatal throwables. This list is derived RxJava's `throwIfFatal`.
+ throw e;
+ } catch (Throwable e) {
return KotlinExtensions.suspendAndThrow(e, continuation);
}
}
diff --git a/retrofit/src/main/java/retrofit2/KotlinExtensions.kt b/retrofit/src/main/java/retrofit2/KotlinExtensions.kt
index d334b25136..8dc4265309 100644
--- a/retrofit/src/main/java/retrofit2/KotlinExtensions.kt
+++ b/retrofit/src/main/java/retrofit2/KotlinExtensions.kt
@@ -116,7 +116,7 @@ suspend fun <T> Call<T>.awaitResponse(): Response<T> {
* The implementation is derived from:
* https://github.com/Kotlin/kotlinx.coroutines/pull/1667#issuecomment-556106349
*/
-internal suspend fun Exception.suspendAndThrow(): Nothing {
+internal suspend fun Throwable.suspendAndThrow(): Nothing {
suspendCoroutineUninterceptedOrReturn<Nothing> { continuation ->
Dispatchers.Default.dispatch(continuation.context) {
continuation.intercepted().resumeWithException(this@suspendAndThrow)
| null | train | test | 2023-08-09T12:55:07 | "2023-01-21T08:43:15Z" | mecoFarid | val |
pinpoint-apm/pinpoint/254_260 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/254 | pinpoint-apm/pinpoint/260 | [
"keyword_pr_to_issue",
"timestamp(timedelta=0.0, similarity=0.8705790600270467)"
] | cacd892144af7362bb0a7df36a8e17cf14b23d6a | 71e34b1ceea13bc904ac6a7c8e8221ed7f887b3b | [] | [] | "2015-03-26T06:27:05Z" | [
"bug",
"enhancement"
] | User node pointing to a node with same application name but different service type throws an exception | In relation to issue #214, applications with the same application name can now be selected separately as long as their service types differ.
However, user nodes are generated on the server map taking only the destination's application name into account.
For example, if there are 2 nodes with the same application name but different service type (ie TOMCAT, SPRING-BOOT both named myApp) with 2 USER nodes each pointing to myApp[TOMCAT], and myApp[SPRING-BOOT], the Web UI throws an error when drawing the server map.
This is because the USER node is generated by extracting the application name of the destination node, which in this case would result in only a single USER node being generated.
![current](https://cloud.githubusercontent.com/assets/10057488/6817488/6a663dea-d2e4-11e4-8097-b5c3c622f259.png)
2 possible solutions exist.
1. Draw only a single USER node that points to both myApp[TOMCAT] and myApp[SPRING-BOOT].
![solution1](https://cloud.githubusercontent.com/assets/10057488/6817489/75cb29d4-d2e4-11e4-8d75-3f725fda8725.png)
2. Draw 2 separate USER nodes each pointing to myApp[TOMCAT] and myApp[SPRING-BOOT].
![solution2](https://cloud.githubusercontent.com/assets/10057488/6817493/7e3dbfc8-d2e4-11e4-8bdf-94025abef7c5.png)
The second solution seems like the better option - but this requires the destination node's service type to already be stored in hbase.
| [
"commons/src/main/java/com/navercorp/pinpoint/common/util/ApplicationMapStatisticsUtils.java",
"web/src/main/java/com/navercorp/pinpoint/web/applicationmap/LinkList.java",
"web/src/main/java/com/navercorp/pinpoint/web/mapper/MapStatisticsCalleeMapper.java"
] | [
"commons/src/main/java/com/navercorp/pinpoint/common/util/ApplicationMapStatisticsUtils.java",
"web/src/main/java/com/navercorp/pinpoint/web/applicationmap/LinkList.java",
"web/src/main/java/com/navercorp/pinpoint/web/mapper/MapStatisticsCalleeMapper.java"
] | [] | diff --git a/commons/src/main/java/com/navercorp/pinpoint/common/util/ApplicationMapStatisticsUtils.java b/commons/src/main/java/com/navercorp/pinpoint/common/util/ApplicationMapStatisticsUtils.java
index 4e5c6433e595..d519c794c27d 100644
--- a/commons/src/main/java/com/navercorp/pinpoint/common/util/ApplicationMapStatisticsUtils.java
+++ b/commons/src/main/java/com/navercorp/pinpoint/common/util/ApplicationMapStatisticsUtils.java
@@ -105,7 +105,13 @@ public static String getDestApplicationNameFromColumnName(byte[] bytes) {
final short length = BytesUtils.bytesToShort(bytes, 4);
return BytesUtils.toStringAndRightTrim(bytes, 6, length);
}
-
+
+ public static String getDestApplicationNameFromColumnNameForUser(byte[] bytes, ServiceType destServiceType) {
+ String destApplicationName = getDestApplicationNameFromColumnName(bytes);
+ String destServiceTypeName = destServiceType.getName();
+ return destApplicationName + "_" + destServiceTypeName;
+ }
+
public static String getHost(byte[] bytes) {
int offset = 6 + BytesUtils.bytesToShort(bytes, 4);
diff --git a/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/LinkList.java b/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/LinkList.java
index 60acd9b93577..d34388190ed9 100644
--- a/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/LinkList.java
+++ b/web/src/main/java/com/navercorp/pinpoint/web/applicationmap/LinkList.java
@@ -56,7 +56,7 @@ public List<Link> findToLink(Application toApplication) {
for (Link link : linkMap.values()) {
Node toNode = link.getTo();
// find all the callers of toApplication/destination
- if (toNode.getApplication().equals(toApplication)) {
+ if (toNode.getApplication().equals(toApplication) && toNode.getServiceType().equals(toApplication.getServiceType())) {
findList.add(link);
}
}
@@ -70,14 +70,14 @@ public List<Link> findToLink(Application toApplication) {
*/
public List<Link> findFromLink(Application fromApplication) {
if (fromApplication == null) {
- throw new NullPointerException("toApplication must not be null");
+ throw new NullPointerException("fromApplication must not be null");
}
List<Link> findList = new ArrayList<Link>();
for (Link link : linkMap.values()) {
Node fromNode = link.getFrom();
- if (fromNode.getApplication().equals(fromApplication)) {
+ if (fromNode.getApplication().equals(fromApplication) && fromNode.getServiceType().equals(fromApplication.getServiceType())) {
findList.add(link);
}
}
diff --git a/web/src/main/java/com/navercorp/pinpoint/web/mapper/MapStatisticsCalleeMapper.java b/web/src/main/java/com/navercorp/pinpoint/web/mapper/MapStatisticsCalleeMapper.java
index cdacbb4706bb..ce930cc19762 100644
--- a/web/src/main/java/com/navercorp/pinpoint/web/mapper/MapStatisticsCalleeMapper.java
+++ b/web/src/main/java/com/navercorp/pinpoint/web/mapper/MapStatisticsCalleeMapper.java
@@ -76,7 +76,7 @@ public LinkDataMap mapRow(Result result, int rowNum) throws Exception {
for (KeyValue kv : result.raw()) {
final byte[] qualifier = kv.getQualifier();
- final Application callerApplication = readCallerApplication(qualifier);
+ final Application callerApplication = readCallerApplication(qualifier, calleeApplication.getServiceType());
if (filter.filter(callerApplication)) {
continue;
}
@@ -103,9 +103,16 @@ public LinkDataMap mapRow(Result result, int rowNum) throws Exception {
return linkDataMap;
}
- private Application readCallerApplication(byte[] qualifier) {
- String callerApplicationName = ApplicationMapStatisticsUtils.getDestApplicationNameFromColumnName(qualifier);
+ private Application readCallerApplication(byte[] qualifier, ServiceType calleeServiceType) {
short callerServiceType = ApplicationMapStatisticsUtils.getDestServiceTypeFromColumnName(qualifier);
+ // Caller may be a user node, and user nodes may call nodes with the same application name but different service type.
+ // To distinguish between these user nodes, append callee's service type to the application name.
+ String callerApplicationName;
+ if (registry.findServiceType(callerServiceType).isUser()) {
+ callerApplicationName = ApplicationMapStatisticsUtils.getDestApplicationNameFromColumnNameForUser(qualifier, calleeServiceType);
+ } else {
+ callerApplicationName = ApplicationMapStatisticsUtils.getDestApplicationNameFromColumnName(qualifier);
+ }
return createApplication(callerApplicationName, callerServiceType);
}
| null | val | train | 2015-03-25T09:05:02 | "2015-03-24T09:24:40Z" | Xylus | test |
pinpoint-apm/pinpoint/384_404 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/384 | pinpoint-apm/pinpoint/404 | [
"keyword_issue_to_pr"
] | 42e60f19f25fbc4c5a1ca7db88d0148af941ec68 | 3363efde5c04075f65c8bba0c705e95b6a6c8056 | [
"resolved in #404 \n"
] | [] | "2015-05-11T09:49:31Z" | [
"bug"
] | Potential deadlock with PluginClassLoader | When asynchronously loading classes and applying interceptors, deadlock may happen when the interceptor itself references a class loaded with PluginClassLoader.
One thread locks on the system class loader and waits to lock the plugin class loader (when applying an interceptor), and another thread locks on the plugin class loader and waits to lock the system class loader.
| [
"commons/src/main/java/com/navercorp/pinpoint/common/plugin/PluginLoader.java",
"commons/src/main/java/com/navercorp/pinpoint/common/plugin/PluginClassLoader.java",
"profiler/src/main/java/com/navercorp/pinpoint/profiler/plugin/DefaultPluginClassLoaderFactory.java"
] | [
"commons/src/main/java/com/navercorp/pinpoint/common/plugin/PluginLoader.java",
"commons/src/main/java/com/navercorp/pinpoint/common/plugin/PluginLoaderClassLoader.java",
"profiler-optional/src/main/java/com/navercorp/pinpoint/profiler/plugin/Java7PluginClassLoader.java",
"profiler/src/main/java/com/navercorp/pinpoint/profiler/plugin/DefaultPluginClassLoaderFactory.java",
"profiler/src/main/java/com/navercorp/pinpoint/profiler/plugin/Java6PluginClassLoader.java"
] | [] | diff --git a/commons/src/main/java/com/navercorp/pinpoint/common/plugin/PluginLoader.java b/commons/src/main/java/com/navercorp/pinpoint/common/plugin/PluginLoader.java
index c91a4c20797c..d5e4e572bf69 100644
--- a/commons/src/main/java/com/navercorp/pinpoint/common/plugin/PluginLoader.java
+++ b/commons/src/main/java/com/navercorp/pinpoint/common/plugin/PluginLoader.java
@@ -47,15 +47,15 @@ public static <T> List<T> load(Class<T> serviceType, URL[] urls) {
return load(serviceType, classLoader);
}
- private static PluginClassLoader createPluginClassLoader(final URL[] urls, final ClassLoader parent) {
+ private static PluginLoaderClassLoader createPluginClassLoader(final URL[] urls, final ClassLoader parent) {
if (SECURITY_MANAGER != null) {
- return AccessController.doPrivileged(new PrivilegedAction<PluginClassLoader>() {
- public PluginClassLoader run() {
- return new PluginClassLoader(urls, parent);
+ return AccessController.doPrivileged(new PrivilegedAction<PluginLoaderClassLoader>() {
+ public PluginLoaderClassLoader run() {
+ return new PluginLoaderClassLoader(urls, parent);
}
});
} else {
- return new PluginClassLoader(urls, parent);
+ return new PluginLoaderClassLoader(urls, parent);
}
}
diff --git a/commons/src/main/java/com/navercorp/pinpoint/common/plugin/PluginClassLoader.java b/commons/src/main/java/com/navercorp/pinpoint/common/plugin/PluginLoaderClassLoader.java
similarity index 80%
rename from commons/src/main/java/com/navercorp/pinpoint/common/plugin/PluginClassLoader.java
rename to commons/src/main/java/com/navercorp/pinpoint/common/plugin/PluginLoaderClassLoader.java
index 20d7d611d3b4..31c9cf00f2e6 100644
--- a/commons/src/main/java/com/navercorp/pinpoint/common/plugin/PluginClassLoader.java
+++ b/commons/src/main/java/com/navercorp/pinpoint/common/plugin/PluginLoaderClassLoader.java
@@ -23,19 +23,19 @@
/**
* @author emeroad
*/
-public class PluginClassLoader extends URLClassLoader {
+public class PluginLoaderClassLoader extends URLClassLoader {
// for debug
// private final String loaderName
- public PluginClassLoader(URL[] urls, ClassLoader parent) {
+ public PluginLoaderClassLoader(URL[] urls, ClassLoader parent) {
super(urls, parent);
}
- public PluginClassLoader(URL[] urls) {
+ public PluginLoaderClassLoader(URL[] urls) {
super(urls);
}
- public PluginClassLoader(URL[] urls, ClassLoader parent, URLStreamHandlerFactory factory) {
+ public PluginLoaderClassLoader(URL[] urls, ClassLoader parent, URLStreamHandlerFactory factory) {
super(urls, parent, factory);
}
diff --git a/profiler-optional/src/main/java/com/navercorp/pinpoint/profiler/plugin/Java7PluginClassLoader.java b/profiler-optional/src/main/java/com/navercorp/pinpoint/profiler/plugin/Java7PluginClassLoader.java
new file mode 100644
index 000000000000..2e4fea3a25a4
--- /dev/null
+++ b/profiler-optional/src/main/java/com/navercorp/pinpoint/profiler/plugin/Java7PluginClassLoader.java
@@ -0,0 +1,40 @@
+/*
+ * Copyright 2014 NAVER Corp.
+ *
+ * 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 com.navercorp.pinpoint.profiler.plugin;
+
+import java.net.URL;
+import java.net.URLClassLoader;
+
+/**
+ * @author Jongho Moon
+ * @author emeroad
+ */
+public class Java7PluginClassLoader extends URLClassLoader {
+ static {
+ ClassLoader.registerAsParallelCapable();
+ }
+
+ public Java7PluginClassLoader(URL[] urls, ClassLoader parent) {
+ super(urls, parent);
+ }
+
+ @Override
+ protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
+ // for debugging
+ return super.loadClass(name, resolve);
+ }
+}
diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/plugin/DefaultPluginClassLoaderFactory.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/plugin/DefaultPluginClassLoaderFactory.java
index 51627eea42c0..d847d810e9b3 100644
--- a/profiler/src/main/java/com/navercorp/pinpoint/profiler/plugin/DefaultPluginClassLoaderFactory.java
+++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/plugin/DefaultPluginClassLoaderFactory.java
@@ -18,6 +18,7 @@
import java.io.Closeable;
import java.io.IOException;
+import java.lang.reflect.Constructor;
import java.net.URL;
import java.security.AccessController;
import java.security.PrivilegedAction;
@@ -27,18 +28,40 @@
import java.util.logging.Logger;
import com.navercorp.pinpoint.bootstrap.plugin.PluginClassLoaderFactory;
-import com.navercorp.pinpoint.common.plugin.PluginClassLoader;
+import com.navercorp.pinpoint.exception.PinpointException;
public class DefaultPluginClassLoaderFactory implements PluginClassLoaderFactory {
- private final Logger logger = Logger.getLogger(DefaultPluginClassLoaderFactory.class.getName());
-
private static final SecurityManager SECURITY_MANAGER = System.getSecurityManager();
+ private static final Constructor<?> CLASS_LOADER_CONSTRUCTOR;
+
+ static {
+ boolean java6 = false;
+
+ try {
+ ClassLoader.class.getDeclaredMethod("registerAsParallelCapable");
+ } catch (Exception e) {
+ java6 = true;
+ }
+
+ String pluginClassLoaderName = java6 ? "com.navercorp.pinpoint.profiler.plugin.Java6PluginClassLoader" : "com.navercorp.pinpoint.profiler.plugin.Java7PluginClassLoader";
+
+ try {
+ Class<?> pluginClassLoaderType = Class.forName(pluginClassLoaderName);
+ CLASS_LOADER_CONSTRUCTOR = pluginClassLoaderType.getDeclaredConstructor(URL[].class, ClassLoader.class);
+ } catch (ClassNotFoundException e) {
+ throw new NoClassDefFoundError("Cannot find plugin class loader: " + pluginClassLoaderName);
+ } catch (Exception e) {
+ throw new PinpointException("Failed to prepare " + pluginClassLoaderName, e);
+ }
+ }
+ private final Logger logger = Logger.getLogger(DefaultPluginClassLoaderFactory.class.getName());
private final URL[] pluginJars;
private final ConcurrentHashMap<ClassLoader, ClassLoader> cache = new ConcurrentHashMap<ClassLoader, ClassLoader>();
private final AtomicReference<ClassLoader> forBootstrapClassLoader = new AtomicReference<ClassLoader>();
+
public DefaultPluginClassLoaderFactory(URL[] pluginJars) {
this.pluginJars = pluginJars;
}
@@ -90,15 +113,23 @@ private ClassLoader getForBootstrap() {
}
}
- private PluginClassLoader createPluginClassLoader(final URL[] urls, final ClassLoader parent) {
+ private ClassLoader createPluginClassLoader(final URL[] urls, final ClassLoader parent) {
if (SECURITY_MANAGER != null) {
- return AccessController.doPrivileged(new PrivilegedAction<PluginClassLoader>() {
- public PluginClassLoader run() {
- return new PluginClassLoader(urls, parent);
+ return AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
+ public ClassLoader run() {
+ return createPluginClassLoader0(urls, parent);
}
});
} else {
- return new PluginClassLoader(urls, parent);
+ return createPluginClassLoader0(urls, parent);
+ }
+ }
+
+ private ClassLoader createPluginClassLoader0(URL[] urls, ClassLoader parent) {
+ try {
+ return (ClassLoader)CLASS_LOADER_CONSTRUCTOR.newInstance(urls, parent);
+ } catch (Exception e) {
+ throw new PinpointException("Failed to create plugin classloader instance", e);
}
}
@@ -111,7 +142,7 @@ private void close(ClassLoader classLoader) {
try {
((Closeable)classLoader).close();
} catch (IOException e) {
- logger.log(Level.WARNING, "PluginClassLoader.close() fail. Caused:" + e.getMessage(), e);
+ logger.log(Level.WARNING, "Java6PluginClassLoader.close() fail. Caused:" + e.getMessage(), e);
}
}
}
diff --git a/profiler/src/main/java/com/navercorp/pinpoint/profiler/plugin/Java6PluginClassLoader.java b/profiler/src/main/java/com/navercorp/pinpoint/profiler/plugin/Java6PluginClassLoader.java
new file mode 100644
index 000000000000..799eb9c5ef1f
--- /dev/null
+++ b/profiler/src/main/java/com/navercorp/pinpoint/profiler/plugin/Java6PluginClassLoader.java
@@ -0,0 +1,93 @@
+/*
+ * Copyright 2014 NAVER Corp.
+ *
+ * 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 com.navercorp.pinpoint.profiler.plugin;
+
+import java.net.URL;
+import java.net.URLClassLoader;
+import java.util.concurrent.locks.ReentrantLock;
+
+/**
+ * @author Jongho Moon
+ * @author emeroad
+ */
+public class Java6PluginClassLoader extends URLClassLoader {
+
+ private final ReentrantLock lock = new ReentrantLock();
+
+ public Java6PluginClassLoader(URL[] urls, ClassLoader parent) {
+ super(urls, parent);
+ }
+
+ @Override
+ protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
+ ClassLoader parent = getParent();
+
+ while (!lock.tryLock()) {
+ try {
+ try {
+ this.wait();
+ } catch (IllegalMonitorStateException e) {
+ try {
+ parent.wait();
+ } catch (IllegalMonitorStateException e2) {
+ // should sleep?
+ }
+ }
+ } catch (InterruptedException e) {
+ throw new RuntimeException("Interrupted", e);
+ }
+ }
+
+ Class<?> c = null;
+
+ try {
+
+ synchronized (this) {
+ c = findLoadedClass(name);
+
+ if (c == null) {
+ try {
+ c = parent.loadClass(name);
+ } catch (ClassNotFoundException e) {
+
+ }
+
+ if (c == null) {
+ c = findClass(name);
+ }
+ }
+
+ if (resolve) {
+ resolveClass(c);
+ }
+ }
+
+
+ } finally {
+ lock.unlock();
+ }
+
+ synchronized (this) {
+ this.notify();
+ }
+
+ synchronized (parent) {
+ parent.notify();
+ }
+ return c;
+ }
+}
| null | train | train | 2015-05-11T11:13:31 | "2015-04-30T07:37:31Z" | Xylus | test |
pinpoint-apm/pinpoint/452_453 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/452 | pinpoint-apm/pinpoint/453 | [
"keyword_pr_to_issue"
] | 8b83c7a7854c91ce2bfe1f7419b13bfc6a34fe83 | 6ad9669642b29393a5e52428393a4f14079416e6 | [] | [] | "2015-05-21T08:34:13Z" | [
"bug"
] | Starting hbase in Quickstart fails if there is an older version of hbase already available | Quickstart's start script does not properly unlink `hbase` under `pinpoint/quickstart/hbase/`.
Thus, the `ln` command creates a new link under the directory previously linked by `hbase`.
This issue should only manifest itself under *nix/osx systems as Windows users would set the path to hbase manually.
| [
"quickstart/bin/start-hbase.sh"
] | [
"quickstart/bin/start-hbase.sh"
] | [] | diff --git a/quickstart/bin/start-hbase.sh b/quickstart/bin/start-hbase.sh
index 299effd02b07..c5d33b2f1cc6 100755
--- a/quickstart/bin/start-hbase.sh
+++ b/quickstart/bin/start-hbase.sh
@@ -27,6 +27,7 @@ BASE_DIR=`dirname "$bin"`
CONF_DIR=$BASE_DIR/conf
HBASE_DIR=$BASE_DIR/hbase
+DATA_DIR=$BASE_DIR/data
function func_check_hbase_installation
{
@@ -58,6 +59,13 @@ function func_download_hbase
fi
}
+function delete_data_directory
+{
+ if [ -d $DATA_DIR ]; then
+ rm -r $DATA_DIR
+ fi
+}
+
function func_install_hbase
{
if [ ! -d $HBASE_DIR ]; then
@@ -71,8 +79,12 @@ function func_install_hbase
echo "Exiting"
exit 0
fi
+ delete_data_directory
tar xzf $HBASE_FILE
rm $HBASE_FILE
+ if [ -h hbase ]; then
+ unlink hbase
+ fi
ln -s $HBASE_VERSION hbase
cp $CONF_DIR/hbase/hbase-site.xml $HBASE_DIR/$HBASE_VERSION/conf/
chmod +x $HBASE_DIR/$HBASE_VERSION/bin/start-hbase.sh
@@ -92,4 +104,4 @@ function func_start_hbase
cd $CURRENT_DIR
}
-func_start_hbase
\ No newline at end of file
+func_start_hbase
| null | val | train | 2015-05-21T07:54:10 | "2015-05-21T07:46:40Z" | Xylus | test |
pinpoint-apm/pinpoint/488_490 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/488 | pinpoint-apm/pinpoint/490 | [
"keyword_pr_to_issue"
] | bce3c67128eed0d80a05519269323892fa0b72ed | 759970bdbe40c26f9a6e5338a41ada7ba650c43d | [] | [] | "2015-05-28T08:32:07Z" | [
"bug"
] | Web throws NPE when filtering calls with RPC internal types | When filtering RPC calls on Pinpoint web, NullPointerException is thrown.
This is due to a missing check inside the filtering logic. WAS -> WAS filtering checks each span event for its `ServiceType` and if it is in the RPC range (9000~9999), does an equals check with the span event's `destinationId`. Since RPC internal methods does not have a `destinationId`, while being within the RPC range, NPE is thrown.
Fix needs 2 checks - to check if the span event's ServiceType is set to record statistics, and to check for null `destinationId`.
| [
"web/src/main/java/com/navercorp/pinpoint/web/filter/FilterHint.java",
"web/src/main/java/com/navercorp/pinpoint/web/filter/FromToResponseFilter.java"
] | [
"web/src/main/java/com/navercorp/pinpoint/web/filter/FilterHint.java",
"web/src/main/java/com/navercorp/pinpoint/web/filter/FromToResponseFilter.java"
] | [] | diff --git a/web/src/main/java/com/navercorp/pinpoint/web/filter/FilterHint.java b/web/src/main/java/com/navercorp/pinpoint/web/filter/FilterHint.java
index 1da96e2f280f..c686337f2610 100644
--- a/web/src/main/java/com/navercorp/pinpoint/web/filter/FilterHint.java
+++ b/web/src/main/java/com/navercorp/pinpoint/web/filter/FilterHint.java
@@ -46,6 +46,10 @@ public boolean containApplicationEndpoint(String applicationName, String endPoin
if (!containApplicationHint(applicationName)) {
return false;
}
+
+ if (endPoint == null) {
+ return false;
+ }
List<Object> list = get(applicationName);
diff --git a/web/src/main/java/com/navercorp/pinpoint/web/filter/FromToResponseFilter.java b/web/src/main/java/com/navercorp/pinpoint/web/filter/FromToResponseFilter.java
index a8fd905f9b4e..ff484bbef567 100644
--- a/web/src/main/java/com/navercorp/pinpoint/web/filter/FromToResponseFilter.java
+++ b/web/src/main/java/com/navercorp/pinpoint/web/filter/FromToResponseFilter.java
@@ -147,8 +147,10 @@ public boolean include(List<SpanBo> transaction) {
for (SpanEventBo event : eventBoList) {
// check only whether a client exists or not.
- if (event.getServiceType().isRpcClient() && toApplicationName.equals(event.getDestinationId())) {
- return checkResponseCondition(event.getEndElapsed(), event.hasException());
+ if (event.getServiceType().isRpcClient() && event.getServiceType().isRecordStatistics()) {
+ if (toApplicationName.equals(event.getDestinationId())) {
+ return checkResponseCondition(event.getEndElapsed(), event.hasException());
+ }
}
}
}
@@ -169,6 +171,10 @@ public boolean include(List<SpanBo> transaction) {
if (!event.getServiceType().isRpcClient()) {
continue;
}
+
+ if (!event.getServiceType().isRecordStatistics()) {
+ continue;
+ }
if (!hint.containApplicationEndpoint(toApplicationName, event.getDestinationId(), event.getServiceType().getCode())) {
continue;
| null | train | train | 2015-05-27T09:59:38 | "2015-05-28T07:43:42Z" | Xylus | test |
pinpoint-apm/pinpoint/488_491 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/488 | pinpoint-apm/pinpoint/491 | [
"keyword_pr_to_issue"
] | 1b5d37598c12c53c733ea362bcf7876cd97c060b | b49d19cd38bea182e8b4cb7a9df29575098e5ef6 | [] | [] | "2015-05-28T09:51:47Z" | [
"bug"
] | Web throws NPE when filtering calls with RPC internal types | When filtering RPC calls on Pinpoint web, NullPointerException is thrown.
This is due to a missing check inside the filtering logic. WAS -> WAS filtering checks each span event for its `ServiceType` and if it is in the RPC range (9000~9999), does an equals check with the span event's `destinationId`. Since RPC internal methods does not have a `destinationId`, while being within the RPC range, NPE is thrown.
Fix needs 2 checks - to check if the span event's ServiceType is set to record statistics, and to check for null `destinationId`.
| [
"web/src/main/java/com/navercorp/pinpoint/web/filter/DefaultFilterBuilder.java",
"web/src/main/java/com/navercorp/pinpoint/web/filter/FilterHint.java",
"web/src/main/java/com/navercorp/pinpoint/web/filter/FromToResponseFilter.java"
] | [
"web/src/main/java/com/navercorp/pinpoint/web/filter/DefaultFilterBuilder.java",
"web/src/main/java/com/navercorp/pinpoint/web/filter/FilterHint.java",
"web/src/main/java/com/navercorp/pinpoint/web/filter/FromToResponseFilter.java"
] | [] | diff --git a/web/src/main/java/com/navercorp/pinpoint/web/filter/DefaultFilterBuilder.java b/web/src/main/java/com/navercorp/pinpoint/web/filter/DefaultFilterBuilder.java
index 9a5d2afaa9b5..e944caa7a5b5 100644
--- a/web/src/main/java/com/navercorp/pinpoint/web/filter/DefaultFilterBuilder.java
+++ b/web/src/main/java/com/navercorp/pinpoint/web/filter/DefaultFilterBuilder.java
@@ -149,7 +149,7 @@ private FromToResponseFilter createFromToResponseFilter(FilterDescriptor descrip
Long fromResponseTime = descriptor.getResponseFrom();
Long toResponseTime = descriptor.getResponseTo();
Boolean includeFailed = descriptor.getIncludeException();
- return new FromToResponseFilter(fromServiceType, fromApplicationName, fromAgentName, toServiceType, toApplicationName, toAgentName,fromResponseTime, toResponseTime, includeFailed, hint);
+ return new FromToResponseFilter(fromServiceType, fromApplicationName, fromAgentName, toServiceType, toApplicationName, toAgentName,fromResponseTime, toResponseTime, includeFailed, hint, this.registry);
}
private FromToFilter createFromToFilter(FilterDescriptor descriptor) {
diff --git a/web/src/main/java/com/navercorp/pinpoint/web/filter/FilterHint.java b/web/src/main/java/com/navercorp/pinpoint/web/filter/FilterHint.java
index 87ee338fdbe9..07a776cbd128 100644
--- a/web/src/main/java/com/navercorp/pinpoint/web/filter/FilterHint.java
+++ b/web/src/main/java/com/navercorp/pinpoint/web/filter/FilterHint.java
@@ -46,6 +46,10 @@ public boolean containApplicationEndpoint(String applicationName, String endPoin
if (!containApplicationHint(applicationName)) {
return false;
}
+
+ if (endPoint == null) {
+ return false;
+ }
List<Object> list = get(applicationName);
diff --git a/web/src/main/java/com/navercorp/pinpoint/web/filter/FromToResponseFilter.java b/web/src/main/java/com/navercorp/pinpoint/web/filter/FromToResponseFilter.java
index 7e18feb8dbae..f6a3497cbc51 100644
--- a/web/src/main/java/com/navercorp/pinpoint/web/filter/FromToResponseFilter.java
+++ b/web/src/main/java/com/navercorp/pinpoint/web/filter/FromToResponseFilter.java
@@ -20,6 +20,7 @@
import com.navercorp.pinpoint.common.bo.SpanBo;
import com.navercorp.pinpoint.common.bo.SpanEventBo;
+import com.navercorp.pinpoint.common.service.ServiceTypeRegistryService;
import com.navercorp.pinpoint.common.trace.ServiceType;
import com.navercorp.pinpoint.common.trace.ServiceTypeCategory;
@@ -43,8 +44,10 @@ public class FromToResponseFilter implements Filter {
private final Boolean includeFailed;
private final FilterHint hint;
+
+ private final ServiceTypeRegistryService registry;
- public FromToResponseFilter(List<ServiceType> fromServiceList, String fromApplicationName, String fromAgentName, List<ServiceType> toServiceList, String toApplicationName, String toAgentName, Long fromResponseTime, Long toResponseTime, Boolean includeFailed, FilterHint hint) {
+ public FromToResponseFilter(List<ServiceType> fromServiceList, String fromApplicationName, String fromAgentName, List<ServiceType> toServiceList, String toApplicationName, String toAgentName, Long fromResponseTime, Long toResponseTime, Boolean includeFailed, FilterHint hint, ServiceTypeRegistryService registry) {
if (fromServiceList == null) {
throw new NullPointerException("fromServiceList must not be null");
@@ -61,6 +64,9 @@ public FromToResponseFilter(List<ServiceType> fromServiceList, String fromApplic
if (hint == null) {
throw new NullPointerException("hint must not be null");
}
+ if (registry == null) {
+ throw new NullPointerException("registry must not be null");
+ }
this.fromServiceCode = fromServiceList;
this.fromApplicationName = fromApplicationName;
@@ -74,8 +80,9 @@ public FromToResponseFilter(List<ServiceType> fromServiceList, String fromApplic
this.toResponseTime = toResponseTime;
this.includeFailed = includeFailed;
-
this.hint = hint;
+
+ this.registry = registry;
}
private boolean checkResponseCondition(long elapsed, boolean hasError) {
@@ -211,8 +218,12 @@ public boolean include(List<SpanBo> transaction) {
return false;
}
- private boolean isRpcClient(short serviceType) {
- return ServiceTypeCategory.RPC.contains(serviceType);
+ private boolean isRpcClient(short serviceTypeCode) {
+ if (ServiceTypeCategory.RPC.contains(serviceTypeCode)) {
+ ServiceType serviceType = this.registry.findServiceType(serviceTypeCode);
+ return serviceType.isRecordStatistics();
+ }
+ return false;
}
| null | test | train | 2015-05-28T10:15:14 | "2015-05-28T07:43:42Z" | Xylus | test |
pinpoint-apm/pinpoint/320_494 | pinpoint-apm/pinpoint | pinpoint-apm/pinpoint/320 | pinpoint-apm/pinpoint/494 | [
"keyword_pr_to_issue"
] | 47517674d43183f7876ac1a6f9dd26b0cb7830a5 | a68591e1eed242dfb1f96d15be611e806c8ac5db | [
"1.0.x backport\n"
] | [] | "2015-05-29T02:07:03Z" | [
"enhancement"
] | change deprecated HTablePool api to HConnection | HTablePool API is deprecated.
full request : #318
hbase : https://issues.apache.org/jira/browse/HBASE-6580
| [
"docker/pinpoint-collector/hbase.properties",
"docker/pinpoint-collector/pinpoint-collector.properties",
"docker/pinpoint-web/hbase.properties",
"quickstart/collector/src/main/resources/hbase.properties",
"quickstart/collector/src/main/resources/pinpoint-collector.properties",
"quickstart/web/src/main/resources/hbase.properties"
] | [
"docker/pinpoint-collector/hbase.properties",
"docker/pinpoint-collector/pinpoint-collector.properties",
"docker/pinpoint-web/hbase.properties",
"quickstart/collector/src/main/resources/hbase.properties",
"quickstart/collector/src/main/resources/pinpoint-collector.properties",
"quickstart/web/src/main/resources/hbase.properties"
] | [] | diff --git a/docker/pinpoint-collector/hbase.properties b/docker/pinpoint-collector/hbase.properties
index ab80251d5b30..4161185c010c 100644
--- a/docker/pinpoint-collector/hbase.properties
+++ b/docker/pinpoint-collector/hbase.properties
@@ -1,3 +1,22 @@
hbase.client.host=HBASE_HOST
hbase.client.port=HBASE_PORT
-hbase.htable.threads.max=4
\ No newline at end of file
+
+# hbase timeout option==================================================================================
+# hbase default:true
+hbase.ipc.client.tcpnodelay=true
+# hbase default:60000
+hbase.rpc.timeout=10000
+# hbase default:Integer.MAX_VALUE
+hbase.client.operation.timeout=10000
+
+# hbase socket read timeout. default: 200000
+hbase.ipc.client.socket.timeout.read=20000
+# socket write timeout. hbase default: 600000
+hbase.ipc.client.socket.timeout.write=60000
+
+# ==================================================================================
+# hbase client thread pool option
+hbase.client.thread.max=128
+hbase.client.threadPool.queueSize=5120
+# prestartAllCoreThreads
+hbase.client.threadPool.prestart=false
\ No newline at end of file
diff --git a/docker/pinpoint-collector/pinpoint-collector.properties b/docker/pinpoint-collector/pinpoint-collector.properties
index 2befb7307b85..8cc0875fb0e3 100644
--- a/docker/pinpoint-collector/pinpoint-collector.properties
+++ b/docker/pinpoint-collector/pinpoint-collector.properties
@@ -1,5 +1,3 @@
-hbase.hTablePoolSize=1024
-
# tcp listen ip
collector.tcpListenIp=0.0.0.0
collector.tcpListenPort=COLLECTOR_TCP_PORT
diff --git a/docker/pinpoint-web/hbase.properties b/docker/pinpoint-web/hbase.properties
index ab80251d5b30..4161185c010c 100644
--- a/docker/pinpoint-web/hbase.properties
+++ b/docker/pinpoint-web/hbase.properties
@@ -1,3 +1,22 @@
hbase.client.host=HBASE_HOST
hbase.client.port=HBASE_PORT
-hbase.htable.threads.max=4
\ No newline at end of file
+
+# hbase timeout option==================================================================================
+# hbase default:true
+hbase.ipc.client.tcpnodelay=true
+# hbase default:60000
+hbase.rpc.timeout=10000
+# hbase default:Integer.MAX_VALUE
+hbase.client.operation.timeout=10000
+
+# hbase socket read timeout. default: 200000
+hbase.ipc.client.socket.timeout.read=20000
+# socket write timeout. hbase default: 600000
+hbase.ipc.client.socket.timeout.write=60000
+
+# ==================================================================================
+# hbase client thread pool option
+hbase.client.thread.max=128
+hbase.client.threadPool.queueSize=5120
+# prestartAllCoreThreads
+hbase.client.threadPool.prestart=false
\ No newline at end of file
diff --git a/quickstart/collector/src/main/resources/hbase.properties b/quickstart/collector/src/main/resources/hbase.properties
index 614a0727bdfe..be6e5ea43e88 100644
--- a/quickstart/collector/src/main/resources/hbase.properties
+++ b/quickstart/collector/src/main/resources/hbase.properties
@@ -1,4 +1,23 @@
# example
hbase.client.host=localhost
hbase.client.port=2181
-hbase.htable.threads.max=4
\ No newline at end of file
+
+# hbase timeout option==================================================================================
+# hbase default:true
+hbase.ipc.client.tcpnodelay=true
+# hbase default:60000
+hbase.rpc.timeout=10000
+# hbase default:Integer.MAX_VALUE
+hbase.client.operation.timeout=10000
+
+# hbase socket read timeout. default: 200000
+hbase.ipc.client.socket.timeout.read=20000
+# socket write timeout. hbase default: 600000
+hbase.ipc.client.socket.timeout.write=60000
+
+# ==================================================================================
+# hbase client thread pool option
+hbase.client.thread.max=128
+hbase.client.threadPool.queueSize=5120
+# prestartAllCoreThreads
+hbase.client.threadPool.prestart=false
\ No newline at end of file
diff --git a/quickstart/collector/src/main/resources/pinpoint-collector.properties b/quickstart/collector/src/main/resources/pinpoint-collector.properties
index c43513cf6c75..dcd60c61e29f 100644
--- a/quickstart/collector/src/main/resources/pinpoint-collector.properties
+++ b/quickstart/collector/src/main/resources/pinpoint-collector.properties
@@ -1,5 +1,3 @@
-hbase.hTablePoolSize=1024
-
# tcp listen ip
collector.tcpListenIp=0.0.0.0
collector.tcpListenPort=29994
diff --git a/quickstart/web/src/main/resources/hbase.properties b/quickstart/web/src/main/resources/hbase.properties
index 614a0727bdfe..be6e5ea43e88 100644
--- a/quickstart/web/src/main/resources/hbase.properties
+++ b/quickstart/web/src/main/resources/hbase.properties
@@ -1,4 +1,23 @@
# example
hbase.client.host=localhost
hbase.client.port=2181
-hbase.htable.threads.max=4
\ No newline at end of file
+
+# hbase timeout option==================================================================================
+# hbase default:true
+hbase.ipc.client.tcpnodelay=true
+# hbase default:60000
+hbase.rpc.timeout=10000
+# hbase default:Integer.MAX_VALUE
+hbase.client.operation.timeout=10000
+
+# hbase socket read timeout. default: 200000
+hbase.ipc.client.socket.timeout.read=20000
+# socket write timeout. hbase default: 600000
+hbase.ipc.client.socket.timeout.write=60000
+
+# ==================================================================================
+# hbase client thread pool option
+hbase.client.thread.max=128
+hbase.client.threadPool.queueSize=5120
+# prestartAllCoreThreads
+hbase.client.threadPool.prestart=false
\ No newline at end of file
| null | train | train | 2015-05-29T03:51:21 | "2015-04-10T10:13:35Z" | emeroad | test |