index int64 0 0 | repo_id stringlengths 9 205 | file_path stringlengths 31 246 | content stringlengths 1 12.2M | __index_level_0__ int64 0 10k |
|---|---|---|---|---|
0 | Create_ds/retrofit/retrofit/src/test/java | Create_ds/retrofit/retrofit/src/test/java/retrofit2/DefaultMethodsTest.java | /*
* 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 static org.assertj.core.api.Assertions.assertThat;
import java.io.IOException;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import org.junit.Rule;
import org.junit.Test;
import retrofit2.helpers.ToStringConverterFactory;
import retrofit2.http.GET;
import retrofit2.http.Query;
public final class DefaultMethodsTest {
@Rule public final MockWebServer server = new MockWebServer();
interface Example {
@GET("/")
Call<String> user(@Query("name") String name);
default Call<String> user() {
return user("hey");
}
}
@Test
public void test() 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");
}
}
| 3,700 |
0 | Create_ds/retrofit/retrofit/src/main/java | Create_ds/retrofit/retrofit/src/main/java/retrofit2/CompletableFutureCallAdapterFactory.java | /*
* 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 android.annotation.TargetApi;
import java.lang.annotation.Annotation;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.concurrent.CompletableFuture;
import javax.annotation.Nullable;
import org.codehaus.mojo.animal_sniffer.IgnoreJRERequirement;
@IgnoreJRERequirement // Only added when CompletableFuture is available (Java 8+ / Android API 24+).
@TargetApi(24)
final class CompletableFutureCallAdapterFactory extends CallAdapter.Factory {
@Override
public @Nullable CallAdapter<?, ?> get(
Type returnType, Annotation[] annotations, Retrofit retrofit) {
if (getRawType(returnType) != CompletableFuture.class) {
return null;
}
if (!(returnType instanceof ParameterizedType)) {
throw new IllegalStateException(
"CompletableFuture return type must be parameterized"
+ " as CompletableFuture<Foo> or CompletableFuture<? extends Foo>");
}
Type innerType = getParameterUpperBound(0, (ParameterizedType) returnType);
if (getRawType(innerType) != Response.class) {
// Generic type is not Response<T>. Use it for body-only adapter.
return new BodyCallAdapter<>(innerType);
}
// Generic type is Response<T>. Extract T and create the Response version of the adapter.
if (!(innerType instanceof ParameterizedType)) {
throw new IllegalStateException(
"Response must be parameterized" + " as Response<Foo> or Response<? extends Foo>");
}
Type responseType = getParameterUpperBound(0, (ParameterizedType) innerType);
return new ResponseCallAdapter<>(responseType);
}
@IgnoreJRERequirement
private static final class BodyCallAdapter<R> implements CallAdapter<R, CompletableFuture<R>> {
private final Type responseType;
BodyCallAdapter(Type responseType) {
this.responseType = responseType;
}
@Override
public Type responseType() {
return responseType;
}
@Override
public CompletableFuture<R> adapt(final Call<R> call) {
CompletableFuture<R> future = new CallCancelCompletableFuture<>(call);
call.enqueue(new BodyCallback(future));
return future;
}
@IgnoreJRERequirement
private class BodyCallback implements Callback<R> {
private final CompletableFuture<R> future;
public BodyCallback(CompletableFuture<R> future) {
this.future = future;
}
@Override
public void onResponse(Call<R> call, Response<R> response) {
if (response.isSuccessful()) {
future.complete(response.body());
} else {
future.completeExceptionally(new HttpException(response));
}
}
@Override
public void onFailure(Call<R> call, Throwable t) {
future.completeExceptionally(t);
}
}
}
@IgnoreJRERequirement
private static final class ResponseCallAdapter<R>
implements CallAdapter<R, CompletableFuture<Response<R>>> {
private final Type responseType;
ResponseCallAdapter(Type responseType) {
this.responseType = responseType;
}
@Override
public Type responseType() {
return responseType;
}
@Override
public CompletableFuture<Response<R>> adapt(final Call<R> call) {
CompletableFuture<Response<R>> future = new CallCancelCompletableFuture<>(call);
call.enqueue(new ResponseCallback(future));
return future;
}
@IgnoreJRERequirement
private class ResponseCallback implements Callback<R> {
private final CompletableFuture<Response<R>> future;
public ResponseCallback(CompletableFuture<Response<R>> future) {
this.future = future;
}
@Override
public void onResponse(Call<R> call, Response<R> response) {
future.complete(response);
}
@Override
public void onFailure(Call<R> call, Throwable t) {
future.completeExceptionally(t);
}
}
}
@IgnoreJRERequirement
private static final class CallCancelCompletableFuture<T> extends CompletableFuture<T> {
private final Call<?> call;
CallCancelCompletableFuture(Call<?> call) {
this.call = call;
}
@Override
public boolean cancel(boolean mayInterruptIfRunning) {
if (mayInterruptIfRunning) {
call.cancel();
}
return super.cancel(mayInterruptIfRunning);
}
}
}
| 3,701 |
0 | Create_ds/retrofit/retrofit/src/main/java | Create_ds/retrofit/retrofit/src/main/java/retrofit2/Invocation.java | /*
* Copyright (C) 2018 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.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
/**
* A single invocation of a Retrofit service interface method. This class captures both the method
* that was called and the arguments to the method.
*
* <p>Retrofit automatically adds an invocation to each OkHttp request as a tag. You can retrieve
* the invocation in an OkHttp interceptor for metrics and monitoring.
*
* <pre><code>
* class InvocationLogger implements Interceptor {
* @Override public Response intercept(Chain chain) throws IOException {
* Request request = chain.request();
* 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());
* }
* return chain.proceed(request);
* }
* }
* </code></pre>
*
* <strong>Note:</strong> use caution when examining an invocation's arguments. Although the
* arguments list is unmodifiable, the arguments themselves may be mutable. They may also be unsafe
* for concurrent access. For best results declare Retrofit service interfaces using only immutable
* types for parameters!
*/
public final class Invocation {
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.
}
private final Method method;
private final List<?> arguments;
/** Trusted constructor assumes ownership of {@code arguments}. */
Invocation(Method method, List<?> arguments) {
this.method = method;
this.arguments = Collections.unmodifiableList(arguments);
}
public Method method() {
return method;
}
public List<?> arguments() {
return arguments;
}
@Override
public String toString() {
return String.format(
"%s.%s() %s", method.getDeclaringClass().getName(), method.getName(), arguments);
}
}
| 3,702 |
0 | Create_ds/retrofit/retrofit/src/main/java | Create_ds/retrofit/retrofit/src/main/java/retrofit2/Response.java | /*
* 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.util.Objects;
import javax.annotation.Nullable;
import okhttp3.Headers;
import okhttp3.Protocol;
import okhttp3.Request;
import okhttp3.ResponseBody;
/** An HTTP response. */
public final class Response<T> {
/** Create a synthetic successful response with {@code body} as the deserialized body. */
public static <T> Response<T> success(@Nullable T body) {
return success(
body,
new okhttp3.Response.Builder() //
.code(200)
.message("OK")
.protocol(Protocol.HTTP_1_1)
.request(new Request.Builder().url("http://localhost/").build())
.build());
}
/**
* Create a synthetic successful response with an HTTP status code of {@code code} and {@code
* body} as the deserialized body.
*/
public static <T> Response<T> success(int code, @Nullable T body) {
if (code < 200 || code >= 300) {
throw new IllegalArgumentException("code < 200 or >= 300: " + code);
}
return success(
body,
new okhttp3.Response.Builder() //
.code(code)
.message("Response.success()")
.protocol(Protocol.HTTP_1_1)
.request(new Request.Builder().url("http://localhost/").build())
.build());
}
/**
* Create a synthetic successful response using {@code headers} with {@code body} as the
* deserialized body.
*/
public static <T> Response<T> success(@Nullable T body, Headers headers) {
Objects.requireNonNull(headers, "headers == null");
return success(
body,
new okhttp3.Response.Builder() //
.code(200)
.message("OK")
.protocol(Protocol.HTTP_1_1)
.headers(headers)
.request(new Request.Builder().url("http://localhost/").build())
.build());
}
/**
* Create a successful response from {@code rawResponse} with {@code body} as the deserialized
* body.
*/
public static <T> Response<T> success(@Nullable T body, okhttp3.Response rawResponse) {
Objects.requireNonNull(rawResponse, "rawResponse == null");
if (!rawResponse.isSuccessful()) {
throw new IllegalArgumentException("rawResponse must be successful response");
}
return new Response<>(rawResponse, body, null);
}
/**
* Create a synthetic error response with an HTTP status code of {@code code} and {@code body} as
* the error body.
*/
public static <T> Response<T> error(int code, ResponseBody body) {
Objects.requireNonNull(body, "body == null");
if (code < 400) throw new IllegalArgumentException("code < 400: " + code);
return error(
body,
new okhttp3.Response.Builder() //
.body(new OkHttpCall.NoContentResponseBody(body.contentType(), body.contentLength()))
.code(code)
.message("Response.error()")
.protocol(Protocol.HTTP_1_1)
.request(new Request.Builder().url("http://localhost/").build())
.build());
}
/** Create an error response from {@code rawResponse} with {@code body} as the error body. */
public static <T> Response<T> error(ResponseBody body, okhttp3.Response rawResponse) {
Objects.requireNonNull(body, "body == null");
Objects.requireNonNull(rawResponse, "rawResponse == null");
if (rawResponse.isSuccessful()) {
throw new IllegalArgumentException("rawResponse should not be successful response");
}
return new Response<>(rawResponse, null, body);
}
private final okhttp3.Response rawResponse;
private final @Nullable T body;
private final @Nullable ResponseBody errorBody;
private Response(
okhttp3.Response rawResponse, @Nullable T body, @Nullable ResponseBody errorBody) {
this.rawResponse = rawResponse;
this.body = body;
this.errorBody = errorBody;
}
/** The raw response from the HTTP client. */
public okhttp3.Response raw() {
return rawResponse;
}
/** HTTP status code. */
public int code() {
return rawResponse.code();
}
/** HTTP status message or null if unknown. */
public String message() {
return rawResponse.message();
}
/** HTTP headers. */
public Headers headers() {
return rawResponse.headers();
}
/** Returns true if {@link #code()} is in the range [200..300). */
public boolean isSuccessful() {
return rawResponse.isSuccessful();
}
/** The deserialized response body of a {@linkplain #isSuccessful() successful} response. */
public @Nullable T body() {
return body;
}
/** The raw response body of an {@linkplain #isSuccessful() unsuccessful} response. */
public @Nullable ResponseBody errorBody() {
return errorBody;
}
@Override
public String toString() {
return rawResponse.toString();
}
}
| 3,703 |
0 | Create_ds/retrofit/retrofit/src/main/java | Create_ds/retrofit/retrofit/src/main/java/retrofit2/RequestBuilder.java | /*
* Copyright (C) 2012 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 java.util.regex.Pattern;
import javax.annotation.Nullable;
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.HttpUrl;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.Request;
import okhttp3.RequestBody;
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_ALWAYS_ENCODE_SET = " \"<>^`{}|\\?#";
/**
* Matches strings that contain {@code .} or {@code ..} as a complete path segment. This also
* matches dots in their percent-encoded form, {@code %2E}.
*
* <p>It is okay to have these strings within a larger path segment (like {@code a..z} or {@code
* index.html}) but when alone they have a special meaning. A single dot resolves to no path
* segment so {@code /one/./three/} becomes {@code /one/three/}. A double-dot pops the preceding
* directory, so {@code /one/../three/} becomes {@code /three/}.
*
* <p>We forbid these in Retrofit paths because they're likely to have the unintended effect. For
* example, passing {@code ..} to {@code DELETE /account/book/{isbn}/} yields {@code DELETE
* /account/}.
*/
private static final Pattern PATH_TRAVERSAL = Pattern.compile("(.*/)?(\\.|%2e|%2E){1,2}(/.*)?");
private final String method;
private final HttpUrl baseUrl;
private @Nullable String relativeUrl;
private @Nullable HttpUrl.Builder urlBuilder;
private final Request.Builder requestBuilder;
private final Headers.Builder headersBuilder;
private @Nullable MediaType contentType;
private final boolean hasBody;
private @Nullable MultipartBody.Builder multipartBuilder;
private @Nullable FormBody.Builder formBuilder;
private @Nullable RequestBody body;
RequestBuilder(
String method,
HttpUrl baseUrl,
@Nullable String relativeUrl,
@Nullable Headers headers,
@Nullable MediaType contentType,
boolean hasBody,
boolean isFormEncoded,
boolean isMultipart) {
this.method = method;
this.baseUrl = baseUrl;
this.relativeUrl = relativeUrl;
this.requestBuilder = new Request.Builder();
this.contentType = contentType;
this.hasBody = hasBody;
if (headers != null) {
headersBuilder = headers.newBuilder();
} else {
headersBuilder = new Headers.Builder();
}
if (isFormEncoded) {
// Will be set to 'body' in 'build'.
formBuilder = new FormBody.Builder();
} else if (isMultipart) {
// Will be set to 'body' in 'build'.
multipartBuilder = new MultipartBody.Builder();
multipartBuilder.setType(MultipartBody.FORM);
}
}
void setRelativeUrl(Object relativeUrl) {
this.relativeUrl = relativeUrl.toString();
}
void addHeader(String name, String value, boolean allowUnsafeNonAsciiValues) {
if ("Content-Type".equalsIgnoreCase(name)) {
try {
contentType = MediaType.get(value);
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException("Malformed content type: " + value, e);
}
} else if (allowUnsafeNonAsciiValues) {
headersBuilder.addUnsafeNonAscii(name, value);
} else {
headersBuilder.add(name, value);
}
}
void addHeaders(Headers headers) {
headersBuilder.addAll(headers);
}
void addPathParam(String name, String value, boolean encoded) {
if (relativeUrl == null) {
// The relative URL is cleared when the first query parameter is set.
throw new AssertionError();
}
String replacement = canonicalizeForPath(value, encoded);
String newRelativeUrl = relativeUrl.replace("{" + name + "}", replacement);
if (PATH_TRAVERSAL.matcher(newRelativeUrl).matches()) {
throw new IllegalArgumentException(
"@Path parameters shouldn't perform path traversal ('.' or '..'): " + value);
}
relativeUrl = newRelativeUrl;
}
private static String canonicalizeForPath(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_ALWAYS_ENCODE_SET.indexOf(codePoint) != -1
|| (!alreadyEncoded && (codePoint == '/' || codePoint == '%'))) {
// Slow path: the character at i requires encoding!
Buffer out = new Buffer();
out.writeUtf8(input, 0, i);
canonicalizeForPath(out, input, i, limit, alreadyEncoded);
return out.readUtf8();
}
}
// Fast path: no characters required encoding.
return input;
}
private static void canonicalizeForPath(
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_ALWAYS_ENCODE_SET.indexOf(codePoint) != -1
|| (!alreadyEncoded && (codePoint == '/' || codePoint == '%'))) {
// 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 {
// This character doesn't need encoding. Just copy it over.
out.writeUtf8CodePoint(codePoint);
}
}
}
void addQueryParam(String name, @Nullable String value, boolean encoded) {
if (relativeUrl != null) {
// Do a one-time combination of the built relative URL and the base URL.
urlBuilder = baseUrl.newBuilder(relativeUrl);
if (urlBuilder == null) {
throw new IllegalArgumentException(
"Malformed URL. Base: " + baseUrl + ", Relative: " + relativeUrl);
}
relativeUrl = null;
}
if (encoded) {
//noinspection ConstantConditions Checked to be non-null by above 'if' block.
urlBuilder.addEncodedQueryParameter(name, value);
} else {
//noinspection ConstantConditions Checked to be non-null by above 'if' block.
urlBuilder.addQueryParameter(name, value);
}
}
@SuppressWarnings("ConstantConditions") // Only called when isFormEncoded was true.
void addFormField(String name, String value, boolean encoded) {
if (encoded) {
formBuilder.addEncoded(name, value);
} else {
formBuilder.add(name, value);
}
}
@SuppressWarnings("ConstantConditions") // Only called when isMultipart was true.
void addPart(Headers headers, RequestBody body) {
multipartBuilder.addPart(headers, body);
}
@SuppressWarnings("ConstantConditions") // Only called when isMultipart was true.
void addPart(MultipartBody.Part part) {
multipartBuilder.addPart(part);
}
void setBody(RequestBody body) {
this.body = body;
}
<T> void addTag(Class<T> cls, @Nullable T value) {
requestBuilder.tag(cls, value);
}
Request.Builder get() {
HttpUrl url;
HttpUrl.Builder urlBuilder = this.urlBuilder;
if (urlBuilder != null) {
url = urlBuilder.build();
} else {
// No query parameters triggered builder creation, just combine the relative URL and base URL.
//noinspection ConstantConditions Non-null if urlBuilder is null.
url = baseUrl.resolve(relativeUrl);
if (url == null) {
throw new IllegalArgumentException(
"Malformed URL. Base: " + baseUrl + ", Relative: " + relativeUrl);
}
}
RequestBody body = this.body;
if (body == null) {
// Try to pull from one of the builders.
if (formBuilder != null) {
body = formBuilder.build();
} else if (multipartBuilder != null) {
body = multipartBuilder.build();
} else if (hasBody) {
// Body is absent, make an empty body.
body = RequestBody.create(null, new byte[0]);
}
}
MediaType contentType = this.contentType;
if (contentType != null) {
if (body != null) {
body = new ContentTypeOverridingRequestBody(body, contentType);
} else {
headersBuilder.add("Content-Type", contentType.toString());
}
}
return requestBuilder.url(url).headers(headersBuilder.build()).method(method, body);
}
private static class ContentTypeOverridingRequestBody extends RequestBody {
private final RequestBody delegate;
private final MediaType contentType;
ContentTypeOverridingRequestBody(RequestBody delegate, MediaType contentType) {
this.delegate = delegate;
this.contentType = contentType;
}
@Override
public MediaType contentType() {
return contentType;
}
@Override
public long contentLength() throws IOException {
return delegate.contentLength();
}
@Override
public void writeTo(BufferedSink sink) throws IOException {
delegate.writeTo(sink);
}
}
}
| 3,704 |
0 | Create_ds/retrofit/retrofit/src/main/java | Create_ds/retrofit/retrofit/src/main/java/retrofit2/Retrofit.java | /*
* Copyright (C) 2012 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 static java.util.Collections.unmodifiableList;
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.net.URL;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Deque;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executor;
import javax.annotation.Nullable;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.http.GET;
import retrofit2.http.HTTP;
import retrofit2.http.Header;
import retrofit2.http.Url;
/**
* Retrofit adapts a Java interface to HTTP calls by using annotations on the declared methods to
* define how requests are made. Create instances using {@linkplain Builder the builder} and pass
* your interface to {@link #create} to generate an implementation.
*
* <p>For example,
*
* <pre><code>
* Retrofit retrofit = new Retrofit.Builder()
* .baseUrl("https://api.example.com/")
* .addConverterFactory(GsonConverterFactory.create())
* .build();
*
* MyApi api = retrofit.create(MyApi.class);
* Response<User> user = api.getUser().execute();
* </code></pre>
*
* @author Bob Lee (bob@squareup.com)
* @author Jake Wharton (jw@squareup.com)
*/
public final class Retrofit {
private final Map<Method, ServiceMethod<?>> serviceMethodCache = new ConcurrentHashMap<>();
final okhttp3.Call.Factory callFactory;
final HttpUrl baseUrl;
final List<Converter.Factory> converterFactories;
final int defaultConverterFactoriesSize;
final List<CallAdapter.Factory> callAdapterFactories;
final int defaultCallAdapterFactoriesSize;
final @Nullable Executor callbackExecutor;
final boolean validateEagerly;
Retrofit(
okhttp3.Call.Factory callFactory,
HttpUrl baseUrl,
List<Converter.Factory> converterFactories,
int defaultConverterFactoriesSize,
List<CallAdapter.Factory> callAdapterFactories,
int defaultCallAdapterFactoriesSize,
@Nullable Executor callbackExecutor,
boolean validateEagerly) {
this.callFactory = callFactory;
this.baseUrl = baseUrl;
this.converterFactories = converterFactories; // Copy+unmodifiable at call site.
this.defaultConverterFactoriesSize = defaultConverterFactoriesSize;
this.callAdapterFactories = callAdapterFactories; // Copy+unmodifiable at call site.
this.defaultCallAdapterFactoriesSize = defaultCallAdapterFactoriesSize;
this.callbackExecutor = callbackExecutor;
this.validateEagerly = validateEagerly;
}
/**
* Create an implementation of the API endpoints defined by the {@code service} interface.
*
* <p>The relative path for a given method is obtained from an annotation on the method describing
* the request type. The built-in methods are {@link retrofit2.http.GET GET}, {@link
* retrofit2.http.PUT PUT}, {@link retrofit2.http.POST POST}, {@link retrofit2.http.PATCH PATCH},
* {@link retrofit2.http.HEAD HEAD}, {@link retrofit2.http.DELETE DELETE} and {@link
* retrofit2.http.OPTIONS OPTIONS}. You can use a custom HTTP method with {@link HTTP @HTTP}. For
* a dynamic URL, omit the path on the annotation and annotate the first parameter with {@link
* Url @Url}.
*
* <p>Method parameters can be used to replace parts of the URL by annotating them with {@link
* retrofit2.http.Path @Path}. Replacement sections are denoted by an identifier surrounded by
* curly braces (e.g., "{foo}"). To add items to the query string of a URL use {@link
* retrofit2.http.Query @Query}.
*
* <p>The body of a request is denoted by the {@link retrofit2.http.Body @Body} annotation. The
* object will be converted to request representation by one of the {@link Converter.Factory}
* instances. A {@link RequestBody} can also be used for a raw representation.
*
* <p>Alternative request body formats are supported by method annotations and corresponding
* parameter annotations:
*
* <ul>
* <li>{@link retrofit2.http.FormUrlEncoded @FormUrlEncoded} - Form-encoded data with key-value
* pairs specified by the {@link retrofit2.http.Field @Field} parameter annotation.
* <li>{@link retrofit2.http.Multipart @Multipart} - RFC 2388-compliant multipart data with
* parts specified by the {@link retrofit2.http.Part @Part} parameter annotation.
* </ul>
*
* <p>Additional static headers can be added for an endpoint using the {@link
* retrofit2.http.Headers @Headers} method annotation. For per-request control over a header
* annotate a parameter with {@link Header @Header}.
*
* <p>By default, methods return a {@link Call} which represents the HTTP request. The generic
* parameter of the call is the response body type and will be converted by one of the {@link
* Converter.Factory} instances. {@link ResponseBody} can also be used for a raw representation.
* {@link Void} can be used if you do not care about the body contents.
*
* <p>For example:
*
* <pre>
* public interface CategoryService {
* @POST("category/{cat}/")
* Call<List<Item>> categoryList(@Path("cat") String a, @Query("page") int b);
* }
* </pre>
*/
@SuppressWarnings("unchecked") // Single-interface proxy creation guarded by parameter safety.
public <T> T create(final Class<T> service) {
validateServiceInterface(service);
return (T)
Proxy.newProxyInstance(
service.getClassLoader(),
new Class<?>[] {service},
new InvocationHandler() {
private final Object[] emptyArgs = new Object[0];
@Override
public @Nullable Object invoke(Object proxy, Method method, @Nullable Object[] args)
throws Throwable {
// If the method is a method from Object then defer to normal invocation.
if (method.getDeclaringClass() == Object.class) {
return method.invoke(this, args);
}
args = args != null ? args : emptyArgs;
Platform platform = Platform.get();
return platform.isDefaultMethod(method)
? platform.invokeDefaultMethod(method, service, proxy, args)
: loadServiceMethod(service, method).invoke(args);
}
});
}
private void validateServiceInterface(Class<?> service) {
if (!service.isInterface()) {
throw new IllegalArgumentException("API declarations must be interfaces.");
}
Deque<Class<?>> check = new ArrayDeque<>(1);
check.add(service);
while (!check.isEmpty()) {
Class<?> candidate = check.removeFirst();
if (candidate.getTypeParameters().length != 0) {
StringBuilder message =
new StringBuilder("Type parameters are unsupported on ").append(candidate.getName());
if (candidate != service) {
message.append(" which is an interface of ").append(service.getName());
}
throw new IllegalArgumentException(message.toString());
}
Collections.addAll(check, candidate.getInterfaces());
}
if (validateEagerly) {
Platform platform = Platform.get();
for (Method method : service.getDeclaredMethods()) {
if (!platform.isDefaultMethod(method) && !Modifier.isStatic(method.getModifiers())) {
loadServiceMethod(service, method);
}
}
}
}
ServiceMethod<?> loadServiceMethod(Class<?> service, Method method) {
ServiceMethod<?> result = serviceMethodCache.get(method);
if (result != null) return result;
synchronized (service) {
result = serviceMethodCache.get(method);
if (result == null) {
result = ServiceMethod.parseAnnotations(this, method);
serviceMethodCache.put(method, result);
}
}
return result;
}
/**
* 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;
}
/** The API base URL. */
public HttpUrl baseUrl() {
return baseUrl;
}
/**
* Returns a list of the factories tried when creating a {@linkplain #callAdapter(Type,
* Annotation[])} call adapter}.
*/
public List<CallAdapter.Factory> callAdapterFactories() {
return callAdapterFactories;
}
/**
* Returns the {@link CallAdapter} for {@code returnType} from the available {@linkplain
* #callAdapterFactories() factories}.
*
* @throws IllegalArgumentException if no call adapter available for {@code type}.
*/
public CallAdapter<?, ?> callAdapter(Type returnType, Annotation[] annotations) {
return nextCallAdapter(null, returnType, annotations);
}
/**
* Returns the {@link CallAdapter} for {@code returnType} from the available {@linkplain
* #callAdapterFactories() factories} except {@code skipPast}.
*
* @throws IllegalArgumentException if no call adapter available for {@code type}.
*/
public CallAdapter<?, ?> nextCallAdapter(
@Nullable CallAdapter.Factory skipPast, Type returnType, Annotation[] annotations) {
Objects.requireNonNull(returnType, "returnType == null");
Objects.requireNonNull(annotations, "annotations == null");
int start = callAdapterFactories.indexOf(skipPast) + 1;
for (int i = start, count = callAdapterFactories.size(); i < count; i++) {
CallAdapter<?, ?> adapter = callAdapterFactories.get(i).get(returnType, annotations, this);
if (adapter != null) {
return adapter;
}
}
StringBuilder builder =
new StringBuilder("Could not locate call adapter for ").append(returnType).append(".\n");
if (skipPast != null) {
builder.append(" Skipped:");
for (int i = 0; i < start; i++) {
builder.append("\n * ").append(callAdapterFactories.get(i).getClass().getName());
}
builder.append('\n');
}
builder.append(" Tried:");
for (int i = start, count = callAdapterFactories.size(); i < count; i++) {
builder.append("\n * ").append(callAdapterFactories.get(i).getClass().getName());
}
throw new IllegalArgumentException(builder.toString());
}
/**
* Returns an unmodifiable list of the factories tried when creating a {@linkplain
* #requestBodyConverter(Type, Annotation[], Annotation[]) request body converter}, a {@linkplain
* #responseBodyConverter(Type, Annotation[]) response body converter}, or a {@linkplain
* #stringConverter(Type, Annotation[]) string converter}.
*/
public List<Converter.Factory> converterFactories() {
return converterFactories;
}
/**
* Returns a {@link Converter} for {@code type} to {@link RequestBody} from the available
* {@linkplain #converterFactories() factories}.
*
* @throws IllegalArgumentException if no converter available for {@code type}.
*/
public <T> Converter<T, RequestBody> requestBodyConverter(
Type type, Annotation[] parameterAnnotations, Annotation[] methodAnnotations) {
return nextRequestBodyConverter(null, type, parameterAnnotations, methodAnnotations);
}
/**
* Returns a {@link Converter} for {@code type} to {@link RequestBody} from the available
* {@linkplain #converterFactories() factories} except {@code skipPast}.
*
* @throws IllegalArgumentException if no converter available for {@code type}.
*/
public <T> Converter<T, RequestBody> nextRequestBodyConverter(
@Nullable Converter.Factory skipPast,
Type type,
Annotation[] parameterAnnotations,
Annotation[] methodAnnotations) {
Objects.requireNonNull(type, "type == null");
Objects.requireNonNull(parameterAnnotations, "parameterAnnotations == null");
Objects.requireNonNull(methodAnnotations, "methodAnnotations == null");
int start = converterFactories.indexOf(skipPast) + 1;
for (int i = start, count = converterFactories.size(); i < count; i++) {
Converter.Factory factory = converterFactories.get(i);
Converter<?, RequestBody> converter =
factory.requestBodyConverter(type, parameterAnnotations, methodAnnotations, this);
if (converter != null) {
//noinspection unchecked
return (Converter<T, RequestBody>) converter;
}
}
StringBuilder builder =
new StringBuilder("Could not locate RequestBody converter for ").append(type).append(".\n");
if (skipPast != null) {
builder.append(" Skipped:");
for (int i = 0; i < start; i++) {
builder.append("\n * ").append(converterFactories.get(i).getClass().getName());
}
builder.append('\n');
}
builder.append(" Tried:");
for (int i = start, count = converterFactories.size(); i < count; i++) {
builder.append("\n * ").append(converterFactories.get(i).getClass().getName());
}
throw new IllegalArgumentException(builder.toString());
}
/**
* Returns a {@link Converter} for {@link ResponseBody} to {@code type} from the available
* {@linkplain #converterFactories() factories}.
*
* @throws IllegalArgumentException if no converter available for {@code type}.
*/
public <T> Converter<ResponseBody, T> responseBodyConverter(Type type, Annotation[] annotations) {
return nextResponseBodyConverter(null, type, annotations);
}
/**
* Returns a {@link Converter} for {@link ResponseBody} to {@code type} from the available
* {@linkplain #converterFactories() factories} except {@code skipPast}.
*
* @throws IllegalArgumentException if no converter available for {@code type}.
*/
public <T> Converter<ResponseBody, T> nextResponseBodyConverter(
@Nullable Converter.Factory skipPast, Type type, Annotation[] annotations) {
Objects.requireNonNull(type, "type == null");
Objects.requireNonNull(annotations, "annotations == null");
int start = converterFactories.indexOf(skipPast) + 1;
for (int i = start, count = converterFactories.size(); i < count; i++) {
Converter<ResponseBody, ?> converter =
converterFactories.get(i).responseBodyConverter(type, annotations, this);
if (converter != null) {
//noinspection unchecked
return (Converter<ResponseBody, T>) converter;
}
}
StringBuilder builder =
new StringBuilder("Could not locate ResponseBody converter for ")
.append(type)
.append(".\n");
if (skipPast != null) {
builder.append(" Skipped:");
for (int i = 0; i < start; i++) {
builder.append("\n * ").append(converterFactories.get(i).getClass().getName());
}
builder.append('\n');
}
builder.append(" Tried:");
for (int i = start, count = converterFactories.size(); i < count; i++) {
builder.append("\n * ").append(converterFactories.get(i).getClass().getName());
}
throw new IllegalArgumentException(builder.toString());
}
/**
* Returns a {@link Converter} for {@code type} to {@link String} from the available {@linkplain
* #converterFactories() factories}.
*/
public <T> Converter<T, String> stringConverter(Type type, Annotation[] annotations) {
Objects.requireNonNull(type, "type == null");
Objects.requireNonNull(annotations, "annotations == null");
for (int i = 0, count = converterFactories.size(); i < count; i++) {
Converter<?, String> converter =
converterFactories.get(i).stringConverter(type, annotations, this);
if (converter != null) {
//noinspection unchecked
return (Converter<T, String>) converter;
}
}
// Nothing matched. Resort to default converter which just calls toString().
//noinspection unchecked
return (Converter<T, String>) BuiltInConverters.ToStringConverter.INSTANCE;
}
/**
* The executor used for {@link Callback} methods on a {@link Call}. This may be {@code null}, in
* which case callbacks should be made synchronously on the background thread.
*/
public @Nullable Executor callbackExecutor() {
return callbackExecutor;
}
public Builder newBuilder() {
return new Builder(this);
}
/**
* Build a new {@link Retrofit}.
*
* <p>Calling {@link #baseUrl} is required before calling {@link #build()}. All other methods are
* optional.
*/
public static final class Builder {
private @Nullable okhttp3.Call.Factory callFactory;
private @Nullable HttpUrl baseUrl;
private final List<Converter.Factory> converterFactories = new ArrayList<>();
private final List<CallAdapter.Factory> callAdapterFactories = new ArrayList<>();
private @Nullable Executor callbackExecutor;
private boolean validateEagerly;
public Builder() {}
Builder(Retrofit retrofit) {
callFactory = retrofit.callFactory;
baseUrl = retrofit.baseUrl;
// Do not add the default BuiltIntConverters and platform-aware converters added by build().
for (int i = 1,
size = retrofit.converterFactories.size() - retrofit.defaultConverterFactoriesSize;
i < size;
i++) {
converterFactories.add(retrofit.converterFactories.get(i));
}
// Do not add the default, platform-aware call adapters added by build().
for (int i = 0,
size =
retrofit.callAdapterFactories.size() - retrofit.defaultCallAdapterFactoriesSize;
i < size;
i++) {
callAdapterFactories.add(retrofit.callAdapterFactories.get(i));
}
callbackExecutor = retrofit.callbackExecutor;
validateEagerly = retrofit.validateEagerly;
}
/**
* The HTTP client used for requests.
*
* <p>This is a convenience method for calling {@link #callFactory}.
*/
public Builder client(OkHttpClient client) {
return callFactory(Objects.requireNonNull(client, "client == null"));
}
/**
* Specify a custom call factory for creating {@link Call} instances.
*
* <p>Note: Calling {@link #client} automatically sets this value.
*/
public Builder callFactory(okhttp3.Call.Factory factory) {
this.callFactory = Objects.requireNonNull(factory, "factory == null");
return this;
}
/**
* Set the API base URL.
*
* @see #baseUrl(HttpUrl)
*/
public Builder baseUrl(URL baseUrl) {
Objects.requireNonNull(baseUrl, "baseUrl == null");
return baseUrl(HttpUrl.get(baseUrl.toString()));
}
/**
* Set the API base URL.
*
* @see #baseUrl(HttpUrl)
*/
public Builder baseUrl(String baseUrl) {
Objects.requireNonNull(baseUrl, "baseUrl == null");
return baseUrl(HttpUrl.get(baseUrl));
}
/**
* Set the API base URL.
*
* <p>The specified endpoint values (such as with {@link GET @GET}) are resolved against this
* value using {@link HttpUrl#resolve(String)}. The behavior of this matches that of an {@code
* <a href="">} link on a website resolving on the current URL.
*
* <p><b>Base URLs should always end in {@code /}.</b>
*
* <p>A trailing {@code /} ensures that endpoints values which are relative paths will correctly
* append themselves to a base which has path components.
*
* <p><b>Correct:</b><br>
* Base URL: http://example.com/api/<br>
* Endpoint: foo/bar/<br>
* Result: http://example.com/api/foo/bar/
*
* <p><b>Incorrect:</b><br>
* Base URL: http://example.com/api<br>
* Endpoint: foo/bar/<br>
* Result: http://example.com/foo/bar/
*
* <p>This method enforces that {@code baseUrl} has a trailing {@code /}.
*
* <p><b>Endpoint values which contain a leading {@code /} are absolute.</b>
*
* <p>Absolute values retain only the host from {@code baseUrl} and ignore any specified path
* components.
*
* <p>Base URL: http://example.com/api/<br>
* Endpoint: /foo/bar/<br>
* Result: http://example.com/foo/bar/
*
* <p>Base URL: http://example.com/<br>
* Endpoint: /foo/bar/<br>
* Result: http://example.com/foo/bar/
*
* <p><b>Endpoint values may be a full URL.</b>
*
* <p>Values which have a host replace the host of {@code baseUrl} and values also with a scheme
* replace the scheme of {@code baseUrl}.
*
* <p>Base URL: http://example.com/<br>
* Endpoint: https://github.com/square/retrofit/<br>
* Result: https://github.com/square/retrofit/
*
* <p>Base URL: http://example.com<br>
* Endpoint: //github.com/square/retrofit/<br>
* Result: http://github.com/square/retrofit/ (note the scheme stays 'http')
*/
public Builder baseUrl(HttpUrl baseUrl) {
Objects.requireNonNull(baseUrl, "baseUrl == null");
List<String> pathSegments = baseUrl.pathSegments();
if (!"".equals(pathSegments.get(pathSegments.size() - 1))) {
throw new IllegalArgumentException("baseUrl must end in /: " + baseUrl);
}
this.baseUrl = baseUrl;
return this;
}
/** Add converter factory for serialization and deserialization of objects. */
public Builder addConverterFactory(Converter.Factory factory) {
converterFactories.add(Objects.requireNonNull(factory, "factory == null"));
return this;
}
/**
* Add a call adapter factory for supporting service method return types other than {@link
* Call}.
*/
public Builder addCallAdapterFactory(CallAdapter.Factory factory) {
callAdapterFactories.add(Objects.requireNonNull(factory, "factory == null"));
return this;
}
/**
* The executor on which {@link Callback} methods are invoked when returning {@link Call} from
* your service method.
*
* <p>Note: {@code executor} is not used for {@linkplain #addCallAdapterFactory custom method
* return types}.
*/
public Builder callbackExecutor(Executor executor) {
this.callbackExecutor = Objects.requireNonNull(executor, "executor == null");
return this;
}
/** Returns a modifiable list of call adapter factories. */
public List<CallAdapter.Factory> callAdapterFactories() {
return this.callAdapterFactories;
}
/** Returns a modifiable list of converter factories. */
public List<Converter.Factory> converterFactories() {
return this.converterFactories;
}
/**
* When calling {@link #create} on the resulting {@link Retrofit} instance, eagerly validate the
* configuration of all methods in the supplied interface.
*/
public Builder validateEagerly(boolean validateEagerly) {
this.validateEagerly = validateEagerly;
return this;
}
/**
* Create the {@link Retrofit} instance using the configured values.
*
* <p>Note: If neither {@link #client} nor {@link #callFactory} is called a default {@link
* OkHttpClient} will be created and used.
*/
public Retrofit build() {
if (baseUrl == null) {
throw new IllegalStateException("Base URL required.");
}
Platform platform = Platform.get();
okhttp3.Call.Factory callFactory = this.callFactory;
if (callFactory == null) {
callFactory = new OkHttpClient();
}
Executor callbackExecutor = this.callbackExecutor;
if (callbackExecutor == null) {
callbackExecutor = platform.defaultCallbackExecutor();
}
// Make a defensive copy of the adapters and add the default Call adapter.
List<CallAdapter.Factory> callAdapterFactories = new ArrayList<>(this.callAdapterFactories);
List<? extends CallAdapter.Factory> defaultCallAdapterFactories =
platform.createDefaultCallAdapterFactories(callbackExecutor);
callAdapterFactories.addAll(defaultCallAdapterFactories);
// Make a defensive copy of the converters.
List<? extends Converter.Factory> defaultConverterFactories =
platform.createDefaultConverterFactories();
int defaultConverterFactoriesSize = defaultConverterFactories.size();
List<Converter.Factory> converterFactories =
new ArrayList<>(1 + this.converterFactories.size() + defaultConverterFactoriesSize);
// 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 BuiltInConverters());
converterFactories.addAll(this.converterFactories);
converterFactories.addAll(defaultConverterFactories);
return new Retrofit(
callFactory,
baseUrl,
unmodifiableList(converterFactories),
defaultConverterFactoriesSize,
unmodifiableList(callAdapterFactories),
defaultCallAdapterFactories.size(),
callbackExecutor,
validateEagerly);
}
}
}
| 3,705 |
0 | Create_ds/retrofit/retrofit/src/main/java | Create_ds/retrofit/retrofit/src/main/java/retrofit2/HttpServiceMethod.java | /*
* 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 static retrofit2.Utils.getRawType;
import static retrofit2.Utils.methodError;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import javax.annotation.Nullable;
import kotlin.Unit;
import kotlin.coroutines.Continuation;
import okhttp3.ResponseBody;
/** Adapts an invocation of an interface method into an HTTP call. */
abstract class HttpServiceMethod<ResponseT, ReturnT> extends ServiceMethod<ReturnT> {
/**
* Inspects the annotations on an interface method to construct a reusable service method that
* speaks HTTP. This requires potentially-expensive reflection so it is best to build each service
* method only once and reuse it.
*/
static <ResponseT, ReturnT> HttpServiceMethod<ResponseT, ReturnT> parseAnnotations(
Retrofit retrofit, Method method, RequestFactory requestFactory) {
boolean isKotlinSuspendFunction = requestFactory.isKotlinSuspendFunction;
boolean continuationWantsResponse = false;
boolean continuationBodyNullable = false;
boolean continuationIsUnit = false;
Annotation[] annotations = method.getAnnotations();
Type adapterType;
if (isKotlinSuspendFunction) {
Type[] parameterTypes = method.getGenericParameterTypes();
Type responseType =
Utils.getParameterLowerBound(
0, (ParameterizedType) parameterTypes[parameterTypes.length - 1]);
if (getRawType(responseType) == Response.class && responseType instanceof ParameterizedType) {
// Unwrap the actual body type from Response<T>.
responseType = Utils.getParameterUpperBound(0, (ParameterizedType) responseType);
continuationWantsResponse = true;
} else {
continuationIsUnit = Utils.isUnit(responseType);
// TODO figure out if type is nullable or not
// Metadata metadata = method.getDeclaringClass().getAnnotation(Metadata.class)
// Find the entry for method
// Determine if return type is nullable or not
}
adapterType = new Utils.ParameterizedTypeImpl(null, Call.class, responseType);
annotations = SkipCallbackExecutorImpl.ensurePresent(annotations);
} else {
adapterType = method.getGenericReturnType();
}
CallAdapter<ResponseT, ReturnT> callAdapter =
createCallAdapter(retrofit, method, adapterType, annotations);
Type responseType = callAdapter.responseType();
if (responseType == okhttp3.Response.class) {
throw methodError(
method,
"'"
+ getRawType(responseType).getName()
+ "' is not a valid response body type. Did you mean ResponseBody?");
}
if (responseType == Response.class) {
throw methodError(method, "Response must include generic type (e.g., Response<String>)");
}
// TODO support Unit for Kotlin?
if (requestFactory.httpMethod.equals("HEAD")
&& !Void.class.equals(responseType)
&& !Utils.isUnit(responseType)) {
throw methodError(method, "HEAD method must use Void or Unit as response type.");
}
Converter<ResponseBody, ResponseT> responseConverter =
createResponseConverter(retrofit, method, responseType);
okhttp3.Call.Factory callFactory = retrofit.callFactory;
if (!isKotlinSuspendFunction) {
return new CallAdapted<>(requestFactory, callFactory, responseConverter, callAdapter);
} else if (continuationWantsResponse) {
//noinspection unchecked Kotlin compiler guarantees ReturnT to be Object.
return (HttpServiceMethod<ResponseT, ReturnT>)
new SuspendForResponse<>(
requestFactory,
callFactory,
responseConverter,
(CallAdapter<ResponseT, Call<ResponseT>>) callAdapter);
} else {
//noinspection unchecked Kotlin compiler guarantees ReturnT to be Object.
return (HttpServiceMethod<ResponseT, ReturnT>)
new SuspendForBody<>(
requestFactory,
callFactory,
responseConverter,
(CallAdapter<ResponseT, Call<ResponseT>>) callAdapter,
continuationBodyNullable,
continuationIsUnit);
}
}
private static <ResponseT, ReturnT> CallAdapter<ResponseT, ReturnT> createCallAdapter(
Retrofit retrofit, Method method, Type returnType, Annotation[] annotations) {
try {
//noinspection unchecked
return (CallAdapter<ResponseT, ReturnT>) retrofit.callAdapter(returnType, annotations);
} catch (RuntimeException e) { // Wide exception range because factories are user code.
throw methodError(method, e, "Unable to create call adapter for %s", returnType);
}
}
private static <ResponseT> Converter<ResponseBody, ResponseT> createResponseConverter(
Retrofit retrofit, Method method, Type responseType) {
Annotation[] annotations = method.getAnnotations();
try {
return retrofit.responseBodyConverter(responseType, annotations);
} catch (RuntimeException e) { // Wide exception range because factories are user code.
throw methodError(method, e, "Unable to create converter for %s", responseType);
}
}
private final RequestFactory requestFactory;
private final okhttp3.Call.Factory callFactory;
private final Converter<ResponseBody, ResponseT> responseConverter;
HttpServiceMethod(
RequestFactory requestFactory,
okhttp3.Call.Factory callFactory,
Converter<ResponseBody, ResponseT> responseConverter) {
this.requestFactory = requestFactory;
this.callFactory = callFactory;
this.responseConverter = responseConverter;
}
@Override
final @Nullable ReturnT invoke(Object[] args) {
Call<ResponseT> call = new OkHttpCall<>(requestFactory, args, callFactory, responseConverter);
return adapt(call, args);
}
protected abstract @Nullable ReturnT adapt(Call<ResponseT> call, Object[] args);
static final class CallAdapted<ResponseT, ReturnT> extends HttpServiceMethod<ResponseT, ReturnT> {
private final CallAdapter<ResponseT, ReturnT> callAdapter;
CallAdapted(
RequestFactory requestFactory,
okhttp3.Call.Factory callFactory,
Converter<ResponseBody, ResponseT> responseConverter,
CallAdapter<ResponseT, ReturnT> callAdapter) {
super(requestFactory, callFactory, responseConverter);
this.callAdapter = callAdapter;
}
@Override
protected ReturnT adapt(Call<ResponseT> call, Object[] args) {
return callAdapter.adapt(call);
}
}
static final class SuspendForResponse<ResponseT> extends HttpServiceMethod<ResponseT, Object> {
private final CallAdapter<ResponseT, Call<ResponseT>> callAdapter;
SuspendForResponse(
RequestFactory requestFactory,
okhttp3.Call.Factory callFactory,
Converter<ResponseBody, ResponseT> responseConverter,
CallAdapter<ResponseT, Call<ResponseT>> callAdapter) {
super(requestFactory, callFactory, responseConverter);
this.callAdapter = callAdapter;
}
@Override
protected Object adapt(Call<ResponseT> call, Object[] args) {
call = callAdapter.adapt(call);
//noinspection unchecked Checked by reflection inside RequestFactory.
Continuation<Response<ResponseT>> continuation =
(Continuation<Response<ResponseT>>) args[args.length - 1];
// See SuspendForBody for explanation about this try/catch.
try {
return KotlinExtensions.awaitResponse(call, continuation);
} catch (Exception e) {
return KotlinExtensions.suspendAndThrow(e, continuation);
}
}
}
static final class SuspendForBody<ResponseT> extends HttpServiceMethod<ResponseT, Object> {
private final CallAdapter<ResponseT, Call<ResponseT>> callAdapter;
private final boolean isNullable;
private final boolean isUnit;
SuspendForBody(
RequestFactory requestFactory,
okhttp3.Call.Factory callFactory,
Converter<ResponseBody, ResponseT> responseConverter,
CallAdapter<ResponseT, Call<ResponseT>> callAdapter,
boolean isNullable,
boolean isUnit) {
super(requestFactory, callFactory, responseConverter);
this.callAdapter = callAdapter;
this.isNullable = isNullable;
this.isUnit = isUnit;
}
@Override
protected Object adapt(Call<ResponseT> call, Object[] args) {
call = callAdapter.adapt(call);
//noinspection unchecked Checked by reflection inside RequestFactory.
Continuation<ResponseT> continuation = (Continuation<ResponseT>) args[args.length - 1];
// Calls to OkHttp Call.enqueue() like those inside await and awaitNullable can sometimes
// invoke the supplied callback with an exception before the invoking stack frame can return.
// Coroutines will intercept the subsequent invocation of the Continuation and throw the
// exception synchronously. A Java Proxy cannot throw checked exceptions without them being
// declared on the interface method. To avoid the synchronous checked exception being wrapped
// in an UndeclaredThrowableException, it is intercepted and supplied to a helper which will
// force suspension to occur so that it can be instead delivered to the continuation to
// bypass this restriction.
try {
if (isUnit) {
//noinspection unchecked Checked by isUnit
return KotlinExtensions.awaitUnit((Call<Unit>) call, (Continuation<Unit>) continuation);
} else if (isNullable) {
return KotlinExtensions.awaitNullable(call, continuation);
} else {
return KotlinExtensions.await(call, continuation);
}
} 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);
}
}
}
}
| 3,706 |
0 | Create_ds/retrofit/retrofit/src/main/java | Create_ds/retrofit/retrofit/src/main/java/retrofit2/Utils.java | /*
* Copyright (C) 2008 Google 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 java.lang.annotation.Annotation;
import java.lang.reflect.Array;
import java.lang.reflect.GenericArrayType;
import java.lang.reflect.GenericDeclaration;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.lang.reflect.WildcardType;
import java.util.Arrays;
import java.util.NoSuchElementException;
import java.util.Objects;
import javax.annotation.Nullable;
import kotlin.Unit;
import okhttp3.ResponseBody;
import okio.Buffer;
final class Utils {
static final Type[] EMPTY_TYPE_ARRAY = new Type[0];
private Utils() {
// No instances.
}
static RuntimeException methodError(Method method, String message, Object... args) {
return methodError(method, null, message, args);
}
@SuppressWarnings("AnnotateFormatMethod")
static RuntimeException methodError(
Method method, @Nullable Throwable cause, String message, Object... args) {
message = String.format(message, args);
return new IllegalArgumentException(
message
+ "\n for method "
+ method.getDeclaringClass().getSimpleName()
+ "."
+ method.getName(),
cause);
}
static RuntimeException parameterError(
Method method, Throwable cause, int p, String message, Object... args) {
return methodError(method, cause, message + " (parameter #" + (p + 1) + ")", args);
}
static RuntimeException parameterError(Method method, int p, String message, Object... args) {
return methodError(method, message + " (parameter #" + (p + 1) + ")", args);
}
static Class<?> getRawType(Type type) {
Objects.requireNonNull(type, "type == null");
if (type instanceof Class<?>) {
// Type is a normal class.
return (Class<?>) type;
}
if (type instanceof ParameterizedType) {
ParameterizedType parameterizedType = (ParameterizedType) type;
// I'm not exactly sure why getRawType() returns Type instead of Class. Neal isn't either but
// suspects some pathological case related to nested classes exists.
Type rawType = parameterizedType.getRawType();
if (!(rawType instanceof Class)) throw new IllegalArgumentException();
return (Class<?>) rawType;
}
if (type instanceof GenericArrayType) {
Type componentType = ((GenericArrayType) type).getGenericComponentType();
return Array.newInstance(getRawType(componentType), 0).getClass();
}
if (type instanceof TypeVariable) {
// We could use the variable's bounds, but that won't work if there are multiple. Having a raw
// type that's more general than necessary is okay.
return Object.class;
}
if (type instanceof WildcardType) {
return getRawType(((WildcardType) type).getUpperBounds()[0]);
}
throw new IllegalArgumentException(
"Expected a Class, ParameterizedType, or "
+ "GenericArrayType, but <"
+ type
+ "> is of type "
+ type.getClass().getName());
}
/** Returns true if {@code a} and {@code b} are equal. */
static boolean equals(Type a, Type b) {
if (a == b) {
return true; // Also handles (a == null && b == null).
} else if (a instanceof Class) {
return a.equals(b); // Class already specifies equals().
} else if (a instanceof ParameterizedType) {
if (!(b instanceof ParameterizedType)) return false;
ParameterizedType pa = (ParameterizedType) a;
ParameterizedType pb = (ParameterizedType) b;
Object ownerA = pa.getOwnerType();
Object ownerB = pb.getOwnerType();
return (ownerA == ownerB || (ownerA != null && ownerA.equals(ownerB)))
&& pa.getRawType().equals(pb.getRawType())
&& Arrays.equals(pa.getActualTypeArguments(), pb.getActualTypeArguments());
} else if (a instanceof GenericArrayType) {
if (!(b instanceof GenericArrayType)) return false;
GenericArrayType ga = (GenericArrayType) a;
GenericArrayType gb = (GenericArrayType) b;
return equals(ga.getGenericComponentType(), gb.getGenericComponentType());
} else if (a instanceof WildcardType) {
if (!(b instanceof WildcardType)) return false;
WildcardType wa = (WildcardType) a;
WildcardType wb = (WildcardType) b;
return Arrays.equals(wa.getUpperBounds(), wb.getUpperBounds())
&& Arrays.equals(wa.getLowerBounds(), wb.getLowerBounds());
} else if (a instanceof TypeVariable) {
if (!(b instanceof TypeVariable)) return false;
TypeVariable<?> va = (TypeVariable<?>) a;
TypeVariable<?> vb = (TypeVariable<?>) b;
return va.getGenericDeclaration() == vb.getGenericDeclaration()
&& va.getName().equals(vb.getName());
} else {
return false; // This isn't a type we support!
}
}
/**
* 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>}.
*/
static Type getGenericSupertype(Type context, Class<?> rawType, Class<?> toResolve) {
if (toResolve == rawType) return context;
// We skip searching through interfaces if unknown is an interface.
if (toResolve.isInterface()) {
Class<?>[] interfaces = rawType.getInterfaces();
for (int i = 0, length = interfaces.length; i < length; i++) {
if (interfaces[i] == toResolve) {
return rawType.getGenericInterfaces()[i];
} else if (toResolve.isAssignableFrom(interfaces[i])) {
return getGenericSupertype(rawType.getGenericInterfaces()[i], interfaces[i], toResolve);
}
}
}
// Check our supertypes.
if (!rawType.isInterface()) {
while (rawType != Object.class) {
Class<?> rawSupertype = rawType.getSuperclass();
if (rawSupertype == toResolve) {
return rawType.getGenericSuperclass();
} else if (toResolve.isAssignableFrom(rawSupertype)) {
return getGenericSupertype(rawType.getGenericSuperclass(), rawSupertype, toResolve);
}
rawType = rawSupertype;
}
}
// We can't resolve this further.
return toResolve;
}
private static int indexOf(Object[] array, Object toFind) {
for (int i = 0; i < array.length; i++) {
if (toFind.equals(array[i])) return i;
}
throw new NoSuchElementException();
}
static String typeToString(Type type) {
return type instanceof Class ? ((Class<?>) type).getName() : type.toString();
}
/**
* Returns the generic form of {@code supertype}. For example, if this is {@code
* ArrayList<String>}, this returns {@code Iterable<String>} given the input {@code
* Iterable.class}.
*
* @param supertype a superclass of, or interface implemented by, this.
*/
static Type getSupertype(Type context, Class<?> contextRawType, Class<?> supertype) {
if (!supertype.isAssignableFrom(contextRawType)) throw new IllegalArgumentException();
return resolve(
context, contextRawType, getGenericSupertype(context, contextRawType, supertype));
}
static Type resolve(Type context, Class<?> contextRawType, Type toResolve) {
// This implementation is made a little more complicated in an attempt to avoid object-creation.
while (true) {
if (toResolve instanceof TypeVariable) {
TypeVariable<?> typeVariable = (TypeVariable<?>) toResolve;
toResolve = resolveTypeVariable(context, contextRawType, typeVariable);
if (toResolve == typeVariable) {
return toResolve;
}
} else if (toResolve instanceof Class && ((Class<?>) toResolve).isArray()) {
Class<?> original = (Class<?>) toResolve;
Type componentType = original.getComponentType();
Type newComponentType = resolve(context, contextRawType, componentType);
return componentType == newComponentType
? original
: new GenericArrayTypeImpl(newComponentType);
} else if (toResolve instanceof GenericArrayType) {
GenericArrayType original = (GenericArrayType) toResolve;
Type componentType = original.getGenericComponentType();
Type newComponentType = resolve(context, contextRawType, componentType);
return componentType == newComponentType
? original
: new GenericArrayTypeImpl(newComponentType);
} else if (toResolve instanceof ParameterizedType) {
ParameterizedType original = (ParameterizedType) toResolve;
Type ownerType = original.getOwnerType();
Type newOwnerType = resolve(context, contextRawType, ownerType);
boolean changed = newOwnerType != ownerType;
Type[] args = original.getActualTypeArguments();
for (int t = 0, length = args.length; t < length; t++) {
Type resolvedTypeArgument = resolve(context, contextRawType, args[t]);
if (resolvedTypeArgument != args[t]) {
if (!changed) {
args = args.clone();
changed = true;
}
args[t] = resolvedTypeArgument;
}
}
return changed
? new ParameterizedTypeImpl(newOwnerType, original.getRawType(), args)
: original;
} else if (toResolve instanceof WildcardType) {
WildcardType original = (WildcardType) toResolve;
Type[] originalLowerBound = original.getLowerBounds();
Type[] originalUpperBound = original.getUpperBounds();
if (originalLowerBound.length == 1) {
Type lowerBound = resolve(context, contextRawType, originalLowerBound[0]);
if (lowerBound != originalLowerBound[0]) {
return new WildcardTypeImpl(new Type[] {Object.class}, new Type[] {lowerBound});
}
} else if (originalUpperBound.length == 1) {
Type upperBound = resolve(context, contextRawType, originalUpperBound[0]);
if (upperBound != originalUpperBound[0]) {
return new WildcardTypeImpl(new Type[] {upperBound}, EMPTY_TYPE_ARRAY);
}
}
return original;
} else {
return toResolve;
}
}
}
private static Type resolveTypeVariable(
Type context, Class<?> contextRawType, TypeVariable<?> unknown) {
Class<?> declaredByRaw = declaringClassOf(unknown);
// We can't reduce this further.
if (declaredByRaw == null) return unknown;
Type declaredBy = getGenericSupertype(context, contextRawType, declaredByRaw);
if (declaredBy instanceof ParameterizedType) {
int index = indexOf(declaredByRaw.getTypeParameters(), unknown);
return ((ParameterizedType) declaredBy).getActualTypeArguments()[index];
}
return unknown;
}
/**
* Returns the declaring class of {@code typeVariable}, or {@code null} if it was not declared by
* a class.
*/
private static @Nullable Class<?> declaringClassOf(TypeVariable<?> typeVariable) {
GenericDeclaration genericDeclaration = typeVariable.getGenericDeclaration();
return genericDeclaration instanceof Class ? (Class<?>) genericDeclaration : null;
}
static void checkNotPrimitive(Type type) {
if (type instanceof Class<?> && ((Class<?>) type).isPrimitive()) {
throw new IllegalArgumentException();
}
}
/** Returns true if {@code annotations} contains an instance of {@code cls}. */
static boolean isAnnotationPresent(Annotation[] annotations, Class<? extends Annotation> cls) {
for (Annotation annotation : annotations) {
if (cls.isInstance(annotation)) {
return true;
}
}
return false;
}
static ResponseBody buffer(final ResponseBody body) throws IOException {
Buffer buffer = new Buffer();
body.source().readAll(buffer);
return ResponseBody.create(body.contentType(), body.contentLength(), buffer);
}
static Type getParameterUpperBound(int index, ParameterizedType type) {
Type[] types = type.getActualTypeArguments();
if (index < 0 || index >= types.length) {
throw new IllegalArgumentException(
"Index " + index + " not in range [0," + types.length + ") for " + type);
}
Type paramType = types[index];
if (paramType instanceof WildcardType) {
return ((WildcardType) paramType).getUpperBounds()[0];
}
return paramType;
}
static Type getParameterLowerBound(int index, ParameterizedType type) {
Type paramType = type.getActualTypeArguments()[index];
if (paramType instanceof WildcardType) {
return ((WildcardType) paramType).getLowerBounds()[0];
}
return paramType;
}
static boolean hasUnresolvableType(@Nullable Type type) {
if (type instanceof Class<?>) {
return false;
}
if (type instanceof ParameterizedType) {
ParameterizedType parameterizedType = (ParameterizedType) type;
for (Type typeArgument : parameterizedType.getActualTypeArguments()) {
if (hasUnresolvableType(typeArgument)) {
return true;
}
}
return false;
}
if (type instanceof GenericArrayType) {
return hasUnresolvableType(((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);
}
static final class ParameterizedTypeImpl implements ParameterizedType {
private final @Nullable Type ownerType;
private final Type rawType;
private final Type[] typeArguments;
ParameterizedTypeImpl(@Nullable Type ownerType, Type rawType, Type... typeArguments) {
// Require an owner type if the raw type needs it.
if (rawType instanceof Class<?>
&& (ownerType == null) != (((Class<?>) rawType).getEnclosingClass() == null)) {
throw new IllegalArgumentException();
}
for (Type typeArgument : typeArguments) {
Objects.requireNonNull(typeArgument, "typeArgument == null");
checkNotPrimitive(typeArgument);
}
this.ownerType = ownerType;
this.rawType = rawType;
this.typeArguments = typeArguments.clone();
}
@Override
public Type[] getActualTypeArguments() {
return typeArguments.clone();
}
@Override
public Type getRawType() {
return rawType;
}
@Override
public @Nullable Type getOwnerType() {
return ownerType;
}
@Override
public boolean equals(Object other) {
return other instanceof ParameterizedType && Utils.equals(this, (ParameterizedType) other);
}
@Override
public int hashCode() {
return Arrays.hashCode(typeArguments)
^ rawType.hashCode()
^ (ownerType != null ? ownerType.hashCode() : 0);
}
@Override
public String toString() {
if (typeArguments.length == 0) return typeToString(rawType);
StringBuilder result = new StringBuilder(30 * (typeArguments.length + 1));
result.append(typeToString(rawType));
result.append("<").append(typeToString(typeArguments[0]));
for (int i = 1; i < typeArguments.length; i++) {
result.append(", ").append(typeToString(typeArguments[i]));
}
return result.append(">").toString();
}
}
private static final class GenericArrayTypeImpl implements GenericArrayType {
private final Type componentType;
GenericArrayTypeImpl(Type componentType) {
this.componentType = componentType;
}
@Override
public Type getGenericComponentType() {
return componentType;
}
@Override
public boolean equals(Object o) {
return o instanceof GenericArrayType && Utils.equals(this, (GenericArrayType) o);
}
@Override
public int hashCode() {
return componentType.hashCode();
}
@Override
public String toString() {
return typeToString(componentType) + "[]";
}
}
/**
* The WildcardType interface supports multiple upper bounds and multiple lower bounds. We only
* support what the Java 6 language needs - at most one bound. If a lower bound is set, the upper
* bound must be Object.class.
*/
private static final class WildcardTypeImpl implements WildcardType {
private final Type upperBound;
private final @Nullable Type lowerBound;
WildcardTypeImpl(Type[] upperBounds, Type[] lowerBounds) {
if (lowerBounds.length > 1) throw new IllegalArgumentException();
if (upperBounds.length != 1) throw new IllegalArgumentException();
if (lowerBounds.length == 1) {
if (lowerBounds[0] == null) throw new NullPointerException();
checkNotPrimitive(lowerBounds[0]);
if (upperBounds[0] != Object.class) throw new IllegalArgumentException();
this.lowerBound = lowerBounds[0];
this.upperBound = Object.class;
} else {
if (upperBounds[0] == null) throw new NullPointerException();
checkNotPrimitive(upperBounds[0]);
this.lowerBound = null;
this.upperBound = upperBounds[0];
}
}
@Override
public Type[] getUpperBounds() {
return new Type[] {upperBound};
}
@Override
public Type[] getLowerBounds() {
return lowerBound != null ? new Type[] {lowerBound} : EMPTY_TYPE_ARRAY;
}
@Override
public boolean equals(Object other) {
return other instanceof WildcardType && Utils.equals(this, (WildcardType) other);
}
@Override
public int hashCode() {
// This equals Arrays.hashCode(getLowerBounds()) ^ Arrays.hashCode(getUpperBounds()).
return (lowerBound != null ? 31 + lowerBound.hashCode() : 1) ^ (31 + upperBound.hashCode());
}
@Override
public String toString() {
if (lowerBound != null) return "? super " + typeToString(lowerBound);
if (upperBound == Object.class) return "?";
return "? extends " + typeToString(upperBound);
}
}
// https://github.com/ReactiveX/RxJava/blob/6a44e5d0543a48f1c378dc833a155f3f71333bc2/
// src/main/java/io/reactivex/exceptions/Exceptions.java#L66
static void throwIfFatal(Throwable t) {
if (t instanceof VirtualMachineError) {
throw (VirtualMachineError) t;
} else if (t instanceof ThreadDeath) {
throw (ThreadDeath) t;
} else if (t instanceof LinkageError) {
throw (LinkageError) t;
}
}
/** Not volatile because we don't mind multiple threads discovering this. */
private static boolean checkForKotlinUnit = true;
static boolean isUnit(Type type) {
if (checkForKotlinUnit) {
try {
return type == Unit.class;
} catch (NoClassDefFoundError ignored) {
checkForKotlinUnit = false;
}
}
return false;
}
}
| 3,707 |
0 | Create_ds/retrofit/retrofit/src/main/java | Create_ds/retrofit/retrofit/src/main/java/retrofit2/RequestFactory.java | /*
* 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 static retrofit2.Utils.methodError;
import static retrofit2.Utils.parameterError;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.net.URI;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.annotation.Nullable;
import kotlin.coroutines.Continuation;
import okhttp3.Headers;
import okhttp3.HttpUrl;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.http.Body;
import retrofit2.http.DELETE;
import retrofit2.http.Field;
import retrofit2.http.FieldMap;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.GET;
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;
import retrofit2.http.POST;
import retrofit2.http.PUT;
import retrofit2.http.Part;
import retrofit2.http.PartMap;
import retrofit2.http.Path;
import retrofit2.http.Query;
import retrofit2.http.QueryMap;
import retrofit2.http.QueryName;
import retrofit2.http.Tag;
import retrofit2.http.Url;
final class RequestFactory {
static RequestFactory parseAnnotations(Retrofit retrofit, Method method) {
return new Builder(retrofit, method).build();
}
private final Method method;
private final HttpUrl baseUrl;
final String httpMethod;
private final @Nullable String relativeUrl;
private final @Nullable Headers headers;
private final @Nullable MediaType contentType;
private final boolean hasBody;
private final boolean isFormEncoded;
private final boolean isMultipart;
private final ParameterHandler<?>[] parameterHandlers;
final boolean isKotlinSuspendFunction;
RequestFactory(Builder builder) {
method = builder.method;
baseUrl = builder.retrofit.baseUrl;
httpMethod = builder.httpMethod;
relativeUrl = builder.relativeUrl;
headers = builder.headers;
contentType = builder.contentType;
hasBody = builder.hasBody;
isFormEncoded = builder.isFormEncoded;
isMultipart = builder.isMultipart;
parameterHandlers = builder.parameterHandlers;
isKotlinSuspendFunction = builder.isKotlinSuspendFunction;
}
okhttp3.Request create(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;
int argumentCount = args.length;
if (argumentCount != handlers.length) {
throw new IllegalArgumentException(
"Argument count ("
+ argumentCount
+ ") doesn't match expected count ("
+ handlers.length
+ ")");
}
RequestBuilder requestBuilder =
new RequestBuilder(
httpMethod,
baseUrl,
relativeUrl,
headers,
contentType,
hasBody,
isFormEncoded,
isMultipart);
if (isKotlinSuspendFunction) {
// The Continuation is the last parameter and the handlers array contains null at that index.
argumentCount--;
}
List<Object> argumentList = new ArrayList<>(argumentCount);
for (int p = 0; p < argumentCount; p++) {
argumentList.add(args[p]);
handlers[p].apply(requestBuilder, args[p]);
}
return requestBuilder.get().tag(Invocation.class, new Invocation(method, argumentList)).build();
}
/**
* Inspects the annotations on an interface method to construct a reusable service method. This
* requires potentially-expensive reflection so it is best to build each service method only once
* and reuse it. Builders cannot be reused.
*/
static final class Builder {
// 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_URL_REGEX = Pattern.compile("\\{(" + PARAM + ")\\}");
private static final Pattern PARAM_NAME_REGEX = Pattern.compile(PARAM);
final Retrofit retrofit;
final Method method;
final Annotation[] methodAnnotations;
final Annotation[][] parameterAnnotationsArray;
final Type[] parameterTypes;
boolean gotField;
boolean gotPart;
boolean gotBody;
boolean gotPath;
boolean gotQuery;
boolean gotQueryName;
boolean gotQueryMap;
boolean gotUrl;
@Nullable String httpMethod;
boolean hasBody;
boolean isFormEncoded;
boolean isMultipart;
@Nullable String relativeUrl;
@Nullable Headers headers;
@Nullable MediaType contentType;
@Nullable Set<String> relativeUrlParamNames;
@Nullable ParameterHandler<?>[] parameterHandlers;
boolean isKotlinSuspendFunction;
Builder(Retrofit retrofit, Method method) {
this.retrofit = retrofit;
this.method = method;
this.methodAnnotations = method.getAnnotations();
this.parameterTypes = method.getGenericParameterTypes();
this.parameterAnnotationsArray = method.getParameterAnnotations();
}
RequestFactory build() {
for (Annotation annotation : methodAnnotations) {
parseMethodAnnotation(annotation);
}
if (httpMethod == null) {
throw methodError(method, "HTTP method annotation is required (e.g., @GET, @POST, etc.).");
}
if (!hasBody) {
if (isMultipart) {
throw methodError(
method,
"Multipart can only be specified on HTTP methods with request body (e.g., @POST).");
}
if (isFormEncoded) {
throw methodError(
method,
"FormUrlEncoded can only be specified on HTTP methods with "
+ "request body (e.g., @POST).");
}
}
int parameterCount = parameterAnnotationsArray.length;
parameterHandlers = new ParameterHandler<?>[parameterCount];
for (int p = 0, lastParameter = parameterCount - 1; p < parameterCount; p++) {
parameterHandlers[p] =
parseParameter(p, parameterTypes[p], parameterAnnotationsArray[p], p == lastParameter);
}
if (relativeUrl == null && !gotUrl) {
throw methodError(method, "Missing either @%s URL or @Url parameter.", httpMethod);
}
if (!isFormEncoded && !isMultipart && !hasBody && gotBody) {
throw methodError(method, "Non-body HTTP method cannot contain @Body.");
}
if (isFormEncoded && !gotField) {
throw methodError(method, "Form-encoded method must contain at least one @Field.");
}
if (isMultipart && !gotPart) {
throw methodError(method, "Multipart method must contain at least one @Part.");
}
return new RequestFactory(this);
}
private void parseMethodAnnotation(Annotation annotation) {
if (annotation instanceof DELETE) {
parseHttpMethodAndPath("DELETE", ((DELETE) annotation).value(), false);
} else if (annotation instanceof GET) {
parseHttpMethodAndPath("GET", ((GET) annotation).value(), false);
} else if (annotation instanceof HEAD) {
parseHttpMethodAndPath("HEAD", ((HEAD) annotation).value(), false);
} else if (annotation instanceof PATCH) {
parseHttpMethodAndPath("PATCH", ((PATCH) annotation).value(), true);
} else if (annotation instanceof POST) {
parseHttpMethodAndPath("POST", ((POST) annotation).value(), true);
} else if (annotation instanceof PUT) {
parseHttpMethodAndPath("PUT", ((PUT) annotation).value(), true);
} else if (annotation instanceof OPTIONS) {
parseHttpMethodAndPath("OPTIONS", ((OPTIONS) annotation).value(), false);
} else if (annotation instanceof HTTP) {
HTTP http = (HTTP) annotation;
parseHttpMethodAndPath(http.method(), http.path(), http.hasBody());
} else if (annotation instanceof retrofit2.http.Headers) {
retrofit2.http.Headers headers = (retrofit2.http.Headers) annotation;
String[] headersToParse = headers.value();
if (headersToParse.length == 0) {
throw methodError(method, "@Headers annotation is empty.");
}
this.headers = parseHeaders(headersToParse, headers.allowUnsafeNonAsciiValues());
} else if (annotation instanceof Multipart) {
if (isFormEncoded) {
throw methodError(method, "Only one encoding annotation is allowed.");
}
isMultipart = true;
} else if (annotation instanceof FormUrlEncoded) {
if (isMultipart) {
throw methodError(method, "Only one encoding annotation is allowed.");
}
isFormEncoded = true;
}
}
private void parseHttpMethodAndPath(String httpMethod, String value, boolean hasBody) {
if (this.httpMethod != null) {
throw methodError(
method,
"Only one HTTP method is allowed. Found: %s and %s.",
this.httpMethod,
httpMethod);
}
this.httpMethod = httpMethod;
this.hasBody = hasBody;
if (value.isEmpty()) {
return;
}
// Get the relative URL path and existing query string, if present.
int question = value.indexOf('?');
if (question != -1 && question < value.length() - 1) {
// Ensure the query string does not have any named parameters.
String queryParams = value.substring(question + 1);
Matcher queryParamMatcher = PARAM_URL_REGEX.matcher(queryParams);
if (queryParamMatcher.find()) {
throw methodError(
method,
"URL query string \"%s\" must not have replace block. "
+ "For dynamic query parameters use @Query.",
queryParams);
}
}
this.relativeUrl = value;
this.relativeUrlParamNames = parsePathParameters(value);
}
private Headers parseHeaders(String[] headers, boolean allowUnsafeNonAsciiValues) {
Headers.Builder builder = new Headers.Builder();
for (String header : headers) {
int colon = header.indexOf(':');
if (colon == -1 || colon == 0 || colon == header.length() - 1) {
throw methodError(
method, "@Headers value must be in the form \"Name: Value\". Found: \"%s\"", header);
}
String headerName = header.substring(0, colon);
String headerValue = header.substring(colon + 1).trim();
if ("Content-Type".equalsIgnoreCase(headerName)) {
try {
contentType = MediaType.get(headerValue);
} catch (IllegalArgumentException e) {
throw methodError(method, e, "Malformed content type: %s", headerValue);
}
} else if (allowUnsafeNonAsciiValues) {
builder.addUnsafeNonAscii(headerName, headerValue);
} else {
builder.add(headerName, headerValue);
}
}
return builder.build();
}
private @Nullable ParameterHandler<?> parseParameter(
int p, Type parameterType, @Nullable Annotation[] annotations, boolean allowContinuation) {
ParameterHandler<?> result = null;
if (annotations != null) {
for (Annotation annotation : annotations) {
ParameterHandler<?> annotationAction =
parseParameterAnnotation(p, parameterType, annotations, annotation);
if (annotationAction == null) {
continue;
}
if (result != null) {
throw parameterError(
method, p, "Multiple Retrofit annotations found, only one allowed.");
}
result = annotationAction;
}
}
if (result == null) {
if (allowContinuation) {
try {
if (Utils.getRawType(parameterType) == Continuation.class) {
isKotlinSuspendFunction = true;
return null;
}
} catch (NoClassDefFoundError ignored) {
// Ignored
}
}
throw parameterError(method, p, "No Retrofit annotation found.");
}
return result;
}
@Nullable
private ParameterHandler<?> parseParameterAnnotation(
int p, Type type, Annotation[] annotations, Annotation annotation) {
if (annotation instanceof Url) {
validateResolvableType(p, type);
if (gotUrl) {
throw parameterError(method, p, "Multiple @Url method annotations found.");
}
if (gotPath) {
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.");
}
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);
}
gotUrl = true;
if (type == HttpUrl.class
|| type == String.class
|| type == URI.class
|| (type instanceof Class && "android.net.Uri".equals(((Class<?>) type).getName()))) {
return new ParameterHandler.RelativeUrl(method, p);
} else {
throw parameterError(
method,
p,
"@Url must be okhttp3.HttpUrl, String, java.net.URI, or android.net.Uri type.");
}
} else if (annotation instanceof Path) {
validateResolvableType(p, type);
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.");
}
if (relativeUrl == null) {
throw parameterError(
method, p, "@Path can only be used with relative url on @%s", httpMethod);
}
gotPath = true;
Path path = (Path) annotation;
String name = path.value();
validatePathName(p, name);
Converter<?, String> converter = retrofit.stringConverter(type, annotations);
return new ParameterHandler.Path<>(method, p, name, converter, path.encoded());
} else if (annotation instanceof Query) {
validateResolvableType(p, type);
Query query = (Query) annotation;
String name = query.value();
boolean encoded = query.encoded();
Class<?> rawParameterType = Utils.getRawType(type);
gotQuery = true;
if (Iterable.class.isAssignableFrom(rawParameterType)) {
if (!(type instanceof ParameterizedType)) {
throw parameterError(
method,
p,
rawParameterType.getSimpleName()
+ " must include generic type (e.g., "
+ rawParameterType.getSimpleName()
+ "<String>)");
}
ParameterizedType parameterizedType = (ParameterizedType) type;
Type iterableType = Utils.getParameterUpperBound(0, parameterizedType);
Converter<?, String> converter = retrofit.stringConverter(iterableType, annotations);
return new ParameterHandler.Query<>(name, converter, encoded).iterable();
} else if (rawParameterType.isArray()) {
Class<?> arrayComponentType = boxIfPrimitive(rawParameterType.getComponentType());
Converter<?, String> converter =
retrofit.stringConverter(arrayComponentType, annotations);
return new ParameterHandler.Query<>(name, converter, encoded).array();
} else {
Converter<?, String> converter = retrofit.stringConverter(type, annotations);
return new ParameterHandler.Query<>(name, converter, encoded);
}
} else if (annotation instanceof QueryName) {
validateResolvableType(p, type);
QueryName query = (QueryName) annotation;
boolean encoded = query.encoded();
Class<?> rawParameterType = Utils.getRawType(type);
gotQueryName = true;
if (Iterable.class.isAssignableFrom(rawParameterType)) {
if (!(type instanceof ParameterizedType)) {
throw parameterError(
method,
p,
rawParameterType.getSimpleName()
+ " must include generic type (e.g., "
+ rawParameterType.getSimpleName()
+ "<String>)");
}
ParameterizedType parameterizedType = (ParameterizedType) type;
Type iterableType = Utils.getParameterUpperBound(0, parameterizedType);
Converter<?, String> converter = retrofit.stringConverter(iterableType, annotations);
return new ParameterHandler.QueryName<>(converter, encoded).iterable();
} else if (rawParameterType.isArray()) {
Class<?> arrayComponentType = boxIfPrimitive(rawParameterType.getComponentType());
Converter<?, String> converter =
retrofit.stringConverter(arrayComponentType, annotations);
return new ParameterHandler.QueryName<>(converter, encoded).array();
} else {
Converter<?, String> converter = retrofit.stringConverter(type, annotations);
return new ParameterHandler.QueryName<>(converter, encoded);
}
} else if (annotation instanceof QueryMap) {
validateResolvableType(p, type);
Class<?> rawParameterType = Utils.getRawType(type);
gotQueryMap = true;
if (!Map.class.isAssignableFrom(rawParameterType)) {
throw parameterError(method, p, "@QueryMap parameter type must be Map.");
}
Type mapType = Utils.getSupertype(type, rawParameterType, Map.class);
if (!(mapType instanceof ParameterizedType)) {
throw parameterError(
method, 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(method, p, "@QueryMap keys must be of type String: " + keyType);
}
Type valueType = Utils.getParameterUpperBound(1, parameterizedType);
Converter<?, String> valueConverter = retrofit.stringConverter(valueType, annotations);
return new ParameterHandler.QueryMap<>(
method, p, valueConverter, ((QueryMap) annotation).encoded());
} else if (annotation instanceof Header) {
validateResolvableType(p, type);
Header header = (Header) annotation;
String name = header.value();
Class<?> rawParameterType = Utils.getRawType(type);
if (Iterable.class.isAssignableFrom(rawParameterType)) {
if (!(type instanceof ParameterizedType)) {
throw parameterError(
method,
p,
rawParameterType.getSimpleName()
+ " must include generic type (e.g., "
+ rawParameterType.getSimpleName()
+ "<String>)");
}
ParameterizedType parameterizedType = (ParameterizedType) type;
Type iterableType = Utils.getParameterUpperBound(0, parameterizedType);
Converter<?, String> converter = retrofit.stringConverter(iterableType, annotations);
return new ParameterHandler.Header<>(name, converter, header.allowUnsafeNonAsciiValues())
.iterable();
} else if (rawParameterType.isArray()) {
Class<?> arrayComponentType = boxIfPrimitive(rawParameterType.getComponentType());
Converter<?, String> converter =
retrofit.stringConverter(arrayComponentType, annotations);
return new ParameterHandler.Header<>(name, converter, header.allowUnsafeNonAsciiValues())
.array();
} else {
Converter<?, String> converter = retrofit.stringConverter(type, annotations);
return new ParameterHandler.Header<>(name, converter, header.allowUnsafeNonAsciiValues());
}
} else if (annotation instanceof HeaderMap) {
if (type == Headers.class) {
return new ParameterHandler.Headers(method, p);
}
validateResolvableType(p, type);
Class<?> rawParameterType = Utils.getRawType(type);
if (!Map.class.isAssignableFrom(rawParameterType)) {
throw parameterError(method, p, "@HeaderMap parameter type must be Map or Headers.");
}
Type mapType = Utils.getSupertype(type, rawParameterType, Map.class);
if (!(mapType instanceof ParameterizedType)) {
throw parameterError(
method, 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(method, 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<>(
method, p, valueConverter, ((HeaderMap) annotation).allowUnsafeNonAsciiValues());
} else if (annotation instanceof Field) {
validateResolvableType(p, type);
if (!isFormEncoded) {
throw parameterError(method, p, "@Field parameters can only be used with form encoding.");
}
Field field = (Field) annotation;
String name = field.value();
boolean encoded = field.encoded();
gotField = true;
Class<?> rawParameterType = Utils.getRawType(type);
if (Iterable.class.isAssignableFrom(rawParameterType)) {
if (!(type instanceof ParameterizedType)) {
throw parameterError(
method,
p,
rawParameterType.getSimpleName()
+ " must include generic type (e.g., "
+ rawParameterType.getSimpleName()
+ "<String>)");
}
ParameterizedType parameterizedType = (ParameterizedType) type;
Type iterableType = Utils.getParameterUpperBound(0, parameterizedType);
Converter<?, String> converter = retrofit.stringConverter(iterableType, annotations);
return new ParameterHandler.Field<>(name, converter, encoded).iterable();
} else if (rawParameterType.isArray()) {
Class<?> arrayComponentType = boxIfPrimitive(rawParameterType.getComponentType());
Converter<?, String> converter =
retrofit.stringConverter(arrayComponentType, annotations);
return new ParameterHandler.Field<>(name, converter, encoded).array();
} else {
Converter<?, String> converter = retrofit.stringConverter(type, annotations);
return new ParameterHandler.Field<>(name, converter, encoded);
}
} else if (annotation instanceof FieldMap) {
validateResolvableType(p, type);
if (!isFormEncoded) {
throw parameterError(
method, p, "@FieldMap parameters can only be used with form encoding.");
}
Class<?> rawParameterType = Utils.getRawType(type);
if (!Map.class.isAssignableFrom(rawParameterType)) {
throw parameterError(method, p, "@FieldMap parameter type must be Map.");
}
Type mapType = Utils.getSupertype(type, rawParameterType, Map.class);
if (!(mapType instanceof ParameterizedType)) {
throw parameterError(
method, 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(method, p, "@FieldMap keys must be of type String: " + keyType);
}
Type valueType = Utils.getParameterUpperBound(1, parameterizedType);
Converter<?, String> valueConverter = retrofit.stringConverter(valueType, annotations);
gotField = true;
return new ParameterHandler.FieldMap<>(
method, p, valueConverter, ((FieldMap) annotation).encoded());
} else if (annotation instanceof Part) {
validateResolvableType(p, type);
if (!isMultipart) {
throw parameterError(
method, p, "@Part parameters can only be used with multipart encoding.");
}
Part part = (Part) annotation;
gotPart = true;
String partName = part.value();
Class<?> rawParameterType = Utils.getRawType(type);
if (partName.isEmpty()) {
if (Iterable.class.isAssignableFrom(rawParameterType)) {
if (!(type instanceof ParameterizedType)) {
throw parameterError(
method,
p,
rawParameterType.getSimpleName()
+ " must include generic type (e.g., "
+ rawParameterType.getSimpleName()
+ "<String>)");
}
ParameterizedType parameterizedType = (ParameterizedType) type;
Type iterableType = Utils.getParameterUpperBound(0, parameterizedType);
if (!MultipartBody.Part.class.isAssignableFrom(Utils.getRawType(iterableType))) {
throw parameterError(
method,
p,
"@Part annotation must supply a name or use MultipartBody.Part parameter type.");
}
return ParameterHandler.RawPart.INSTANCE.iterable();
} else if (rawParameterType.isArray()) {
Class<?> arrayComponentType = rawParameterType.getComponentType();
if (!MultipartBody.Part.class.isAssignableFrom(arrayComponentType)) {
throw parameterError(
method,
p,
"@Part annotation must supply a name or use MultipartBody.Part parameter type.");
}
return ParameterHandler.RawPart.INSTANCE.array();
} else if (MultipartBody.Part.class.isAssignableFrom(rawParameterType)) {
return ParameterHandler.RawPart.INSTANCE;
} else {
throw parameterError(
method,
p,
"@Part annotation must supply a name or use MultipartBody.Part parameter type.");
}
} else {
Headers headers =
Headers.of(
"Content-Disposition",
"form-data; name=\"" + partName + "\"",
"Content-Transfer-Encoding",
part.encoding());
if (Iterable.class.isAssignableFrom(rawParameterType)) {
if (!(type instanceof ParameterizedType)) {
throw parameterError(
method,
p,
rawParameterType.getSimpleName()
+ " must include generic type (e.g., "
+ rawParameterType.getSimpleName()
+ "<String>)");
}
ParameterizedType parameterizedType = (ParameterizedType) type;
Type iterableType = Utils.getParameterUpperBound(0, parameterizedType);
if (MultipartBody.Part.class.isAssignableFrom(Utils.getRawType(iterableType))) {
throw parameterError(
method,
p,
"@Part parameters using the MultipartBody.Part must not "
+ "include a part name in the annotation.");
}
Converter<?, RequestBody> converter =
retrofit.requestBodyConverter(iterableType, annotations, methodAnnotations);
return new ParameterHandler.Part<>(method, p, headers, converter).iterable();
} else if (rawParameterType.isArray()) {
Class<?> arrayComponentType = boxIfPrimitive(rawParameterType.getComponentType());
if (MultipartBody.Part.class.isAssignableFrom(arrayComponentType)) {
throw parameterError(
method,
p,
"@Part parameters using the MultipartBody.Part must not "
+ "include a part name in the annotation.");
}
Converter<?, RequestBody> converter =
retrofit.requestBodyConverter(arrayComponentType, annotations, methodAnnotations);
return new ParameterHandler.Part<>(method, p, headers, converter).array();
} else if (MultipartBody.Part.class.isAssignableFrom(rawParameterType)) {
throw parameterError(
method,
p,
"@Part parameters using the MultipartBody.Part must not "
+ "include a part name in the annotation.");
} else {
Converter<?, RequestBody> converter =
retrofit.requestBodyConverter(type, annotations, methodAnnotations);
return new ParameterHandler.Part<>(method, p, headers, converter);
}
}
} else if (annotation instanceof PartMap) {
validateResolvableType(p, type);
if (!isMultipart) {
throw parameterError(
method, p, "@PartMap parameters can only be used with multipart encoding.");
}
gotPart = true;
Class<?> rawParameterType = Utils.getRawType(type);
if (!Map.class.isAssignableFrom(rawParameterType)) {
throw parameterError(method, p, "@PartMap parameter type must be Map.");
}
Type mapType = Utils.getSupertype(type, rawParameterType, Map.class);
if (!(mapType instanceof ParameterizedType)) {
throw parameterError(
method, 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(method, p, "@PartMap keys must be of type String: " + keyType);
}
Type valueType = Utils.getParameterUpperBound(1, parameterizedType);
if (MultipartBody.Part.class.isAssignableFrom(Utils.getRawType(valueType))) {
throw parameterError(
method,
p,
"@PartMap values cannot be MultipartBody.Part. "
+ "Use @Part List<Part> or a different value type instead.");
}
Converter<?, RequestBody> valueConverter =
retrofit.requestBodyConverter(valueType, annotations, methodAnnotations);
PartMap partMap = (PartMap) annotation;
return new ParameterHandler.PartMap<>(method, p, valueConverter, partMap.encoding());
} else if (annotation instanceof Body) {
validateResolvableType(p, type);
if (isFormEncoded || isMultipart) {
throw parameterError(
method, p, "@Body parameters cannot be used with form or multi-part encoding.");
}
if (gotBody) {
throw parameterError(method, p, "Multiple @Body method annotations found.");
}
Converter<?, RequestBody> converter;
try {
converter = retrofit.requestBodyConverter(type, annotations, methodAnnotations);
} catch (RuntimeException e) {
// Wide exception range because factories are user code.
throw parameterError(method, e, p, "Unable to create @Body converter for %s", type);
}
gotBody = true;
return new ParameterHandler.Body<>(method, p, converter);
} else if (annotation instanceof Tag) {
validateResolvableType(p, type);
Class<?> tagType = Utils.getRawType(type);
for (int i = p - 1; i >= 0; i--) {
ParameterHandler<?> otherHandler = parameterHandlers[i];
if (otherHandler instanceof ParameterHandler.Tag
&& ((ParameterHandler.Tag) otherHandler).cls.equals(tagType)) {
throw parameterError(
method,
p,
"@Tag type "
+ tagType.getName()
+ " is duplicate of parameter #"
+ (i + 1)
+ " and would always overwrite its value.");
}
}
return new ParameterHandler.Tag<>(tagType);
}
return null; // Not a Retrofit annotation.
}
private void validateResolvableType(int p, Type type) {
if (Utils.hasUnresolvableType(type)) {
throw parameterError(
method, p, "Parameter type must not include a type variable or wildcard: %s", type);
}
}
private void validatePathName(int p, String name) {
if (!PARAM_NAME_REGEX.matcher(name).matches()) {
throw parameterError(
method,
p,
"@Path parameter name must match %s. Found: %s",
PARAM_URL_REGEX.pattern(),
name);
}
// Verify URL replacement name is actually present in the URL path.
if (!relativeUrlParamNames.contains(name)) {
throw parameterError(method, p, "URL \"%s\" does not contain \"{%s}\".", relativeUrl, name);
}
}
/**
* 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 = PARAM_URL_REGEX.matcher(path);
Set<String> patterns = new LinkedHashSet<>();
while (m.find()) {
patterns.add(m.group(1));
}
return patterns;
}
private static Class<?> boxIfPrimitive(Class<?> type) {
if (boolean.class == type) return Boolean.class;
if (byte.class == type) return Byte.class;
if (char.class == type) return Character.class;
if (double.class == type) return Double.class;
if (float.class == type) return Float.class;
if (int.class == type) return Integer.class;
if (long.class == type) return Long.class;
if (short.class == type) return Short.class;
return type;
}
}
}
| 3,708 |
0 | Create_ds/retrofit/retrofit/src/main/java | Create_ds/retrofit/retrofit/src/main/java/retrofit2/OkHttpCall.java | /*
* 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 static retrofit2.Utils.throwIfFatal;
import java.io.IOException;
import java.util.Objects;
import javax.annotation.Nullable;
import javax.annotation.concurrent.GuardedBy;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;
import okio.ForwardingSource;
import okio.Okio;
import okio.Timeout;
final class OkHttpCall<T> implements Call<T> {
private final RequestFactory requestFactory;
private final Object[] args;
private final okhttp3.Call.Factory callFactory;
private final Converter<ResponseBody, T> responseConverter;
private volatile boolean canceled;
@GuardedBy("this")
private @Nullable okhttp3.Call rawCall;
@GuardedBy("this") // Either a RuntimeException, non-fatal Error, or IOException.
private @Nullable Throwable creationFailure;
@GuardedBy("this")
private boolean executed;
OkHttpCall(
RequestFactory requestFactory,
Object[] args,
okhttp3.Call.Factory callFactory,
Converter<ResponseBody, T> responseConverter) {
this.requestFactory = requestFactory;
this.args = args;
this.callFactory = callFactory;
this.responseConverter = responseConverter;
}
@SuppressWarnings("CloneDoesntCallSuperClone") // We are a final type & this saves clearing state.
@Override
public OkHttpCall<T> clone() {
return new OkHttpCall<>(requestFactory, args, callFactory, responseConverter);
}
@Override
public synchronized Request 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 (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();
} catch (RuntimeException | Error | IOException e) {
throwIfFatal(e); // Do not assign a fatal error to creationFailure.
creationFailure = e;
throw e;
}
}
@Override
public void enqueue(final Callback<T> callback) {
Objects.requireNonNull(callback, "callback == null");
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) {
throwIfFatal(t);
failure = creationFailure = t;
}
}
}
if (failure != null) {
callback.onFailure(this, failure);
return;
}
if (canceled) {
call.cancel();
}
call.enqueue(
new okhttp3.Callback() {
@Override
public void onResponse(okhttp3.Call call, okhttp3.Response rawResponse) {
Response<T> response;
try {
response = parseResponse(rawResponse);
} catch (Throwable e) {
throwIfFatal(e);
callFailure(e);
return;
}
try {
callback.onResponse(OkHttpCall.this, response);
} catch (Throwable t) {
throwIfFatal(t);
t.printStackTrace(); // TODO this is not great
}
}
@Override
public void onFailure(okhttp3.Call call, IOException e) {
callFailure(e);
}
private void callFailure(Throwable e) {
try {
callback.onFailure(OkHttpCall.this, e);
} catch (Throwable t) {
throwIfFatal(t);
t.printStackTrace(); // TODO this is not great
}
}
});
}
@Override
public synchronized boolean isExecuted() {
return executed;
}
@Override
public Response<T> execute() throws IOException {
okhttp3.Call call;
synchronized (this) {
if (executed) throw new IllegalStateException("Already executed.");
executed = true;
call = getRawCall();
}
if (canceled) {
call.cancel();
}
return parseResponse(call.execute());
}
private okhttp3.Call createRawCall() throws IOException {
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 {
ResponseBody rawBody = rawResponse.body();
// Remove the body's source (the only stateful object) so we can pass the response along.
rawResponse =
rawResponse
.newBuilder()
.body(new NoContentResponseBody(rawBody.contentType(), rawBody.contentLength()))
.build();
int code = rawResponse.code();
if (code < 200 || code >= 300) {
try {
// Buffer the entire body to avoid future I/O.
ResponseBody bufferedBody = Utils.buffer(rawBody);
return Response.error(bufferedBody, rawResponse);
} finally {
rawBody.close();
}
}
if (code == 204 || code == 205) {
rawBody.close();
return Response.success(null, rawResponse);
}
ExceptionCatchingResponseBody catchingBody = new ExceptionCatchingResponseBody(rawBody);
try {
T body = responseConverter.convert(catchingBody);
return Response.success(body, rawResponse);
} catch (RuntimeException e) {
// If the underlying source threw an exception, propagate that rather than indicating it was
// a runtime exception.
catchingBody.throwIfCaught();
throw e;
}
}
@Override
public void cancel() {
canceled = true;
okhttp3.Call call;
synchronized (this) {
call = rawCall;
}
if (call != null) {
call.cancel();
}
}
@Override
public boolean isCanceled() {
if (canceled) {
return true;
}
synchronized (this) {
return rawCall != null && rawCall.isCanceled();
}
}
static final class NoContentResponseBody extends ResponseBody {
private final @Nullable MediaType contentType;
private final long contentLength;
NoContentResponseBody(@Nullable MediaType contentType, long contentLength) {
this.contentType = contentType;
this.contentLength = contentLength;
}
@Override
public MediaType contentType() {
return contentType;
}
@Override
public long contentLength() {
return contentLength;
}
@Override
public BufferedSource source() {
throw new IllegalStateException("Cannot read raw response body of a converted body.");
}
}
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() {
return delegate.contentType();
}
@Override
public long contentLength() {
return delegate.contentLength();
}
@Override
public BufferedSource source() {
return delegateSource;
}
@Override
public void close() {
delegate.close();
}
void throwIfCaught() throws IOException {
if (thrownException != null) {
throw thrownException;
}
}
}
}
| 3,709 |
0 | Create_ds/retrofit/retrofit/src/main/java | Create_ds/retrofit/retrofit/src/main/java/retrofit2/Call.java | /*
* 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;
import okio.Timeout;
/**
* An invocation of a Retrofit method that sends a request to a webserver and returns a response.
* Each call yields its own HTTP request and response pair. Use {@link #clone} to make multiple
* calls with the same parameters to the same webserver; this may be used to implement polling or to
* retry a failed call.
*
* <p>Calls may be executed synchronously with {@link #execute}, or asynchronously with {@link
* #enqueue}. In either case the call can be canceled at any time with {@link #cancel}. A call that
* is busy writing its request or reading its response may receive a {@link IOException}; this is
* working as designed.
*
* @param <T> Successful response body type.
*/
public interface Call<T> extends Cloneable {
/**
* Synchronously send the request and return its response.
*
* @throws IOException if a problem occurred talking to the server.
* @throws RuntimeException (and subclasses) if an unexpected error occurs creating the request or
* decoding the response.
*/
Response<T> execute() throws IOException;
/**
* Asynchronously send the request and notify {@code callback} of its response or if an error
* occurred talking to the server, creating the request, or processing the response.
*/
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.
*/
void cancel();
/** True if {@link #cancel()} was called. */
boolean isCanceled();
/**
* Create a new, identical call to this one which can be enqueued or executed even if this call
* has already been.
*/
Call<T> clone();
/** 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();
}
| 3,710 |
0 | Create_ds/retrofit/retrofit/src/main/java | Create_ds/retrofit/retrofit/src/main/java/retrofit2/ParameterHandler.java | /*
* 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 java.lang.reflect.Array;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.Objects;
import javax.annotation.Nullable;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
abstract class ParameterHandler<T> {
abstract void apply(RequestBuilder builder, @Nullable T value) throws IOException;
final ParameterHandler<Iterable<T>> iterable() {
return new ParameterHandler<Iterable<T>>() {
@Override
void apply(RequestBuilder builder, @Nullable Iterable<T> values) throws IOException {
if (values == null) return; // Skip null values.
for (T value : values) {
ParameterHandler.this.apply(builder, value);
}
}
};
}
final ParameterHandler<Object> array() {
return new ParameterHandler<Object>() {
@Override
void apply(RequestBuilder builder, @Nullable Object values) throws IOException {
if (values == null) return; // Skip null values.
for (int i = 0, size = Array.getLength(values); i < size; i++) {
//noinspection unchecked
ParameterHandler.this.apply(builder, (T) Array.get(values, i));
}
}
};
}
static final class RelativeUrl extends ParameterHandler<Object> {
private final Method method;
private final int p;
RelativeUrl(Method method, int p) {
this.method = method;
this.p = p;
}
@Override
void apply(RequestBuilder builder, @Nullable Object value) {
if (value == null) {
throw Utils.parameterError(method, p, "@Url parameter is null.");
}
builder.setRelativeUrl(value);
}
}
static final class Header<T> extends ParameterHandler<T> {
private final String name;
private final Converter<T, String> valueConverter;
private final boolean allowUnsafeNonAsciiValues;
Header(String name, Converter<T, String> valueConverter, boolean allowUnsafeNonAsciiValues) {
this.name = Objects.requireNonNull(name, "name == null");
this.valueConverter = valueConverter;
this.allowUnsafeNonAsciiValues = allowUnsafeNonAsciiValues;
}
@Override
void apply(RequestBuilder builder, @Nullable T value) throws IOException {
if (value == null) return; // Skip null values.
String headerValue = valueConverter.convert(value);
if (headerValue == null) return; // Skip converted but null values.
builder.addHeader(name, headerValue, allowUnsafeNonAsciiValues);
}
}
static final class Path<T> extends ParameterHandler<T> {
private final Method method;
private final int p;
private final String name;
private final Converter<T, String> valueConverter;
private final boolean encoded;
Path(Method method, int p, String name, Converter<T, String> valueConverter, boolean encoded) {
this.method = method;
this.p = p;
this.name = Objects.requireNonNull(name, "name == null");
this.valueConverter = valueConverter;
this.encoded = encoded;
}
@Override
void apply(RequestBuilder builder, @Nullable T value) throws IOException {
if (value == null) {
throw Utils.parameterError(
method, p, "Path parameter \"" + name + "\" value must not be null.");
}
builder.addPathParam(name, valueConverter.convert(value), encoded);
}
}
static final class Query<T> extends ParameterHandler<T> {
private final String name;
private final Converter<T, String> valueConverter;
private final boolean encoded;
Query(String name, Converter<T, String> valueConverter, boolean encoded) {
this.name = Objects.requireNonNull(name, "name == null");
this.valueConverter = valueConverter;
this.encoded = encoded;
}
@Override
void apply(RequestBuilder builder, @Nullable T value) throws IOException {
if (value == null) return; // Skip null values.
String queryValue = valueConverter.convert(value);
if (queryValue == null) return; // Skip converted but null values
builder.addQueryParam(name, queryValue, encoded);
}
}
static final class QueryName<T> extends ParameterHandler<T> {
private final Converter<T, String> nameConverter;
private final boolean encoded;
QueryName(Converter<T, String> nameConverter, boolean encoded) {
this.nameConverter = nameConverter;
this.encoded = encoded;
}
@Override
void apply(RequestBuilder builder, @Nullable T value) throws IOException {
if (value == null) return; // Skip null values.
builder.addQueryParam(nameConverter.convert(value), null, encoded);
}
}
static final class QueryMap<T> extends ParameterHandler<Map<String, T>> {
private final Method method;
private final int p;
private final Converter<T, String> valueConverter;
private final boolean encoded;
QueryMap(Method method, int p, Converter<T, String> valueConverter, boolean encoded) {
this.method = method;
this.p = p;
this.valueConverter = valueConverter;
this.encoded = encoded;
}
@Override
void apply(RequestBuilder builder, @Nullable Map<String, T> value) throws IOException {
if (value == null) {
throw Utils.parameterError(method, p, "Query map was null");
}
for (Map.Entry<String, T> entry : value.entrySet()) {
String entryKey = entry.getKey();
if (entryKey == null) {
throw Utils.parameterError(method, p, "Query map contained null key.");
}
T entryValue = entry.getValue();
if (entryValue == null) {
throw Utils.parameterError(
method, p, "Query map contained null value for key '" + entryKey + "'.");
}
String convertedEntryValue = valueConverter.convert(entryValue);
if (convertedEntryValue == null) {
throw Utils.parameterError(
method,
p,
"Query map value '"
+ entryValue
+ "' converted to null by "
+ valueConverter.getClass().getName()
+ " for key '"
+ entryKey
+ "'.");
}
builder.addQueryParam(entryKey, convertedEntryValue, encoded);
}
}
}
static final class HeaderMap<T> extends ParameterHandler<Map<String, T>> {
private final Method method;
private final int p;
private final Converter<T, String> valueConverter;
private final boolean allowUnsafeNonAsciiValues;
HeaderMap(
Method method,
int p,
Converter<T, String> valueConverter,
boolean allowUnsafeNonAsciiValues) {
this.method = method;
this.p = p;
this.valueConverter = valueConverter;
this.allowUnsafeNonAsciiValues = allowUnsafeNonAsciiValues;
}
@Override
void apply(RequestBuilder builder, @Nullable Map<String, T> value) throws IOException {
if (value == null) {
throw Utils.parameterError(method, p, "Header map was null.");
}
for (Map.Entry<String, T> entry : value.entrySet()) {
String headerName = entry.getKey();
if (headerName == null) {
throw Utils.parameterError(method, p, "Header map contained null key.");
}
T headerValue = entry.getValue();
if (headerValue == null) {
throw Utils.parameterError(
method, p, "Header map contained null value for key '" + headerName + "'.");
}
builder.addHeader(
headerName, valueConverter.convert(headerValue), allowUnsafeNonAsciiValues);
}
}
}
static final class Headers extends ParameterHandler<okhttp3.Headers> {
private final Method method;
private final int p;
Headers(Method method, int p) {
this.method = method;
this.p = p;
}
@Override
void apply(RequestBuilder builder, @Nullable okhttp3.Headers headers) {
if (headers == null) {
throw Utils.parameterError(method, p, "Headers parameter must not be null.");
}
builder.addHeaders(headers);
}
}
static final class Field<T> extends ParameterHandler<T> {
private final String name;
private final Converter<T, String> valueConverter;
private final boolean encoded;
Field(String name, Converter<T, String> valueConverter, boolean encoded) {
this.name = Objects.requireNonNull(name, "name == null");
this.valueConverter = valueConverter;
this.encoded = encoded;
}
@Override
void apply(RequestBuilder builder, @Nullable T value) throws IOException {
if (value == null) return; // Skip null values.
String fieldValue = valueConverter.convert(value);
if (fieldValue == null) return; // Skip null converted values
builder.addFormField(name, fieldValue, encoded);
}
}
static final class FieldMap<T> extends ParameterHandler<Map<String, T>> {
private final Method method;
private final int p;
private final Converter<T, String> valueConverter;
private final boolean encoded;
FieldMap(Method method, int p, Converter<T, String> valueConverter, boolean encoded) {
this.method = method;
this.p = p;
this.valueConverter = valueConverter;
this.encoded = encoded;
}
@Override
void apply(RequestBuilder builder, @Nullable Map<String, T> value) throws IOException {
if (value == null) {
throw Utils.parameterError(method, p, "Field map was null.");
}
for (Map.Entry<String, T> entry : value.entrySet()) {
String entryKey = entry.getKey();
if (entryKey == null) {
throw Utils.parameterError(method, p, "Field map contained null key.");
}
T entryValue = entry.getValue();
if (entryValue == null) {
throw Utils.parameterError(
method, p, "Field map contained null value for key '" + entryKey + "'.");
}
String fieldEntry = valueConverter.convert(entryValue);
if (fieldEntry == null) {
throw Utils.parameterError(
method,
p,
"Field map value '"
+ entryValue
+ "' converted to null by "
+ valueConverter.getClass().getName()
+ " for key '"
+ entryKey
+ "'.");
}
builder.addFormField(entryKey, fieldEntry, encoded);
}
}
}
static final class Part<T> extends ParameterHandler<T> {
private final Method method;
private final int p;
private final okhttp3.Headers headers;
private final Converter<T, RequestBody> converter;
Part(Method method, int p, okhttp3.Headers headers, Converter<T, RequestBody> converter) {
this.method = method;
this.p = p;
this.headers = headers;
this.converter = converter;
}
@Override
void apply(RequestBuilder builder, @Nullable T value) {
if (value == null) return; // Skip null values.
RequestBody body;
try {
body = converter.convert(value);
} catch (IOException e) {
throw Utils.parameterError(method, p, "Unable to convert " + value + " to RequestBody", e);
}
builder.addPart(headers, body);
}
}
static final class RawPart extends ParameterHandler<MultipartBody.Part> {
static final RawPart INSTANCE = new RawPart();
private RawPart() {}
@Override
void apply(RequestBuilder builder, @Nullable MultipartBody.Part value) {
if (value != null) { // Skip null values.
builder.addPart(value);
}
}
}
static final class PartMap<T> extends ParameterHandler<Map<String, T>> {
private final Method method;
private final int p;
private final Converter<T, RequestBody> valueConverter;
private final String transferEncoding;
PartMap(
Method method, int p, Converter<T, RequestBody> valueConverter, String transferEncoding) {
this.method = method;
this.p = p;
this.valueConverter = valueConverter;
this.transferEncoding = transferEncoding;
}
@Override
void apply(RequestBuilder builder, @Nullable Map<String, T> value) throws IOException {
if (value == null) {
throw Utils.parameterError(method, p, "Part map was null.");
}
for (Map.Entry<String, T> entry : value.entrySet()) {
String entryKey = entry.getKey();
if (entryKey == null) {
throw Utils.parameterError(method, p, "Part map contained null key.");
}
T entryValue = entry.getValue();
if (entryValue == null) {
throw Utils.parameterError(
method, p, "Part map contained null value for key '" + entryKey + "'.");
}
okhttp3.Headers headers =
okhttp3.Headers.of(
"Content-Disposition",
"form-data; name=\"" + entryKey + "\"",
"Content-Transfer-Encoding",
transferEncoding);
builder.addPart(headers, valueConverter.convert(entryValue));
}
}
}
static final class Body<T> extends ParameterHandler<T> {
private final Method method;
private final int p;
private final Converter<T, RequestBody> converter;
Body(Method method, int p, Converter<T, RequestBody> converter) {
this.method = method;
this.p = p;
this.converter = converter;
}
@Override
void apply(RequestBuilder builder, @Nullable T value) {
if (value == null) {
throw Utils.parameterError(method, p, "Body parameter value must not be null.");
}
RequestBody body;
try {
body = converter.convert(value);
} catch (IOException e) {
throw Utils.parameterError(method, e, p, "Unable to convert " + value + " to RequestBody");
}
builder.setBody(body);
}
}
static final class Tag<T> extends ParameterHandler<T> {
final Class<T> cls;
Tag(Class<T> cls) {
this.cls = cls;
}
@Override
void apply(RequestBuilder builder, @Nullable T value) {
builder.addTag(cls, value);
}
}
}
| 3,711 |
0 | Create_ds/retrofit/retrofit/src/main/java | Create_ds/retrofit/retrofit/src/main/java/retrofit2/ServiceMethod.java | /*
* 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 static retrofit2.Utils.methodError;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import javax.annotation.Nullable;
abstract class ServiceMethod<T> {
static <T> ServiceMethod<T> parseAnnotations(Retrofit retrofit, Method method) {
RequestFactory requestFactory = RequestFactory.parseAnnotations(retrofit, method);
Type returnType = method.getGenericReturnType();
if (Utils.hasUnresolvableType(returnType)) {
throw methodError(
method,
"Method return type must not include a type variable or wildcard: %s",
returnType);
}
if (returnType == void.class) {
throw methodError(method, "Service methods cannot return void.");
}
return HttpServiceMethod.parseAnnotations(retrofit, method, requestFactory);
}
abstract @Nullable T invoke(Object[] args);
}
| 3,712 |
0 | Create_ds/retrofit/retrofit/src/main/java | Create_ds/retrofit/retrofit/src/main/java/retrofit2/CallAdapter.java | /*
* 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.lang.annotation.Annotation;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import javax.annotation.Nullable;
/**
* Adapts a {@link Call} with response type {@code R} into the type of {@code T}. Instances are
* created by {@linkplain Factory a factory} which is {@linkplain
* Retrofit.Builder#addCallAdapterFactory(Factory) installed} into the {@link Retrofit} instance.
*/
public interface CallAdapter<R, T> {
/**
* Returns the value type that this adapter uses when converting the HTTP response body to a Java
* object. For example, the response type for {@code Call<Repo>} is {@code Repo}. This type is
* used to prepare the {@code call} passed to {@code #adapt}.
*
* <p>Note: This is typically not the same type as the {@code returnType} provided to this call
* adapter's factory.
*/
Type responseType();
/**
* Returns an instance of {@code T} which delegates to {@code call}.
*
* <p>For example, given an instance for a hypothetical utility, {@code Async}, this instance
* would return a new {@code Async<R>} which invoked {@code call} when run.
*
* <pre><code>
* @Override
* public <R> Async<R> adapt(final Call<R> call) {
* return Async.create(new Callable<Response<R>>() {
* @Override
* public Response<R> call() throws Exception {
* return call.execute();
* }
* });
* }
* </code></pre>
*/
T adapt(Call<R> call);
/**
* Creates {@link CallAdapter} instances based on the return type of {@linkplain
* Retrofit#create(Class) the service interface} methods.
*/
abstract class Factory {
/**
* Returns a call adapter for interface methods that return {@code returnType}, or null if it
* cannot be handled by this factory.
*/
public abstract @Nullable CallAdapter<?, ?> get(
Type returnType, Annotation[] annotations, Retrofit retrofit);
/**
* Extract the upper bound of the generic parameter at {@code index} from {@code type}. For
* example, index 1 of {@code Map<String, ? extends Runnable>} returns {@code Runnable}.
*/
protected static Type getParameterUpperBound(int index, ParameterizedType type) {
return Utils.getParameterUpperBound(index, type);
}
/**
* Extract the raw class type from {@code type}. For example, the type representing {@code
* List<? extends Runnable>} returns {@code List.class}.
*/
protected static Class<?> getRawType(Type type) {
return Utils.getRawType(type);
}
}
}
| 3,713 |
0 | Create_ds/retrofit/retrofit/src/main/java | Create_ds/retrofit/retrofit/src/main/java/retrofit2/Converter.java | /*
* Copyright (C) 2012 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 java.lang.annotation.Annotation;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import javax.annotation.Nullable;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.http.Body;
import retrofit2.http.Field;
import retrofit2.http.FieldMap;
import retrofit2.http.Header;
import retrofit2.http.HeaderMap;
import retrofit2.http.Part;
import retrofit2.http.PartMap;
import retrofit2.http.Path;
import retrofit2.http.Query;
import retrofit2.http.QueryMap;
/**
* Convert objects to and from their representation in HTTP. Instances are created by {@linkplain
* Factory a factory} which is {@linkplain Retrofit.Builder#addConverterFactory(Factory) installed}
* into the {@link Retrofit} instance.
*/
public interface Converter<F, T> {
@Nullable
T convert(F value) throws IOException;
/** Creates {@link Converter} instances based on a type and target usage. */
abstract class Factory {
/**
* Returns a {@link Converter} for converting an HTTP response body to {@code type}, or null if
* {@code type} cannot be handled by this factory. This is used to create converters for
* response types such as {@code SimpleResponse} from a {@code Call<SimpleResponse>}
* declaration.
*/
public @Nullable Converter<ResponseBody, ?> responseBodyConverter(
Type type, Annotation[] annotations, Retrofit retrofit) {
return null;
}
/**
* Returns a {@link Converter} for converting {@code type} to an HTTP request body, or null if
* {@code type} cannot be handled by this factory. This is used to create converters for types
* specified by {@link Body @Body}, {@link Part @Part}, and {@link PartMap @PartMap} values.
*/
public @Nullable Converter<?, RequestBody> requestBodyConverter(
Type type,
Annotation[] parameterAnnotations,
Annotation[] methodAnnotations,
Retrofit retrofit) {
return null;
}
/**
* 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 HeaderMap @HeaderMap}, {@link Path @Path}, {@link Query @Query}, and {@link
* QueryMap @QueryMap} values.
*/
public @Nullable Converter<?, String> stringConverter(
Type type, Annotation[] annotations, Retrofit retrofit) {
return null;
}
/**
* Extract the upper bound of the generic parameter at {@code index} from {@code type}. For
* example, index 1 of {@code Map<String, ? extends Runnable>} returns {@code Runnable}.
*/
protected static Type getParameterUpperBound(int index, ParameterizedType type) {
return Utils.getParameterUpperBound(index, type);
}
/**
* Extract the raw class type from {@code type}. For example, the type representing {@code
* List<? extends Runnable>} returns {@code List.class}.
*/
protected static Class<?> getRawType(Type type) {
return Utils.getRawType(type);
}
}
}
| 3,714 |
0 | Create_ds/retrofit/retrofit/src/main/java | Create_ds/retrofit/retrofit/src/main/java/retrofit2/Platform.java | /*
* 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 retrofit2;
import static java.util.Arrays.asList;
import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;
import android.annotation.TargetApi;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodHandles.Lookup;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
import java.util.concurrent.Executor;
import javax.annotation.Nullable;
import org.codehaus.mojo.animal_sniffer.IgnoreJRERequirement;
abstract class Platform {
private static final Platform PLATFORM = createPlatform();
static Platform get() {
return PLATFORM;
}
private static Platform createPlatform() {
switch (System.getProperty("java.vm.name")) {
case "Dalvik":
if (Android24.isSupported()) {
return new Android24();
}
return new Android21();
case "RoboVM":
return new RoboVm();
default:
if (Java16.isSupported()) {
return new Java16();
}
if (Java14.isSupported()) {
return new Java14();
}
return new Java8();
}
}
abstract @Nullable Executor defaultCallbackExecutor();
abstract List<? extends CallAdapter.Factory> createDefaultCallAdapterFactories(
@Nullable Executor callbackExecutor);
abstract List<? extends Converter.Factory> createDefaultConverterFactories();
abstract boolean isDefaultMethod(Method method);
abstract @Nullable Object invokeDefaultMethod(
Method method, Class<?> declaringClass, Object proxy, Object... args) throws Throwable;
private static final class Android21 extends Platform {
@Override
boolean isDefaultMethod(Method method) {
return false;
}
@Nullable
@Override
Object invokeDefaultMethod(
Method method, Class<?> declaringClass, Object proxy, Object... args) {
throw new AssertionError();
}
@Override
Executor defaultCallbackExecutor() {
return MainThreadExecutor.INSTANCE;
}
@Override
List<? extends CallAdapter.Factory> createDefaultCallAdapterFactories(
@Nullable Executor callbackExecutor) {
return singletonList(new DefaultCallAdapterFactory(callbackExecutor));
}
@Override
List<? extends Converter.Factory> createDefaultConverterFactories() {
return emptyList();
}
}
@IgnoreJRERequirement // Only used on Android API 24+
@TargetApi(24)
private static final class Android24 extends Platform {
static boolean isSupported() {
return Build.VERSION.SDK_INT >= 24;
}
private @Nullable Constructor<Lookup> lookupConstructor;
@Override
Executor defaultCallbackExecutor() {
return MainThreadExecutor.INSTANCE;
}
@Override
List<? extends CallAdapter.Factory> createDefaultCallAdapterFactories(
@Nullable Executor callbackExecutor) {
return asList(
new CompletableFutureCallAdapterFactory(),
new DefaultCallAdapterFactory(callbackExecutor));
}
@Override
List<? extends Converter.Factory> createDefaultConverterFactories() {
return singletonList(new OptionalConverterFactory());
}
@Override
public boolean isDefaultMethod(Method method) {
return method.isDefault();
}
@Nullable
@Override
public Object invokeDefaultMethod(
Method method, Class<?> declaringClass, Object proxy, Object... args) throws Throwable {
if (Build.VERSION.SDK_INT < 26) {
throw new UnsupportedOperationException(
"Calling default methods on API 24 and 25 is not supported");
}
Constructor<Lookup> lookupConstructor = this.lookupConstructor;
if (lookupConstructor == null) {
lookupConstructor = Lookup.class.getDeclaredConstructor(Class.class, int.class);
lookupConstructor.setAccessible(true);
this.lookupConstructor = lookupConstructor;
}
return lookupConstructor
.newInstance(declaringClass, -1 /* trusted */)
.unreflectSpecial(method, declaringClass)
.bindTo(proxy)
.invokeWithArguments(args);
}
}
private static final class RoboVm extends Platform {
@Nullable
@Override
Executor defaultCallbackExecutor() {
return null;
}
@Override
List<? extends CallAdapter.Factory> createDefaultCallAdapterFactories(
@Nullable Executor callbackExecutor) {
return singletonList(new DefaultCallAdapterFactory(callbackExecutor));
}
@Override
List<? extends Converter.Factory> createDefaultConverterFactories() {
return emptyList();
}
@Override
boolean isDefaultMethod(Method method) {
return false;
}
@Nullable
@Override
Object invokeDefaultMethod(
Method method, Class<?> declaringClass, Object proxy, Object... args) {
throw new AssertionError();
}
}
@IgnoreJRERequirement // Only used on JVM and Java 8 is the minimum-supported version.
@SuppressWarnings("NewApi") // Not used for Android.
private static final class Java8 extends Platform {
private @Nullable Constructor<Lookup> lookupConstructor;
@Nullable
@Override
Executor defaultCallbackExecutor() {
return null;
}
@Override
List<? extends CallAdapter.Factory> createDefaultCallAdapterFactories(
@Nullable Executor callbackExecutor) {
return asList(
new CompletableFutureCallAdapterFactory(),
new DefaultCallAdapterFactory(callbackExecutor));
}
@Override
List<? extends Converter.Factory> createDefaultConverterFactories() {
return singletonList(new OptionalConverterFactory());
}
@Override
public boolean isDefaultMethod(Method method) {
return method.isDefault();
}
@Override
public @Nullable Object invokeDefaultMethod(
Method method, Class<?> declaringClass, Object proxy, Object... args) throws Throwable {
Constructor<Lookup> lookupConstructor = this.lookupConstructor;
if (lookupConstructor == null) {
lookupConstructor = Lookup.class.getDeclaredConstructor(Class.class, int.class);
lookupConstructor.setAccessible(true);
this.lookupConstructor = lookupConstructor;
}
return lookupConstructor
.newInstance(declaringClass, -1 /* trusted */)
.unreflectSpecial(method, declaringClass)
.bindTo(proxy)
.invokeWithArguments(args);
}
}
/**
* Java 14 allows a regular lookup to succeed for invoking default methods.
*
* <p>https://bugs.openjdk.java.net/browse/JDK-8209005
*/
@IgnoreJRERequirement // Only used on JVM and Java 14.
@SuppressWarnings("NewApi") // Not used for Android.
private static final class Java14 extends Platform {
static boolean isSupported() {
try {
Object version = Runtime.class.getMethod("version").invoke(null);
Integer feature = (Integer) version.getClass().getMethod("feature").invoke(version);
return feature >= 14;
} catch (InvocationTargetException | IllegalAccessException | NoSuchMethodException ignored) {
return false;
}
}
@Nullable
@Override
Executor defaultCallbackExecutor() {
return null;
}
@Override
List<? extends CallAdapter.Factory> createDefaultCallAdapterFactories(
@Nullable Executor callbackExecutor) {
return asList(
new CompletableFutureCallAdapterFactory(),
new DefaultCallAdapterFactory(callbackExecutor));
}
@Override
List<? extends Converter.Factory> createDefaultConverterFactories() {
return singletonList(new OptionalConverterFactory());
}
@Override
public boolean isDefaultMethod(Method method) {
return method.isDefault();
}
@Nullable
@Override
public Object invokeDefaultMethod(
Method method, Class<?> declaringClass, Object proxy, Object... args) throws Throwable {
return MethodHandles.lookup()
.unreflectSpecial(method, declaringClass)
.bindTo(proxy)
.invokeWithArguments(args);
}
}
/**
* Java 16 has a supported public API for invoking default methods on a proxy. We invoke it
* reflectively because we cannot compile against the API directly.
*/
@IgnoreJRERequirement // Only used on JVM and Java 16.
@SuppressWarnings("NewApi") // Not used for Android.
private static final class Java16 extends Platform {
static boolean isSupported() {
try {
Object version = Runtime.class.getMethod("version").invoke(null);
Integer feature = (Integer) version.getClass().getMethod("feature").invoke(version);
return feature >= 16;
} catch (InvocationTargetException | IllegalAccessException | NoSuchMethodException ignored) {
return false;
}
}
private @Nullable Method invokeDefaultMethod;
@Nullable
@Override
Executor defaultCallbackExecutor() {
return null;
}
@Override
List<? extends CallAdapter.Factory> createDefaultCallAdapterFactories(
@Nullable Executor callbackExecutor) {
return asList(
new CompletableFutureCallAdapterFactory(),
new DefaultCallAdapterFactory(callbackExecutor));
}
@Override
List<? extends Converter.Factory> createDefaultConverterFactories() {
return singletonList(new OptionalConverterFactory());
}
@Override
public boolean isDefaultMethod(Method method) {
return method.isDefault();
}
@SuppressWarnings("JavaReflectionMemberAccess") // Only available on Java 16, as we expect.
@Nullable
@Override
public Object invokeDefaultMethod(
Method method, Class<?> declaringClass, Object proxy, Object... args) throws Throwable {
Method invokeDefaultMethod = this.invokeDefaultMethod;
if (invokeDefaultMethod == null) {
invokeDefaultMethod =
InvocationHandler.class.getMethod(
"invokeDefault", Object.class, Method.class, Object[].class);
this.invokeDefaultMethod = invokeDefaultMethod;
}
return invokeDefaultMethod.invoke(null, proxy, method, args);
}
}
private static final class MainThreadExecutor implements Executor {
static final Executor INSTANCE = new MainThreadExecutor();
private final Handler handler = new Handler(Looper.getMainLooper());
@Override
public void execute(Runnable r) {
handler.post(r);
}
}
}
| 3,715 |
0 | Create_ds/retrofit/retrofit/src/main/java | Create_ds/retrofit/retrofit/src/main/java/retrofit2/Callback.java | /*
* Copyright (C) 2012 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;
/**
* Communicates responses from a server or offline requests. One and only one method will be invoked
* in response to a given request.
*
* <p>Callback methods are executed using the {@link Retrofit} callback executor. When none is
* specified, the following defaults are used:
*
* <ul>
* <li>Android: Callbacks are executed on the application's main (UI) thread.
* <li>JVM: Callbacks are executed on the background thread which performed the request.
* </ul>
*
* @param <T> Successful response body type.
*/
public interface Callback<T> {
/**
* Invoked for a received HTTP response.
*
* <p>Note: An HTTP response may still indicate an application-level failure such as a 404 or 500.
* Call {@link Response#isSuccessful()} to determine if the response indicates success.
*/
void onResponse(Call<T> call, Response<T> response);
/**
* Invoked when a network exception occurred talking to the server or when an unexpected exception
* occurred creating the request or processing the response.
*/
void onFailure(Call<T> call, Throwable t);
}
| 3,716 |
0 | Create_ds/retrofit/retrofit/src/main/java | Create_ds/retrofit/retrofit/src/main/java/retrofit2/BuiltInConverters.java | /*
* 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 java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import javax.annotation.Nullable;
import kotlin.Unit;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.http.Streaming;
final class BuiltInConverters extends Converter.Factory {
@Override
public @Nullable Converter<ResponseBody, ?> responseBodyConverter(
Type type, Annotation[] annotations, Retrofit retrofit) {
if (type == ResponseBody.class) {
return Utils.isAnnotationPresent(annotations, Streaming.class)
? StreamingResponseBodyConverter.INSTANCE
: BufferingResponseBodyConverter.INSTANCE;
}
if (type == Void.class) {
return VoidResponseBodyConverter.INSTANCE;
}
if (Utils.isUnit(type)) {
return UnitResponseBodyConverter.INSTANCE;
}
return null;
}
@Override
public @Nullable Converter<?, RequestBody> requestBodyConverter(
Type type,
Annotation[] parameterAnnotations,
Annotation[] methodAnnotations,
Retrofit retrofit) {
if (RequestBody.class.isAssignableFrom(Utils.getRawType(type))) {
return RequestBodyConverter.INSTANCE;
}
return null;
}
static final class VoidResponseBodyConverter implements Converter<ResponseBody, Void> {
static final VoidResponseBodyConverter INSTANCE = new VoidResponseBodyConverter();
@Override
public Void convert(ResponseBody value) {
value.close();
return null;
}
}
static final class UnitResponseBodyConverter implements Converter<ResponseBody, Unit> {
static final UnitResponseBodyConverter INSTANCE = new UnitResponseBodyConverter();
@Override
public Unit convert(ResponseBody value) {
value.close();
return Unit.INSTANCE;
}
}
static final class RequestBodyConverter implements Converter<RequestBody, RequestBody> {
static final RequestBodyConverter INSTANCE = new RequestBodyConverter();
@Override
public RequestBody convert(RequestBody value) {
return value;
}
}
static final class StreamingResponseBodyConverter
implements Converter<ResponseBody, ResponseBody> {
static final StreamingResponseBodyConverter INSTANCE = new StreamingResponseBodyConverter();
@Override
public ResponseBody convert(ResponseBody value) {
return value;
}
}
static final class BufferingResponseBodyConverter
implements Converter<ResponseBody, ResponseBody> {
static final BufferingResponseBodyConverter INSTANCE = new BufferingResponseBodyConverter();
@Override
public ResponseBody convert(ResponseBody value) throws IOException {
try {
// Buffer the entire body to avoid future I/O.
return Utils.buffer(value);
} finally {
value.close();
}
}
}
static final class ToStringConverter implements Converter<Object, String> {
static final ToStringConverter INSTANCE = new ToStringConverter();
@Override
public String convert(Object value) {
return value.toString();
}
}
}
| 3,717 |
0 | Create_ds/retrofit/retrofit/src/main/java | Create_ds/retrofit/retrofit/src/main/java/retrofit2/SkipCallbackExecutor.java | /*
* Copyright (C) 2019 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 static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import java.lang.reflect.Type;
/**
* Change the behavior of a {@code Call<BodyType>} return type to not use the {@linkplain
* Retrofit#callbackExecutor() callback executor} for invoking the {@link Callback#onResponse(Call,
* Response) onResponse} or {@link Callback#onFailure(Call, Throwable) onFailure} methods.
*
* <pre><code>
* @SkipCallbackExecutor
* @GET("user/{id}/token")
* Call<String> getToken(@Path("id") long id);
* </code></pre>
*
* This annotation can also be used when a {@link CallAdapter.Factory} <em>explicitly</em> delegates
* to the built-in factory for {@link Call} via {@link Retrofit#nextCallAdapter(CallAdapter.Factory,
* Type, Annotation[])} in order for the returned {@link Call} to skip the executor. (Note: by
* default, a {@link Call} supplied directly to a {@link CallAdapter} will already skip the callback
* executor. The annotation is only useful when looking up the built-in adapter.)
*/
@Documented
@Target(METHOD)
@Retention(RUNTIME)
public @interface SkipCallbackExecutor {}
| 3,718 |
0 | Create_ds/retrofit/retrofit/src/main/java | Create_ds/retrofit/retrofit/src/main/java/retrofit2/SkipCallbackExecutorImpl.java | /*
* Copyright (C) 2019 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.lang.annotation.Annotation;
// This class conforms to the annotation requirements documented on Annotation.
final class SkipCallbackExecutorImpl implements SkipCallbackExecutor {
private static final SkipCallbackExecutor INSTANCE = new SkipCallbackExecutorImpl();
static Annotation[] ensurePresent(Annotation[] annotations) {
if (Utils.isAnnotationPresent(annotations, SkipCallbackExecutor.class)) {
return annotations;
}
Annotation[] newAnnotations = new Annotation[annotations.length + 1];
// Place the skip annotation first since we're guaranteed to check for it in the call adapter.
newAnnotations[0] = SkipCallbackExecutorImpl.INSTANCE;
System.arraycopy(annotations, 0, newAnnotations, 1, annotations.length);
return newAnnotations;
}
@Override
public Class<? extends Annotation> annotationType() {
return SkipCallbackExecutor.class;
}
@Override
public boolean equals(Object obj) {
return obj instanceof SkipCallbackExecutor;
}
@Override
public int hashCode() {
return 0;
}
@Override
public String toString() {
return "@" + SkipCallbackExecutor.class.getName() + "()";
}
}
| 3,719 |
0 | Create_ds/retrofit/retrofit/src/main/java | Create_ds/retrofit/retrofit/src/main/java/retrofit2/HttpException.java | /*
* 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.util.Objects;
import javax.annotation.Nullable;
/** Exception for an unexpected, non-2xx HTTP response. */
public class HttpException extends RuntimeException {
private static String getMessage(Response<?> response) {
Objects.requireNonNull(response, "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 @Nullable Response<?> response() {
return response;
}
}
| 3,720 |
0 | Create_ds/retrofit/retrofit/src/main/java | Create_ds/retrofit/retrofit/src/main/java/retrofit2/DefaultCallAdapterFactory.java | /*
* 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 java.lang.annotation.Annotation;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Objects;
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;
DefaultCallAdapterFactory(@Nullable Executor callbackExecutor) {
this.callbackExecutor = callbackExecutor;
}
@Override
public @Nullable CallAdapter<?, ?> get(
Type returnType, Annotation[] annotations, Retrofit retrofit) {
if (getRawType(returnType) != Call.class) {
return null;
}
if (!(returnType instanceof ParameterizedType)) {
throw new IllegalArgumentException(
"Call return type must be parameterized as Call<Foo> or Call<? extends Foo>");
}
final Type responseType = Utils.getParameterUpperBound(0, (ParameterizedType) returnType);
final Executor executor =
Utils.isAnnotationPresent(annotations, SkipCallbackExecutor.class)
? null
: callbackExecutor;
return new CallAdapter<Object, Call<?>>() {
@Override
public Type responseType() {
return responseType;
}
@Override
public Call<Object> adapt(Call<Object> call) {
return executor == null ? call : new ExecutorCallbackCall<>(executor, call);
}
};
}
static final class ExecutorCallbackCall<T> implements Call<T> {
final Executor callbackExecutor;
final Call<T> delegate;
ExecutorCallbackCall(Executor callbackExecutor, Call<T> delegate) {
this.callbackExecutor = callbackExecutor;
this.delegate = delegate;
}
@Override
public void enqueue(final Callback<T> callback) {
Objects.requireNonNull(callback, "callback == null");
delegate.enqueue(
new Callback<T>() {
@Override
public void onResponse(Call<T> call, final Response<T> response) {
callbackExecutor.execute(
() -> {
if (delegate.isCanceled()) {
// Emulate OkHttp's behavior of throwing/delivering an IOException on
// cancellation.
callback.onFailure(ExecutorCallbackCall.this, new IOException("Canceled"));
} else {
callback.onResponse(ExecutorCallbackCall.this, response);
}
});
}
@Override
public void onFailure(Call<T> call, final Throwable t) {
callbackExecutor.execute(() -> callback.onFailure(ExecutorCallbackCall.this, t));
}
});
}
@Override
public boolean isExecuted() {
return delegate.isExecuted();
}
@Override
public Response<T> execute() throws IOException {
return delegate.execute();
}
@Override
public void cancel() {
delegate.cancel();
}
@Override
public boolean isCanceled() {
return delegate.isCanceled();
}
@SuppressWarnings("CloneDoesntCallSuperClone") // Performing deep clone.
@Override
public Call<T> clone() {
return new ExecutorCallbackCall<>(callbackExecutor, delegate.clone());
}
@Override
public Request request() {
return delegate.request();
}
@Override
public Timeout timeout() {
return delegate.timeout();
}
}
}
| 3,721 |
0 | Create_ds/retrofit/retrofit/src/main/java | Create_ds/retrofit/retrofit/src/main/java/retrofit2/package-info.java | // Copyright 2014 Square, Inc.
/**
* Retrofit turns your REST API into a Java interface.
*
* <pre>
* public interface GitHubService {
* @GET("/users/{user}/repos")
* List<Repo> listRepos(@Path("user") String user);
* }
* </pre>
*/
@retrofit2.internal.EverythingIsNonNull
package retrofit2;
| 3,722 |
0 | Create_ds/retrofit/retrofit/src/main/java | Create_ds/retrofit/retrofit/src/main/java/retrofit2/OptionalConverterFactory.java | /*
* 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;
import android.annotation.TargetApi;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Optional;
import javax.annotation.Nullable;
import okhttp3.ResponseBody;
import org.codehaus.mojo.animal_sniffer.IgnoreJRERequirement;
@IgnoreJRERequirement // Only added when Optional is available (Java 8+ / Android API 24+).
@TargetApi(24)
final class OptionalConverterFactory extends Converter.Factory {
@Override
public @Nullable Converter<ResponseBody, ?> responseBodyConverter(
Type type, Annotation[] annotations, Retrofit retrofit) {
if (getRawType(type) != Optional.class) {
return null;
}
Type innerType = getParameterUpperBound(0, (ParameterizedType) type);
Converter<ResponseBody, Object> delegate =
retrofit.responseBodyConverter(innerType, annotations);
return new OptionalConverter<>(delegate);
}
@IgnoreJRERequirement
static final class OptionalConverter<T> implements Converter<ResponseBody, Optional<T>> {
final Converter<ResponseBody, T> delegate;
OptionalConverter(Converter<ResponseBody, T> delegate) {
this.delegate = delegate;
}
@Override
public Optional<T> convert(ResponseBody value) throws IOException {
return Optional.ofNullable(delegate.convert(value));
}
}
}
| 3,723 |
0 | Create_ds/retrofit/retrofit/src/main/java/retrofit2 | Create_ds/retrofit/retrofit/src/main/java/retrofit2/internal/EverythingIsNonNull.java | /*
* Copyright (C) 2018 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.internal;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import javax.annotation.Nonnull;
import javax.annotation.meta.TypeQualifierDefault;
/**
* Extends {@code ParametersAreNonnullByDefault} to also apply to Method results and fields.
*
* @see javax.annotation.ParametersAreNonnullByDefault
*/
@Documented
@Nonnull
@TypeQualifierDefault({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface EverythingIsNonNull {}
| 3,724 |
0 | Create_ds/retrofit/retrofit/src/main/java/retrofit2 | Create_ds/retrofit/retrofit/src/main/java/retrofit2/http/POST.java | /*
* 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 retrofit2.http;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import okhttp3.HttpUrl;
/** Make a POST request. */
@Documented
@Target(METHOD)
@Retention(RUNTIME)
public @interface POST {
/**
* A relative or absolute path, or full URL of the endpoint. This value is optional if the first
* parameter of the method is annotated with {@link Url @Url}.
*
* <p>See {@linkplain retrofit2.Retrofit.Builder#baseUrl(HttpUrl) base URL} for details of how
* this is resolved against a base URL to create the full endpoint URL.
*/
String value() default "";
}
| 3,725 |
0 | Create_ds/retrofit/retrofit/src/main/java/retrofit2 | Create_ds/retrofit/retrofit/src/main/java/retrofit2/http/Streaming.java | /*
* 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 retrofit2.http;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import okhttp3.ResponseBody;
/**
* Treat the response body on methods returning {@link ResponseBody ResponseBody} as is, i.e.
* without converting the body to {@code byte[]}.
*/
@Documented
@Target(METHOD)
@Retention(RUNTIME)
public @interface Streaming {}
| 3,726 |
0 | Create_ds/retrofit/retrofit/src/main/java/retrofit2 | Create_ds/retrofit/retrofit/src/main/java/retrofit2/http/PATCH.java | /*
* 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 retrofit2.http;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import okhttp3.HttpUrl;
/** Make a PATCH request. */
@Documented
@Target(METHOD)
@Retention(RUNTIME)
public @interface PATCH {
/**
* A relative or absolute path, or full URL of the endpoint. This value is optional if the first
* parameter of the method is annotated with {@link Url @Url}.
*
* <p>See {@linkplain retrofit2.Retrofit.Builder#baseUrl(HttpUrl) base URL} for details of how
* this is resolved against a base URL to create the full endpoint URL.
*/
String value() default "";
}
| 3,727 |
0 | Create_ds/retrofit/retrofit/src/main/java/retrofit2 | Create_ds/retrofit/retrofit/src/main/java/retrofit2/http/Tag.java | /*
* Copyright (C) 2019 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;
/**
* Adds the argument instance as a request tag using the type as the key.
*
* <pre><code>
* @GET("/")
* Call<ResponseBody> foo(@Tag String tag);
* </code></pre>
*
* Tag arguments may be {@code null} which will omit them from the request. Passing a parameterized
* type such as {@code List<String>} will use the raw type (i.e., {@code List.class}) as the key.
* Duplicate tag types are not allowed.
*/
@Documented
@Target(PARAMETER)
@Retention(RUNTIME)
public @interface Tag {}
| 3,728 |
0 | Create_ds/retrofit/retrofit/src/main/java/retrofit2 | Create_ds/retrofit/retrofit/src/main/java/retrofit2/http/Body.java | /*
* Copyright (C) 2011 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 retrofit2.Converter;
import retrofit2.Retrofit;
/**
* Use this annotation on a service method param when you want to directly control the request body
* of a POST/PUT request (instead of sending in as request parameters or form-style request body).
* The object will be serialized using the {@link Retrofit Retrofit} instance {@link Converter
* Converter} and the result will be set directly as the request body.
*
* <p>Body parameters may not be {@code null}.
*/
@Documented
@Target(PARAMETER)
@Retention(RUNTIME)
public @interface Body {}
| 3,729 |
0 | Create_ds/retrofit/retrofit/src/main/java/retrofit2 | Create_ds/retrofit/retrofit/src/main/java/retrofit2/http/FieldMap.java | /*
* 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 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;
/**
* Named key/value pairs for a form-encoded request.
*
* <p>Simple Example:
*
* <pre><code>
* @FormUrlEncoded
* @POST("/things")
* Call<ResponseBody> things(@FieldMap Map<String, String> fields);
* </code></pre>
*
* Calling with {@code foo.things(ImmutableMap.of("foo", "bar", "kit", "kat")} yields a request body
* of {@code foo=bar&kit=kat}.
*
* <p>A {@code null} value for the map, as a key, or as a value is not allowed.
*
* @see FormUrlEncoded
* @see Field
*/
@Documented
@Target(PARAMETER)
@Retention(RUNTIME)
public @interface FieldMap {
/** Specifies whether the names and values are already URL encoded. */
boolean encoded() default false;
}
| 3,730 |
0 | Create_ds/retrofit/retrofit/src/main/java/retrofit2 | Create_ds/retrofit/retrofit/src/main/java/retrofit2/http/Part.java | /*
* 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 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 retrofit2.Converter;
/**
* Denotes a single part of a multi-part request.
*
* <p>The parameter type on which this annotation exists will be processed in one of three ways:
*
* <ul>
* <li>If the type is {@link okhttp3.MultipartBody.Part} the contents will be used directly. Omit
* the name from the annotation (i.e., {@code @Part MultipartBody.Part part}).
* <li>If the type is {@link okhttp3.RequestBody RequestBody} the value will be used directly with
* its content type. Supply the part name in the annotation (e.g., {@code @Part("foo")
* RequestBody foo}).
* <li>Other object types will be converted to an appropriate representation by using {@linkplain
* Converter a converter}. Supply the part name in the annotation (e.g., {@code @Part("foo")
* Image photo}).
* </ul>
*
* <p>Values may be {@code null} which will omit them from the request body.
*
* <p>
*
* <pre><code>
* @Multipart
* @POST("/")
* Call<ResponseBody> example(
* @Part("description") String description,
* @Part(value = "image", encoding = "8-bit") RequestBody image);
* </code></pre>
*
* <p>Part parameters may not be {@code null}.
*/
@Documented
@Target(PARAMETER)
@Retention(RUNTIME)
public @interface Part {
/**
* The name of the part. Required for all parameter types except {@link
* okhttp3.MultipartBody.Part}.
*/
String value() default "";
/** The {@code Content-Transfer-Encoding} of this part. */
String encoding() default "binary";
}
| 3,731 |
0 | Create_ds/retrofit/retrofit/src/main/java/retrofit2 | Create_ds/retrofit/retrofit/src/main/java/retrofit2/http/Url.java | /*
* 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.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 okhttp3.HttpUrl;
import retrofit2.Retrofit;
/**
* URL resolved against the {@linkplain Retrofit#baseUrl() base URL}.
*
* <pre><code>
* @GET
* Call<ResponseBody> list(@Url String url);
* </code></pre>
*
* <p>See {@linkplain retrofit2.Retrofit.Builder#baseUrl(HttpUrl) base URL} for details of how the
* value will be resolved against a base URL to create the full endpoint URL.
*/
@Documented
@Target(PARAMETER)
@Retention(RUNTIME)
public @interface Url {}
| 3,732 |
0 | Create_ds/retrofit/retrofit/src/main/java/retrofit2 | Create_ds/retrofit/retrofit/src/main/java/retrofit2/http/Headers.java | /*
* 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 retrofit2.http;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
/**
* Adds headers literally supplied in the {@code value}.
*
* <pre><code>
* @Headers("Cache-Control: max-age=640000")
* @GET("/")
* ...
*
* @Headers({
* "X-Foo: Bar",
* "X-Ping: Pong"
* })
* @GET("/")
* ...
* </code></pre>
*
* <p>Parameter keys and values only allows ascii values by default. Specify {@link
* #allowUnsafeNonAsciiValues() allowUnsafeNonAsciiValues=true} to change this behavior.
*
* <p>@Headers({ "X-Foo: Bar", "X-Ping: Pong" }, allowUnsafeNonAsciiValues=true) @GET("/")
*
* <p><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)
@Retention(RUNTIME)
public @interface Headers {
/** The query parameter name. */
String[] value();
/**
* Specifies whether the parameter {@linkplain #value() name} and value are already URL encoded.
*/
boolean allowUnsafeNonAsciiValues() default false;
}
| 3,733 |
0 | Create_ds/retrofit/retrofit/src/main/java/retrofit2 | Create_ds/retrofit/retrofit/src/main/java/retrofit2/http/HTTP.java | /*
* 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 retrofit2.http;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import okhttp3.HttpUrl;
/**
* Use a custom HTTP verb for a request.
*
* <pre><code>
* interface Service {
* @HTTP(method = "CUSTOM", path = "custom/endpoint/")
* Call<ResponseBody> customEndpoint();
* }
* </code></pre>
*
* This annotation can also used for sending {@code DELETE} with a request body:
*
* <pre><code>
* interface Service {
* @HTTP(method = "DELETE", path = "remove/", hasBody = true)
* Call<ResponseBody> deleteObject(@Body RequestBody object);
* }
* </code></pre>
*/
@Documented
@Target(METHOD)
@Retention(RUNTIME)
public @interface HTTP {
String method();
/**
* A relative or absolute path, or full URL of the endpoint. This value is optional if the first
* parameter of the method is annotated with {@link Url @Url}.
*
* <p>See {@linkplain retrofit2.Retrofit.Builder#baseUrl(HttpUrl) base URL} for details of how
* this is resolved against a base URL to create the full endpoint URL.
*/
String path() default "";
boolean hasBody() default false;
}
| 3,734 |
0 | Create_ds/retrofit/retrofit/src/main/java/retrofit2 | Create_ds/retrofit/retrofit/src/main/java/retrofit2/http/QueryName.java | /*
* 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 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;
/**
* Query parameter appended to the URL that has no value.
*
* <p>Passing a {@link java.util.List List} or array will result in a query parameter for each
* non-{@code null} item.
*
* <p>Simple Example:
*
* <pre><code>
* @GET("/friends")
* Call<ResponseBody> friends(@QueryName String filter);
* </code></pre>
*
* Calling with {@code foo.friends("contains(Bob)")} yields {@code /friends?contains(Bob)}.
*
* <p>Array/Varargs Example:
*
* <pre><code>
* @GET("/friends")
* Call<ResponseBody> friends(@QueryName String... filters);
* </code></pre>
*
* Calling with {@code foo.friends("contains(Bob)", "age(42)")} yields {@code
* /friends?contains(Bob)&age(42)}.
*
* <p>Parameter names are URL encoded by default. Specify {@link #encoded() encoded=true} to change
* this behavior.
*
* <pre><code>
* @GET("/friends")
* Call<ResponseBody> friends(@QueryName(encoded=true) String filter);
* </code></pre>
*
* Calling with {@code foo.friends("name+age"))} yields {@code /friends?name+age}.
*
* @see Query
* @see QueryMap
*/
@Documented
@Target(PARAMETER)
@Retention(RUNTIME)
public @interface QueryName {
/** Specifies whether the parameter is already URL encoded. */
boolean encoded() default false;
}
| 3,735 |
0 | Create_ds/retrofit/retrofit/src/main/java/retrofit2 | Create_ds/retrofit/retrofit/src/main/java/retrofit2/http/QueryMap.java | /*
* 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 retrofit2.http;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import java.lang.reflect.Type;
import retrofit2.Retrofit;
/**
* Query parameter keys and values appended to the URL.
*
* <p>Values are converted to strings using {@link Retrofit#stringConverter(Type, Annotation[])} (or
* {@link Object#toString()}, if no matching string converter is installed).
*
* <p>Simple Example:
*
* <pre><code>
* @GET("/friends")
* Call<ResponseBody> friends(@QueryMap Map<String, String> filters);
* </code></pre>
*
* Calling with {@code foo.friends(ImmutableMap.of("group", "coworker", "age", "42"))} yields {@code
* /friends?group=coworker&age=42}.
*
* <p>Map keys and values representing parameter values are URL encoded by default. Specify {@link
* #encoded() encoded=true} to change this behavior.
*
* <pre><code>
* @GET("/friends")
* Call<ResponseBody> friends(@QueryMap(encoded=true) Map<String, String> filters);
* </code></pre>
*
* Calling with {@code foo.list(ImmutableMap.of("group", "coworker+bowling"))} yields {@code
* /friends?group=coworker+bowling}.
*
* <p>A {@code null} value for the map, as a key, or as a value is not allowed.
*
* @see Query
* @see QueryName
*/
@Documented
@Target(PARAMETER)
@Retention(RUNTIME)
public @interface QueryMap {
/** Specifies whether parameter names and values are already URL encoded. */
boolean encoded() default false;
}
| 3,736 |
0 | Create_ds/retrofit/retrofit/src/main/java/retrofit2 | Create_ds/retrofit/retrofit/src/main/java/retrofit2/http/Query.java | /*
* 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 retrofit2.http;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import java.lang.reflect.Type;
import retrofit2.Retrofit;
/**
* Query parameter appended to the URL.
*
* <p>Values are converted to strings using {@link Retrofit#stringConverter(Type, Annotation[])} (or
* {@link Object#toString()}, if no matching string converter is installed) and then URL encoded.
* {@code null} values are ignored. Passing a {@link java.util.List List} or array will result in a
* query parameter for each non-{@code null} item.
*
* <p>Simple Example:
*
* <pre><code>
* @GET("/friends")
* Call<ResponseBody> friends(@Query("page") int page);
* </code></pre>
*
* Calling with {@code foo.friends(1)} yields {@code /friends?page=1}.
*
* <p>Example with {@code null}:
*
* <pre><code>
* @GET("/friends")
* Call<ResponseBody> friends(@Query("group") String group);
* </code></pre>
*
* Calling with {@code foo.friends(null)} yields {@code /friends}.
*
* <p>Array/Varargs Example:
*
* <pre><code>
* @GET("/friends")
* Call<ResponseBody> friends(@Query("group") String... groups);
* </code></pre>
*
* Calling with {@code foo.friends("coworker", "bowling")} yields {@code
* /friends?group=coworker&group=bowling}.
*
* <p>Parameter names and values are URL encoded by default. Specify {@link #encoded() encoded=true}
* to change this behavior.
*
* <pre><code>
* @GET("/friends")
* Call<ResponseBody> friends(@Query(value="group", encoded=true) String group);
* </code></pre>
*
* Calling with {@code foo.friends("foo+bar"))} yields {@code /friends?group=foo+bar}.
*
* @see QueryMap
* @see QueryName
*/
@Documented
@Target(PARAMETER)
@Retention(RUNTIME)
public @interface Query {
/** The query parameter name. */
String value();
/**
* Specifies whether the parameter {@linkplain #value() name} and value are already URL encoded.
*/
boolean encoded() default false;
}
| 3,737 |
0 | Create_ds/retrofit/retrofit/src/main/java/retrofit2 | Create_ds/retrofit/retrofit/src/main/java/retrofit2/http/HEAD.java | /*
* 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 retrofit2.http;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import okhttp3.HttpUrl;
/** Make a HEAD request. */
@Documented
@Target(METHOD)
@Retention(RUNTIME)
public @interface HEAD {
/**
* A relative or absolute path, or full URL of the endpoint. This value is optional if the first
* parameter of the method is annotated with {@link Url @Url}.
*
* <p>See {@linkplain retrofit2.Retrofit.Builder#baseUrl(HttpUrl) base URL} for details of how
* this is resolved against a base URL to create the full endpoint URL.
*/
String value() default "";
}
| 3,738 |
0 | Create_ds/retrofit/retrofit/src/main/java/retrofit2 | Create_ds/retrofit/retrofit/src/main/java/retrofit2/http/OPTIONS.java | /*
* 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.http;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import okhttp3.HttpUrl;
/** Make an OPTIONS request. */
@Documented
@Target(METHOD)
@Retention(RUNTIME)
public @interface OPTIONS {
/**
* A relative or absolute path, or full URL of the endpoint. This value is optional if the first
* parameter of the method is annotated with {@link Url @Url}.
*
* <p>See {@linkplain retrofit2.Retrofit.Builder#baseUrl(HttpUrl) base URL} for details of how
* this is resolved against a base URL to create the full endpoint URL.
*/
String value() default "";
}
| 3,739 |
0 | Create_ds/retrofit/retrofit/src/main/java/retrofit2 | Create_ds/retrofit/retrofit/src/main/java/retrofit2/http/PUT.java | /*
* 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 retrofit2.http;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import okhttp3.HttpUrl;
/** Make a PUT request. */
@Documented
@Target(METHOD)
@Retention(RUNTIME)
public @interface PUT {
/**
* A relative or absolute path, or full URL of the endpoint. This value is optional if the first
* parameter of the method is annotated with {@link Url @Url}.
*
* <p>See {@linkplain retrofit2.Retrofit.Builder#baseUrl(HttpUrl) base URL} for details of how
* this is resolved against a base URL to create the full endpoint URL.
*/
String value() default "";
}
| 3,740 |
0 | Create_ds/retrofit/retrofit/src/main/java/retrofit2 | Create_ds/retrofit/retrofit/src/main/java/retrofit2/http/FormUrlEncoded.java | /*
* 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 retrofit2.http;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
/**
* Denotes that the request body will use form URL encoding. Fields should be declared as parameters
* and annotated with {@link Field @Field}.
*
* <p>Requests made with this annotation will have {@code application/x-www-form-urlencoded} MIME
* type. Field names and values will be UTF-8 encoded before being URI-encoded in accordance to <a
* href="https://datatracker.ietf.org/doc/html/rfc3986">RFC-3986</a>.
*/
@Documented
@Target(METHOD)
@Retention(RUNTIME)
public @interface FormUrlEncoded {}
| 3,741 |
0 | Create_ds/retrofit/retrofit/src/main/java/retrofit2 | Create_ds/retrofit/retrofit/src/main/java/retrofit2/http/Field.java | /*
* 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 retrofit2.http;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import java.lang.reflect.Type;
import retrofit2.Retrofit;
/**
* Named pair for a form-encoded request.
*
* <p>Values are converted to strings using {@link Retrofit#stringConverter(Type, Annotation[])} (or
* {@link Object#toString()}, if no matching string converter is installed) and then form URL
* encoded. {@code null} values are ignored. Passing a {@link java.util.List List} or array will
* result in a field pair for each non-{@code null} item.
*
* <p>Simple Example:
*
* <pre><code>
* @FormUrlEncoded
* @POST("/")
* Call<ResponseBody> example(
* @Field("name") String name,
* @Field("occupation") String occupation);
* </code></pre>
*
* Calling with {@code foo.example("Bob Smith", "President")} yields a request body of {@code
* name=Bob+Smith&occupation=President}.
*
* <p>Array/Varargs Example:
*
* <pre><code>
* @FormUrlEncoded
* @POST("/list")
* Call<ResponseBody> example(@Field("name") String... names);
* </code></pre>
*
* Calling with {@code foo.example("Bob Smith", "Jane Doe")} yields a request body of {@code
* name=Bob+Smith&name=Jane+Doe}.
*
* @see FormUrlEncoded
* @see FieldMap
*/
@Documented
@Target(PARAMETER)
@Retention(RUNTIME)
public @interface Field {
String value();
/** Specifies whether the {@linkplain #value() name} and value are already URL encoded. */
boolean encoded() default false;
}
| 3,742 |
0 | Create_ds/retrofit/retrofit/src/main/java/retrofit2 | Create_ds/retrofit/retrofit/src/main/java/retrofit2/http/Header.java | /*
* 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 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;
/**
* Replaces the header with the value of its target.
*
* <pre><code>
* @GET("/")
* Call<ResponseBody> foo(@Header("Accept-Language") String lang);
* </code></pre>
*
* Header parameters may be {@code null} which will omit them from the request. Passing a {@link
* java.util.List List} or array will result in a header for each non-{@code null} item.
*
* <p>Parameter keys and values only allows ascii values by default. Specify {@link
* #allowUnsafeNonAsciiValues() allowUnsafeNonAsciiValues=true} to change this behavior.
*
* <pre><code>
* @GET("/")
* Call<ResponseBody> foo(@Header("Accept-Language", allowUnsafeNonAsciiValues=true) String lang);
* </code></pre>
*
* <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)
@Target(PARAMETER)
public @interface Header {
/** The query parameter name. */
String value();
/**
* Specifies whether the parameter {@linkplain #value() name} and value are already URL encoded.
*/
boolean allowUnsafeNonAsciiValues() default false;
}
| 3,743 |
0 | Create_ds/retrofit/retrofit/src/main/java/retrofit2 | Create_ds/retrofit/retrofit/src/main/java/retrofit2/http/DELETE.java | /*
* 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 retrofit2.http;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import okhttp3.HttpUrl;
/** Make a DELETE request. */
@Documented
@Target(METHOD)
@Retention(RUNTIME)
public @interface DELETE {
/**
* A relative or absolute path, or full URL of the endpoint. This value is optional if the first
* parameter of the method is annotated with {@link Url @Url}.
*
* <p>See {@linkplain retrofit2.Retrofit.Builder#baseUrl(HttpUrl) base URL} for details of how
* this is resolved against a base URL to create the full endpoint URL.
*/
String value() default "";
}
| 3,744 |
0 | Create_ds/retrofit/retrofit/src/main/java/retrofit2 | Create_ds/retrofit/retrofit/src/main/java/retrofit2/http/GET.java | /*
* 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 retrofit2.http;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import okhttp3.HttpUrl;
/** Make a GET request. */
@Documented
@Target(METHOD)
@Retention(RUNTIME)
public @interface GET {
/**
* A relative or absolute path, or full URL of the endpoint. This value is optional if the first
* parameter of the method is annotated with {@link Url @Url}.
*
* <p>See {@linkplain retrofit2.Retrofit.Builder#baseUrl(HttpUrl) base URL} for details of how
* this is resolved against a base URL to create the full endpoint URL.
*/
String value() default "";
}
| 3,745 |
0 | Create_ds/retrofit/retrofit/src/main/java/retrofit2 | Create_ds/retrofit/retrofit/src/main/java/retrofit2/http/package-info.java | // Copyright 2014 Square, Inc.
/** Annotations for interface methods to control the HTTP request behavior. */
package retrofit2.http;
| 3,746 |
0 | Create_ds/retrofit/retrofit/src/main/java/retrofit2 | Create_ds/retrofit/retrofit/src/main/java/retrofit2/http/PartMap.java | /*
* 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 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 retrofit2.Converter;
/**
* Denotes name and value parts of a multi-part request.
*
* <p>Values of the map on which this annotation exists will be processed in one of two ways:
*
* <ul>
* <li>If the type is {@link okhttp3.RequestBody RequestBody} the value will be used directly with
* its content type.
* <li>Other object types will be converted to an appropriate representation by using {@linkplain
* Converter a converter}.
* </ul>
*
* <p>
*
* <pre><code>
* @Multipart
* @POST("/upload")
* Call<ResponseBody> upload(
* @Part("file") RequestBody file,
* @PartMap Map<String, RequestBody> params);
* </code></pre>
*
* <p>A {@code null} value for the map, as a key, or as a value is not allowed.
*
* @see Multipart
* @see Part
*/
@Documented
@Target(PARAMETER)
@Retention(RUNTIME)
public @interface PartMap {
/** The {@code Content-Transfer-Encoding} of the parts. */
String encoding() default "binary";
}
| 3,747 |
0 | Create_ds/retrofit/retrofit/src/main/java/retrofit2 | Create_ds/retrofit/retrofit/src/main/java/retrofit2/http/Multipart.java | /*
* 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 retrofit2.http;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
/**
* Denotes that the request body is multi-part. Parts should be declared as parameters and annotated
* with {@link Part @Part}.
*/
@Documented
@Target(METHOD)
@Retention(RUNTIME)
public @interface Multipart {}
| 3,748 |
0 | Create_ds/retrofit/retrofit/src/main/java/retrofit2 | Create_ds/retrofit/retrofit/src/main/java/retrofit2/http/HeaderMap.java | /*
* 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.Annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import java.lang.reflect.Type;
import java.util.Map;
import retrofit2.Retrofit;
/**
* Adds headers specified in the {@link Map} or {@link okhttp3.Headers}.
*
* <p>Values in the map are converted to strings using {@link Retrofit#stringConverter(Type,
* Annotation[])} (or {@link Object#toString()}, if no matching string converter is installed).
*
* <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>
*
* <p>Map keys and values representing parameter values allow only ascii values by default.
* Specify {@link #allowUnsafeNonAsciiValues() allowUnsafeNonAsciiValues=true} to change this behavior.
*
* <pre>
* @GET("/search")
* void list(@HeaderMap(allowUnsafeNonAsciiValues=true) Map<String, String> headers);
*
* @see Header
* @see Headers
*/
@Documented
@Target(PARAMETER)
@Retention(RUNTIME)
public @interface HeaderMap {
/** Specifies whether the parameter values are allowed with unsafe non ascii values. */
boolean allowUnsafeNonAsciiValues() default false;
}
| 3,749 |
0 | Create_ds/retrofit/retrofit/src/main/java/retrofit2 | Create_ds/retrofit/retrofit/src/main/java/retrofit2/http/Path.java | /*
* 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 retrofit2.http;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import java.lang.reflect.Type;
import retrofit2.Retrofit;
/**
* Named replacement in a URL path segment. Values are converted to strings using {@link
* Retrofit#stringConverter(Type, Annotation[])} (or {@link Object#toString()}, if no matching
* string converter is installed) and then URL encoded.
*
* <p>Simple example:
*
* <pre><code>
* @GET("/image/{id}")
* Call<ResponseBody> example(@Path("id") int id);
* </code></pre>
*
* Calling with {@code foo.example(1)} yields {@code /image/1}.
*
* <p>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", encoded=true) String name);
* </code></pre>
*
* Calling {@code foo.encoded("John+Doe")} yields {@code /user/John%2BDoe} whereas {@code
* foo.notEncoded("John+Doe")} yields {@code /user/John+Doe}.
*
* <p>Path parameters may not be {@code null}.
*/
@Documented
@Retention(RUNTIME)
@Target(PARAMETER)
public @interface Path {
String value();
/**
* Specifies whether the argument value to the annotated method parameter is already URL encoded.
*/
boolean encoded() default false;
}
| 3,750 |
0 | Create_ds/retrofit/samples/src/main/java/com/example | Create_ds/retrofit/samples/src/main/java/com/example/retrofit/DynamicBaseUrl.java | /*
* 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 com.example.retrofit;
import java.io.IOException;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.http.GET;
/**
* This example uses an OkHttp interceptor to change the target hostname dynamically at runtime.
* Typically this would be used to implement client-side load balancing or to use the webserver
* that's nearest geographically.
*/
public final class DynamicBaseUrl {
public interface Pop {
@GET("robots.txt")
Call<ResponseBody> robots();
}
static final class HostSelectionInterceptor implements Interceptor {
private volatile String host;
public void setHost(String host) {
this.host = host;
}
@Override
public okhttp3.Response intercept(Chain chain) throws IOException {
Request request = chain.request();
String host = this.host;
if (host != null) {
HttpUrl newUrl = request.url().newBuilder().host(host).build();
request = request.newBuilder().url(newUrl).build();
}
return chain.proceed(request);
}
}
public static void main(String... args) throws IOException {
HostSelectionInterceptor hostSelectionInterceptor = new HostSelectionInterceptor();
OkHttpClient okHttpClient =
new OkHttpClient.Builder().addInterceptor(hostSelectionInterceptor).build();
Retrofit retrofit =
new Retrofit.Builder().baseUrl("http://www.github.com/").callFactory(okHttpClient).build();
Pop pop = retrofit.create(Pop.class);
Response<ResponseBody> response1 = pop.robots().execute();
System.out.println("Response from: " + response1.raw().request().url());
System.out.println(response1.body().string());
hostSelectionInterceptor.setHost("www.pepsi.com");
Response<ResponseBody> response2 = pop.robots().execute();
System.out.println("Response from: " + response2.raw().request().url());
System.out.println(response2.body().string());
}
}
| 3,751 |
0 | Create_ds/retrofit/samples/src/main/java/com/example | Create_ds/retrofit/samples/src/main/java/com/example/retrofit/ErrorHandlingAdapter.java | /*
* 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 com.example.retrofit;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.concurrent.Executor;
import javax.annotation.Nullable;
import retrofit2.Call;
import retrofit2.CallAdapter;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.GET;
/**
* A sample showing a custom {@link CallAdapter} which adapts the built-in {@link Call} to a custom
* version whose callback has more granular methods.
*/
public final class ErrorHandlingAdapter {
/** A callback which offers granular callbacks for various conditions. */
interface MyCallback<T> {
/** Called for [200, 300) responses. */
void success(Response<T> response);
/** Called for 401 responses. */
void unauthenticated(Response<?> response);
/** Called for [400, 500) responses, except 401. */
void clientError(Response<?> response);
/** Called for [500, 600) response. */
void serverError(Response<?> response);
/** Called for network errors while making the call. */
void networkError(IOException e);
/** Called for unexpected errors while making the call. */
void unexpectedError(Throwable t);
}
interface MyCall<T> {
void cancel();
void enqueue(MyCallback<T> callback);
MyCall<T> clone();
// Left as an exercise for the reader...
// TODO MyResponse<T> execute() throws MyHttpException;
}
public static class ErrorHandlingCallAdapterFactory extends CallAdapter.Factory {
@Override
public @Nullable CallAdapter<?, ?> get(
Type returnType, Annotation[] annotations, Retrofit retrofit) {
if (getRawType(returnType) != MyCall.class) {
return null;
}
if (!(returnType instanceof ParameterizedType)) {
throw new IllegalStateException(
"MyCall must have generic type (e.g., MyCall<ResponseBody>)");
}
Type responseType = getParameterUpperBound(0, (ParameterizedType) returnType);
Executor callbackExecutor = retrofit.callbackExecutor();
return new ErrorHandlingCallAdapter<>(responseType, callbackExecutor);
}
private static final class ErrorHandlingCallAdapter<R> implements CallAdapter<R, MyCall<R>> {
private final Type responseType;
private final Executor callbackExecutor;
ErrorHandlingCallAdapter(Type responseType, Executor callbackExecutor) {
this.responseType = responseType;
this.callbackExecutor = callbackExecutor;
}
@Override
public Type responseType() {
return responseType;
}
@Override
public MyCall<R> adapt(Call<R> call) {
return new MyCallAdapter<>(call, callbackExecutor);
}
}
}
/** Adapts a {@link Call} to {@link MyCall}. */
static class MyCallAdapter<T> implements MyCall<T> {
private final Call<T> call;
private final Executor callbackExecutor;
MyCallAdapter(Call<T> call, Executor callbackExecutor) {
this.call = call;
this.callbackExecutor = callbackExecutor;
}
@Override
public void cancel() {
call.cancel();
}
@Override
public void enqueue(final MyCallback<T> callback) {
call.enqueue(
new Callback<T>() {
@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.
int code = response.code();
if (code >= 200 && code < 300) {
callback.success(response);
} else if (code == 401) {
callback.unauthenticated(response);
} else if (code >= 400 && code < 500) {
callback.clientError(response);
} else if (code >= 500 && code < 600) {
callback.serverError(response);
} else {
callback.unexpectedError(new RuntimeException("Unexpected response " + 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.
if (t instanceof IOException) {
callback.networkError((IOException) t);
} else {
callback.unexpectedError(t);
}
}
});
}
@Override
public MyCall<T> clone() {
return new MyCallAdapter<>(call.clone(), callbackExecutor);
}
}
interface HttpBinService {
@GET("/ip")
MyCall<Ip> getIp();
}
static class Ip {
String origin;
}
public static void main(String... args) {
Retrofit retrofit =
new Retrofit.Builder()
.baseUrl("http://httpbin.org")
.addCallAdapterFactory(new ErrorHandlingCallAdapterFactory())
.addConverterFactory(GsonConverterFactory.create())
.build();
HttpBinService service = retrofit.create(HttpBinService.class);
MyCall<Ip> ip = service.getIp();
ip.enqueue(
new MyCallback<Ip>() {
@Override
public void success(Response<Ip> response) {
System.out.println("SUCCESS! " + response.body().origin);
}
@Override
public void unauthenticated(Response<?> response) {
System.out.println("UNAUTHENTICATED");
}
@Override
public void clientError(Response<?> response) {
System.out.println("CLIENT ERROR " + response.code() + " " + response.message());
}
@Override
public void serverError(Response<?> response) {
System.out.println("SERVER ERROR " + response.code() + " " + response.message());
}
@Override
public void networkError(IOException e) {
System.err.println("NETWORK ERROR " + e.getMessage());
}
@Override
public void unexpectedError(Throwable t) {
System.err.println("FATAL ERROR " + t.getMessage());
}
});
}
}
| 3,752 |
0 | Create_ds/retrofit/samples/src/main/java/com/example | Create_ds/retrofit/samples/src/main/java/com/example/retrofit/RxJavaObserveOnMainThread.java | /*
* 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 com.example.retrofit;
import static rx.schedulers.Schedulers.io;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import javax.annotation.Nullable;
import retrofit2.Call;
import retrofit2.CallAdapter;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import rx.Observable;
import rx.Scheduler;
import rx.schedulers.Schedulers;
public final class RxJavaObserveOnMainThread {
@SuppressWarnings("UnusedVariable")
public static void main(String... args) {
Scheduler observeOn = Schedulers.computation(); // Or use mainThread() for Android.
Retrofit retrofit =
new Retrofit.Builder()
.baseUrl("http://example.com")
.addCallAdapterFactory(new ObserveOnMainCallAdapterFactory(observeOn))
.addCallAdapterFactory(RxJavaCallAdapterFactory.createWithScheduler(io()))
.build();
// Services created with this instance that use Observable will execute on the 'io' scheduler
// and notify their observer on the 'computation' scheduler.
}
static final class ObserveOnMainCallAdapterFactory extends CallAdapter.Factory {
final Scheduler scheduler;
ObserveOnMainCallAdapterFactory(Scheduler scheduler) {
this.scheduler = scheduler;
}
@Override
public @Nullable CallAdapter<?, ?> get(
Type returnType, Annotation[] annotations, Retrofit retrofit) {
if (getRawType(returnType) != Observable.class) {
return null; // Ignore non-Observable types.
}
// Look up the next call adapter which would otherwise be used if this one was not present.
//noinspection unchecked returnType checked above to be Observable.
final CallAdapter<Object, Observable<?>> delegate =
(CallAdapter<Object, Observable<?>>)
retrofit.nextCallAdapter(this, returnType, annotations);
return new CallAdapter<Object, Object>() {
@Override
public Object adapt(Call<Object> call) {
// Delegate to get the normal Observable...
Observable<?> o = delegate.adapt(call);
// ...and change it to send notifications to the observer on the specified scheduler.
return o.observeOn(scheduler);
}
@Override
public Type responseType() {
return delegate.responseType();
}
};
}
}
}
| 3,753 |
0 | Create_ds/retrofit/samples/src/main/java/com/example | Create_ds/retrofit/samples/src/main/java/com/example/retrofit/DeserializeErrorBody.java | /*
* 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 com.example.retrofit;
import java.io.IOException;
import java.lang.annotation.Annotation;
import okhttp3.ResponseBody;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import retrofit2.Call;
import retrofit2.Converter;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.GET;
public final class DeserializeErrorBody {
interface Service {
@GET("/user")
Call<User> getUser();
}
static class User {
// normal fields...
}
static class ErrorBody {
String message;
}
public static void main(String... args) throws IOException {
// Create a local web server which response with a 404 and JSON body.
MockWebServer server = new MockWebServer();
server.start();
server.enqueue(
new MockResponse()
.setResponseCode(404)
.setBody("{\"message\":\"Unable to locate resource\"}"));
// Create our Service instance with a Retrofit pointing at the local web server and Gson.
Retrofit retrofit =
new Retrofit.Builder()
.baseUrl(server.url("/"))
.addConverterFactory(GsonConverterFactory.create())
.build();
Service service = retrofit.create(Service.class);
Response<User> response = service.getUser().execute();
// Normally you would check response.isSuccess() here before doing the following, but we know
// this call will always fail. You could also use response.code() to determine whether to
// convert the error body and/or which type to use for conversion.
// Look up a converter for the Error type on the Retrofit instance.
Converter<ResponseBody, ErrorBody> errorConverter =
retrofit.responseBodyConverter(ErrorBody.class, new Annotation[0]);
// Convert the error body into our Error type.
ErrorBody errorBody = errorConverter.convert(response.errorBody());
System.out.println("ERROR: " + errorBody.message);
server.shutdown();
}
}
| 3,754 |
0 | Create_ds/retrofit/samples/src/main/java/com/example | Create_ds/retrofit/samples/src/main/java/com/example/retrofit/JsonQueryParameters.java | /*
* 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 com.example.retrofit;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.annotation.Retention;
import java.lang.reflect.Type;
import javax.annotation.Nullable;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import okhttp3.mockwebserver.RecordedRequest;
import okio.Buffer;
import retrofit2.Call;
import retrofit2.Converter;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.GET;
import retrofit2.http.Query;
public final class JsonQueryParameters {
@Retention(RUNTIME)
@interface Json {}
static class JsonStringConverterFactory extends Converter.Factory {
private final Converter.Factory delegateFactory;
JsonStringConverterFactory(Converter.Factory delegateFactory) {
this.delegateFactory = delegateFactory;
}
@Override
public @Nullable Converter<?, String> stringConverter(
Type type, Annotation[] annotations, Retrofit retrofit) {
for (Annotation annotation : annotations) {
if (annotation instanceof Json) {
// NOTE: If you also have a JSON converter factory installed in addition to this factory,
// you can call retrofit.requestBodyConverter(type, annotations) instead of having a
// reference to it explicitly as a field.
Converter<?, RequestBody> delegate =
delegateFactory.requestBodyConverter(type, annotations, new Annotation[0], retrofit);
return new DelegateToStringConverter<>(delegate);
}
}
return null;
}
static class DelegateToStringConverter<T> implements Converter<T, String> {
private final Converter<T, RequestBody> delegate;
DelegateToStringConverter(Converter<T, RequestBody> delegate) {
this.delegate = delegate;
}
@Override
public String convert(T value) throws IOException {
Buffer buffer = new Buffer();
delegate.convert(value).writeTo(buffer);
return buffer.readUtf8();
}
}
}
static class Filter {
final String userId;
Filter(String userId) {
this.userId = userId;
}
}
interface Service {
@GET("/filter")
Call<ResponseBody> example(@Json @Query("value") Filter value);
}
@SuppressWarnings("UnusedVariable")
public static void main(String... args) throws IOException, InterruptedException {
MockWebServer server = new MockWebServer();
server.start();
server.enqueue(new MockResponse());
Retrofit retrofit =
new Retrofit.Builder()
.baseUrl(server.url("/"))
.addConverterFactory(new JsonStringConverterFactory(GsonConverterFactory.create()))
.build();
Service service = retrofit.create(Service.class);
Call<ResponseBody> call = service.example(new Filter("123"));
Response<ResponseBody> response = call.execute();
// TODO handle user response...
// Print the request path that the server saw to show the JSON query param:
RecordedRequest recordedRequest = server.takeRequest();
System.out.println(recordedRequest.getPath());
server.shutdown();
}
}
| 3,755 |
0 | Create_ds/retrofit/samples/src/main/java/com/example | Create_ds/retrofit/samples/src/main/java/com/example/retrofit/AnnotatedConverters.java | /*
* 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 com.example.retrofit;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import com.google.gson.GsonBuilder;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.annotation.Retention;
import java.lang.reflect.Type;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.annotation.Nullable;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Default;
import org.simpleframework.xml.DefaultType;
import retrofit2.Call;
import retrofit2.Converter;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.moshi.MoshiConverterFactory;
import retrofit2.converter.simplexml.SimpleXmlConverterFactory;
import retrofit2.http.GET;
final class AnnotatedConverters {
public static final class AnnotatedConverterFactory extends Converter.Factory {
private final Map<Class<? extends Annotation>, Converter.Factory> factories;
public static final class Builder {
private final Map<Class<? extends Annotation>, Converter.Factory> factories =
new LinkedHashMap<>();
public Builder add(Class<? extends Annotation> cls, Converter.Factory factory) {
if (cls == null) {
throw new NullPointerException("cls == null");
}
if (factory == null) {
throw new NullPointerException("factory == null");
}
factories.put(cls, factory);
return this;
}
public AnnotatedConverterFactory build() {
return new AnnotatedConverterFactory(factories);
}
}
AnnotatedConverterFactory(Map<Class<? extends Annotation>, Converter.Factory> factories) {
this.factories = new LinkedHashMap<>(factories);
}
@Override
public @Nullable Converter<ResponseBody, ?> responseBodyConverter(
Type type, Annotation[] annotations, Retrofit retrofit) {
for (Annotation annotation : annotations) {
Converter.Factory factory = factories.get(annotation.annotationType());
if (factory != null) {
return factory.responseBodyConverter(type, annotations, retrofit);
}
}
return null;
}
@Override
public @Nullable Converter<?, RequestBody> requestBodyConverter(
Type type,
Annotation[] parameterAnnotations,
Annotation[] methodAnnotations,
Retrofit retrofit) {
for (Annotation annotation : parameterAnnotations) {
Converter.Factory factory = factories.get(annotation.annotationType());
if (factory != null) {
return factory.requestBodyConverter(
type, parameterAnnotations, methodAnnotations, retrofit);
}
}
return null;
}
}
@Retention(RUNTIME)
public @interface Moshi {}
@Retention(RUNTIME)
public @interface Gson {}
@Retention(RUNTIME)
public @interface SimpleXml {}
@Default(value = DefaultType.FIELD)
static final class Library {
@Attribute String name;
}
interface Service {
@GET("/")
@Moshi
Call<Library> exampleMoshi();
@GET("/")
@Gson
Call<Library> exampleGson();
@GET("/")
@SimpleXml
Call<Library> exampleSimpleXml();
@GET("/")
Call<Library> exampleDefault();
}
public static void main(String... args) throws IOException {
MockWebServer server = new MockWebServer();
server.start();
server.enqueue(new MockResponse().setBody("{\"name\": \"Moshi\"}"));
server.enqueue(new MockResponse().setBody("{\"name\": \"Gson\"}"));
server.enqueue(new MockResponse().setBody("<user name=\"SimpleXML\"/>"));
server.enqueue(new MockResponse().setBody("{\"name\": \"Gson\"}"));
com.squareup.moshi.Moshi moshi = new com.squareup.moshi.Moshi.Builder().build();
com.google.gson.Gson gson = new GsonBuilder().create();
MoshiConverterFactory moshiConverterFactory = MoshiConverterFactory.create(moshi);
GsonConverterFactory gsonConverterFactory = GsonConverterFactory.create(gson);
SimpleXmlConverterFactory simpleXmlConverterFactory = SimpleXmlConverterFactory.create();
Retrofit retrofit =
new Retrofit.Builder()
.baseUrl(server.url("/"))
.addConverterFactory(
new AnnotatedConverterFactory.Builder()
.add(Moshi.class, moshiConverterFactory)
.add(Gson.class, gsonConverterFactory)
.add(SimpleXml.class, simpleXmlConverterFactory)
.build())
.addConverterFactory(gsonConverterFactory)
.build();
Service service = retrofit.create(Service.class);
Library library1 = service.exampleMoshi().execute().body();
System.out.println("Library 1: " + library1.name);
Library library2 = service.exampleGson().execute().body();
System.out.println("Library 2: " + library2.name);
Library library3 = service.exampleSimpleXml().execute().body();
System.out.println("Library 3: " + library3.name);
Library library4 = service.exampleDefault().execute().body();
System.out.println("Library 4: " + library4.name);
server.shutdown();
}
}
| 3,756 |
0 | Create_ds/retrofit/samples/src/main/java/com/example | Create_ds/retrofit/samples/src/main/java/com/example/retrofit/ChunkingConverter.java | /*
* 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 com.example.retrofit;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import java.lang.reflect.Type;
import javax.annotation.Nullable;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import okhttp3.mockwebserver.RecordedRequest;
import okio.BufferedSink;
import retrofit2.Call;
import retrofit2.Converter;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.Body;
import retrofit2.http.POST;
public final class ChunkingConverter {
@Target(PARAMETER)
@Retention(RUNTIME)
@interface Chunked {}
/**
* A converter which removes known content lengths to force chunking when {@code @Chunked} is
* present on {@code @Body} params.
*/
static class ChunkingConverterFactory extends Converter.Factory {
@Override
public @Nullable Converter<Object, RequestBody> requestBodyConverter(
Type type,
Annotation[] parameterAnnotations,
Annotation[] methodAnnotations,
Retrofit retrofit) {
boolean isBody = false;
boolean isChunked = false;
for (Annotation annotation : parameterAnnotations) {
isBody |= annotation instanceof Body;
isChunked |= annotation instanceof Chunked;
}
if (!isBody || !isChunked) {
return null;
}
// Look up the real converter to delegate to.
final Converter<Object, RequestBody> delegate =
retrofit.nextRequestBodyConverter(this, type, parameterAnnotations, methodAnnotations);
// Wrap it in a Converter which removes the content length from the delegate's body.
return value -> {
final RequestBody realBody = delegate.convert(value);
return new RequestBody() {
@Override
public MediaType contentType() {
return realBody.contentType();
}
@Override
public void writeTo(BufferedSink sink) throws IOException {
realBody.writeTo(sink);
}
};
};
}
}
static class Repo {
final String owner;
final String name;
Repo(String owner, String name) {
this.owner = owner;
this.name = name;
}
}
interface Service {
@POST("/")
Call<ResponseBody> sendNormal(@Body Repo repo);
@POST("/")
Call<ResponseBody> sendChunked(@Chunked @Body Repo repo);
}
public static void main(String... args) throws IOException, InterruptedException {
MockWebServer server = new MockWebServer();
server.enqueue(new MockResponse());
server.enqueue(new MockResponse());
server.start();
Retrofit retrofit =
new Retrofit.Builder()
.baseUrl(server.url("/"))
.addConverterFactory(new ChunkingConverterFactory())
.addConverterFactory(GsonConverterFactory.create())
.build();
Service service = retrofit.create(Service.class);
Repo retrofitRepo = new Repo("square", "retrofit");
service.sendNormal(retrofitRepo).execute();
RecordedRequest normalRequest = server.takeRequest();
System.out.println(
"Normal @Body Transfer-Encoding: " + normalRequest.getHeader("Transfer-Encoding"));
service.sendChunked(retrofitRepo).execute();
RecordedRequest chunkedRequest = server.takeRequest();
System.out.println(
"@Chunked @Body Transfer-Encoding: " + chunkedRequest.getHeader("Transfer-Encoding"));
server.shutdown();
}
}
| 3,757 |
0 | Create_ds/retrofit/samples/src/main/java/com/example | Create_ds/retrofit/samples/src/main/java/com/example/retrofit/SimpleService.java | /*
* Copyright (C) 2012 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 com.example.retrofit;
import java.io.IOException;
import java.util.List;
import retrofit2.Call;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.GET;
import retrofit2.http.Path;
public final class SimpleService {
public static final String API_URL = "https://api.github.com";
public static class Contributor {
public final String login;
public final int contributions;
public Contributor(String login, int contributions) {
this.login = login;
this.contributions = contributions;
}
}
public interface GitHub {
@GET("/repos/{owner}/{repo}/contributors")
Call<List<Contributor>> contributors(@Path("owner") String owner, @Path("repo") String repo);
}
public static void main(String... args) throws IOException {
// Create a very simple REST adapter which points the GitHub API.
Retrofit retrofit =
new Retrofit.Builder()
.baseUrl(API_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
// Create an instance of our GitHub API interface.
GitHub github = retrofit.create(GitHub.class);
// Create a call instance for looking up Retrofit contributors.
Call<List<Contributor>> call = github.contributors("square", "retrofit");
// Fetch and print a list of the contributors to the library.
List<Contributor> contributors = call.execute().body();
for (Contributor contributor : contributors) {
System.out.println(contributor.login + " (" + contributor.contributions + ")");
}
}
}
| 3,758 |
0 | Create_ds/retrofit/samples/src/main/java/com/example | Create_ds/retrofit/samples/src/main/java/com/example/retrofit/SimpleMockService.java | // Copyright 2013 Square, Inc.
package com.example.retrofit;
import com.example.retrofit.SimpleService.Contributor;
import com.example.retrofit.SimpleService.GitHub;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import retrofit2.Call;
import retrofit2.Retrofit;
import retrofit2.mock.BehaviorDelegate;
import retrofit2.mock.MockRetrofit;
import retrofit2.mock.NetworkBehavior;
/**
* An example of using {@link MockRetrofit} to create a mock service implementation with fake data.
* This re-uses the GitHub service from {@link SimpleService} for its mocking.
*/
public final class SimpleMockService {
/** A mock implementation of the {@link GitHub} API interface. */
static final class MockGitHub implements GitHub {
private final BehaviorDelegate<GitHub> delegate;
private final Map<String, Map<String, List<Contributor>>> ownerRepoContributors;
MockGitHub(BehaviorDelegate<GitHub> delegate) {
this.delegate = delegate;
ownerRepoContributors = new LinkedHashMap<>();
// Seed some mock data.
addContributor("square", "retrofit", "John Doe", 12);
addContributor("square", "retrofit", "Bob Smith", 2);
addContributor("square", "retrofit", "Big Bird", 40);
addContributor("square", "picasso", "Proposition Joe", 39);
addContributor("square", "picasso", "Keiser Soze", 152);
}
@Override
public Call<List<Contributor>> contributors(String owner, String repo) {
List<Contributor> response = Collections.emptyList();
Map<String, List<Contributor>> repoContributors = ownerRepoContributors.get(owner);
if (repoContributors != null) {
List<Contributor> contributors = repoContributors.get(repo);
if (contributors != null) {
response = contributors;
}
}
return delegate.returningResponse(response).contributors(owner, repo);
}
void addContributor(String owner, String repo, String name, int contributions) {
Map<String, List<Contributor>> repoContributors = ownerRepoContributors.get(owner);
if (repoContributors == null) {
repoContributors = new LinkedHashMap<>();
ownerRepoContributors.put(owner, repoContributors);
}
List<Contributor> contributors = repoContributors.get(repo);
if (contributors == null) {
contributors = new ArrayList<>();
repoContributors.put(repo, contributors);
}
contributors.add(new Contributor(name, contributions));
}
}
public static void main(String... args) throws IOException {
// Create a very simple Retrofit adapter which points the GitHub API.
Retrofit retrofit = new Retrofit.Builder().baseUrl(SimpleService.API_URL).build();
// Create a MockRetrofit object with a NetworkBehavior which manages the fake behavior of calls.
NetworkBehavior behavior = NetworkBehavior.create();
MockRetrofit mockRetrofit =
new MockRetrofit.Builder(retrofit).networkBehavior(behavior).build();
BehaviorDelegate<GitHub> delegate = mockRetrofit.create(GitHub.class);
MockGitHub gitHub = new MockGitHub(delegate);
// Query for some contributors for a few repositories.
printContributors(gitHub, "square", "retrofit");
printContributors(gitHub, "square", "picasso");
// Using the mock-only methods, add some additional data.
System.out.println("Adding more mock data...\n");
gitHub.addContributor("square", "retrofit", "Foo Bar", 61);
gitHub.addContributor("square", "picasso", "Kit Kat", 53);
// Reduce the delay to make the next calls complete faster.
behavior.setDelay(500, TimeUnit.MILLISECONDS);
// Query for the contributors again so we can see the mock data that was added.
printContributors(gitHub, "square", "retrofit");
printContributors(gitHub, "square", "picasso");
}
private static void printContributors(GitHub gitHub, String owner, String repo)
throws IOException {
System.out.println(String.format("== Contributors for %s/%s ==", owner, repo));
Call<List<Contributor>> contributors = gitHub.contributors(owner, repo);
for (Contributor contributor : contributors.execute().body()) {
System.out.println(contributor.login + " (" + contributor.contributions + ")");
}
System.out.println();
}
}
| 3,759 |
0 | Create_ds/retrofit/samples/src/main/java/com/example | Create_ds/retrofit/samples/src/main/java/com/example/retrofit/Crawler.java | /*
* 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 com.example.retrofit;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import javax.annotation.Nullable;
import okhttp3.ConnectionPool;
import okhttp3.Dispatcher;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.ResponseBody;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Converter;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.http.GET;
import retrofit2.http.Url;
/** A simple web crawler that uses a Retrofit service to turn URLs into webpages. */
public final class Crawler {
private final Set<HttpUrl> fetchedUrls =
Collections.synchronizedSet(new LinkedHashSet<HttpUrl>());
private final ConcurrentHashMap<String, AtomicInteger> hostnames = new ConcurrentHashMap<>();
private final PageService pageService;
public Crawler(PageService pageService) {
this.pageService = pageService;
}
public void crawlPage(HttpUrl url) {
// Skip hosts that we've visited many times.
AtomicInteger hostnameCount = new AtomicInteger();
AtomicInteger previous = hostnames.putIfAbsent(url.host(), hostnameCount);
if (previous != null) hostnameCount = previous;
if (hostnameCount.incrementAndGet() > 100) return;
// Asynchronously visit URL.
pageService
.get(url)
.enqueue(
new Callback<Page>() {
@Override
public void onResponse(Call<Page> call, Response<Page> response) {
if (!response.isSuccessful()) {
System.out.println(call.request().url() + ": failed: " + response.code());
return;
}
// Print this page's URL and title.
Page page = response.body();
HttpUrl base = response.raw().request().url();
System.out.println(base + ": " + page.title);
// Enqueue its links for visiting.
for (String link : page.links) {
HttpUrl linkUrl = base.resolve(link);
if (linkUrl != null && fetchedUrls.add(linkUrl)) {
crawlPage(linkUrl);
}
}
}
@Override
public void onFailure(Call<Page> call, Throwable t) {
System.out.println(call.request().url() + ": failed: " + t);
}
});
}
public static void main(String... args) throws Exception {
Dispatcher dispatcher = new Dispatcher(Executors.newFixedThreadPool(20));
dispatcher.setMaxRequests(20);
dispatcher.setMaxRequestsPerHost(1);
OkHttpClient okHttpClient =
new OkHttpClient.Builder()
.dispatcher(dispatcher)
.connectionPool(new ConnectionPool(100, 30, TimeUnit.SECONDS))
.build();
Retrofit retrofit =
new Retrofit.Builder()
.baseUrl(HttpUrl.get("https://example.com/"))
.addConverterFactory(PageAdapter.FACTORY)
.client(okHttpClient)
.build();
PageService pageService = retrofit.create(PageService.class);
Crawler crawler = new Crawler(pageService);
crawler.crawlPage(HttpUrl.get(args[0]));
}
interface PageService {
@GET
Call<Page> get(@Url HttpUrl url);
}
static class Page {
final String title;
final List<String> links;
Page(String title, List<String> links) {
this.title = title;
this.links = links;
}
}
static final class PageAdapter implements Converter<ResponseBody, Page> {
static final Converter.Factory FACTORY =
new Converter.Factory() {
@Override
public @Nullable Converter<ResponseBody, ?> responseBodyConverter(
Type type, Annotation[] annotations, Retrofit retrofit) {
if (type == Page.class) return new PageAdapter();
return null;
}
};
@Override
public Page convert(ResponseBody responseBody) throws IOException {
Document document = Jsoup.parse(responseBody.string());
List<String> links = new ArrayList<>();
for (Element element : document.select("a[href]")) {
links.add(element.attr("href"));
}
return new Page(document.title(), Collections.unmodifiableList(links));
}
}
}
| 3,760 |
0 | Create_ds/retrofit/samples/src/main/java/com/example | Create_ds/retrofit/samples/src/main/java/com/example/retrofit/InvocationMetrics.java | /*
* Copyright (C) 2018 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 com.example.retrofit;
import java.io.IOException;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Invocation;
import retrofit2.Retrofit;
import retrofit2.http.GET;
import retrofit2.http.Url;
/** This example prints HTTP call metrics with the initiating method names and arguments. */
public final class InvocationMetrics {
public interface Browse {
@GET("/robots.txt")
Call<ResponseBody> robots();
@GET("/favicon.ico")
Call<ResponseBody> favicon();
@GET("/")
Call<ResponseBody> home();
@GET
Call<ResponseBody> page(@Url String path);
}
static final class InvocationLogger implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
long startNanos = System.nanoTime();
Response response = chain.proceed(request);
long elapsedNanos = System.nanoTime() - startNanos;
Invocation invocation = request.tag(Invocation.class);
if (invocation != null) {
System.out.printf(
"%s.%s %s HTTP %s (%.0f ms)%n",
invocation.method().getDeclaringClass().getSimpleName(),
invocation.method().getName(),
invocation.arguments(),
response.code(),
elapsedNanos / 1_000_000.0);
}
return response;
}
}
public static void main(String... args) throws IOException {
InvocationLogger invocationLogger = new InvocationLogger();
OkHttpClient okHttpClient = new OkHttpClient.Builder().addInterceptor(invocationLogger).build();
Retrofit retrofit =
new Retrofit.Builder().baseUrl("https://square.com/").callFactory(okHttpClient).build();
Browse browse = retrofit.create(Browse.class);
browse.robots().execute();
browse.favicon().execute();
browse.home().execute();
browse.page("sitemap.xml").execute();
browse.page("notfound").execute();
}
}
| 3,761 |
0 | Create_ds/retrofit/samples/src/main/java/com/example | Create_ds/retrofit/samples/src/main/java/com/example/retrofit/JsonAndXmlConverters.java | /*
* 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 com.example.retrofit;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.annotation.Retention;
import java.lang.reflect.Type;
import javax.annotation.Nullable;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Default;
import org.simpleframework.xml.DefaultType;
import retrofit2.Call;
import retrofit2.Converter;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.simplexml.SimpleXmlConverterFactory;
import retrofit2.http.GET;
/**
* Both the Gson converter and the Simple Framework converter accept all types. Because of this, you
* cannot use both in a single service by default. In order to work around this, we can create
* an @Json and @Xml annotation to declare which serialization format each endpoint should use and
* then write our own Converter.Factory which delegates to either the Gson or Simple Framework
* converter.
*/
public final class JsonAndXmlConverters {
@Retention(RUNTIME)
@interface Json {}
@Retention(RUNTIME)
@interface Xml {}
static class QualifiedTypeConverterFactory extends Converter.Factory {
private final Converter.Factory jsonFactory;
private final Converter.Factory xmlFactory;
QualifiedTypeConverterFactory(Converter.Factory jsonFactory, Converter.Factory xmlFactory) {
this.jsonFactory = jsonFactory;
this.xmlFactory = xmlFactory;
}
@Override
public @Nullable Converter<ResponseBody, ?> responseBodyConverter(
Type type, Annotation[] annotations, Retrofit retrofit) {
for (Annotation annotation : annotations) {
if (annotation instanceof Json) {
return jsonFactory.responseBodyConverter(type, annotations, retrofit);
}
if (annotation instanceof Xml) {
return xmlFactory.responseBodyConverter(type, annotations, retrofit);
}
}
return null;
}
@Override
public @Nullable Converter<?, RequestBody> requestBodyConverter(
Type type,
Annotation[] parameterAnnotations,
Annotation[] methodAnnotations,
Retrofit retrofit) {
for (Annotation annotation : parameterAnnotations) {
if (annotation instanceof Json) {
return jsonFactory.requestBodyConverter(
type, parameterAnnotations, methodAnnotations, retrofit);
}
if (annotation instanceof Xml) {
return xmlFactory.requestBodyConverter(
type, parameterAnnotations, methodAnnotations, retrofit);
}
}
return null;
}
}
@Default(value = DefaultType.FIELD)
static class User {
@Attribute public String name;
}
interface Service {
@GET("/")
@Json
Call<User> exampleJson();
@GET("/")
@Xml
Call<User> exampleXml();
}
public static void main(String... args) throws IOException {
MockWebServer server = new MockWebServer();
server.start();
server.enqueue(new MockResponse().setBody("{\"name\": \"Jason\"}"));
server.enqueue(new MockResponse().setBody("<user name=\"Eximel\"/>"));
Retrofit retrofit =
new Retrofit.Builder()
.baseUrl(server.url("/"))
.addConverterFactory(
new QualifiedTypeConverterFactory(
GsonConverterFactory.create(), SimpleXmlConverterFactory.create()))
.build();
Service service = retrofit.create(Service.class);
User user1 = service.exampleJson().execute().body();
System.out.println("User 1: " + user1.name);
User user2 = service.exampleXml().execute().body();
System.out.println("User 2: " + user2.name);
server.shutdown();
}
}
| 3,762 |
0 | Create_ds/retrofit/samples/src/main/java/com/example | Create_ds/retrofit/samples/src/main/java/com/example/retrofit/package-info.java | @javax.annotation.ParametersAreNonnullByDefault
package com.example.retrofit;
| 3,763 |
0 | Create_ds/retrofit/retrofit-adapters/rxjava3/src/test/java/retrofit2/adapter | Create_ds/retrofit/retrofit-adapters/rxjava3/src/test/java/retrofit2/adapter/rxjava3/ObservableWithSchedulerTest.java | /*
* Copyright (C) 2020 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.rxjava3;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.schedulers.TestScheduler;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.http.GET;
public final class ObservableWithSchedulerTest {
@Rule public final MockWebServer server = new MockWebServer();
@Rule public final RecordingObserver.Rule observerRule = new RecordingObserver.Rule();
interface Service {
@GET("/")
Observable<String> body();
@GET("/")
Observable<Response<String>> response();
@GET("/")
Observable<Result<String>> result();
}
private final TestScheduler scheduler = new TestScheduler();
private Service service;
@Before
public void setUp() {
Retrofit retrofit =
new Retrofit.Builder()
.baseUrl(server.url("/"))
.addConverterFactory(new StringConverterFactory())
.addCallAdapterFactory(RxJava3CallAdapterFactory.createWithScheduler(scheduler))
.build();
service = retrofit.create(Service.class);
}
@Test
public void bodyUsesScheduler() {
server.enqueue(new MockResponse());
RecordingObserver<Object> observer = observerRule.create();
service.body().subscribe(observer);
observer.assertNoEvents();
scheduler.triggerActions();
observer.assertAnyValue().assertComplete();
}
@Test
public void responseUsesScheduler() {
server.enqueue(new MockResponse());
RecordingObserver<Object> observer = observerRule.create();
service.response().subscribe(observer);
observer.assertNoEvents();
scheduler.triggerActions();
observer.assertAnyValue().assertComplete();
}
@Test
public void resultUsesScheduler() {
server.enqueue(new MockResponse());
RecordingObserver<Object> observer = observerRule.create();
service.result().subscribe(observer);
observer.assertNoEvents();
scheduler.triggerActions();
observer.assertAnyValue().assertComplete();
}
}
| 3,764 |
0 | Create_ds/retrofit/retrofit-adapters/rxjava3/src/test/java/retrofit2/adapter | Create_ds/retrofit/retrofit-adapters/rxjava3/src/test/java/retrofit2/adapter/rxjava3/ObservableTest.java | /*
* Copyright (C) 2020 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.rxjava3;
import static okhttp3.mockwebserver.SocketPolicy.DISCONNECT_AFTER_REQUEST;
import static org.assertj.core.api.Assertions.assertThat;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.plugins.RxJavaPlugins;
import java.io.IOException;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.http.GET;
public final class ObservableTest {
@Rule public final MockWebServer server = new MockWebServer();
@Rule public final RecordingObserver.Rule observerRule = new RecordingObserver.Rule();
interface Service {
@GET("/")
Observable<String> body();
@GET("/")
Observable<Response<String>> response();
@GET("/")
Observable<Result<String>> result();
}
private Service service;
@Before
public void setUp() {
Retrofit retrofit =
new Retrofit.Builder()
.baseUrl(server.url("/"))
.addConverterFactory(new StringConverterFactory())
.addCallAdapterFactory(RxJava3CallAdapterFactory.createSynchronous())
.build();
service = retrofit.create(Service.class);
}
@Test
public void bodySuccess200() {
server.enqueue(new MockResponse().setBody("Hi"));
RecordingObserver<String> observer = observerRule.create();
service.body().subscribe(observer);
observer.assertValue("Hi").assertComplete();
}
@Test
public void bodySuccess404() {
server.enqueue(new MockResponse().setResponseCode(404));
RecordingObserver<String> observer = observerRule.create();
service.body().subscribe(observer);
// Required for backwards compatibility.
observer.assertError(HttpException.class, "HTTP 404 Client Error");
}
@Test
public void bodyFailure() {
server.enqueue(new MockResponse().setSocketPolicy(DISCONNECT_AFTER_REQUEST));
RecordingObserver<String> observer = observerRule.create();
service.body().subscribe(observer);
observer.assertError(IOException.class);
}
@Test
public void responseSuccess200() {
server.enqueue(new MockResponse());
RecordingObserver<Response<String>> observer = observerRule.create();
service.response().subscribe(observer);
assertThat(observer.takeValue().isSuccessful()).isTrue();
observer.assertComplete();
}
@Test
public void responseSuccess404() {
server.enqueue(new MockResponse().setResponseCode(404));
RecordingObserver<Response<String>> observer = observerRule.create();
service.response().subscribe(observer);
assertThat(observer.takeValue().isSuccessful()).isFalse();
observer.assertComplete();
}
@Test
public void responseFailure() {
server.enqueue(new MockResponse().setSocketPolicy(DISCONNECT_AFTER_REQUEST));
RecordingObserver<Response<String>> observer = observerRule.create();
service.response().subscribe(observer);
observer.assertError(IOException.class);
}
@Test
public void resultSuccess200() {
server.enqueue(new MockResponse().setBody("Hi"));
RecordingObserver<Result<String>> observer = observerRule.create();
service.result().subscribe(observer);
Result<String> result = observer.takeValue();
assertThat(result.isError()).isFalse();
assertThat(result.response().isSuccessful()).isTrue();
observer.assertComplete();
}
@Test
public void resultSuccess404() {
server.enqueue(new MockResponse().setResponseCode(404));
RecordingObserver<Result<String>> observer = observerRule.create();
service.result().subscribe(observer);
Result<String> result = observer.takeValue();
assertThat(result.isError()).isFalse();
assertThat(result.response().isSuccessful()).isFalse();
observer.assertComplete();
}
@Test
public void resultFailure() {
server.enqueue(new MockResponse().setSocketPolicy(DISCONNECT_AFTER_REQUEST));
RecordingObserver<Result<String>> observer = observerRule.create();
service.result().subscribe(observer);
Result<String> result = observer.takeValue();
assertThat(result.isError()).isTrue();
assertThat(result.error()).isInstanceOf(IOException.class);
observer.assertComplete();
}
@Test
public void observableAssembly() {
try {
final Observable<String> justMe = Observable.just("me");
RxJavaPlugins.setOnObservableAssembly(f -> justMe);
assertThat(service.body()).isEqualTo(justMe);
} finally {
RxJavaPlugins.reset();
}
}
@Test
public void subscribeTwice() {
server.enqueue(new MockResponse().setBody("Hi"));
server.enqueue(new MockResponse().setBody("Hey"));
Observable<String> observable = service.body();
RecordingObserver<String> observer1 = observerRule.create();
observable.subscribe(observer1);
observer1.assertValue("Hi").assertComplete();
RecordingObserver<String> observer2 = observerRule.create();
observable.subscribe(observer2);
observer2.assertValue("Hey").assertComplete();
}
}
| 3,765 |
0 | Create_ds/retrofit/retrofit-adapters/rxjava3/src/test/java/retrofit2/adapter | Create_ds/retrofit/retrofit-adapters/rxjava3/src/test/java/retrofit2/adapter/rxjava3/CancelDisposeTest.java | /*
* Copyright (C) 2020 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.rxjava3;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.disposables.Disposable;
import java.util.List;
import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.mockwebserver.MockWebServer;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import retrofit2.Retrofit;
import retrofit2.http.GET;
public final class CancelDisposeTest {
@Rule public final MockWebServer server = new MockWebServer();
interface Service {
@GET("/")
Observable<String> go();
}
private final OkHttpClient client = new OkHttpClient();
private Service service;
@Before
public void setUp() {
Retrofit retrofit =
new Retrofit.Builder()
.baseUrl(server.url("/"))
.addConverterFactory(new StringConverterFactory())
.addCallAdapterFactory(RxJava3CallAdapterFactory.create())
.callFactory(client)
.build();
service = retrofit.create(Service.class);
}
@Test
public void disposeCancelsCall() {
Disposable disposable = service.go().subscribe();
List<Call> calls = client.dispatcher().runningCalls();
assertEquals(1, calls.size());
disposable.dispose();
assertTrue(calls.get(0).isCanceled());
}
@SuppressWarnings("ResultOfMethodCallIgnored")
@Test
public void disposeBeforeEnqueueDoesNotEnqueue() {
service.go().test(true);
List<Call> calls = client.dispatcher().runningCalls();
assertEquals(0, calls.size());
}
@Test
public void cancelDoesNotDispose() {
Disposable disposable = service.go().subscribe();
List<Call> calls = client.dispatcher().runningCalls();
assertEquals(1, calls.size());
calls.get(0).cancel();
assertFalse(disposable.isDisposed());
}
}
| 3,766 |
0 | Create_ds/retrofit/retrofit-adapters/rxjava3/src/test/java/retrofit2/adapter | Create_ds/retrofit/retrofit-adapters/rxjava3/src/test/java/retrofit2/adapter/rxjava3/RecordingCompletableObserver.java | /*
* Copyright (C) 2020 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.rxjava3;
import static org.assertj.core.api.Assertions.assertThat;
import io.reactivex.rxjava3.core.CompletableObserver;
import io.reactivex.rxjava3.core.Notification;
import io.reactivex.rxjava3.disposables.Disposable;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
/** A test {@link CompletableObserver} and JUnit rule which guarantees all events are asserted. */
final class RecordingCompletableObserver implements CompletableObserver {
private final Deque<Notification<?>> events = new ArrayDeque<>();
private RecordingCompletableObserver() {}
@Override
public void onSubscribe(Disposable disposable) {}
@Override
public void onComplete() {
events.add(Notification.createOnComplete());
}
@Override
public void onError(Throwable e) {
events.add(Notification.createOnError(e));
}
private Notification<?> takeNotification() {
Notification<?> notification = events.pollFirst();
if (notification == null) {
throw new AssertionError("No event found!");
}
return notification;
}
public Throwable takeError() {
Notification<?> notification = takeNotification();
assertThat(notification.isOnError())
.as("Expected onError event but was " + notification)
.isTrue();
return notification.getError();
}
public void assertComplete() {
Notification<?> notification = takeNotification();
assertThat(notification.isOnComplete())
.as("Expected onCompleted event but was " + notification)
.isTrue();
assertNoEvents();
}
public void assertError(Throwable throwable) {
assertThat(takeError()).isEqualTo(throwable);
}
public void assertError(Class<? extends Throwable> errorClass) {
assertError(errorClass, null);
}
public void assertError(Class<? extends Throwable> errorClass, String message) {
Throwable throwable = takeError();
assertThat(throwable).isInstanceOf(errorClass);
if (message != null) {
assertThat(throwable).hasMessage(message);
}
assertNoEvents();
}
public void assertNoEvents() {
assertThat(events).as("Unconsumed events found!").isEmpty();
}
public static final class Rule implements TestRule {
final List<RecordingCompletableObserver> subscribers = new ArrayList<>();
public <T> RecordingCompletableObserver create() {
RecordingCompletableObserver subscriber = new RecordingCompletableObserver();
subscribers.add(subscriber);
return subscriber;
}
@Override
public Statement apply(final Statement base, Description description) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
base.evaluate();
for (RecordingCompletableObserver subscriber : subscribers) {
subscriber.assertNoEvents();
}
}
};
}
}
}
| 3,767 |
0 | Create_ds/retrofit/retrofit-adapters/rxjava3/src/test/java/retrofit2/adapter | Create_ds/retrofit/retrofit-adapters/rxjava3/src/test/java/retrofit2/adapter/rxjava3/StringConverterFactory.java | /*
* Copyright (C) 2020 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.rxjava3;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Converter;
import retrofit2.Retrofit;
final class StringConverterFactory extends Converter.Factory {
@Override
public Converter<ResponseBody, String> responseBodyConverter(
Type type, Annotation[] annotations, Retrofit retrofit) {
return ResponseBody::string;
}
@Override
public Converter<String, RequestBody> requestBodyConverter(
Type type,
Annotation[] parameterAnnotations,
Annotation[] methodAnnotations,
Retrofit retrofit) {
return value -> RequestBody.create(MediaType.get("text/plain"), value);
}
}
| 3,768 |
0 | Create_ds/retrofit/retrofit-adapters/rxjava3/src/test/java/retrofit2/adapter | Create_ds/retrofit/retrofit-adapters/rxjava3/src/test/java/retrofit2/adapter/rxjava3/SingleWithSchedulerTest.java | /*
* Copyright (C) 2020 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.rxjava3;
import io.reactivex.rxjava3.core.Single;
import io.reactivex.rxjava3.schedulers.TestScheduler;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.http.GET;
public final class SingleWithSchedulerTest {
@Rule public final MockWebServer server = new MockWebServer();
@Rule public final RecordingSingleObserver.Rule observerRule = new RecordingSingleObserver.Rule();
interface Service {
@GET("/")
Single<String> body();
@GET("/")
Single<Response<String>> response();
@GET("/")
Single<Result<String>> result();
}
private final TestScheduler scheduler = new TestScheduler();
private Service service;
@Before
public void setUp() {
Retrofit retrofit =
new Retrofit.Builder()
.baseUrl(server.url("/"))
.addConverterFactory(new StringConverterFactory())
.addCallAdapterFactory(RxJava3CallAdapterFactory.createWithScheduler(scheduler))
.build();
service = retrofit.create(Service.class);
}
@Test
public void bodyUsesScheduler() {
server.enqueue(new MockResponse());
RecordingSingleObserver<Object> observer = observerRule.create();
service.body().subscribe(observer);
observer.assertNoEvents();
scheduler.triggerActions();
observer.assertAnyValue();
}
@Test
public void responseUsesScheduler() {
server.enqueue(new MockResponse());
RecordingSingleObserver<Object> observer = observerRule.create();
service.response().subscribe(observer);
observer.assertNoEvents();
scheduler.triggerActions();
observer.assertAnyValue();
}
@Test
public void resultUsesScheduler() {
server.enqueue(new MockResponse());
RecordingSingleObserver<Object> observer = observerRule.create();
service.result().subscribe(observer);
observer.assertNoEvents();
scheduler.triggerActions();
observer.assertAnyValue();
}
}
| 3,769 |
0 | Create_ds/retrofit/retrofit-adapters/rxjava3/src/test/java/retrofit2/adapter | Create_ds/retrofit/retrofit-adapters/rxjava3/src/test/java/retrofit2/adapter/rxjava3/CompletableTest.java | /*
* Copyright (C) 2020 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.rxjava3;
import static okhttp3.mockwebserver.SocketPolicy.DISCONNECT_AFTER_REQUEST;
import io.reactivex.rxjava3.core.Completable;
import java.io.IOException;
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;
public final class CompletableTest {
@Rule public final MockWebServer server = new MockWebServer();
@Rule
public final RecordingCompletableObserver.Rule observerRule =
new RecordingCompletableObserver.Rule();
interface Service {
@GET("/")
Completable completable();
}
private Service service;
@Before
public void setUp() {
Retrofit retrofit =
new Retrofit.Builder()
.baseUrl(server.url("/"))
.addCallAdapterFactory(RxJava3CallAdapterFactory.createSynchronous())
.build();
service = retrofit.create(Service.class);
}
@Test
public void completableSuccess200() {
server.enqueue(new MockResponse().setBody("Hi"));
RecordingCompletableObserver observer = observerRule.create();
service.completable().subscribe(observer);
observer.assertComplete();
}
@Test
public void completableSuccess404() {
server.enqueue(new MockResponse().setResponseCode(404));
RecordingCompletableObserver observer = observerRule.create();
service.completable().subscribe(observer);
// Required for backwards compatibility.
observer.assertError(HttpException.class, "HTTP 404 Client Error");
}
@Test
public void completableFailure() {
server.enqueue(new MockResponse().setSocketPolicy(DISCONNECT_AFTER_REQUEST));
RecordingCompletableObserver observer = observerRule.create();
service.completable().subscribe(observer);
observer.assertError(IOException.class);
}
@Test
public void subscribeTwice() {
server.enqueue(new MockResponse().setBody("Hi"));
server.enqueue(new MockResponse().setBody("Hey"));
Completable observable = service.completable();
RecordingCompletableObserver observer1 = observerRule.create();
observable.subscribe(observer1);
observer1.assertComplete();
RecordingCompletableObserver observer2 = observerRule.create();
observable.subscribe(observer2);
observer2.assertComplete();
}
}
| 3,770 |
0 | Create_ds/retrofit/retrofit-adapters/rxjava3/src/test/java/retrofit2/adapter | Create_ds/retrofit/retrofit-adapters/rxjava3/src/test/java/retrofit2/adapter/rxjava3/MaybeThrowingTest.java | /*
* Copyright (C) 2020 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.rxjava3;
import static okhttp3.mockwebserver.SocketPolicy.DISCONNECT_AFTER_REQUEST;
import static org.assertj.core.api.Assertions.assertThat;
import io.reactivex.rxjava3.core.Maybe;
import io.reactivex.rxjava3.core.MaybeObserver;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.exceptions.CompositeException;
import io.reactivex.rxjava3.exceptions.Exceptions;
import io.reactivex.rxjava3.plugins.RxJavaPlugins;
import java.util.concurrent.atomic.AtomicReference;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestRule;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.http.GET;
public final class MaybeThrowingTest {
@Rule public final MockWebServer server = new MockWebServer();
@Rule public final TestRule resetRule = new RxJavaPluginsResetRule();
@Rule public final RecordingMaybeObserver.Rule subscriberRule = new RecordingMaybeObserver.Rule();
interface Service {
@GET("/")
Maybe<String> body();
@GET("/")
Maybe<Response<String>> response();
@GET("/")
Maybe<Result<String>> result();
}
private Service service;
@Before
public void setUp() {
Retrofit retrofit =
new Retrofit.Builder()
.baseUrl(server.url("/"))
.addConverterFactory(new StringConverterFactory())
.addCallAdapterFactory(RxJava3CallAdapterFactory.createSynchronous())
.build();
service = retrofit.create(Service.class);
}
@Test
public void bodyThrowingInOnSuccessDeliveredToPlugin() {
server.enqueue(new MockResponse());
final AtomicReference<Throwable> throwableRef = new AtomicReference<>();
RxJavaPlugins.setErrorHandler(
throwable -> {
if (!throwableRef.compareAndSet(null, throwable)) {
throw Exceptions.propagate(throwable);
}
});
RecordingMaybeObserver<String> observer = subscriberRule.create();
final RuntimeException e = new RuntimeException();
service
.body()
.subscribe(
new ForwardingObserver<String>(observer) {
@Override
public void onSuccess(String value) {
throw e;
}
});
assertThat(throwableRef.get().getCause()).isSameAs(e);
}
@Test
public void bodyThrowingInOnErrorDeliveredToPlugin() {
server.enqueue(new MockResponse().setResponseCode(404));
final AtomicReference<Throwable> throwableRef = new AtomicReference<>();
RxJavaPlugins.setErrorHandler(
throwable -> {
if (!throwableRef.compareAndSet(null, throwable)) {
throw Exceptions.propagate(throwable);
}
});
RecordingMaybeObserver<String> observer = subscriberRule.create();
final AtomicReference<Throwable> errorRef = new AtomicReference<>();
final RuntimeException e = new RuntimeException();
service
.body()
.subscribe(
new ForwardingObserver<String>(observer) {
@Override
public void onError(Throwable throwable) {
if (!errorRef.compareAndSet(null, throwable)) {
throw Exceptions.propagate(throwable);
}
throw e;
}
});
//noinspection ThrowableResultOfMethodCallIgnored
CompositeException composite = (CompositeException) throwableRef.get();
assertThat(composite.getExceptions()).containsExactly(errorRef.get(), e);
}
@Test
public void responseThrowingInOnSuccessDeliveredToPlugin() {
server.enqueue(new MockResponse());
final AtomicReference<Throwable> throwableRef = new AtomicReference<>();
RxJavaPlugins.setErrorHandler(
throwable -> {
if (!throwableRef.compareAndSet(null, throwable)) {
throw Exceptions.propagate(throwable);
}
});
RecordingMaybeObserver<Response<String>> observer = subscriberRule.create();
final RuntimeException e = new RuntimeException();
service
.response()
.subscribe(
new ForwardingObserver<Response<String>>(observer) {
@Override
public void onSuccess(Response<String> value) {
throw e;
}
});
assertThat(throwableRef.get().getCause()).isSameAs(e);
}
@Test
public void responseThrowingInOnErrorDeliveredToPlugin() {
server.enqueue(new MockResponse().setSocketPolicy(DISCONNECT_AFTER_REQUEST));
final AtomicReference<Throwable> throwableRef = new AtomicReference<>();
RxJavaPlugins.setErrorHandler(
throwable -> {
if (!throwableRef.compareAndSet(null, throwable)) {
throw Exceptions.propagate(throwable);
}
});
RecordingMaybeObserver<Response<String>> observer = subscriberRule.create();
final AtomicReference<Throwable> errorRef = new AtomicReference<>();
final RuntimeException e = new RuntimeException();
service
.response()
.subscribe(
new ForwardingObserver<Response<String>>(observer) {
@Override
public void onError(Throwable throwable) {
if (!errorRef.compareAndSet(null, throwable)) {
throw Exceptions.propagate(throwable);
}
throw e;
}
});
//noinspection ThrowableResultOfMethodCallIgnored
CompositeException composite = (CompositeException) throwableRef.get();
assertThat(composite.getExceptions()).containsExactly(errorRef.get(), e);
}
@Test
public void resultThrowingInOnSuccessDeliveredToPlugin() {
server.enqueue(new MockResponse());
final AtomicReference<Throwable> throwableRef = new AtomicReference<>();
RxJavaPlugins.setErrorHandler(
throwable -> {
if (!throwableRef.compareAndSet(null, throwable)) {
throw Exceptions.propagate(throwable);
}
});
RecordingMaybeObserver<Result<String>> observer = subscriberRule.create();
final RuntimeException e = new RuntimeException();
service
.result()
.subscribe(
new ForwardingObserver<Result<String>>(observer) {
@Override
public void onSuccess(Result<String> value) {
throw e;
}
});
assertThat(throwableRef.get().getCause()).isSameAs(e);
}
@Ignore("Single's contract is onNext|onError so we have no way of triggering this case")
@Test
public void resultThrowingInOnErrorDeliveredToPlugin() {
server.enqueue(new MockResponse());
final AtomicReference<Throwable> throwableRef = new AtomicReference<>();
RxJavaPlugins.setErrorHandler(
throwable -> {
if (!throwableRef.compareAndSet(null, throwable)) {
throw Exceptions.propagate(throwable);
}
});
RecordingMaybeObserver<Result<String>> observer = subscriberRule.create();
final RuntimeException first = new RuntimeException();
final RuntimeException second = new RuntimeException();
service
.result()
.subscribe(
new ForwardingObserver<Result<String>>(observer) {
@Override
public void onSuccess(Result<String> value) {
// The only way to trigger onError for Result is if onSuccess throws.
throw first;
}
@Override
public void onError(Throwable throwable) {
throw second;
}
});
//noinspection ThrowableResultOfMethodCallIgnored
CompositeException composite = (CompositeException) throwableRef.get();
assertThat(composite.getExceptions()).containsExactly(first, second);
}
private abstract static class ForwardingObserver<T> implements MaybeObserver<T> {
private final MaybeObserver<T> delegate;
ForwardingObserver(MaybeObserver<T> delegate) {
this.delegate = delegate;
}
@Override
public void onSubscribe(Disposable disposable) {
delegate.onSubscribe(disposable);
}
@Override
public void onSuccess(T value) {
delegate.onSuccess(value);
}
@Override
public void onError(Throwable throwable) {
delegate.onError(throwable);
}
@Override
public void onComplete() {
delegate.onComplete();
}
}
}
| 3,771 |
0 | Create_ds/retrofit/retrofit-adapters/rxjava3/src/test/java/retrofit2/adapter | Create_ds/retrofit/retrofit-adapters/rxjava3/src/test/java/retrofit2/adapter/rxjava3/RxJava3CallAdapterFactoryTest.java | /*
* Copyright (C) 2020 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.rxjava3;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;
import com.google.common.reflect.TypeToken;
import io.reactivex.rxjava3.core.Flowable;
import io.reactivex.rxjava3.core.Maybe;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.core.Single;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import retrofit2.CallAdapter;
import retrofit2.Response;
import retrofit2.Retrofit;
public class RxJava3CallAdapterFactoryTest {
private static final Annotation[] NO_ANNOTATIONS = new Annotation[0];
private final CallAdapter.Factory factory = RxJava3CallAdapterFactory.createSynchronous();
private Retrofit retrofit;
@Before
public void setUp() {
retrofit =
new Retrofit.Builder()
.baseUrl("http://localhost:1")
.addConverterFactory(new StringConverterFactory())
.addCallAdapterFactory(factory)
.build();
}
@Test
public void nullSchedulerThrows() {
try {
RxJava3CallAdapterFactory.createWithScheduler(null);
fail();
} catch (NullPointerException e) {
assertThat(e).hasMessage("scheduler == null");
}
}
@Test
public void nonRxJavaTypeReturnsNull() {
CallAdapter<?, ?> adapter = factory.get(String.class, NO_ANNOTATIONS, retrofit);
assertThat(adapter).isNull();
}
@Test
public void responseTypes() {
Type oBodyClass = new TypeToken<Observable<String>>() {}.getType();
assertThat(factory.get(oBodyClass, NO_ANNOTATIONS, retrofit).responseType())
.isEqualTo(String.class);
Type sBodyClass = new TypeToken<Single<String>>() {}.getType();
assertThat(factory.get(sBodyClass, NO_ANNOTATIONS, retrofit).responseType())
.isEqualTo(String.class);
Type mBodyClass = new TypeToken<Maybe<String>>() {}.getType();
assertThat(factory.get(mBodyClass, NO_ANNOTATIONS, retrofit).responseType())
.isEqualTo(String.class);
Type fBodyClass = new TypeToken<Flowable<String>>() {}.getType();
assertThat(factory.get(fBodyClass, NO_ANNOTATIONS, retrofit).responseType())
.isEqualTo(String.class);
Type oBodyWildcard = new TypeToken<Observable<? extends String>>() {}.getType();
assertThat(factory.get(oBodyWildcard, NO_ANNOTATIONS, retrofit).responseType())
.isEqualTo(String.class);
Type sBodyWildcard = new TypeToken<Single<? extends String>>() {}.getType();
assertThat(factory.get(sBodyWildcard, NO_ANNOTATIONS, retrofit).responseType())
.isEqualTo(String.class);
Type mBodyWildcard = new TypeToken<Maybe<? extends String>>() {}.getType();
assertThat(factory.get(mBodyWildcard, NO_ANNOTATIONS, retrofit).responseType())
.isEqualTo(String.class);
Type fBodyWildcard = new TypeToken<Flowable<? extends String>>() {}.getType();
assertThat(factory.get(fBodyWildcard, NO_ANNOTATIONS, retrofit).responseType())
.isEqualTo(String.class);
Type oBodyGeneric = new TypeToken<Observable<List<String>>>() {}.getType();
assertThat(factory.get(oBodyGeneric, NO_ANNOTATIONS, retrofit).responseType())
.isEqualTo(new TypeToken<List<String>>() {}.getType());
Type sBodyGeneric = new TypeToken<Single<List<String>>>() {}.getType();
assertThat(factory.get(sBodyGeneric, NO_ANNOTATIONS, retrofit).responseType())
.isEqualTo(new TypeToken<List<String>>() {}.getType());
Type mBodyGeneric = new TypeToken<Maybe<List<String>>>() {}.getType();
assertThat(factory.get(mBodyGeneric, NO_ANNOTATIONS, retrofit).responseType())
.isEqualTo(new TypeToken<List<String>>() {}.getType());
Type fBodyGeneric = new TypeToken<Flowable<List<String>>>() {}.getType();
assertThat(factory.get(fBodyGeneric, NO_ANNOTATIONS, retrofit).responseType())
.isEqualTo(new TypeToken<List<String>>() {}.getType());
Type oResponseClass = new TypeToken<Observable<Response<String>>>() {}.getType();
assertThat(factory.get(oResponseClass, NO_ANNOTATIONS, retrofit).responseType())
.isEqualTo(String.class);
Type sResponseClass = new TypeToken<Single<Response<String>>>() {}.getType();
assertThat(factory.get(sResponseClass, NO_ANNOTATIONS, retrofit).responseType())
.isEqualTo(String.class);
Type mResponseClass = new TypeToken<Maybe<Response<String>>>() {}.getType();
assertThat(factory.get(mResponseClass, NO_ANNOTATIONS, retrofit).responseType())
.isEqualTo(String.class);
Type fResponseClass = new TypeToken<Flowable<Response<String>>>() {}.getType();
assertThat(factory.get(fResponseClass, NO_ANNOTATIONS, retrofit).responseType())
.isEqualTo(String.class);
Type oResponseWildcard = new TypeToken<Observable<Response<? extends String>>>() {}.getType();
assertThat(factory.get(oResponseWildcard, NO_ANNOTATIONS, retrofit).responseType())
.isEqualTo(String.class);
Type sResponseWildcard = new TypeToken<Single<Response<? extends String>>>() {}.getType();
assertThat(factory.get(sResponseWildcard, NO_ANNOTATIONS, retrofit).responseType())
.isEqualTo(String.class);
Type mResponseWildcard = new TypeToken<Maybe<Response<? extends String>>>() {}.getType();
assertThat(factory.get(mResponseWildcard, NO_ANNOTATIONS, retrofit).responseType())
.isEqualTo(String.class);
Type fResponseWildcard = new TypeToken<Flowable<Response<? extends String>>>() {}.getType();
assertThat(factory.get(fResponseWildcard, NO_ANNOTATIONS, retrofit).responseType())
.isEqualTo(String.class);
Type oResultClass = new TypeToken<Observable<Result<String>>>() {}.getType();
assertThat(factory.get(oResultClass, NO_ANNOTATIONS, retrofit).responseType())
.isEqualTo(String.class);
Type sResultClass = new TypeToken<Single<Result<String>>>() {}.getType();
assertThat(factory.get(sResultClass, NO_ANNOTATIONS, retrofit).responseType())
.isEqualTo(String.class);
Type mResultClass = new TypeToken<Maybe<Result<String>>>() {}.getType();
assertThat(factory.get(mResultClass, NO_ANNOTATIONS, retrofit).responseType())
.isEqualTo(String.class);
Type fResultClass = new TypeToken<Flowable<Result<String>>>() {}.getType();
assertThat(factory.get(fResultClass, NO_ANNOTATIONS, retrofit).responseType())
.isEqualTo(String.class);
Type oResultWildcard = new TypeToken<Observable<Result<? extends String>>>() {}.getType();
assertThat(factory.get(oResultWildcard, NO_ANNOTATIONS, retrofit).responseType())
.isEqualTo(String.class);
Type sResultWildcard = new TypeToken<Single<Result<? extends String>>>() {}.getType();
assertThat(factory.get(sResultWildcard, NO_ANNOTATIONS, retrofit).responseType())
.isEqualTo(String.class);
Type mResultWildcard = new TypeToken<Maybe<Result<? extends String>>>() {}.getType();
assertThat(factory.get(mResultWildcard, NO_ANNOTATIONS, retrofit).responseType())
.isEqualTo(String.class);
Type fResultWildcard = new TypeToken<Flowable<Result<? extends String>>>() {}.getType();
assertThat(factory.get(fResultWildcard, NO_ANNOTATIONS, retrofit).responseType())
.isEqualTo(String.class);
}
@Test
public void rawBodyTypeThrows() {
Type observableType = new TypeToken<Observable>() {}.getType();
try {
factory.get(observableType, NO_ANNOTATIONS, retrofit);
fail();
} catch (IllegalStateException e) {
assertThat(e)
.hasMessage(
"Observable return type must be parameterized as Observable<Foo> or Observable<? extends Foo>");
}
Type singleType = new TypeToken<Single>() {}.getType();
try {
factory.get(singleType, NO_ANNOTATIONS, retrofit);
fail();
} catch (IllegalStateException e) {
assertThat(e)
.hasMessage(
"Single return type must be parameterized as Single<Foo> or Single<? extends Foo>");
}
Type maybeType = new TypeToken<Maybe>() {}.getType();
try {
factory.get(maybeType, NO_ANNOTATIONS, retrofit);
fail();
} catch (IllegalStateException e) {
assertThat(e)
.hasMessage(
"Maybe return type must be parameterized as Maybe<Foo> or Maybe<? extends Foo>");
}
Type flowableType = new TypeToken<Flowable>() {}.getType();
try {
factory.get(flowableType, NO_ANNOTATIONS, retrofit);
fail();
} catch (IllegalStateException e) {
assertThat(e)
.hasMessage(
"Flowable return type must be parameterized as Flowable<Foo> or Flowable<? extends Foo>");
}
}
@Test
public void rawResponseTypeThrows() {
Type observableType = new TypeToken<Observable<Response>>() {}.getType();
try {
factory.get(observableType, NO_ANNOTATIONS, retrofit);
fail();
} catch (IllegalStateException e) {
assertThat(e)
.hasMessage("Response must be parameterized as Response<Foo> or Response<? extends Foo>");
}
Type singleType = new TypeToken<Single<Response>>() {}.getType();
try {
factory.get(singleType, NO_ANNOTATIONS, retrofit);
fail();
} catch (IllegalStateException e) {
assertThat(e)
.hasMessage("Response must be parameterized as Response<Foo> or Response<? extends Foo>");
}
Type maybeType = new TypeToken<Maybe<Response>>() {}.getType();
try {
factory.get(maybeType, NO_ANNOTATIONS, retrofit);
fail();
} catch (IllegalStateException e) {
assertThat(e)
.hasMessage("Response must be parameterized as Response<Foo> or Response<? extends Foo>");
}
Type flowableType = new TypeToken<Flowable<Response>>() {}.getType();
try {
factory.get(flowableType, NO_ANNOTATIONS, retrofit);
fail();
} catch (IllegalStateException e) {
assertThat(e)
.hasMessage("Response must be parameterized as Response<Foo> or Response<? extends Foo>");
}
}
@Test
public void rawResultTypeThrows() {
Type observableType = new TypeToken<Observable<Result>>() {}.getType();
try {
factory.get(observableType, NO_ANNOTATIONS, retrofit);
fail();
} catch (IllegalStateException e) {
assertThat(e)
.hasMessage("Result must be parameterized as Result<Foo> or Result<? extends Foo>");
}
Type singleType = new TypeToken<Single<Result>>() {}.getType();
try {
factory.get(singleType, NO_ANNOTATIONS, retrofit);
fail();
} catch (IllegalStateException e) {
assertThat(e)
.hasMessage("Result must be parameterized as Result<Foo> or Result<? extends Foo>");
}
Type maybeType = new TypeToken<Maybe<Result>>() {}.getType();
try {
factory.get(maybeType, NO_ANNOTATIONS, retrofit);
fail();
} catch (IllegalStateException e) {
assertThat(e)
.hasMessage("Result must be parameterized as Result<Foo> or Result<? extends Foo>");
}
Type flowableType = new TypeToken<Flowable<Result>>() {}.getType();
try {
factory.get(flowableType, NO_ANNOTATIONS, retrofit);
fail();
} catch (IllegalStateException e) {
assertThat(e)
.hasMessage("Result must be parameterized as Result<Foo> or Result<? extends Foo>");
}
}
}
| 3,772 |
0 | Create_ds/retrofit/retrofit-adapters/rxjava3/src/test/java/retrofit2/adapter | Create_ds/retrofit/retrofit-adapters/rxjava3/src/test/java/retrofit2/adapter/rxjava3/CancelDisposeTestSync.java | /*
* Copyright (C) 2020 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.rxjava3;
import static org.junit.Assert.assertEquals;
import io.reactivex.rxjava3.core.Observable;
import okhttp3.OkHttpClient;
import okhttp3.mockwebserver.MockWebServer;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import retrofit2.Retrofit;
import retrofit2.http.GET;
public final class CancelDisposeTestSync {
@Rule public final MockWebServer server = new MockWebServer();
interface Service {
@GET("/")
Observable<String> go();
}
private final OkHttpClient client = new OkHttpClient();
private Service service;
@Before
public void setUp() {
Retrofit retrofit =
new Retrofit.Builder()
.baseUrl(server.url("/"))
.addConverterFactory(new StringConverterFactory())
.addCallAdapterFactory(RxJava3CallAdapterFactory.createSynchronous())
.callFactory(client)
.build();
service = retrofit.create(Service.class);
}
@SuppressWarnings("ResultOfMethodCallIgnored")
@Test
public void disposeBeforeExecuteDoesNotEnqueue() {
service.go().test(true);
assertEquals(0, server.getRequestCount());
}
}
| 3,773 |
0 | Create_ds/retrofit/retrofit-adapters/rxjava3/src/test/java/retrofit2/adapter | Create_ds/retrofit/retrofit-adapters/rxjava3/src/test/java/retrofit2/adapter/rxjava3/MaybeWithSchedulerTest.java | /*
* Copyright (C) 2020 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.rxjava3;
import io.reactivex.rxjava3.core.Maybe;
import io.reactivex.rxjava3.schedulers.TestScheduler;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.http.GET;
public final class MaybeWithSchedulerTest {
@Rule public final MockWebServer server = new MockWebServer();
@Rule public final RecordingMaybeObserver.Rule observerRule = new RecordingMaybeObserver.Rule();
interface Service {
@GET("/")
Maybe<String> body();
@GET("/")
Maybe<Response<String>> response();
@GET("/")
Maybe<Result<String>> result();
}
private final TestScheduler scheduler = new TestScheduler();
private Service service;
@Before
public void setUp() {
Retrofit retrofit =
new Retrofit.Builder()
.baseUrl(server.url("/"))
.addConverterFactory(new StringConverterFactory())
.addCallAdapterFactory(RxJava3CallAdapterFactory.createWithScheduler(scheduler))
.build();
service = retrofit.create(Service.class);
}
@Test
public void bodyUsesScheduler() {
server.enqueue(new MockResponse());
RecordingMaybeObserver<Object> observer = observerRule.create();
service.body().subscribe(observer);
observer.assertNoEvents();
scheduler.triggerActions();
observer.assertAnyValue();
}
@Test
public void responseUsesScheduler() {
server.enqueue(new MockResponse());
RecordingMaybeObserver<Object> observer = observerRule.create();
service.response().subscribe(observer);
observer.assertNoEvents();
scheduler.triggerActions();
observer.assertAnyValue();
}
@Test
public void resultUsesScheduler() {
server.enqueue(new MockResponse());
RecordingMaybeObserver<Object> observer = observerRule.create();
service.result().subscribe(observer);
observer.assertNoEvents();
scheduler.triggerActions();
observer.assertAnyValue();
}
}
| 3,774 |
0 | Create_ds/retrofit/retrofit-adapters/rxjava3/src/test/java/retrofit2/adapter | Create_ds/retrofit/retrofit-adapters/rxjava3/src/test/java/retrofit2/adapter/rxjava3/AsyncTest.java | /*
* Copyright (C) 2020 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.rxjava3;
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.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import io.reactivex.rxjava3.core.Completable;
import io.reactivex.rxjava3.exceptions.CompositeException;
import io.reactivex.rxjava3.exceptions.Exceptions;
import io.reactivex.rxjava3.observers.TestObserver;
import io.reactivex.rxjava3.plugins.RxJavaPlugins;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicReference;
import okhttp3.Dispatcher;
import okhttp3.OkHttpClient;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava3.CompletableThrowingTest.ForwardingCompletableObserver;
import retrofit2.http.GET;
public final class AsyncTest {
@Rule public final MockWebServer server = new MockWebServer();
interface Service {
@GET("/")
Completable completable();
}
private Service service;
private final List<Throwable> uncaughtExceptions = new ArrayList<>();
@Before
public void setUp() {
ExecutorService executorService =
Executors.newCachedThreadPool(
r -> {
Thread thread = new Thread(r);
thread.setUncaughtExceptionHandler((t, e) -> uncaughtExceptions.add(e));
return thread;
});
OkHttpClient client =
new OkHttpClient.Builder().dispatcher(new Dispatcher(executorService)).build();
Retrofit retrofit =
new Retrofit.Builder()
.baseUrl(server.url("/"))
.client(client)
.addCallAdapterFactory(RxJava3CallAdapterFactory.create())
.build();
service = retrofit.create(Service.class);
}
@After
public void tearDown() {
assertTrue("Uncaught exceptions: " + uncaughtExceptions, uncaughtExceptions.isEmpty());
}
@Test
public void success() throws InterruptedException {
TestObserver<Void> observer = new TestObserver<>();
service.completable().subscribe(observer);
assertFalse(observer.await(1, SECONDS));
server.enqueue(new MockResponse());
observer.await(1, SECONDS);
observer.assertComplete();
}
@Test
public void failure() throws InterruptedException {
TestObserver<Void> observer = new TestObserver<>();
service.completable().subscribe(observer);
assertFalse(observer.await(1, SECONDS));
server.enqueue(new MockResponse().setSocketPolicy(DISCONNECT_AFTER_REQUEST));
observer.await(1, SECONDS);
observer.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.setErrorHandler(
throwable -> {
if (!errorRef.compareAndSet(null, throwable)) {
throw Exceptions.propagate(throwable); // Don't swallow secondary errors!
}
latch.countDown();
});
TestObserver<Void> observer = new TestObserver<>();
final RuntimeException e = new RuntimeException();
service
.completable()
.subscribe(
new ForwardingCompletableObserver(observer) {
@Override
public void onComplete() {
throw e;
}
});
latch.await(1, SECONDS);
assertThat(errorRef.get().getCause()).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.setErrorHandler(
throwable -> {
if (!pluginRef.compareAndSet(null, throwable)) {
throw Exceptions.propagate(throwable); // Don't swallow secondary errors!
}
latch.countDown();
});
TestObserver<Void> observer = new TestObserver<>();
final RuntimeException e = new RuntimeException();
final AtomicReference<Throwable> errorRef = new AtomicReference<>();
service
.completable()
.subscribe(
new ForwardingCompletableObserver(observer) {
@Override
public void onError(Throwable throwable) {
errorRef.set(throwable);
throw e;
}
});
latch.await(1, SECONDS);
//noinspection ThrowableResultOfMethodCallIgnored
CompositeException composite = (CompositeException) pluginRef.get();
assertThat(composite.getExceptions()).containsExactly(errorRef.get(), e);
}
@Test
public void bodyThrowingFatalInOnErrorPropagates() throws InterruptedException {
server.enqueue(new MockResponse().setResponseCode(404));
final CountDownLatch latch = new CountDownLatch(1);
TestObserver<Void> observer = new TestObserver<>();
final Error e = new OutOfMemoryError("Not real");
service
.completable()
.subscribe(
new ForwardingCompletableObserver(observer) {
@Override
public void onError(Throwable throwable) {
throw e;
}
});
latch.await(1, SECONDS);
assertEquals(1, uncaughtExceptions.size());
assertSame(e, uncaughtExceptions.remove(0));
}
}
| 3,775 |
0 | Create_ds/retrofit/retrofit-adapters/rxjava3/src/test/java/retrofit2/adapter | Create_ds/retrofit/retrofit-adapters/rxjava3/src/test/java/retrofit2/adapter/rxjava3/SingleThrowingTest.java | /*
* Copyright (C) 2020 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.rxjava3;
import static okhttp3.mockwebserver.SocketPolicy.DISCONNECT_AFTER_REQUEST;
import static org.assertj.core.api.Assertions.assertThat;
import io.reactivex.rxjava3.core.Single;
import io.reactivex.rxjava3.core.SingleObserver;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.exceptions.CompositeException;
import io.reactivex.rxjava3.exceptions.Exceptions;
import io.reactivex.rxjava3.plugins.RxJavaPlugins;
import java.util.concurrent.atomic.AtomicReference;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestRule;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.http.GET;
public final class SingleThrowingTest {
@Rule public final MockWebServer server = new MockWebServer();
@Rule public final TestRule resetRule = new RxJavaPluginsResetRule();
@Rule
public final RecordingSingleObserver.Rule subscriberRule = new RecordingSingleObserver.Rule();
interface Service {
@GET("/")
Single<String> body();
@GET("/")
Single<Response<String>> response();
@GET("/")
Single<Result<String>> result();
}
private Service service;
@Before
public void setUp() {
Retrofit retrofit =
new Retrofit.Builder()
.baseUrl(server.url("/"))
.addConverterFactory(new StringConverterFactory())
.addCallAdapterFactory(RxJava3CallAdapterFactory.createSynchronous())
.build();
service = retrofit.create(Service.class);
}
@Test
public void bodyThrowingInOnSuccessDeliveredToPlugin() {
server.enqueue(new MockResponse());
final AtomicReference<Throwable> throwableRef = new AtomicReference<>();
RxJavaPlugins.setErrorHandler(
throwable -> {
if (!throwableRef.compareAndSet(null, throwable)) {
throw Exceptions.propagate(throwable);
}
});
RecordingSingleObserver<String> observer = subscriberRule.create();
final RuntimeException e = new RuntimeException();
service
.body()
.subscribe(
new ForwardingObserver<String>(observer) {
@Override
public void onSuccess(String value) {
throw e;
}
});
assertThat(throwableRef.get().getCause()).isSameAs(e);
}
@Test
public void bodyThrowingInOnErrorDeliveredToPlugin() {
server.enqueue(new MockResponse().setResponseCode(404));
final AtomicReference<Throwable> throwableRef = new AtomicReference<>();
RxJavaPlugins.setErrorHandler(
throwable -> {
if (!throwableRef.compareAndSet(null, throwable)) {
throw Exceptions.propagate(throwable);
}
});
RecordingSingleObserver<String> observer = subscriberRule.create();
final AtomicReference<Throwable> errorRef = new AtomicReference<>();
final RuntimeException e = new RuntimeException();
service
.body()
.subscribe(
new ForwardingObserver<String>(observer) {
@Override
public void onError(Throwable throwable) {
if (!errorRef.compareAndSet(null, throwable)) {
throw Exceptions.propagate(throwable);
}
throw e;
}
});
//noinspection ThrowableResultOfMethodCallIgnored
CompositeException composite = (CompositeException) throwableRef.get();
assertThat(composite.getExceptions()).containsExactly(errorRef.get(), e);
}
@Test
public void responseThrowingInOnSuccessDeliveredToPlugin() {
server.enqueue(new MockResponse());
final AtomicReference<Throwable> throwableRef = new AtomicReference<>();
RxJavaPlugins.setErrorHandler(
throwable -> {
if (!throwableRef.compareAndSet(null, throwable)) {
throw Exceptions.propagate(throwable);
}
});
RecordingSingleObserver<Response<String>> observer = subscriberRule.create();
final RuntimeException e = new RuntimeException();
service
.response()
.subscribe(
new ForwardingObserver<Response<String>>(observer) {
@Override
public void onSuccess(Response<String> value) {
throw e;
}
});
assertThat(throwableRef.get().getCause()).isSameAs(e);
}
@Test
public void responseThrowingInOnErrorDeliveredToPlugin() {
server.enqueue(new MockResponse().setSocketPolicy(DISCONNECT_AFTER_REQUEST));
final AtomicReference<Throwable> throwableRef = new AtomicReference<>();
RxJavaPlugins.setErrorHandler(
throwable -> {
if (!throwableRef.compareAndSet(null, throwable)) {
throw Exceptions.propagate(throwable);
}
});
RecordingSingleObserver<Response<String>> observer = subscriberRule.create();
final AtomicReference<Throwable> errorRef = new AtomicReference<>();
final RuntimeException e = new RuntimeException();
service
.response()
.subscribe(
new ForwardingObserver<Response<String>>(observer) {
@Override
public void onError(Throwable throwable) {
if (!errorRef.compareAndSet(null, throwable)) {
throw Exceptions.propagate(throwable);
}
throw e;
}
});
//noinspection ThrowableResultOfMethodCallIgnored
CompositeException composite = (CompositeException) throwableRef.get();
assertThat(composite.getExceptions()).containsExactly(errorRef.get(), e);
}
@Test
public void resultThrowingInOnSuccessDeliveredToPlugin() {
server.enqueue(new MockResponse());
final AtomicReference<Throwable> throwableRef = new AtomicReference<>();
RxJavaPlugins.setErrorHandler(
throwable -> {
if (!throwableRef.compareAndSet(null, throwable)) {
throw Exceptions.propagate(throwable);
}
});
RecordingSingleObserver<Result<String>> observer = subscriberRule.create();
final RuntimeException e = new RuntimeException();
service
.result()
.subscribe(
new ForwardingObserver<Result<String>>(observer) {
@Override
public void onSuccess(Result<String> value) {
throw e;
}
});
assertThat(throwableRef.get().getCause()).isSameAs(e);
}
@Ignore("Single's contract is onNext|onError so we have no way of triggering this case")
@Test
public void resultThrowingInOnErrorDeliveredToPlugin() {
server.enqueue(new MockResponse());
final AtomicReference<Throwable> throwableRef = new AtomicReference<>();
RxJavaPlugins.setErrorHandler(
throwable -> {
if (!throwableRef.compareAndSet(null, throwable)) {
throw Exceptions.propagate(throwable);
}
});
RecordingSingleObserver<Result<String>> observer = subscriberRule.create();
final RuntimeException first = new RuntimeException();
final RuntimeException second = new RuntimeException();
service
.result()
.subscribe(
new ForwardingObserver<Result<String>>(observer) {
@Override
public void onSuccess(Result<String> value) {
// The only way to trigger onError for Result is if onSuccess throws.
throw first;
}
@Override
public void onError(Throwable throwable) {
throw second;
}
});
//noinspection ThrowableResultOfMethodCallIgnored
CompositeException composite = (CompositeException) throwableRef.get();
assertThat(composite.getExceptions()).containsExactly(first, second);
}
private abstract static class ForwardingObserver<T> implements SingleObserver<T> {
private final SingleObserver<T> delegate;
ForwardingObserver(SingleObserver<T> delegate) {
this.delegate = delegate;
}
@Override
public void onSubscribe(Disposable disposable) {
delegate.onSubscribe(disposable);
}
@Override
public void onSuccess(T value) {
delegate.onSuccess(value);
}
@Override
public void onError(Throwable throwable) {
delegate.onError(throwable);
}
}
}
| 3,776 |
0 | Create_ds/retrofit/retrofit-adapters/rxjava3/src/test/java/retrofit2/adapter | Create_ds/retrofit/retrofit-adapters/rxjava3/src/test/java/retrofit2/adapter/rxjava3/FlowableThrowingTest.java | /*
* Copyright (C) 2020 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.rxjava3;
import static okhttp3.mockwebserver.SocketPolicy.DISCONNECT_AFTER_REQUEST;
import static org.assertj.core.api.Assertions.assertThat;
import io.reactivex.rxjava3.core.Flowable;
import io.reactivex.rxjava3.exceptions.CompositeException;
import io.reactivex.rxjava3.exceptions.Exceptions;
import io.reactivex.rxjava3.plugins.RxJavaPlugins;
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 org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.http.GET;
public final class FlowableThrowingTest {
@Rule public final MockWebServer server = new MockWebServer();
@Rule public final TestRule resetRule = new RxJavaPluginsResetRule();
@Rule public final RecordingSubscriber.Rule subscriberRule = new RecordingSubscriber.Rule();
interface Service {
@GET("/")
Flowable<String> body();
@GET("/")
Flowable<Response<String>> response();
@GET("/")
Flowable<Result<String>> result();
}
private Service service;
@Before
public void setUp() {
Retrofit retrofit =
new Retrofit.Builder()
.baseUrl(server.url("/"))
.addConverterFactory(new StringConverterFactory())
.addCallAdapterFactory(RxJava3CallAdapterFactory.createSynchronous())
.build();
service = retrofit.create(Service.class);
}
@Test
public void bodyThrowingInOnNextDeliveredToError() {
server.enqueue(new MockResponse());
RecordingSubscriber<String> subscriber = subscriberRule.create();
final RuntimeException e = new RuntimeException();
service
.body()
.safeSubscribe(
new ForwardingSubscriber<String>(subscriber) {
@Override
public void onNext(String value) {
throw e;
}
});
subscriber.assertError(e);
}
@Test
public void bodyThrowingInOnCompleteDeliveredToPlugin() {
server.enqueue(new MockResponse());
final AtomicReference<Throwable> throwableRef = new AtomicReference<>();
RxJavaPlugins.setErrorHandler(
throwable -> {
if (!throwableRef.compareAndSet(null, throwable)) {
throw Exceptions.propagate(throwable);
}
});
RecordingSubscriber<String> subscriber = subscriberRule.create();
final RuntimeException e = new RuntimeException();
service
.body()
.subscribe(
new ForwardingSubscriber<String>(subscriber) {
@Override
public void onComplete() {
throw e;
}
});
subscriber.assertAnyValue();
assertThat(throwableRef.get().getCause()).isSameAs(e);
}
@Test
public void bodyThrowingInOnErrorDeliveredToPlugin() {
server.enqueue(new MockResponse().setResponseCode(404));
final AtomicReference<Throwable> throwableRef = new AtomicReference<>();
RxJavaPlugins.setErrorHandler(
throwable -> {
if (!throwableRef.compareAndSet(null, throwable)) {
throw Exceptions.propagate(throwable);
}
});
RecordingSubscriber<String> subscriber = subscriberRule.create();
final AtomicReference<Throwable> errorRef = new AtomicReference<>();
final RuntimeException e = new RuntimeException();
service
.body()
.subscribe(
new ForwardingSubscriber<String>(subscriber) {
@Override
public void onError(Throwable throwable) {
if (!errorRef.compareAndSet(null, throwable)) {
throw Exceptions.propagate(throwable);
}
throw e;
}
});
//noinspection ThrowableResultOfMethodCallIgnored
CompositeException composite = (CompositeException) throwableRef.get();
assertThat(composite.getExceptions()).containsExactly(errorRef.get(), e);
}
@Test
public void responseThrowingInOnNextDeliveredToError() {
server.enqueue(new MockResponse());
RecordingSubscriber<Response<String>> subscriber = subscriberRule.create();
final RuntimeException e = new RuntimeException();
service
.response()
.safeSubscribe(
new ForwardingSubscriber<Response<String>>(subscriber) {
@Override
public void onNext(Response<String> value) {
throw e;
}
});
subscriber.assertError(e);
}
@Test
public void responseThrowingInOnCompleteDeliveredToPlugin() {
server.enqueue(new MockResponse());
final AtomicReference<Throwable> throwableRef = new AtomicReference<>();
RxJavaPlugins.setErrorHandler(
throwable -> {
if (!throwableRef.compareAndSet(null, throwable)) {
throw Exceptions.propagate(throwable);
}
});
RecordingSubscriber<Response<String>> subscriber = subscriberRule.create();
final RuntimeException e = new RuntimeException();
service
.response()
.subscribe(
new ForwardingSubscriber<Response<String>>(subscriber) {
@Override
public void onComplete() {
throw e;
}
});
subscriber.assertAnyValue();
assertThat(throwableRef.get().getCause()).isSameAs(e);
}
@Test
public void responseThrowingInOnErrorDeliveredToPlugin() {
server.enqueue(new MockResponse().setSocketPolicy(DISCONNECT_AFTER_REQUEST));
final AtomicReference<Throwable> throwableRef = new AtomicReference<>();
RxJavaPlugins.setErrorHandler(
throwable -> {
if (!throwableRef.compareAndSet(null, throwable)) {
throw Exceptions.propagate(throwable);
}
});
RecordingSubscriber<Response<String>> subscriber = subscriberRule.create();
final AtomicReference<Throwable> errorRef = new AtomicReference<>();
final RuntimeException e = new RuntimeException();
service
.response()
.subscribe(
new ForwardingSubscriber<Response<String>>(subscriber) {
@Override
public void onError(Throwable throwable) {
if (!errorRef.compareAndSet(null, throwable)) {
throw Exceptions.propagate(throwable);
}
throw e;
}
});
//noinspection ThrowableResultOfMethodCallIgnored
CompositeException composite = (CompositeException) throwableRef.get();
assertThat(composite.getExceptions()).containsExactly(errorRef.get(), e);
}
@Test
public void resultThrowingInOnNextDeliveredToError() {
server.enqueue(new MockResponse());
RecordingSubscriber<Result<String>> subscriber = subscriberRule.create();
final RuntimeException e = new RuntimeException();
service
.result()
.safeSubscribe(
new ForwardingSubscriber<Result<String>>(subscriber) {
@Override
public void onNext(Result<String> value) {
throw e;
}
});
subscriber.assertError(e);
}
@Test
public void resultThrowingInOnCompletedDeliveredToPlugin() {
server.enqueue(new MockResponse());
final AtomicReference<Throwable> throwableRef = new AtomicReference<>();
RxJavaPlugins.setErrorHandler(
throwable -> {
if (!throwableRef.compareAndSet(null, throwable)) {
throw Exceptions.propagate(throwable);
}
});
RecordingSubscriber<Result<String>> subscriber = subscriberRule.create();
final RuntimeException e = new RuntimeException();
service
.result()
.subscribe(
new ForwardingSubscriber<Result<String>>(subscriber) {
@Override
public void onComplete() {
throw e;
}
});
subscriber.assertAnyValue();
assertThat(throwableRef.get().getCause()).isSameAs(e);
}
@Test
public void resultThrowingInOnErrorDeliveredToPlugin() {
server.enqueue(new MockResponse());
final AtomicReference<Throwable> throwableRef = new AtomicReference<>();
RxJavaPlugins.setErrorHandler(
throwable -> {
if (!throwableRef.compareAndSet(null, throwable)) {
throw Exceptions.propagate(throwable);
}
});
RecordingSubscriber<Result<String>> subscriber = subscriberRule.create();
final RuntimeException first = new RuntimeException();
final RuntimeException second = new RuntimeException();
service
.result()
.safeSubscribe(
new ForwardingSubscriber<Result<String>>(subscriber) {
@Override
public void onNext(Result<String> value) {
// The only way to trigger onError for a result is if onNext throws.
throw first;
}
@Override
public void onError(Throwable throwable) {
throw second;
}
});
//noinspection ThrowableResultOfMethodCallIgnored
CompositeException composite = (CompositeException) throwableRef.get();
assertThat(composite.getExceptions()).containsExactly(first, second);
}
private abstract static class ForwardingSubscriber<T> implements Subscriber<T> {
private final Subscriber<T> delegate;
ForwardingSubscriber(Subscriber<T> delegate) {
this.delegate = delegate;
}
@Override
public void onSubscribe(Subscription subscription) {
delegate.onSubscribe(subscription);
}
@Override
public void onNext(T value) {
delegate.onNext(value);
}
@Override
public void onError(Throwable throwable) {
delegate.onError(throwable);
}
@Override
public void onComplete() {
delegate.onComplete();
}
}
}
| 3,777 |
0 | Create_ds/retrofit/retrofit-adapters/rxjava3/src/test/java/retrofit2/adapter | Create_ds/retrofit/retrofit-adapters/rxjava3/src/test/java/retrofit2/adapter/rxjava3/RecordingObserver.java | /*
* Copyright (C) 2020 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.rxjava3;
import static org.assertj.core.api.Assertions.assertThat;
import io.reactivex.rxjava3.core.Notification;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
/** A test {@link Observer} and JUnit rule which guarantees all events are asserted. */
final class RecordingObserver<T> implements Observer<T> {
private final Deque<Notification<T>> events = new ArrayDeque<>();
private RecordingObserver() {}
@Override
public void onSubscribe(Disposable disposable) {}
@Override
public void onNext(T value) {
events.add(Notification.createOnNext(value));
}
@Override
public void onComplete() {
events.add(Notification.createOnComplete());
}
@Override
public void onError(Throwable e) {
events.add(Notification.createOnError(e));
}
private Notification<T> takeNotification() {
Notification<T> notification = events.pollFirst();
if (notification == null) {
throw new AssertionError("No event found!");
}
return notification;
}
public T takeValue() {
Notification<T> notification = takeNotification();
assertThat(notification.isOnNext())
.as("Expected onNext event but was " + notification)
.isTrue();
return notification.getValue();
}
public Throwable takeError() {
Notification<T> notification = takeNotification();
assertThat(notification.isOnError())
.as("Expected onError event but was " + notification)
.isTrue();
return notification.getError();
}
public RecordingObserver<T> assertAnyValue() {
takeValue();
return this;
}
public RecordingObserver<T> assertValue(T value) {
assertThat(takeValue()).isEqualTo(value);
return this;
}
public void assertComplete() {
Notification<T> notification = takeNotification();
assertThat(notification.isOnComplete())
.as("Expected onCompleted event but was " + notification)
.isTrue();
assertNoEvents();
}
public void assertError(Throwable throwable) {
assertThat(takeError()).isEqualTo(throwable);
}
public void assertError(Class<? extends Throwable> errorClass) {
assertError(errorClass, null);
}
public void assertError(Class<? extends Throwable> errorClass, String message) {
Throwable throwable = takeError();
assertThat(throwable).isInstanceOf(errorClass);
if (message != null) {
assertThat(throwable).hasMessage(message);
}
assertNoEvents();
}
public void assertNoEvents() {
assertThat(events).as("Unconsumed events found!").isEmpty();
}
public static final class Rule implements TestRule {
final List<RecordingObserver<?>> subscribers = new ArrayList<>();
public <T> RecordingObserver<T> create() {
RecordingObserver<T> subscriber = new RecordingObserver<>();
subscribers.add(subscriber);
return subscriber;
}
@Override
public Statement apply(final Statement base, Description description) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
base.evaluate();
for (RecordingObserver<?> subscriber : subscribers) {
subscriber.assertNoEvents();
}
}
};
}
}
}
| 3,778 |
0 | Create_ds/retrofit/retrofit-adapters/rxjava3/src/test/java/retrofit2/adapter | Create_ds/retrofit/retrofit-adapters/rxjava3/src/test/java/retrofit2/adapter/rxjava3/RxJavaPluginsResetRule.java | /*
* Copyright (C) 2020 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.rxjava3;
import io.reactivex.rxjava3.plugins.RxJavaPlugins;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
final class RxJavaPluginsResetRule implements TestRule {
@Override
public Statement apply(final Statement base, Description description) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
RxJavaPlugins.reset();
try {
base.evaluate();
} finally {
RxJavaPlugins.reset();
}
}
};
}
}
| 3,779 |
0 | Create_ds/retrofit/retrofit-adapters/rxjava3/src/test/java/retrofit2/adapter | Create_ds/retrofit/retrofit-adapters/rxjava3/src/test/java/retrofit2/adapter/rxjava3/FlowableWithSchedulerTest.java | /*
* Copyright (C) 2020 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.rxjava3;
import io.reactivex.rxjava3.core.Flowable;
import io.reactivex.rxjava3.schedulers.TestScheduler;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.http.GET;
public final class FlowableWithSchedulerTest {
@Rule public final MockWebServer server = new MockWebServer();
@Rule public final RecordingSubscriber.Rule subscriberRule = new RecordingSubscriber.Rule();
interface Service {
@GET("/")
Flowable<String> body();
@GET("/")
Flowable<Response<String>> response();
@GET("/")
Flowable<Result<String>> result();
}
private final TestScheduler scheduler = new TestScheduler();
private Service service;
@Before
public void setUp() {
Retrofit retrofit =
new Retrofit.Builder()
.baseUrl(server.url("/"))
.addConverterFactory(new StringConverterFactory())
.addCallAdapterFactory(RxJava3CallAdapterFactory.createWithScheduler(scheduler))
.build();
service = retrofit.create(Service.class);
}
@Test
public void bodyUsesScheduler() {
server.enqueue(new MockResponse());
RecordingSubscriber<Object> subscriber = subscriberRule.create();
service.body().subscribe(subscriber);
subscriber.assertNoEvents();
scheduler.triggerActions();
subscriber.assertAnyValue().assertComplete();
}
@Test
public void responseUsesScheduler() {
server.enqueue(new MockResponse());
RecordingSubscriber<Object> subscriber = subscriberRule.create();
service.response().subscribe(subscriber);
subscriber.assertNoEvents();
scheduler.triggerActions();
subscriber.assertAnyValue().assertComplete();
}
@Test
public void resultUsesScheduler() {
server.enqueue(new MockResponse());
RecordingSubscriber<Object> subscriber = subscriberRule.create();
service.result().subscribe(subscriber);
subscriber.assertNoEvents();
scheduler.triggerActions();
subscriber.assertAnyValue().assertComplete();
}
}
| 3,780 |
0 | Create_ds/retrofit/retrofit-adapters/rxjava3/src/test/java/retrofit2/adapter | Create_ds/retrofit/retrofit-adapters/rxjava3/src/test/java/retrofit2/adapter/rxjava3/ResultTest.java | /*
* Copyright (C) 2020 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.rxjava3;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;
import java.io.IOException;
import org.junit.Test;
import retrofit2.Response;
public final class ResultTest {
@Test
public void response() {
Response<String> response = Response.success("Hi");
Result<String> result = Result.response(response);
assertThat(result.isError()).isFalse();
assertThat(result.error()).isNull();
assertThat(result.response()).isSameAs(response);
}
@Test
public void nullResponseThrows() {
try {
Result.response(null);
fail();
} catch (NullPointerException e) {
assertThat(e).hasMessage("response == null");
}
}
@Test
public void error() {
Throwable error = new IOException();
Result<Object> result = Result.error(error);
assertThat(result.isError()).isTrue();
assertThat(result.error()).isSameAs(error);
assertThat(result.response()).isNull();
}
@Test
public void nullErrorThrows() {
try {
Result.error(null);
fail();
} catch (NullPointerException e) {
assertThat(e).hasMessage("error == null");
}
}
}
| 3,781 |
0 | Create_ds/retrofit/retrofit-adapters/rxjava3/src/test/java/retrofit2/adapter | Create_ds/retrofit/retrofit-adapters/rxjava3/src/test/java/retrofit2/adapter/rxjava3/RecordingMaybeObserver.java | /*
* Copyright (C) 2020 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.rxjava3;
import static org.assertj.core.api.Assertions.assertThat;
import io.reactivex.rxjava3.core.MaybeObserver;
import io.reactivex.rxjava3.core.Notification;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
/** A test {@link Observer} and JUnit rule which guarantees all events are asserted. */
final class RecordingMaybeObserver<T> implements MaybeObserver<T> {
private final Deque<Notification<T>> events = new ArrayDeque<>();
private RecordingMaybeObserver() {}
@Override
public void onSubscribe(Disposable disposable) {}
@Override
public void onSuccess(T value) {
events.add(Notification.createOnNext(value));
}
@Override
public void onError(Throwable e) {
events.add(Notification.createOnError(e));
}
@Override
public void onComplete() {
events.add(Notification.createOnComplete());
}
private Notification<T> takeNotification() {
Notification<T> notification = events.pollFirst();
if (notification == null) {
throw new AssertionError("No event found!");
}
return notification;
}
public T takeValue() {
Notification<T> notification = takeNotification();
assertThat(notification.isOnNext())
.as("Expected onNext event but was " + notification)
.isTrue();
return notification.getValue();
}
public Throwable takeError() {
Notification<T> notification = takeNotification();
assertThat(notification.isOnError())
.as("Expected onError event but was " + notification)
.isTrue();
return notification.getError();
}
public RecordingMaybeObserver<T> assertAnyValue() {
takeValue();
return this;
}
public RecordingMaybeObserver<T> assertValue(T value) {
assertThat(takeValue()).isEqualTo(value);
return this;
}
public void assertError(Throwable throwable) {
assertThat(takeError()).isEqualTo(throwable);
}
public void assertError(Class<? extends Throwable> errorClass) {
assertError(errorClass, null);
}
public void assertError(Class<? extends Throwable> errorClass, String message) {
Throwable throwable = takeError();
assertThat(throwable).isInstanceOf(errorClass);
if (message != null) {
assertThat(throwable).hasMessage(message);
}
assertNoEvents();
}
public void assertNoEvents() {
assertThat(events).as("Unconsumed events found!").isEmpty();
}
public static final class Rule implements TestRule {
final List<RecordingMaybeObserver<?>> subscribers = new ArrayList<>();
public <T> RecordingMaybeObserver<T> create() {
RecordingMaybeObserver<T> subscriber = new RecordingMaybeObserver<>();
subscribers.add(subscriber);
return subscriber;
}
@Override
public Statement apply(final Statement base, Description description) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
base.evaluate();
for (RecordingMaybeObserver<?> subscriber : subscribers) {
subscriber.assertNoEvents();
}
}
};
}
}
}
| 3,782 |
0 | Create_ds/retrofit/retrofit-adapters/rxjava3/src/test/java/retrofit2/adapter | Create_ds/retrofit/retrofit-adapters/rxjava3/src/test/java/retrofit2/adapter/rxjava3/FlowableTest.java | /*
* Copyright (C) 2020 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.rxjava3;
import static okhttp3.mockwebserver.SocketPolicy.DISCONNECT_AFTER_REQUEST;
import static org.assertj.core.api.Assertions.assertThat;
import io.reactivex.rxjava3.core.Flowable;
import java.io.IOException;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.http.GET;
public final class FlowableTest {
@Rule public final MockWebServer server = new MockWebServer();
@Rule public final RecordingSubscriber.Rule subscriberRule = new RecordingSubscriber.Rule();
interface Service {
@GET("/")
Flowable<String> body();
@GET("/")
Flowable<Response<String>> response();
@GET("/")
Flowable<Result<String>> result();
}
private Service service;
@Before
public void setUp() {
Retrofit retrofit =
new Retrofit.Builder()
.baseUrl(server.url("/"))
.addConverterFactory(new StringConverterFactory())
.addCallAdapterFactory(RxJava3CallAdapterFactory.createSynchronous())
.build();
service = retrofit.create(Service.class);
}
@Test
public void bodySuccess200() {
server.enqueue(new MockResponse().setBody("Hi"));
RecordingSubscriber<String> subscriber = subscriberRule.create();
service.body().subscribe(subscriber);
subscriber.assertValue("Hi").assertComplete();
}
@Test
public void bodySuccess404() {
server.enqueue(new MockResponse().setResponseCode(404));
RecordingSubscriber<String> subscriber = subscriberRule.create();
service.body().subscribe(subscriber);
// Required for backwards compatibility.
subscriber.assertError(HttpException.class, "HTTP 404 Client Error");
}
@Test
public void bodyFailure() {
server.enqueue(new MockResponse().setSocketPolicy(DISCONNECT_AFTER_REQUEST));
RecordingSubscriber<String> subscriber = subscriberRule.create();
service.body().subscribe(subscriber);
subscriber.assertError(IOException.class);
}
@Test
public void responseSuccess200() {
server.enqueue(new MockResponse());
RecordingSubscriber<Response<String>> subscriber = subscriberRule.create();
service.response().subscribe(subscriber);
assertThat(subscriber.takeValue().isSuccessful()).isTrue();
subscriber.assertComplete();
}
@Test
public void responseSuccess404() {
server.enqueue(new MockResponse().setResponseCode(404));
RecordingSubscriber<Response<String>> subscriber = subscriberRule.create();
service.response().subscribe(subscriber);
assertThat(subscriber.takeValue().isSuccessful()).isFalse();
subscriber.assertComplete();
}
@Test
public void responseFailure() {
server.enqueue(new MockResponse().setSocketPolicy(DISCONNECT_AFTER_REQUEST));
RecordingSubscriber<Response<String>> subscriber = subscriberRule.create();
service.response().subscribe(subscriber);
subscriber.assertError(IOException.class);
}
@Test
public void resultSuccess200() {
server.enqueue(new MockResponse());
RecordingSubscriber<Result<String>> subscriber = subscriberRule.create();
service.result().subscribe(subscriber);
Result<String> result = subscriber.takeValue();
assertThat(result.isError()).isFalse();
assertThat(result.response().isSuccessful()).isTrue();
subscriber.assertComplete();
}
@Test
public void resultSuccess404() {
server.enqueue(new MockResponse().setResponseCode(404));
RecordingSubscriber<Result<String>> subscriber = subscriberRule.create();
service.result().subscribe(subscriber);
Result<String> result = subscriber.takeValue();
assertThat(result.isError()).isFalse();
assertThat(result.response().isSuccessful()).isFalse();
subscriber.assertComplete();
}
@Test
public void resultFailure() {
server.enqueue(new MockResponse().setSocketPolicy(DISCONNECT_AFTER_REQUEST));
RecordingSubscriber<Result<String>> subscriber = subscriberRule.create();
service.result().subscribe(subscriber);
Result<String> result = subscriber.takeValue();
assertThat(result.isError()).isTrue();
assertThat(result.error()).isInstanceOf(IOException.class);
subscriber.assertComplete();
}
@Test
public void subscribeTwice() {
server.enqueue(new MockResponse().setBody("Hi"));
server.enqueue(new MockResponse().setBody("Hey"));
Flowable<String> observable = service.body();
RecordingSubscriber<Object> subscriber1 = subscriberRule.create();
observable.subscribe(subscriber1);
subscriber1.assertValue("Hi").assertComplete();
RecordingSubscriber<Object> subscriber2 = subscriberRule.create();
observable.subscribe(subscriber2);
subscriber2.assertValue("Hey").assertComplete();
}
}
| 3,783 |
0 | Create_ds/retrofit/retrofit-adapters/rxjava3/src/test/java/retrofit2/adapter | Create_ds/retrofit/retrofit-adapters/rxjava3/src/test/java/retrofit2/adapter/rxjava3/MaybeTest.java | /*
* Copyright (C) 2020 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.rxjava3;
import static okhttp3.mockwebserver.SocketPolicy.DISCONNECT_AFTER_REQUEST;
import static org.assertj.core.api.Assertions.assertThat;
import io.reactivex.rxjava3.core.Maybe;
import java.io.IOException;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.http.GET;
public final class MaybeTest {
@Rule public final MockWebServer server = new MockWebServer();
@Rule public final RecordingMaybeObserver.Rule observerRule = new RecordingMaybeObserver.Rule();
interface Service {
@GET("/")
Maybe<String> body();
@GET("/")
Maybe<Response<String>> response();
@GET("/")
Maybe<Result<String>> result();
}
private Service service;
@Before
public void setUp() {
Retrofit retrofit =
new Retrofit.Builder()
.baseUrl(server.url("/"))
.addConverterFactory(new StringConverterFactory())
.addCallAdapterFactory(RxJava3CallAdapterFactory.createSynchronous())
.build();
service = retrofit.create(Service.class);
}
@Test
public void bodySuccess200() {
server.enqueue(new MockResponse().setBody("Hi"));
RecordingMaybeObserver<String> observer = observerRule.create();
service.body().subscribe(observer);
observer.assertValue("Hi");
}
@Test
public void bodySuccess404() {
server.enqueue(new MockResponse().setResponseCode(404));
RecordingMaybeObserver<String> observer = observerRule.create();
service.body().subscribe(observer);
// Required for backwards compatibility.
observer.assertError(HttpException.class, "HTTP 404 Client Error");
}
@Test
public void bodyFailure() {
server.enqueue(new MockResponse().setSocketPolicy(DISCONNECT_AFTER_REQUEST));
RecordingMaybeObserver<String> observer = observerRule.create();
service.body().subscribe(observer);
observer.assertError(IOException.class);
}
@Test
public void responseSuccess200() {
server.enqueue(new MockResponse().setBody("Hi"));
RecordingMaybeObserver<Response<String>> observer = observerRule.create();
service.response().subscribe(observer);
Response<String> response = observer.takeValue();
assertThat(response.isSuccessful()).isTrue();
}
@Test
public void responseSuccess404() {
server.enqueue(new MockResponse().setResponseCode(404));
RecordingMaybeObserver<Response<String>> observer = observerRule.create();
service.response().subscribe(observer);
assertThat(observer.takeValue().isSuccessful()).isFalse();
}
@Test
public void responseFailure() {
server.enqueue(new MockResponse().setSocketPolicy(DISCONNECT_AFTER_REQUEST));
RecordingMaybeObserver<Response<String>> observer = observerRule.create();
service.response().subscribe(observer);
observer.assertError(IOException.class);
}
@Test
public void resultSuccess200() {
server.enqueue(new MockResponse().setBody("Hi"));
RecordingMaybeObserver<Result<String>> observer = observerRule.create();
service.result().subscribe(observer);
Result<String> result = observer.takeValue();
assertThat(result.isError()).isFalse();
assertThat(result.response().isSuccessful()).isTrue();
}
@Test
public void resultSuccess404() {
server.enqueue(new MockResponse().setResponseCode(404));
RecordingMaybeObserver<Result<String>> observer = observerRule.create();
service.result().subscribe(observer);
Result<String> result = observer.takeValue();
assertThat(result.isError()).isFalse();
assertThat(result.response().isSuccessful()).isFalse();
}
@Test
public void resultFailure() {
server.enqueue(new MockResponse().setSocketPolicy(DISCONNECT_AFTER_REQUEST));
RecordingMaybeObserver<Result<String>> observer = observerRule.create();
service.result().subscribe(observer);
Result<String> result = observer.takeValue();
assertThat(result.isError()).isTrue();
assertThat(result.error()).isInstanceOf(IOException.class);
}
@Test
public void subscribeTwice() {
server.enqueue(new MockResponse().setBody("Hi"));
server.enqueue(new MockResponse().setBody("Hey"));
Maybe<String> observable = service.body();
RecordingMaybeObserver<Object> observer1 = observerRule.create();
observable.subscribe(observer1);
observer1.assertValue("Hi");
RecordingMaybeObserver<Object> observer2 = observerRule.create();
observable.subscribe(observer2);
observer2.assertValue("Hey");
}
}
| 3,784 |
0 | Create_ds/retrofit/retrofit-adapters/rxjava3/src/test/java/retrofit2/adapter | Create_ds/retrofit/retrofit-adapters/rxjava3/src/test/java/retrofit2/adapter/rxjava3/SingleTest.java | /*
* Copyright (C) 2020 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.rxjava3;
import static okhttp3.mockwebserver.SocketPolicy.DISCONNECT_AFTER_REQUEST;
import static org.assertj.core.api.Assertions.assertThat;
import io.reactivex.rxjava3.core.Single;
import java.io.IOException;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.http.GET;
public final class SingleTest {
@Rule public final MockWebServer server = new MockWebServer();
@Rule public final RecordingSingleObserver.Rule observerRule = new RecordingSingleObserver.Rule();
interface Service {
@GET("/")
Single<String> body();
@GET("/")
Single<Response<String>> response();
@GET("/")
Single<Result<String>> result();
}
private Service service;
@Before
public void setUp() {
Retrofit retrofit =
new Retrofit.Builder()
.baseUrl(server.url("/"))
.addConverterFactory(new StringConverterFactory())
.addCallAdapterFactory(RxJava3CallAdapterFactory.createSynchronous())
.build();
service = retrofit.create(Service.class);
}
@Test
public void bodySuccess200() {
server.enqueue(new MockResponse().setBody("Hi"));
RecordingSingleObserver<String> observer = observerRule.create();
service.body().subscribe(observer);
observer.assertValue("Hi");
}
@Test
public void bodySuccess404() {
server.enqueue(new MockResponse().setResponseCode(404));
RecordingSingleObserver<String> observer = observerRule.create();
service.body().subscribe(observer);
// Required for backwards compatibility.
observer.assertError(HttpException.class, "HTTP 404 Client Error");
}
@Test
public void bodyFailure() {
server.enqueue(new MockResponse().setSocketPolicy(DISCONNECT_AFTER_REQUEST));
RecordingSingleObserver<String> observer = observerRule.create();
service.body().subscribe(observer);
observer.assertError(IOException.class);
}
@Test
public void responseSuccess200() {
server.enqueue(new MockResponse().setBody("Hi"));
RecordingSingleObserver<Response<String>> observer = observerRule.create();
service.response().subscribe(observer);
Response<String> response = observer.takeValue();
assertThat(response.isSuccessful()).isTrue();
}
@Test
public void responseSuccess404() {
server.enqueue(new MockResponse().setResponseCode(404));
RecordingSingleObserver<Response<String>> observer = observerRule.create();
service.response().subscribe(observer);
assertThat(observer.takeValue().isSuccessful()).isFalse();
}
@Test
public void responseFailure() {
server.enqueue(new MockResponse().setSocketPolicy(DISCONNECT_AFTER_REQUEST));
RecordingSingleObserver<Response<String>> observer = observerRule.create();
service.response().subscribe(observer);
observer.assertError(IOException.class);
}
@Test
public void resultSuccess200() {
server.enqueue(new MockResponse().setBody("Hi"));
RecordingSingleObserver<Result<String>> observer = observerRule.create();
service.result().subscribe(observer);
Result<String> result = observer.takeValue();
assertThat(result.isError()).isFalse();
assertThat(result.response().isSuccessful()).isTrue();
}
@Test
public void resultSuccess404() {
server.enqueue(new MockResponse().setResponseCode(404));
RecordingSingleObserver<Result<String>> observer = observerRule.create();
service.result().subscribe(observer);
Result<String> result = observer.takeValue();
assertThat(result.isError()).isFalse();
assertThat(result.response().isSuccessful()).isFalse();
}
@Test
public void resultFailure() {
server.enqueue(new MockResponse().setSocketPolicy(DISCONNECT_AFTER_REQUEST));
RecordingSingleObserver<Result<String>> observer = observerRule.create();
service.result().subscribe(observer);
Result<String> result = observer.takeValue();
assertThat(result.isError()).isTrue();
assertThat(result.error()).isInstanceOf(IOException.class);
}
@Test
public void subscribeTwice() {
server.enqueue(new MockResponse().setBody("Hi"));
server.enqueue(new MockResponse().setBody("Hey"));
Single<String> observable = service.body();
RecordingSingleObserver<Object> observer1 = observerRule.create();
observable.subscribe(observer1);
observer1.assertValue("Hi");
RecordingSingleObserver<Object> observer2 = observerRule.create();
observable.subscribe(observer2);
observer2.assertValue("Hey");
}
}
| 3,785 |
0 | Create_ds/retrofit/retrofit-adapters/rxjava3/src/test/java/retrofit2/adapter | Create_ds/retrofit/retrofit-adapters/rxjava3/src/test/java/retrofit2/adapter/rxjava3/RecordingSingleObserver.java | /*
* Copyright (C) 2020 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.rxjava3;
import static org.assertj.core.api.Assertions.assertThat;
import io.reactivex.rxjava3.core.Notification;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.core.SingleObserver;
import io.reactivex.rxjava3.disposables.Disposable;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
/** A test {@link Observer} and JUnit rule which guarantees all events are asserted. */
final class RecordingSingleObserver<T> implements SingleObserver<T> {
private final Deque<Notification<T>> events = new ArrayDeque<>();
private RecordingSingleObserver() {}
@Override
public void onSubscribe(Disposable disposable) {}
@Override
public void onSuccess(T value) {
events.add(Notification.createOnNext(value));
}
@Override
public void onError(Throwable e) {
events.add(Notification.createOnError(e));
}
private Notification<T> takeNotification() {
Notification<T> notification = events.pollFirst();
if (notification == null) {
throw new AssertionError("No event found!");
}
return notification;
}
public T takeValue() {
Notification<T> notification = takeNotification();
assertThat(notification.isOnNext())
.as("Expected onNext event but was " + notification)
.isTrue();
return notification.getValue();
}
public Throwable takeError() {
Notification<T> notification = takeNotification();
assertThat(notification.isOnError())
.as("Expected onError event but was " + notification)
.isTrue();
return notification.getError();
}
public RecordingSingleObserver<T> assertAnyValue() {
takeValue();
return this;
}
public RecordingSingleObserver<T> assertValue(T value) {
assertThat(takeValue()).isEqualTo(value);
return this;
}
public void assertError(Throwable throwable) {
assertThat(takeError()).isEqualTo(throwable);
}
public void assertError(Class<? extends Throwable> errorClass) {
assertError(errorClass, null);
}
public void assertError(Class<? extends Throwable> errorClass, String message) {
Throwable throwable = takeError();
assertThat(throwable).isInstanceOf(errorClass);
if (message != null) {
assertThat(throwable).hasMessage(message);
}
assertNoEvents();
}
public void assertNoEvents() {
assertThat(events).as("Unconsumed events found!").isEmpty();
}
public static final class Rule implements TestRule {
final List<RecordingSingleObserver<?>> subscribers = new ArrayList<>();
public <T> RecordingSingleObserver<T> create() {
RecordingSingleObserver<T> subscriber = new RecordingSingleObserver<>();
subscribers.add(subscriber);
return subscriber;
}
@Override
public Statement apply(final Statement base, Description description) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
base.evaluate();
for (RecordingSingleObserver<?> subscriber : subscribers) {
subscriber.assertNoEvents();
}
}
};
}
}
}
| 3,786 |
0 | Create_ds/retrofit/retrofit-adapters/rxjava3/src/test/java/retrofit2/adapter | Create_ds/retrofit/retrofit-adapters/rxjava3/src/test/java/retrofit2/adapter/rxjava3/ObservableThrowingTest.java | /*
* Copyright (C) 2020 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.rxjava3;
import static okhttp3.mockwebserver.SocketPolicy.DISCONNECT_AFTER_REQUEST;
import static org.assertj.core.api.Assertions.assertThat;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.exceptions.CompositeException;
import io.reactivex.rxjava3.exceptions.Exceptions;
import io.reactivex.rxjava3.plugins.RxJavaPlugins;
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.Response;
import retrofit2.Retrofit;
import retrofit2.http.GET;
public final class ObservableThrowingTest {
@Rule public final MockWebServer server = new MockWebServer();
@Rule public final TestRule resetRule = new RxJavaPluginsResetRule();
@Rule public final RecordingObserver.Rule subscriberRule = new RecordingObserver.Rule();
interface Service {
@GET("/")
Observable<String> body();
@GET("/")
Observable<Response<String>> response();
@GET("/")
Observable<Result<String>> result();
}
private Service service;
@Before
public void setUp() {
Retrofit retrofit =
new Retrofit.Builder()
.baseUrl(server.url("/"))
.addConverterFactory(new StringConverterFactory())
.addCallAdapterFactory(RxJava3CallAdapterFactory.createSynchronous())
.build();
service = retrofit.create(Service.class);
}
@Test
public void bodyThrowingInOnNextDeliveredToError() {
server.enqueue(new MockResponse());
RecordingObserver<String> observer = subscriberRule.create();
final RuntimeException e = new RuntimeException();
service
.body()
.subscribe(
new ForwardingObserver<String>(observer) {
@Override
public void onNext(String value) {
throw e;
}
});
observer.assertError(e);
}
@Test
public void bodyThrowingInOnCompleteDeliveredToPlugin() {
server.enqueue(new MockResponse());
final AtomicReference<Throwable> throwableRef = new AtomicReference<>();
RxJavaPlugins.setErrorHandler(
throwable -> {
if (!throwableRef.compareAndSet(null, throwable)) {
throw Exceptions.propagate(throwable);
}
});
RecordingObserver<String> observer = subscriberRule.create();
final RuntimeException e = new RuntimeException();
service
.body()
.subscribe(
new ForwardingObserver<String>(observer) {
@Override
public void onComplete() {
throw e;
}
});
observer.assertAnyValue();
assertThat(throwableRef.get().getCause()).isSameAs(e);
}
@Test
public void bodyThrowingInOnErrorDeliveredToPlugin() {
server.enqueue(new MockResponse().setResponseCode(404));
final AtomicReference<Throwable> throwableRef = new AtomicReference<>();
RxJavaPlugins.setErrorHandler(
throwable -> {
if (!throwableRef.compareAndSet(null, throwable)) {
throw Exceptions.propagate(throwable);
}
});
RecordingObserver<String> observer = subscriberRule.create();
final AtomicReference<Throwable> errorRef = new AtomicReference<>();
final RuntimeException e = new RuntimeException();
service
.body()
.subscribe(
new ForwardingObserver<String>(observer) {
@Override
public void onError(Throwable throwable) {
if (!errorRef.compareAndSet(null, throwable)) {
throw Exceptions.propagate(throwable);
}
throw e;
}
});
//noinspection ThrowableResultOfMethodCallIgnored
CompositeException composite = (CompositeException) throwableRef.get();
assertThat(composite.getExceptions()).containsExactly(errorRef.get(), e);
}
@Test
public void responseThrowingInOnNextDeliveredToError() {
server.enqueue(new MockResponse());
RecordingObserver<Response<String>> observer = subscriberRule.create();
final RuntimeException e = new RuntimeException();
service
.response()
.subscribe(
new ForwardingObserver<Response<String>>(observer) {
@Override
public void onNext(Response<String> value) {
throw e;
}
});
observer.assertError(e);
}
@Test
public void responseThrowingInOnCompleteDeliveredToPlugin() {
server.enqueue(new MockResponse());
final AtomicReference<Throwable> throwableRef = new AtomicReference<>();
RxJavaPlugins.setErrorHandler(
throwable -> {
if (!throwableRef.compareAndSet(null, throwable)) {
throw Exceptions.propagate(throwable);
}
});
RecordingObserver<Response<String>> observer = subscriberRule.create();
final RuntimeException e = new RuntimeException();
service
.response()
.subscribe(
new ForwardingObserver<Response<String>>(observer) {
@Override
public void onComplete() {
throw e;
}
});
observer.assertAnyValue();
assertThat(throwableRef.get().getCause()).isSameAs(e);
}
@Test
public void responseThrowingInOnErrorDeliveredToPlugin() {
server.enqueue(new MockResponse().setSocketPolicy(DISCONNECT_AFTER_REQUEST));
final AtomicReference<Throwable> throwableRef = new AtomicReference<>();
RxJavaPlugins.setErrorHandler(
throwable -> {
if (!throwableRef.compareAndSet(null, throwable)) {
throw Exceptions.propagate(throwable);
}
});
RecordingObserver<Response<String>> observer = subscriberRule.create();
final AtomicReference<Throwable> errorRef = new AtomicReference<>();
final RuntimeException e = new RuntimeException();
service
.response()
.subscribe(
new ForwardingObserver<Response<String>>(observer) {
@Override
public void onError(Throwable throwable) {
if (!errorRef.compareAndSet(null, throwable)) {
throw Exceptions.propagate(throwable);
}
throw e;
}
});
//noinspection ThrowableResultOfMethodCallIgnored
CompositeException composite = (CompositeException) throwableRef.get();
assertThat(composite.getExceptions()).containsExactly(errorRef.get(), e);
}
@Test
public void resultThrowingInOnNextDeliveredToError() {
server.enqueue(new MockResponse());
RecordingObserver<Result<String>> observer = subscriberRule.create();
final RuntimeException e = new RuntimeException();
service
.result()
.subscribe(
new ForwardingObserver<Result<String>>(observer) {
@Override
public void onNext(Result<String> value) {
throw e;
}
});
observer.assertError(e);
}
@Test
public void resultThrowingInOnCompletedDeliveredToPlugin() {
server.enqueue(new MockResponse());
final AtomicReference<Throwable> throwableRef = new AtomicReference<>();
RxJavaPlugins.setErrorHandler(
throwable -> {
if (!throwableRef.compareAndSet(null, throwable)) {
throw Exceptions.propagate(throwable);
}
});
RecordingObserver<Result<String>> observer = subscriberRule.create();
final RuntimeException e = new RuntimeException();
service
.result()
.subscribe(
new ForwardingObserver<Result<String>>(observer) {
@Override
public void onComplete() {
throw e;
}
});
observer.assertAnyValue();
assertThat(throwableRef.get().getCause()).isSameAs(e);
}
@Test
public void resultThrowingInOnErrorDeliveredToPlugin() {
server.enqueue(new MockResponse());
final AtomicReference<Throwable> throwableRef = new AtomicReference<>();
RxJavaPlugins.setErrorHandler(
throwable -> {
if (!throwableRef.compareAndSet(null, throwable)) {
throw Exceptions.propagate(throwable);
}
});
RecordingObserver<Result<String>> observer = subscriberRule.create();
final RuntimeException first = new RuntimeException();
final RuntimeException second = new RuntimeException();
service
.result()
.subscribe(
new ForwardingObserver<Result<String>>(observer) {
@Override
public void onNext(Result<String> value) {
// The only way to trigger onError for a result is if onNext throws.
throw first;
}
@Override
public void onError(Throwable throwable) {
throw second;
}
});
//noinspection ThrowableResultOfMethodCallIgnored
CompositeException composite = (CompositeException) throwableRef.get();
assertThat(composite.getExceptions()).containsExactly(first, second);
}
private abstract static class ForwardingObserver<T> implements Observer<T> {
private final Observer<T> delegate;
ForwardingObserver(Observer<T> delegate) {
this.delegate = delegate;
}
@Override
public void onSubscribe(Disposable disposable) {
delegate.onSubscribe(disposable);
}
@Override
public void onNext(T value) {
delegate.onNext(value);
}
@Override
public void onError(Throwable throwable) {
delegate.onError(throwable);
}
@Override
public void onComplete() {
delegate.onComplete();
}
}
}
| 3,787 |
0 | Create_ds/retrofit/retrofit-adapters/rxjava3/src/test/java/retrofit2/adapter | Create_ds/retrofit/retrofit-adapters/rxjava3/src/test/java/retrofit2/adapter/rxjava3/CompletableWithSchedulerTest.java | /*
* Copyright (C) 2020 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.rxjava3;
import io.reactivex.rxjava3.core.Completable;
import io.reactivex.rxjava3.schedulers.TestScheduler;
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;
public final class CompletableWithSchedulerTest {
@Rule public final MockWebServer server = new MockWebServer();
@Rule
public final RecordingCompletableObserver.Rule observerRule =
new RecordingCompletableObserver.Rule();
interface Service {
@GET("/")
Completable completable();
}
private final TestScheduler scheduler = new TestScheduler();
private Service service;
@Before
public void setUp() {
Retrofit retrofit =
new Retrofit.Builder()
.baseUrl(server.url("/"))
.addCallAdapterFactory(RxJava3CallAdapterFactory.createWithScheduler(scheduler))
.build();
service = retrofit.create(Service.class);
}
@Test
public void completableUsesScheduler() {
server.enqueue(new MockResponse());
RecordingCompletableObserver observer = observerRule.create();
service.completable().subscribe(observer);
observer.assertNoEvents();
scheduler.triggerActions();
observer.assertComplete();
}
}
| 3,788 |
0 | Create_ds/retrofit/retrofit-adapters/rxjava3/src/test/java/retrofit2/adapter | Create_ds/retrofit/retrofit-adapters/rxjava3/src/test/java/retrofit2/adapter/rxjava3/CompletableThrowingTest.java | /*
* Copyright (C) 2020 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.rxjava3;
import static org.assertj.core.api.Assertions.assertThat;
import io.reactivex.rxjava3.core.Completable;
import io.reactivex.rxjava3.core.CompletableObserver;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.exceptions.CompositeException;
import io.reactivex.rxjava3.exceptions.Exceptions;
import io.reactivex.rxjava3.plugins.RxJavaPlugins;
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;
public final class CompletableThrowingTest {
@Rule public final MockWebServer server = new MockWebServer();
@Rule public final TestRule resetRule = new RxJavaPluginsResetRule();
@Rule
public final RecordingCompletableObserver.Rule observerRule =
new RecordingCompletableObserver.Rule();
interface Service {
@GET("/")
Completable completable();
}
private Service service;
@Before
public void setUp() {
Retrofit retrofit =
new Retrofit.Builder()
.baseUrl(server.url("/"))
.addCallAdapterFactory(RxJava3CallAdapterFactory.createSynchronous())
.build();
service = retrofit.create(Service.class);
}
@Test
public void throwingInOnCompleteDeliveredToPlugin() {
server.enqueue(new MockResponse());
final AtomicReference<Throwable> errorRef = new AtomicReference<>();
RxJavaPlugins.setErrorHandler(
throwable -> {
if (!errorRef.compareAndSet(null, throwable)) {
throw Exceptions.propagate(throwable); // Don't swallow secondary errors!
}
});
RecordingCompletableObserver observer = observerRule.create();
final RuntimeException e = new RuntimeException();
service
.completable()
.subscribe(
new ForwardingCompletableObserver(observer) {
@Override
public void onComplete() {
throw e;
}
});
assertThat(errorRef.get().getCause()).isSameAs(e);
}
@Test
public void bodyThrowingInOnErrorDeliveredToPlugin() {
server.enqueue(new MockResponse().setResponseCode(404));
final AtomicReference<Throwable> pluginRef = new AtomicReference<>();
RxJavaPlugins.setErrorHandler(
throwable -> {
if (!pluginRef.compareAndSet(null, throwable)) {
throw Exceptions.propagate(throwable); // Don't swallow secondary errors!
}
});
RecordingCompletableObserver observer = observerRule.create();
final RuntimeException e = new RuntimeException();
final AtomicReference<Throwable> errorRef = new AtomicReference<>();
service
.completable()
.subscribe(
new ForwardingCompletableObserver(observer) {
@Override
public void onError(Throwable throwable) {
errorRef.set(throwable);
throw e;
}
});
//noinspection ThrowableResultOfMethodCallIgnored
CompositeException composite = (CompositeException) pluginRef.get();
assertThat(composite.getExceptions()).containsExactly(errorRef.get(), e);
}
abstract static class ForwardingCompletableObserver implements CompletableObserver {
private final CompletableObserver delegate;
ForwardingCompletableObserver(CompletableObserver delegate) {
this.delegate = delegate;
}
@Override
public void onSubscribe(Disposable disposable) {
delegate.onSubscribe(disposable);
}
@Override
public void onComplete() {
delegate.onComplete();
}
@Override
public void onError(Throwable throwable) {
delegate.onError(throwable);
}
}
}
| 3,789 |
0 | Create_ds/retrofit/retrofit-adapters/rxjava3/src/test/java/retrofit2/adapter | Create_ds/retrofit/retrofit-adapters/rxjava3/src/test/java/retrofit2/adapter/rxjava3/RecordingSubscriber.java | /*
* Copyright (C) 2020 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.rxjava3;
import static org.assertj.core.api.Assertions.assertThat;
import io.reactivex.rxjava3.core.FlowableSubscriber;
import io.reactivex.rxjava3.core.Notification;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
/** A test {@link Subscriber} and JUnit rule which guarantees all events are asserted. */
final class RecordingSubscriber<T> implements FlowableSubscriber<T> {
private final long initialRequest;
private final Deque<Notification<T>> events = new ArrayDeque<>();
private Subscription subscription;
private RecordingSubscriber(long initialRequest) {
this.initialRequest = initialRequest;
}
@Override
public void onSubscribe(Subscription subscription) {
this.subscription = subscription;
subscription.request(initialRequest);
}
@Override
public void onNext(T value) {
events.add(Notification.createOnNext(value));
}
@Override
public void onComplete() {
events.add(Notification.createOnComplete());
}
@Override
public void onError(Throwable e) {
events.add(Notification.createOnError(e));
}
private Notification<T> takeNotification() {
Notification<T> notification = events.pollFirst();
if (notification == null) {
throw new AssertionError("No event found!");
}
return notification;
}
public T takeValue() {
Notification<T> notification = takeNotification();
assertThat(notification.isOnNext())
.as("Expected onNext event but was " + notification)
.isTrue();
return notification.getValue();
}
public Throwable takeError() {
Notification<T> notification = takeNotification();
assertThat(notification.isOnError())
.as("Expected onError event but was " + notification)
.isTrue();
return notification.getError();
}
public RecordingSubscriber<T> assertAnyValue() {
takeValue();
return this;
}
public RecordingSubscriber<T> assertValue(T value) {
assertThat(takeValue()).isEqualTo(value);
return this;
}
public void assertComplete() {
Notification<T> notification = takeNotification();
assertThat(notification.isOnComplete())
.as("Expected onCompleted event but was " + notification)
.isTrue();
assertNoEvents();
}
public void assertError(Throwable throwable) {
assertThat(takeError()).isEqualTo(throwable);
}
public void assertError(Class<? extends Throwable> errorClass) {
assertError(errorClass, null);
}
public void assertError(Class<? extends Throwable> errorClass, String message) {
Throwable throwable = takeError();
assertThat(throwable).isInstanceOf(errorClass);
if (message != null) {
assertThat(throwable).hasMessage(message);
}
assertNoEvents();
}
public void assertNoEvents() {
assertThat(events).as("Unconsumed events found!").isEmpty();
}
public void request(long amount) {
if (subscription == null) {
throw new IllegalStateException("onSubscribe has not been called yet. Did you subscribe()?");
}
subscription.request(amount);
}
public static final class Rule implements TestRule {
final List<RecordingSubscriber<?>> subscribers = new ArrayList<>();
public <T> RecordingSubscriber<T> create() {
return createWithInitialRequest(Long.MAX_VALUE);
}
public <T> RecordingSubscriber<T> createWithInitialRequest(long initialRequest) {
RecordingSubscriber<T> subscriber = new RecordingSubscriber<>(initialRequest);
subscribers.add(subscriber);
return subscriber;
}
@Override
public Statement apply(final Statement base, Description description) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
base.evaluate();
for (RecordingSubscriber<?> subscriber : subscribers) {
subscriber.assertNoEvents();
}
}
};
}
}
}
| 3,790 |
0 | Create_ds/retrofit/retrofit-adapters/rxjava3/src/main/java/retrofit2/adapter | Create_ds/retrofit/retrofit-adapters/rxjava3/src/main/java/retrofit2/adapter/rxjava3/BodyObservable.java | /*
* Copyright (C) 2020 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.rxjava3;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.exceptions.CompositeException;
import io.reactivex.rxjava3.exceptions.Exceptions;
import io.reactivex.rxjava3.plugins.RxJavaPlugins;
import retrofit2.Response;
final class BodyObservable<T> extends Observable<T> {
private final Observable<Response<T>> upstream;
BodyObservable(Observable<Response<T>> upstream) {
this.upstream = upstream;
}
@Override
protected void subscribeActual(Observer<? super T> observer) {
upstream.subscribe(new BodyObserver<>(observer));
}
private static class BodyObserver<R> implements Observer<Response<R>> {
private final Observer<? super R> observer;
private boolean terminated;
BodyObserver(Observer<? super R> observer) {
this.observer = observer;
}
@Override
public void onSubscribe(Disposable disposable) {
observer.onSubscribe(disposable);
}
@Override
public void onNext(Response<R> response) {
if (response.isSuccessful()) {
observer.onNext(response.body());
} else {
terminated = true;
Throwable t = new HttpException(response);
try {
observer.onError(t);
} catch (Throwable inner) {
Exceptions.throwIfFatal(inner);
RxJavaPlugins.onError(new CompositeException(t, inner));
}
}
}
@Override
public void onComplete() {
if (!terminated) {
observer.onComplete();
}
}
@Override
public void onError(Throwable throwable) {
if (!terminated) {
observer.onError(throwable);
} else {
// This should never happen! onNext handles and forwards errors automatically.
Throwable broken =
new AssertionError(
"This should never happen! Report as a bug with the full stacktrace.");
//noinspection UnnecessaryInitCause Two-arg AssertionError constructor is 1.7+ only.
broken.initCause(throwable);
RxJavaPlugins.onError(broken);
}
}
}
}
| 3,791 |
0 | Create_ds/retrofit/retrofit-adapters/rxjava3/src/main/java/retrofit2/adapter | Create_ds/retrofit/retrofit-adapters/rxjava3/src/main/java/retrofit2/adapter/rxjava3/CallEnqueueObservable.java | /*
* Copyright (C) 2020 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.rxjava3;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.exceptions.CompositeException;
import io.reactivex.rxjava3.exceptions.Exceptions;
import io.reactivex.rxjava3.plugins.RxJavaPlugins;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
final class CallEnqueueObservable<T> extends Observable<Response<T>> {
private final Call<T> originalCall;
CallEnqueueObservable(Call<T> originalCall) {
this.originalCall = originalCall;
}
@Override
protected void subscribeActual(Observer<? super Response<T>> observer) {
// Since Call is a one-shot type, clone it for each new observer.
Call<T> call = originalCall.clone();
CallCallback<T> callback = new CallCallback<>(call, observer);
observer.onSubscribe(callback);
if (!callback.isDisposed()) {
call.enqueue(callback);
}
}
private static final class CallCallback<T> implements Disposable, Callback<T> {
private final Call<?> call;
private final Observer<? super Response<T>> observer;
private volatile boolean disposed;
boolean terminated = false;
CallCallback(Call<?> call, Observer<? super Response<T>> observer) {
this.call = call;
this.observer = observer;
}
@Override
public void onResponse(Call<T> call, Response<T> response) {
if (disposed) return;
try {
observer.onNext(response);
if (!disposed) {
terminated = true;
observer.onComplete();
}
} catch (Throwable t) {
Exceptions.throwIfFatal(t);
if (terminated) {
RxJavaPlugins.onError(t);
} else if (!disposed) {
try {
observer.onError(t);
} catch (Throwable inner) {
Exceptions.throwIfFatal(inner);
RxJavaPlugins.onError(new CompositeException(t, inner));
}
}
}
}
@Override
public void onFailure(Call<T> call, Throwable t) {
if (call.isCanceled()) return;
try {
observer.onError(t);
} catch (Throwable inner) {
Exceptions.throwIfFatal(inner);
RxJavaPlugins.onError(new CompositeException(t, inner));
}
}
@Override
public void dispose() {
disposed = true;
call.cancel();
}
@Override
public boolean isDisposed() {
return disposed;
}
}
}
| 3,792 |
0 | Create_ds/retrofit/retrofit-adapters/rxjava3/src/main/java/retrofit2/adapter | Create_ds/retrofit/retrofit-adapters/rxjava3/src/main/java/retrofit2/adapter/rxjava3/RxJava3CallAdapter.java | /*
* Copyright (C) 2020 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.rxjava3;
import io.reactivex.rxjava3.core.BackpressureStrategy;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.core.Scheduler;
import io.reactivex.rxjava3.plugins.RxJavaPlugins;
import java.lang.reflect.Type;
import javax.annotation.Nullable;
import retrofit2.Call;
import retrofit2.CallAdapter;
import retrofit2.Response;
final class RxJava3CallAdapter<R> implements CallAdapter<R, Object> {
private final Type responseType;
private final @Nullable Scheduler scheduler;
private final boolean isAsync;
private final boolean isResult;
private final boolean isBody;
private final boolean isFlowable;
private final boolean isSingle;
private final boolean isMaybe;
private final boolean isCompletable;
RxJava3CallAdapter(
Type responseType,
@Nullable Scheduler scheduler,
boolean isAsync,
boolean isResult,
boolean isBody,
boolean isFlowable,
boolean isSingle,
boolean isMaybe,
boolean isCompletable) {
this.responseType = responseType;
this.scheduler = scheduler;
this.isAsync = isAsync;
this.isResult = isResult;
this.isBody = isBody;
this.isFlowable = isFlowable;
this.isSingle = isSingle;
this.isMaybe = isMaybe;
this.isCompletable = isCompletable;
}
@Override
public Type responseType() {
return responseType;
}
@Override
public Object adapt(Call<R> call) {
Observable<Response<R>> responseObservable =
isAsync ? new CallEnqueueObservable<>(call) : new CallExecuteObservable<>(call);
Observable<?> observable;
if (isResult) {
observable = new ResultObservable<>(responseObservable);
} else if (isBody) {
observable = new BodyObservable<>(responseObservable);
} else {
observable = responseObservable;
}
if (scheduler != null) {
observable = observable.subscribeOn(scheduler);
}
if (isFlowable) {
// We only ever deliver a single value, and the RS spec states that you MUST request at least
// one element which means we never need to honor backpressure.
return observable.toFlowable(BackpressureStrategy.MISSING);
}
if (isSingle) {
return observable.singleOrError();
}
if (isMaybe) {
return observable.singleElement();
}
if (isCompletable) {
return observable.ignoreElements();
}
return RxJavaPlugins.onAssembly(observable);
}
}
| 3,793 |
0 | Create_ds/retrofit/retrofit-adapters/rxjava3/src/main/java/retrofit2/adapter | Create_ds/retrofit/retrofit-adapters/rxjava3/src/main/java/retrofit2/adapter/rxjava3/ResultObservable.java | /*
* Copyright (C) 2020 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.rxjava3;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.exceptions.CompositeException;
import io.reactivex.rxjava3.exceptions.Exceptions;
import io.reactivex.rxjava3.plugins.RxJavaPlugins;
import retrofit2.Response;
final class ResultObservable<T> extends Observable<Result<T>> {
private final Observable<Response<T>> upstream;
ResultObservable(Observable<Response<T>> upstream) {
this.upstream = upstream;
}
@Override
protected void subscribeActual(Observer<? super Result<T>> observer) {
upstream.subscribe(new ResultObserver<>(observer));
}
private static class ResultObserver<R> implements Observer<Response<R>> {
private final Observer<? super Result<R>> observer;
ResultObserver(Observer<? super Result<R>> observer) {
this.observer = observer;
}
@Override
public void onSubscribe(Disposable disposable) {
observer.onSubscribe(disposable);
}
@Override
public void onNext(Response<R> response) {
observer.onNext(Result.response(response));
}
@Override
public void onError(Throwable throwable) {
try {
observer.onNext(Result.error(throwable));
} catch (Throwable t) {
try {
observer.onError(t);
} catch (Throwable inner) {
Exceptions.throwIfFatal(inner);
RxJavaPlugins.onError(new CompositeException(t, inner));
}
return;
}
observer.onComplete();
}
@Override
public void onComplete() {
observer.onComplete();
}
}
}
| 3,794 |
0 | Create_ds/retrofit/retrofit-adapters/rxjava3/src/main/java/retrofit2/adapter | Create_ds/retrofit/retrofit-adapters/rxjava3/src/main/java/retrofit2/adapter/rxjava3/CallExecuteObservable.java | /*
* Copyright (C) 2020 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.rxjava3;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.exceptions.CompositeException;
import io.reactivex.rxjava3.exceptions.Exceptions;
import io.reactivex.rxjava3.plugins.RxJavaPlugins;
import retrofit2.Call;
import retrofit2.Response;
final class CallExecuteObservable<T> extends Observable<Response<T>> {
private final Call<T> originalCall;
CallExecuteObservable(Call<T> originalCall) {
this.originalCall = originalCall;
}
@Override
protected void subscribeActual(Observer<? super Response<T>> observer) {
// Since Call is a one-shot type, clone it for each new observer.
Call<T> call = originalCall.clone();
CallDisposable disposable = new CallDisposable(call);
observer.onSubscribe(disposable);
if (disposable.isDisposed()) {
return;
}
boolean terminated = false;
try {
Response<T> response = call.execute();
if (!disposable.isDisposed()) {
observer.onNext(response);
}
if (!disposable.isDisposed()) {
terminated = true;
observer.onComplete();
}
} catch (Throwable t) {
Exceptions.throwIfFatal(t);
if (terminated) {
RxJavaPlugins.onError(t);
} else if (!disposable.isDisposed()) {
try {
observer.onError(t);
} catch (Throwable inner) {
Exceptions.throwIfFatal(inner);
RxJavaPlugins.onError(new CompositeException(t, inner));
}
}
}
}
private static final class CallDisposable implements Disposable {
private final Call<?> call;
private volatile boolean disposed;
CallDisposable(Call<?> call) {
this.call = call;
}
@Override
public void dispose() {
disposed = true;
call.cancel();
}
@Override
public boolean isDisposed() {
return disposed;
}
}
}
| 3,795 |
0 | Create_ds/retrofit/retrofit-adapters/rxjava3/src/main/java/retrofit2/adapter | Create_ds/retrofit/retrofit-adapters/rxjava3/src/main/java/retrofit2/adapter/rxjava3/HttpException.java | /*
* Copyright (C) 2020 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.rxjava3;
import retrofit2.Response;
/** @deprecated Use {@link retrofit2.HttpException}. */
@Deprecated
public final class HttpException extends retrofit2.HttpException {
public HttpException(Response<?> response) {
super(response);
}
}
| 3,796 |
0 | Create_ds/retrofit/retrofit-adapters/rxjava3/src/main/java/retrofit2/adapter | Create_ds/retrofit/retrofit-adapters/rxjava3/src/main/java/retrofit2/adapter/rxjava3/Result.java | /*
* Copyright (C) 2020 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.rxjava3;
import java.io.IOException;
import javax.annotation.Nullable;
import retrofit2.Response;
/** The result of executing an HTTP request. */
public final class Result<T> {
@SuppressWarnings("ConstantConditions") // Guarding public API nullability.
public static <T> Result<T> error(Throwable error) {
if (error == null) throw new NullPointerException("error == null");
return new Result<>(null, error);
}
@SuppressWarnings("ConstantConditions") // Guarding public API nullability.
public static <T> Result<T> response(Response<T> response) {
if (response == null) throw new NullPointerException("response == null");
return new Result<>(response, null);
}
private final @Nullable Response<T> response;
private final @Nullable Throwable error;
private Result(@Nullable Response<T> response, @Nullable Throwable error) {
this.response = response;
this.error = error;
}
/**
* The response received from executing an HTTP request. Only present when {@link #isError()} is
* false, null otherwise.
*/
public @Nullable Response<T> response() {
return response;
}
/**
* The error experienced while attempting to execute an HTTP request. Only present when {@link
* #isError()} is true, null otherwise.
*
* <p>If the error is an {@link IOException} then there was a problem with the transport to the
* remote server. Any other exception type indicates an unexpected failure and should be
* considered fatal (configuration error, programming error, etc.).
*/
public @Nullable Throwable error() {
return error;
}
/** {@code true} if the request resulted in an error. See {@link #error()} for the cause. */
public boolean isError() {
return error != null;
}
}
| 3,797 |
0 | Create_ds/retrofit/retrofit-adapters/rxjava3/src/main/java/retrofit2/adapter | Create_ds/retrofit/retrofit-adapters/rxjava3/src/main/java/retrofit2/adapter/rxjava3/RxJava3CallAdapterFactory.java | /*
* Copyright (C) 2020 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.rxjava3;
import io.reactivex.rxjava3.core.Completable;
import io.reactivex.rxjava3.core.Flowable;
import io.reactivex.rxjava3.core.Maybe;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.core.Scheduler;
import io.reactivex.rxjava3.core.Single;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import javax.annotation.Nullable;
import retrofit2.CallAdapter;
import retrofit2.HttpException;
import retrofit2.Response;
import retrofit2.Retrofit;
/**
* A {@linkplain CallAdapter.Factory call adapter} which uses RxJava 3 for creating observables.
*
* <p>Adding this class to {@link Retrofit} allows you to return an {@link Observable}, {@link
* Flowable}, {@link Single}, {@link Completable} or {@link Maybe} from service methods.
*
* <pre><code>
* interface MyService {
* @GET("user/me")
* Observable<User> getUser()
* }
* </code></pre>
*
* There are three configurations supported for the {@code Observable}, {@code Flowable}, {@code
* Single}, {@link Completable} and {@code Maybe} type parameter:
*
* <ul>
* <li>Direct body (e.g., {@code Observable<User>}) calls {@code onNext} with the deserialized
* body for 2XX responses and calls {@code onError} with {@link HttpException} for non-2XX
* responses and {@link IOException} for network errors.
* <li>Response wrapped body (e.g., {@code Observable<Response<User>>}) calls {@code onNext} with
* a {@link Response} object for all HTTP responses and calls {@code onError} with {@link
* IOException} for network errors
* <li>Result wrapped body (e.g., {@code Observable<Result<User>>}) calls {@code onNext} with a
* {@link Result} object for all HTTP responses and errors.
* </ul>
*/
public final class RxJava3CallAdapterFactory extends CallAdapter.Factory {
/**
* Returns an instance which creates asynchronous observables that run on a background thread by
* default. Applying {@code subscribeOn(..)} has no effect on instances created by the returned
* factory.
*/
public static RxJava3CallAdapterFactory create() {
return new RxJava3CallAdapterFactory(null, true);
}
/**
* Returns an instance which creates synchronous observables that do not operate on any scheduler
* by default. Applying {@code subscribeOn(..)} will change the scheduler on which the HTTP calls
* are made.
*/
public static RxJava3CallAdapterFactory createSynchronous() {
return new RxJava3CallAdapterFactory(null, false);
}
/**
* Returns an instance which creates synchronous observables that {@code subscribeOn(..)} the
* supplied {@code scheduler} by default.
*/
@SuppressWarnings("ConstantConditions") // Guarding public API nullability.
public static RxJava3CallAdapterFactory createWithScheduler(Scheduler scheduler) {
if (scheduler == null) throw new NullPointerException("scheduler == null");
return new RxJava3CallAdapterFactory(scheduler, false);
}
private final @Nullable Scheduler scheduler;
private final boolean isAsync;
private RxJava3CallAdapterFactory(@Nullable Scheduler scheduler, boolean isAsync) {
this.scheduler = scheduler;
this.isAsync = isAsync;
}
@Override
public @Nullable CallAdapter<?, ?> get(
Type returnType, Annotation[] annotations, Retrofit retrofit) {
Class<?> rawType = getRawType(returnType);
if (rawType == Completable.class) {
// Completable is not parameterized (which is what the rest of this method deals with) so it
// can only be created with a single configuration.
return new RxJava3CallAdapter(
Void.class, scheduler, isAsync, false, true, false, false, false, true);
}
boolean isFlowable = rawType == Flowable.class;
boolean isSingle = rawType == Single.class;
boolean isMaybe = rawType == Maybe.class;
if (rawType != Observable.class && !isFlowable && !isSingle && !isMaybe) {
return null;
}
boolean isResult = false;
boolean isBody = false;
Type responseType;
if (!(returnType instanceof ParameterizedType)) {
String name =
isFlowable ? "Flowable" : isSingle ? "Single" : isMaybe ? "Maybe" : "Observable";
throw new IllegalStateException(
name
+ " return type must be parameterized"
+ " as "
+ name
+ "<Foo> or "
+ name
+ "<? extends Foo>");
}
Type observableType = getParameterUpperBound(0, (ParameterizedType) returnType);
Class<?> rawObservableType = getRawType(observableType);
if (rawObservableType == Response.class) {
if (!(observableType instanceof ParameterizedType)) {
throw new IllegalStateException(
"Response must be parameterized" + " as Response<Foo> or Response<? extends Foo>");
}
responseType = getParameterUpperBound(0, (ParameterizedType) observableType);
} else if (rawObservableType == Result.class) {
if (!(observableType instanceof ParameterizedType)) {
throw new IllegalStateException(
"Result must be parameterized" + " as Result<Foo> or Result<? extends Foo>");
}
responseType = getParameterUpperBound(0, (ParameterizedType) observableType);
isResult = true;
} else {
responseType = observableType;
isBody = true;
}
return new RxJava3CallAdapter(
responseType, scheduler, isAsync, isResult, isBody, isFlowable, isSingle, isMaybe, false);
}
}
| 3,798 |
0 | Create_ds/retrofit/retrofit-adapters/rxjava3/src/main/java/retrofit2/adapter | Create_ds/retrofit/retrofit-adapters/rxjava3/src/main/java/retrofit2/adapter/rxjava3/package-info.java | @retrofit2.internal.EverythingIsNonNull
package retrofit2.adapter.rxjava3;
| 3,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.