├── .gitattributes ├── gradle ├── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties └── libs.versions.toml ├── renovate.json ├── retrofit2-synchronous-adapter ├── src │ ├── main │ │ └── java │ │ │ └── com │ │ │ └── jaredsburrows │ │ │ └── retrofit2 │ │ │ └── adapter │ │ │ └── synchronous │ │ │ ├── package-info.java │ │ │ ├── SynchronousBodyCallAdapter.java │ │ │ ├── SynchronousResponseCallAdapter.java │ │ │ └── SynchronousCallAdapterFactory.java │ └── test │ │ └── java │ │ ├── retrofit2 │ │ └── helpers │ │ │ └── StringConverterFactory.java │ │ └── com │ │ └── jaredsburrows │ │ └── retrofit2 │ │ └── adapter │ │ └── synchronous │ │ ├── SynchronousCallAdapterFactoryTest.java │ │ ├── ExampleUsageTest.java │ │ ├── SynchronousGsonConverterFactoryTest.java │ │ └── SynchronousCallTest.java ├── gradle.properties └── build.gradle ├── .github ├── dependabot.yml └── workflows │ └── build.yml ├── .editorconfig ├── settings.gradle ├── CHANGELOG.md ├── gradle.properties ├── mkdocs.yml ├── .gitignore ├── gradlew.bat ├── README.md ├── gradlew └── LICENSE /.gitattributes: -------------------------------------------------------------------------------- 1 | # Set the default behavior, in case people don't have core.autocrlf set. 2 | * text eol=lf 3 | *.bat eol=crlf 4 | *.jar binary 5 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jaredsburrows/retrofit2-synchronous-adapter/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /renovate.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://docs.renovatebot.com/renovate-schema.json", 3 | "extends": [ 4 | "config:recommended" 5 | ], 6 | "semanticCommits": "disabled" 7 | } 8 | -------------------------------------------------------------------------------- /retrofit2-synchronous-adapter/src/main/java/com/jaredsburrows/retrofit2/adapter/synchronous/package-info.java: -------------------------------------------------------------------------------- 1 | @retrofit2.internal.EverythingIsNonNull 2 | package com.jaredsburrows.retrofit2.adapter.synchronous; 3 | -------------------------------------------------------------------------------- /retrofit2-synchronous-adapter/gradle.properties: -------------------------------------------------------------------------------- 1 | POM_ARTIFACT_ID=retrofit2-synchronous-adapter 2 | POM_NAME=Retrofit 2 Synchronous Adapter 3 | POM_DESCRIPTION=This adapter allows synchronous return types for Retrofit 2. 4 | 5 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | 3 | updates: 4 | - package-ecosystem: "github-actions" 5 | directory: "/" 6 | schedule: 7 | interval: "weekly" 8 | - package-ecosystem: "gradle" 9 | directory: "/" 10 | schedule: 11 | interval: "weekly" 12 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-9.1.0-all.zip 4 | networkTimeout=10000 5 | validateDistributionUrl=true 6 | zipStoreBase=GRADLE_USER_HOME 7 | zipStorePath=wrapper/dists 8 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | # Change these settings to your own preference 4 | [*] 5 | indent_style = space 6 | indent_size = 2 7 | 8 | # We recommend you to keep these unchanged 9 | end_of_line = lf 10 | charset = utf-8 11 | trim_trailing_whitespace = true 12 | insert_final_newline = true 13 | 14 | [*.md] 15 | trim_trailing_whitespace = false 16 | -------------------------------------------------------------------------------- /retrofit2-synchronous-adapter/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'com.vanniktech.maven.publish' version '0.34.0' 3 | id 'java-library' 4 | } 5 | 6 | dependencies { 7 | implementation libs.retrofit 8 | 9 | compileOnly libs.jsr305 10 | 11 | testImplementation libs.junit 12 | testImplementation libs.truth 13 | testImplementation libs.mockito.inline 14 | testImplementation libs.mockwebserver 15 | testImplementation libs.gson 16 | testImplementation libs.jsr305 17 | } 18 | -------------------------------------------------------------------------------- /gradle/libs.versions.toml: -------------------------------------------------------------------------------- 1 | [versions] 2 | retrofit = "3.0.0" 3 | 4 | [libraries] 5 | gson = { module = "com.squareup.retrofit2:converter-gson", version.ref = "retrofit" } 6 | jsr305 = { module = "com.google.code.findbugs:jsr305", version = "3.0.2" } 7 | junit = { module = "junit:junit", version = "4.13.2" } 8 | mockito-inline = { module = "org.mockito:mockito-inline", version = "5.2.0" } 9 | mockwebserver = { module = "com.squareup.okhttp3:mockwebserver", version = "5.2.0" } 10 | retrofit = { module = "com.squareup.retrofit2:retrofit", version.ref = "retrofit" } 11 | truth = { module = "com.google.truth:truth", version = "1.4.4" } 12 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | pluginManagement { 2 | repositories { 3 | gradlePluginPortal() 4 | google() 5 | mavenCentral() 6 | } 7 | } 8 | 9 | plugins { 10 | id 'com.gradle.develocity' version '4.2.1' 11 | } 12 | 13 | develocity { 14 | buildScan { 15 | termsOfUseUrl = 'https://gradle.com/terms-of-service' 16 | termsOfUseAgree = 'yes' 17 | def isCI = System.getenv('CI') != null 18 | publishing.onlyIf { isCI } 19 | } 20 | } 21 | 22 | dependencyResolutionManagement { 23 | repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS) 24 | 25 | repositories { 26 | gradlePluginPortal() 27 | google() 28 | mavenCentral() 29 | } 30 | } 31 | 32 | rootProject.name = 'retrofit2-synchronous-adapter' 33 | 34 | include ':retrofit2-synchronous-adapter' 35 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Change Log 2 | 3 | ## Version 0.5.0 (2018-09-23) 4 | 5 | * Handle responses better - `Response.success` and `Response.error` 6 | * Add nonnull annotations where needed - jsr305 7 | 8 | ## Version 0.4.0 (2017-08-28) 9 | 10 | * Update nullability annotations 11 | * Add support for `Response` 12 | 13 | ## Version 0.3.0 (2017-07-11) 14 | 15 | * Throw `HttpException` when an error occurs 16 | 17 | ## Version 0.2.0 (2017-06-07) 18 | 19 | * Add nullability annotations 20 | 21 | ## Version 0.1.5 (2017-06-03) 22 | 23 | * Throw `HttpException` instead of `IOException` 24 | 25 | ## Version 0.1.4 (2017-03-07) 26 | ## Version 0.1.3 (2017-03-07) 27 | ## Version 0.1.2 (2017-03-07) 28 | ## Version 0.1.1 (2017-03-07) 29 | 30 | * Formatting changes 31 | 32 | ## Version 0.1.0 (2017-03-06) 33 | 34 | * Initial release 35 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | SONATYPE_HOST=DEFAULT 2 | SONATYPE_AUTOMATIC_RELEASE=true 3 | RELEASE_SIGNING_ENABLED=true 4 | 5 | GROUP=com.jaredsburrows.retrofit 6 | VERSION_NAME=0.7.0-SNAPSHOT 7 | 8 | POM_INCEPTION_YEAR=2017 9 | POM_PACKAGING=jar 10 | POM_URL=https://github.com/jaredsburrows/retrofit2-synchronous-adapter 11 | 12 | POM_ISSUE_SYSTEM=github 13 | POM_ISSUE_URL=https://github.com/jaredsburrows/retrofit2-synchronous-adapter/issues 14 | 15 | POM_SCM_URL=https://github.com/jaredsburrows/retrofit2-synchronous-adapter 16 | POM_SCM_CONNECTION=scm:git:git://github.com/jaredsburrows/retrofit2-synchronous-adapter.git 17 | POM_SCM_DEV_CONNECTION=scm:git:ssh://git@github.com/jaredsburrows/retrofit2-synchronous-adapter.git 18 | 19 | POM_LICENSE_NAME=The Apache Software License, Version 2.0 20 | POM_LICENSE_URL=http://www.apache.org/licenses/LICENSE-2.0.txt 21 | POM_LICENSE_DIST=repo 22 | 23 | POM_DEVELOPER_ID=jaredsburrows 24 | POM_DEVELOPER_NAME=Jared Burrows 25 | POM_DEVELOPER_EMAIL=jaredsburrows@gmail.com 26 | -------------------------------------------------------------------------------- /retrofit2-synchronous-adapter/src/main/java/com/jaredsburrows/retrofit2/adapter/synchronous/SynchronousBodyCallAdapter.java: -------------------------------------------------------------------------------- 1 | package com.jaredsburrows.retrofit2.adapter.synchronous; 2 | 3 | import java.io.IOException; 4 | import java.lang.reflect.Type; 5 | import javax.annotation.Nullable; 6 | import retrofit2.Call; 7 | import retrofit2.CallAdapter; 8 | import retrofit2.HttpException; 9 | import retrofit2.Response; 10 | 11 | /** 12 | * {@link CallAdapter} allows you to return deserialized type: 13 | *

14 |  * interface MyService {
15 |  *   @GET("user/me")
16 |  *   User getUser()
17 |  * }
18 |  * 
19 | */ 20 | final class SynchronousBodyCallAdapter implements CallAdapter { 21 | private final Type responseType; 22 | 23 | SynchronousBodyCallAdapter(Type responseType) { 24 | this.responseType = responseType; 25 | } 26 | 27 | @Override public Type responseType() { 28 | return responseType; 29 | } 30 | 31 | @Override @Nullable public Object adapt(Call call) { 32 | Response response; 33 | 34 | // Make the initial call 35 | try { 36 | response = call.execute(); 37 | } catch (IOException e) { 38 | throw new RuntimeException(e); 39 | } 40 | 41 | // If successful(200 OK), return the response with body 42 | if (response.isSuccessful()) { 43 | return response.body(); 44 | } 45 | 46 | // If an error occurs, return HttpException including response 47 | throw new HttpException(response); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /retrofit2-synchronous-adapter/src/test/java/retrofit2/helpers/StringConverterFactory.java: -------------------------------------------------------------------------------- 1 | package retrofit2.helpers; 2 | 3 | import java.lang.annotation.Annotation; 4 | import java.lang.reflect.Type; 5 | import javax.annotation.Nullable; 6 | import okhttp3.MediaType; 7 | import okhttp3.RequestBody; 8 | import okhttp3.ResponseBody; 9 | import retrofit2.Converter; 10 | import retrofit2.Retrofit; 11 | 12 | /** 13 | * From: https://github.com/square/retrofit/blob/d51805b9af79d631b43b5e8b85d12581989b1d49/retrofit-adapters/guava/src/test/java/retrofit2/adapter/guava/StringConverterFactory.java#L26 14 | */ 15 | public class StringConverterFactory extends Converter.Factory { 16 | private static final MediaType MEDIA_TYPE = MediaType.get("text/plain"); 17 | 18 | @Nullable @Override public Converter responseBodyConverter(Type type, 19 | Annotation[] annotations, Retrofit retrofit) { 20 | if (String.class.equals(type)) { 21 | return (Converter) ResponseBody::string; 22 | } 23 | return null; 24 | } 25 | 26 | @Nullable @Override public Converter requestBodyConverter(Type type, 27 | Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) { 28 | if (String.class.equals(type)) { 29 | return (Converter) StringConverterFactory::create; 30 | } 31 | return null; 32 | } 33 | 34 | @SuppressWarnings("deprecation") 35 | private static RequestBody create(String value) { 36 | return RequestBody.create(MEDIA_TYPE, value); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /mkdocs.yml: -------------------------------------------------------------------------------- 1 | site_name: "Retrofit2 Synchronous Adapter" 2 | site_url: https://jaredsburrows.github.io/retrofit2-synchronous-adapter 3 | repo_name: retrofit2-synchronous-adapter 4 | repo_url: https://github.com/jaredsburrows/retrofit2-synchronous-adapter 5 | site_description: "Retrofit2 Synchronous Adapter" 6 | site_author: Jared Burrows 7 | remote_branch: gh-pages 8 | edit_uri: "" 9 | 10 | copyright: 'Copyright © 2024 Jared Burrows' 11 | 12 | theme: 13 | name: 'material' 14 | palette: 15 | - media: "(prefers-color-scheme: light)" 16 | scheme: default 17 | toggle: 18 | icon: octicons/sun-24 19 | name: "Switch to Dark Mode" 20 | - media: "(prefers-color-scheme: dark)" 21 | scheme: slate 22 | toggle: 23 | icon: octicons/moon-24 24 | name: "Switch to Light Mode" 25 | features: 26 | - navigation.sections 27 | - navigation.tracking 28 | - navigation.tabs 29 | - content.tabs.link 30 | - toc.integrate 31 | 32 | markdown_extensions: 33 | - admonition 34 | - attr_list 35 | - codehilite: 36 | guess_lang: false 37 | - footnotes 38 | - meta 39 | - pymdownx.betterem: 40 | smart_enable: all 41 | - pymdownx.caret 42 | - pymdownx.details 43 | - pymdownx.emoji: 44 | - pymdownx.inlinehilite 45 | - pymdownx.magiclink 46 | - pymdownx.smartsymbols 47 | - pymdownx.superfences 48 | - pymdownx.tabbed: 49 | alternate_style: true 50 | - pymdownx.tilde 51 | - smarty 52 | - tables 53 | - toc: 54 | permalink: true 55 | 56 | nav: 57 | - 'Overview': 58 | - 'Overview': index.md 59 | - 'API': javadoc/ 60 | - 'Change Log': 61 | - 'Change Log': changelog.md 62 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Created by https://www.gitignore.io/api/osx,intellij,android,gradle,java 2 | 3 | ### OSX ### 4 | .DS_Store 5 | .AppleDouble 6 | .LSOverride 7 | 8 | # Files that might appear in the root of a volume 9 | .DocumentRevisions-V100 10 | .fseventsd 11 | .Spotlight-V100 12 | .TemporaryItems 13 | .Trashes 14 | .VolumeIcon.icns 15 | 16 | ### Intellij ### 17 | .idea/ 18 | *.iml 19 | 20 | ### Android ### 21 | # Built application files 22 | *.apk 23 | *.ap_ 24 | 25 | # Files for the Dalvik VM 26 | *.dex 27 | 28 | # Java class files 29 | *.class 30 | 31 | # Gradle files 32 | .gradle/ 33 | build/ 34 | 35 | # Local configuration file (sdk path, etc) 36 | local.properties 37 | 38 | # Proguard folder generated by Eclipse 39 | proguard/ 40 | 41 | # Log Files 42 | *.log 43 | 44 | # Android Studio Navigation editor temp files 45 | .navigation/ 46 | 47 | # Android Studio captures folder 48 | captures/ 49 | 50 | # Intellij 51 | *.iml 52 | 53 | # Keystore files 54 | *.jks 55 | 56 | ### Android Patch ### 57 | gen-external-apklibs 58 | 59 | 60 | ### Gradle ### 61 | .gradle 62 | build/ 63 | /buildSrc 64 | 65 | # Ignore Gradle GUI config 66 | gradle-app.setting 67 | 68 | # Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored) 69 | !gradle-wrapper.jar 70 | 71 | # Cache of project 72 | .gradletasknamecache 73 | 74 | # # Work around https://youtrack.jetbrains.com/issue/IDEA-116898 75 | # gradle/wrapper/gradle-wrapper.properties 76 | 77 | 78 | ### Java ### 79 | *.class 80 | 81 | # Mobile Tools for Java (J2ME) 82 | .mtj.tmp/ 83 | 84 | # Package Files # 85 | *.jar 86 | *.war 87 | *.ear 88 | 89 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 90 | hs_err_pid* 91 | -------------------------------------------------------------------------------- /retrofit2-synchronous-adapter/src/main/java/com/jaredsburrows/retrofit2/adapter/synchronous/SynchronousResponseCallAdapter.java: -------------------------------------------------------------------------------- 1 | package com.jaredsburrows.retrofit2.adapter.synchronous; 2 | 3 | import java.io.IOException; 4 | import java.lang.reflect.Type; 5 | import okhttp3.MediaType; 6 | import okhttp3.ResponseBody; 7 | import retrofit2.Call; 8 | import retrofit2.CallAdapter; 9 | import retrofit2.Response; 10 | 11 | /** 12 | * {@link CallAdapter} allows you to return deserialized type wrapped in {@link Response}: 13 | *

14 |  * interface MyService {
15 |  *   @GET("user/me")
16 |  *   Response<User> getUser()
17 |  * }
18 |  * 
19 | */ 20 | final class SynchronousResponseCallAdapter implements CallAdapter> { 21 | private static final MediaType DEFAULT_MEDIA_TYPE = MediaType.get("text/plain"); 22 | private static final String DEFAULT_EMPTY_CONTENT = ""; 23 | private final Type responseType; 24 | 25 | SynchronousResponseCallAdapter(Type responseType) { 26 | this.responseType = responseType; 27 | } 28 | 29 | @Override public Type responseType() { 30 | return responseType; 31 | } 32 | 33 | @Override public Response adapt(Call call) { 34 | Response response; 35 | 36 | // Make the initial call 37 | try { 38 | response = call.execute(); 39 | } catch (IOException e) { 40 | throw new RuntimeException(e); 41 | } 42 | 43 | // If successful(200 OK) and Response type, return the response with body 44 | if (response.isSuccessful()) { 45 | return Response.success(response.body(), response.raw()); 46 | } 47 | 48 | // If unsuccessful(non 200 OK) and Response type, return the response with body 49 | ResponseBody errorBody = response.errorBody(); 50 | okhttp3.Response raw = response.raw(); 51 | if (errorBody == null) { 52 | return Response.error(ResponseBody.create(DEFAULT_MEDIA_TYPE, DEFAULT_EMPTY_CONTENT), raw); 53 | } else { 54 | return Response.error(errorBody, raw); 55 | } 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /retrofit2-synchronous-adapter/src/main/java/com/jaredsburrows/retrofit2/adapter/synchronous/SynchronousCallAdapterFactory.java: -------------------------------------------------------------------------------- 1 | package com.jaredsburrows.retrofit2.adapter.synchronous; 2 | 3 | import java.lang.annotation.Annotation; 4 | import java.lang.reflect.ParameterizedType; 5 | import java.lang.reflect.Type; 6 | import javax.annotation.Nullable; 7 | import retrofit2.Call; 8 | import retrofit2.CallAdapter; 9 | import retrofit2.Response; 10 | import retrofit2.Retrofit; 11 | 12 | /** 13 | * A synchronous {@link CallAdapter.Factory} that uses the same thread for both I/O and 14 | * application-level callbacks. 15 | *

16 | * Adding this class to {@link Retrofit} allows you to return direct deserialized type from service 17 | * methods: 18 | *


19 |  * interface MyService {
20 |  *   @GET("user/me")
21 |  *   User getUser()
22 |  * }
23 |  * 
24 | * or allows you to return deserialized type wrapped in {@link Response}: 25 | *

26 |  * interface MyService {
27 |  *   @GET("user/me")
28 |  *   Response<User> getUser()
29 |  * }
30 |  * 
31 | * {@link CallAdapter.Factory} returns the deserialized body for 2XX responses, sets {@link 32 | * retrofit2.HttpException} errors for non-2XX responses, and for network errors. 33 | */ 34 | public final class SynchronousCallAdapterFactory extends CallAdapter.Factory { 35 | private SynchronousCallAdapterFactory() { 36 | } 37 | 38 | public static CallAdapter.Factory create() { 39 | return new SynchronousCallAdapterFactory(); 40 | } 41 | 42 | @Override @Nullable public CallAdapter get( 43 | Type returnType, Annotation[] annotations, Retrofit retrofit) { 44 | // Prevent the Async calls via Call class 45 | if (getRawType(returnType) == Call.class) { 46 | return null; 47 | } 48 | 49 | // Return type is not Response. Use it for body-only adapter. 50 | if (getRawType(returnType) != Response.class) { 51 | return new SynchronousBodyCallAdapter<>(returnType); 52 | } 53 | 54 | // Make sure Response is parameterized 55 | if (!(returnType instanceof ParameterizedType)) { 56 | throw new IllegalStateException( 57 | "Response must be parameterized as Response or Response"); 58 | } 59 | 60 | // Handle Response return types 61 | Type responseType = getParameterUpperBound(0, (ParameterizedType) returnType); 62 | return new SynchronousResponseCallAdapter<>(responseType); 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | @rem SPDX-License-Identifier: Apache-2.0 17 | @rem 18 | 19 | @if "%DEBUG%"=="" @echo off 20 | @rem ########################################################################## 21 | @rem 22 | @rem Gradle startup script for Windows 23 | @rem 24 | @rem ########################################################################## 25 | 26 | @rem Set local scope for the variables with windows NT shell 27 | if "%OS%"=="Windows_NT" setlocal 28 | 29 | set DIRNAME=%~dp0 30 | if "%DIRNAME%"=="" set DIRNAME=. 31 | @rem This is normally unused 32 | set APP_BASE_NAME=%~n0 33 | set APP_HOME=%DIRNAME% 34 | 35 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 36 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 37 | 38 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 39 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 40 | 41 | @rem Find java.exe 42 | if defined JAVA_HOME goto findJavaFromJavaHome 43 | 44 | set JAVA_EXE=java.exe 45 | %JAVA_EXE% -version >NUL 2>&1 46 | if %ERRORLEVEL% equ 0 goto execute 47 | 48 | echo. 1>&2 49 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 50 | echo. 1>&2 51 | echo Please set the JAVA_HOME variable in your environment to match the 1>&2 52 | echo location of your Java installation. 1>&2 53 | 54 | goto fail 55 | 56 | :findJavaFromJavaHome 57 | set JAVA_HOME=%JAVA_HOME:"=% 58 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 59 | 60 | if exist "%JAVA_EXE%" goto execute 61 | 62 | echo. 1>&2 63 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 64 | echo. 1>&2 65 | echo Please set the JAVA_HOME variable in your environment to match the 1>&2 66 | echo location of your Java installation. 1>&2 67 | 68 | goto fail 69 | 70 | :execute 71 | @rem Setup the command line 72 | 73 | 74 | 75 | @rem Execute Gradle 76 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* 77 | 78 | :end 79 | @rem End local scope for the variables with windows NT shell 80 | if %ERRORLEVEL% equ 0 goto mainEnd 81 | 82 | :fail 83 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 84 | rem the _cmd.exe /c_ return code! 85 | set EXIT_CODE=%ERRORLEVEL% 86 | if %EXIT_CODE% equ 0 set EXIT_CODE=1 87 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% 88 | exit /b %EXIT_CODE% 89 | 90 | :mainEnd 91 | if "%OS%"=="Windows_NT" endlocal 92 | 93 | :omega 94 | -------------------------------------------------------------------------------- /retrofit2-synchronous-adapter/src/test/java/com/jaredsburrows/retrofit2/adapter/synchronous/SynchronousCallAdapterFactoryTest.java: -------------------------------------------------------------------------------- 1 | package com.jaredsburrows.retrofit2.adapter.synchronous; 2 | 3 | import static com.google.common.truth.Truth.assertThat; 4 | import static org.junit.Assert.fail; 5 | 6 | import com.google.gson.reflect.TypeToken; 7 | import java.lang.annotation.Annotation; 8 | import java.lang.reflect.Type; 9 | import java.util.List; 10 | import okhttp3.mockwebserver.MockWebServer; 11 | import org.junit.Before; 12 | import org.junit.Rule; 13 | import org.junit.Test; 14 | import retrofit2.Call; 15 | import retrofit2.CallAdapter; 16 | import retrofit2.Response; 17 | import retrofit2.Retrofit; 18 | import retrofit2.helpers.StringConverterFactory; 19 | 20 | /** 21 | * This test does not use {@link retrofit2.Call} and uses the {@link SynchronousCallAdapterFactory} 22 | * instead. 23 | * From: https://github.com/square/retrofit/blob/d51805b9af79d631b43b5e8b85d12581989b1d49/retrofit-adapters/guava/src/test/java/retrofit2/adapter/guava/GuavaCallAdapterFactoryTest.java#L34 24 | */ 25 | public final class SynchronousCallAdapterFactoryTest { 26 | @Rule public final MockWebServer server = new MockWebServer(); 27 | private static final Annotation[] NO_ANNOTATIONS = new Annotation[0]; 28 | private final CallAdapter.Factory factory = SynchronousCallAdapterFactory.create(); 29 | private Retrofit retrofit; 30 | 31 | @Before public void setUp() { 32 | retrofit = new Retrofit.Builder() 33 | .baseUrl(server.url("/")) 34 | .addConverterFactory(new StringConverterFactory()) 35 | .addCallAdapterFactory(SynchronousCallAdapterFactory.create()) // Add synchronous adapter 36 | .addCallAdapterFactory(factory) 37 | .build(); 38 | } 39 | 40 | @Test public void responseType() { 41 | Type bodyClass = new TypeToken() { 42 | }.getType(); 43 | assertThat(factory.get(bodyClass, NO_ANNOTATIONS, retrofit).responseType()) 44 | .isEqualTo(String.class); 45 | Type bodyGeneric = new TypeToken>() { 46 | }.getType(); 47 | assertThat(factory.get(bodyGeneric, NO_ANNOTATIONS, retrofit).responseType()) 48 | .isEqualTo(new TypeToken>() { 49 | }.getType()); 50 | Type responseClass = new TypeToken>() { 51 | }.getType(); 52 | assertThat(factory.get(responseClass, NO_ANNOTATIONS, retrofit).responseType()) 53 | .isEqualTo(String.class); 54 | Type responseWildcard = new TypeToken>() { 55 | }.getType(); 56 | assertThat(factory.get(responseWildcard, NO_ANNOTATIONS, retrofit).responseType()) 57 | .isEqualTo(String.class); 58 | } 59 | 60 | @Test public void rawTypeReturnsNull() { 61 | // Act and Assert 62 | assertThat(factory.get(Call.class, NO_ANNOTATIONS, retrofit)).isNull(); 63 | } 64 | 65 | @SuppressWarnings("rawtypes") // we want to ensure raw types cannot be used 66 | @Test public void rawResponseTypeThrows() { 67 | Type observableType = new TypeToken() { 68 | }.getType(); 69 | try { 70 | factory.get(observableType, NO_ANNOTATIONS, retrofit); 71 | fail(); 72 | } catch (IllegalStateException e) { 73 | assertThat(e).hasMessageThat().isEqualTo( 74 | "Response must be parameterized as Response or Response"); 75 | } 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Retrofit 2 Synchronous Adapter 2 | 3 | [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://www.apache.org/licenses/LICENSE-2.0) 4 | [![Maven](https://img.shields.io/maven-central/v/com.jaredsburrows.retrofit/retrofit2-synchronous-adapter?label=maven&style=flat)](https://search.maven.org/artifact/com.jaredsburrows.retrofit/retrofit2-synchronous-adapter) 5 | [![Build](https://github.com/jaredsburrows/retrofit2-synchronous-adapter/actions/workflows/build.yml/badge.svg)](https://github.com/jaredsburrows/retrofit2-synchronous-adapter/actions/workflows/build.yml) 6 | [![Twitter Follow](https://img.shields.io/twitter/follow/jaredsburrows.svg?style=social)](https://twitter.com/jaredsburrows) 7 | 8 | A synchronous `CallAdapter.Factory` implementation for Retrofit 2. 9 | 10 | This project brings Retrofit 1's synchronous usage to Retrofit 2. 11 | 12 | ## Usage 13 | 14 | ```java 15 | // Setup retrofit 16 | Retrofit retrofit = new Retrofit.Builder() 17 | .baseUrl("https://api.example.com") 18 | .addCallAdapterFactory(SynchronousCallAdapterFactory.create()) 19 | .build(); 20 | 21 | // Create your service 22 | interface Service { 23 | @GET("/") ApiResponse response(); // Return type directly 24 | @GET("/") Response responseApi(); // Return Response information with type 25 | @GET("/") ResponseBody body(); // Return generic type directly 26 | @GET("/") Response responseBody(); // Return Response information with generic type 27 | } 28 | 29 | // Initiate the service 30 | Service example = retrofit.create(Service.class); 31 | 32 | // Make your HTTP request 33 | ApiResponse response = example.response(); 34 | ResponseBody body = example.body(); 35 | Response responseBody = example.responseBody(); 36 | Response responseApi = example.responseApi(); 37 | ``` 38 | 39 | ## Download 40 | 41 | **Release:** 42 | ```groovy 43 | repositories { 44 | mavenCentral() 45 | } 46 | 47 | dependencies { 48 | compile 'com.jaredsburrows.retrofit:retrofit2-synchronous-adapter:0.6.0' 49 | } 50 | ``` 51 | Release versions are available in the [Sonatype's release repository](https://repo1.maven.org/maven2/com/jaredsburrows/retrofit/retrofit2-synchronous-adapter/). 52 | 53 | **Snapshot:** 54 | ```groovy 55 | repositories { 56 | maven { url 'https://oss.sonatype.org/content/repositories/snapshots' } 57 | } 58 | 59 | dependencies { 60 | compile 'com.jaredsburrows.retrofit:retrofit2-synchronous-adapter:0.7.0-SNAPSHOT' 61 | } 62 | ``` 63 | Snapshot versions are available in the [Sonatype's snapshots repository](https://oss.sonatype.org/content/repositories/snapshots/com/jaredsburrows/retrofit/retrofit2-synchronous-adapter/). 64 | 65 | Documentation is available at [jaredsburrows.github.io/retrofit2-synchronous-adapter/docs/0.x/](https://jaredsburrows.github.io/retrofit2-synchronous-adapter/docs/0.x/). 66 | 67 | ## License 68 | 69 | ``` 70 | Copyright (C) 2017 Jared Burrows 71 | 72 | Licensed under the Apache License, Version 2.0 (the "License"); 73 | you may not use this file except in compliance with the License. 74 | You may obtain a copy of the License at 75 | 76 | https://www.apache.org/licenses/LICENSE-2.0 77 | 78 | Unless required by applicable law or agreed to in writing, software 79 | distributed under the License is distributed on an "AS IS" BASIS, 80 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 81 | See the License for the specific language governing permissions and 82 | limitations under the License. 83 | ``` 84 | -------------------------------------------------------------------------------- /retrofit2-synchronous-adapter/src/test/java/com/jaredsburrows/retrofit2/adapter/synchronous/ExampleUsageTest.java: -------------------------------------------------------------------------------- 1 | package com.jaredsburrows.retrofit2.adapter.synchronous; 2 | 3 | import static com.google.common.truth.Truth.assertThat; 4 | 5 | import com.google.gson.annotations.SerializedName; 6 | import okhttp3.ResponseBody; 7 | import okhttp3.mockwebserver.MockResponse; 8 | import okhttp3.mockwebserver.MockWebServer; 9 | import org.junit.Before; 10 | import org.junit.Rule; 11 | import org.junit.Test; 12 | import retrofit2.Response; 13 | import retrofit2.Retrofit; 14 | import retrofit2.converter.gson.GsonConverterFactory; 15 | import retrofit2.http.GET; 16 | 17 | /** 18 | * This test is to valid the code in the readme. 19 | */ 20 | public final class ExampleUsageTest { 21 | @Rule public final MockWebServer server = new MockWebServer(); 22 | private Service example; 23 | 24 | interface Service { 25 | @GET("/") TestDto returnDto(); 26 | 27 | @GET("/") Response responseDto(); 28 | 29 | @GET("/") Void returnVoid(); 30 | 31 | @GET("/") Response responseVoid(); 32 | 33 | @GET("/") ResponseBody returnResponseBody(); 34 | 35 | @GET("/") Response responseResponseBody(); 36 | } 37 | 38 | static class TestDto { 39 | @SerializedName("name") String name; 40 | } 41 | 42 | @Before public void setUp() { 43 | Retrofit retrofit = new Retrofit.Builder().baseUrl(server.url("/")) 44 | .addCallAdapterFactory(SynchronousCallAdapterFactory.create()) // Add synchronous adapter 45 | .addConverterFactory(GsonConverterFactory.create()) 46 | .build(); 47 | example = retrofit.create(Service.class); 48 | } 49 | 50 | @Test public void testGsonDtoType() { 51 | server.enqueue(new MockResponse().setBody("{\"name\":\"value\"}")); 52 | TestDto response = example.returnDto(); 53 | assertThat(response.name).isEqualTo("value"); 54 | } 55 | 56 | @Test public void testResponseOfGsonDto() { 57 | server.enqueue(new MockResponse().setBody("{\"name\":\"value\"}")); 58 | Response response = example.responseDto(); 59 | assertThat(response.body().name).isEqualTo("value"); 60 | } 61 | 62 | @Test public void testVoidResponse() { 63 | server.enqueue(new MockResponse().setBody("{\"name\":\"value\"}")); 64 | Void response = example.returnVoid(); 65 | assertThat(response).isNull(); 66 | } 67 | 68 | @Test public void testVoidResponseNoResponse() { 69 | server.enqueue(new MockResponse()); 70 | Void response = example.returnVoid(); 71 | assertThat(response).isNull(); 72 | 73 | server.enqueue(new MockResponse().setBody("")); 74 | Void response2 = example.returnVoid(); 75 | assertThat(response2).isNull(); 76 | } 77 | 78 | @Test public void testResponseOfVoid() { 79 | server.enqueue(new MockResponse().setBody("{\"name\":\"value\"}")); 80 | Response response = example.responseVoid(); 81 | assertThat(response.body()).isNull(); 82 | } 83 | 84 | @Test public void testResponseOfVoidNoResponse() { 85 | server.enqueue(new MockResponse()); 86 | Response response = example.responseVoid(); 87 | assertThat(response.body()).isNull(); 88 | 89 | server.enqueue(new MockResponse().setBody("")); 90 | Response response2 = example.responseVoid(); 91 | assertThat(response2.body()).isNull(); 92 | } 93 | 94 | @Test public void testResponseBody() { 95 | server.enqueue(new MockResponse().setBody("{\"name\":\"value\"}")); 96 | ResponseBody response = example.returnResponseBody(); 97 | assertThat(response).isNotNull(); 98 | } 99 | 100 | @Test public void testResponseBodyNoResponse() { 101 | server.enqueue(new MockResponse()); 102 | ResponseBody response = example.returnResponseBody(); 103 | assertThat(response).isNotNull(); 104 | 105 | server.enqueue(new MockResponse().setBody("")); 106 | ResponseBody response2 = example.returnResponseBody(); 107 | assertThat(response2).isNotNull(); 108 | } 109 | 110 | @Test public void testResponseOfResponseBody() { 111 | server.enqueue(new MockResponse().setBody("{\"name\":\"value\"}")); 112 | Response response = example.responseResponseBody(); 113 | assertThat(response.body()).isNotNull(); 114 | } 115 | 116 | @Test public void testResponseOfResponseBodyNoResponse() { 117 | server.enqueue(new MockResponse()); 118 | Response response = example.responseResponseBody(); 119 | assertThat(response.body()).isNotNull(); // empty but non-null 120 | 121 | server.enqueue(new MockResponse().setBody("")); 122 | Response response2 = example.responseResponseBody(); 123 | assertThat(response2.body()).isNotNull(); // empty but non-null 124 | } 125 | } 126 | -------------------------------------------------------------------------------- /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | name: Build 2 | 3 | on: 4 | push: 5 | branches: 6 | - master 7 | pull_request: 8 | types: [ opened, labeled, unlabeled, synchronize ] 9 | 10 | env: 11 | GRADLE_OPTS: "-Dorg.gradle.jvmargs=-Xmx4g -Dorg.gradle.daemon=false -Dkotlin.incremental=false" 12 | JAVA_VERSION: 21 13 | 14 | jobs: 15 | build: 16 | runs-on: ubuntu-latest 17 | 18 | permissions: 19 | checks: write 20 | pull-requests: write 21 | 22 | steps: 23 | - name: Checkout Project 24 | uses: actions/checkout@v4.2.2 25 | 26 | - name: Setup Gradle 27 | uses: gradle/actions/setup-gradle@v4.4.1 28 | with: 29 | gradle-home-cache-cleanup: true 30 | - run: ./gradlew --version 31 | 32 | - name: Validate Gradle Wrapper 33 | uses: gradle/actions/wrapper-validation@v4.4.1 34 | 35 | - name: Configure JDK ${{ env.JAVA_VERSION }} 36 | uses: actions/setup-java@v4.7.1 37 | with: 38 | distribution: temurin 39 | java-version: ${{ env.JAVA_VERSION }} 40 | cache: gradle 41 | 42 | - name: Setup Gradle 43 | uses: gradle/actions/setup-gradle@v4.4.1 44 | with: 45 | gradle-home-cache-cleanup: true 46 | - run: ./gradlew --version 47 | 48 | - name: Run Build and Unit Tests 49 | run: ./gradlew build -s 50 | 51 | - name: Publish Test Report 52 | uses: EnricoMi/publish-unit-test-result-action@v2.20.0 53 | if: always() 54 | with: 55 | comment_mode: off 56 | files: '**/build/test-results/test/TEST-*.xml' 57 | 58 | - name: Upload Artifacts 59 | uses: actions/upload-artifact@v4.6.2 60 | if: github.repository == 'jaredsburrows/retrofit2-synchronous-adapter' && github.ref == 'refs/heads/master' 61 | with: 62 | name: retrofit2-synchronous-adapter-${{ github.workflow }}-${{ github.run_id }} 63 | path: | 64 | build/libs 65 | build/outputs 66 | build/publications 67 | build/distributions 68 | build/reports 69 | build/test-results 70 | 71 | publish: 72 | name: Publish Snapshot 73 | runs-on: ubuntu-latest 74 | if: github.repository == 'jaredsburrows/retrofit2-synchronous-adapter' && github.ref == 'refs/heads/master' 75 | needs: 76 | - build 77 | 78 | permissions: 79 | contents: read 80 | pages: write 81 | id-token: write 82 | 83 | environment: 84 | name: github-pages 85 | url: ${{ steps.deployment.outputs.page_url }} 86 | 87 | steps: 88 | - name: Checkout Project 89 | uses: actions/checkout@v4.2.2 90 | 91 | - name: Setup Gradle 92 | uses: gradle/actions/setup-gradle@v4.4.1 93 | with: 94 | gradle-home-cache-cleanup: true 95 | - run: ./gradlew --version 96 | 97 | - name: Validate Gradle Wrapper 98 | uses: gradle/actions/wrapper-validation@v4.4.1 99 | 100 | - name: Configure JDK ${{ env.JAVA_VERSION }} 101 | uses: actions/setup-java@v4.7.1 102 | with: 103 | distribution: temurin 104 | java-version: ${{ env.JAVA_VERSION }} 105 | cache: gradle 106 | 107 | - name: Setup Gradle 108 | uses: gradle/gradle-build-action@v3.5.0 109 | 110 | - name: Publish 111 | run: ./gradlew publish -s -i 112 | env: 113 | ORG_GRADLE_PROJECT_mavenCentralUsername: ${{ secrets.SONATYPE_NEXUS_USERNAME }} 114 | ORG_GRADLE_PROJECT_mavenCentralPassword: ${{ secrets.SONATYPE_NEXUS_PASSWORD }} 115 | ORG_GRADLE_PROJECT_signingInMemoryKey: ${{ secrets.SIGNING_PRIVATE_KEY }} 116 | ORG_GRADLE_PROJECT_signingInMemoryKeyPassword: ${{ secrets.SIGNING_PASSWORD }} 117 | 118 | - name: Install Python 119 | uses: actions/setup-python@v5.6.0 120 | with: 121 | python-version: 3.14.0 122 | 123 | - name: Install MkDocs Material 124 | run: pip install mkdocs-material 125 | 126 | - name: Copy docs 127 | run: | 128 | mkdir -p docs 129 | cp README.md docs/index.md 130 | cp CHANGELOG.md docs/changelog.md 131 | mv retrofit2-synchronous-adapter/build/docs/javadoc/ docs/javadoc 132 | 133 | - name: Build MkDocs 134 | run: mkdocs build 135 | 136 | - name: Upload Artifact 137 | uses: actions/upload-pages-artifact@v3.0.1 138 | with: 139 | path: site 140 | 141 | - name: Deploy to GitHub Pages 142 | id: deployment 143 | uses: actions/deploy-pages@v4.0.5 144 | 145 | # - name: Generate Docs 146 | # run: ./gradlew javadoc 147 | # 148 | # - name: Publish Website 149 | # uses: peaceiris/actions-gh-pages@v4.0.0 150 | # with: 151 | # github_token: ${{ secrets.GITHUB_TOKEN }} 152 | # publish_dir: retrofit2-synchronous-adapter/build/docs/javadoc 153 | # user_name: "Github Actions" 154 | # user_email: "action@github.com" 155 | -------------------------------------------------------------------------------- /retrofit2-synchronous-adapter/src/test/java/com/jaredsburrows/retrofit2/adapter/synchronous/SynchronousGsonConverterFactoryTest.java: -------------------------------------------------------------------------------- 1 | package com.jaredsburrows.retrofit2.adapter.synchronous; 2 | 3 | import static com.google.common.truth.Truth.assertThat; 4 | 5 | import com.google.gson.Gson; 6 | import com.google.gson.GsonBuilder; 7 | import com.google.gson.TypeAdapter; 8 | import com.google.gson.stream.JsonReader; 9 | import com.google.gson.stream.JsonToken; 10 | import com.google.gson.stream.JsonWriter; 11 | import java.io.IOException; 12 | import okhttp3.mockwebserver.MockResponse; 13 | import okhttp3.mockwebserver.MockWebServer; 14 | import okhttp3.mockwebserver.RecordedRequest; 15 | import org.junit.Before; 16 | import org.junit.Rule; 17 | import org.junit.Test; 18 | import retrofit2.Retrofit; 19 | import retrofit2.converter.gson.GsonConverterFactory; 20 | import retrofit2.http.Body; 21 | import retrofit2.http.POST; 22 | 23 | /** 24 | * This test does not use {@link retrofit2.Call} and uses the {@link SynchronousCallAdapterFactory} 25 | * instead. 26 | * From: https://github.com/square/retrofit/blob/d51805b9af79d631b43b5e8b85d12581989b1d49/retrofit-converters/gson/src/test/java/retrofit2/converter/gson/GsonConverterFactoryTest.java#L42 27 | */ 28 | public final class SynchronousGsonConverterFactoryTest { 29 | interface AnInterface { 30 | String getName(); 31 | } 32 | 33 | static class AnImplementation implements AnInterface { 34 | private final String theName; 35 | 36 | AnImplementation(String name) { 37 | theName = name; 38 | } 39 | 40 | @Override public String getName() { 41 | return theName; 42 | } 43 | } 44 | 45 | static class AnInterfaceAdapter extends TypeAdapter { 46 | @Override public void write(JsonWriter jsonWriter, AnInterface anInterface) throws IOException { 47 | jsonWriter.beginObject(); 48 | jsonWriter.name("name").value(anInterface.getName()); 49 | jsonWriter.endObject(); 50 | } 51 | 52 | @Override public AnInterface read(JsonReader jsonReader) throws IOException { 53 | jsonReader.beginObject(); 54 | 55 | String name = null; 56 | while (jsonReader.peek() != JsonToken.END_OBJECT) { 57 | if ("name".equals(jsonReader.nextName())) { 58 | name = jsonReader.nextString(); 59 | } 60 | } 61 | 62 | jsonReader.endObject(); 63 | return new AnImplementation(name); 64 | } 65 | } 66 | 67 | interface Service { 68 | @POST("/") AnImplementation anImplementation(@Body AnImplementation impl); 69 | 70 | @POST("/") AnInterface anInterface(@Body AnInterface impl); 71 | } 72 | 73 | @Rule public final MockWebServer server = new MockWebServer(); 74 | 75 | private Service service; 76 | 77 | @Before public void setUp() { 78 | Gson gson = new GsonBuilder() 79 | .registerTypeAdapter(AnInterface.class, new AnInterfaceAdapter()) 80 | .setLenient() 81 | .create(); 82 | Retrofit retrofit = new Retrofit.Builder() 83 | .baseUrl(server.url("/")) 84 | .addConverterFactory(GsonConverterFactory.create(gson)) 85 | .addCallAdapterFactory(SynchronousCallAdapterFactory.create()) // Add synchronous adapter 86 | .build(); 87 | service = retrofit.create(Service.class); 88 | } 89 | 90 | @Test public void anInterface() throws Exception { 91 | server.enqueue(new MockResponse().setBody("{\"name\":\"value\"}")); 92 | 93 | AnInterface response = service.anInterface(new AnImplementation("value")); 94 | assertThat(response.getName()).isEqualTo("value"); 95 | 96 | RecordedRequest request = server.takeRequest(); 97 | assertThat(request.getBody().readUtf8()).isEqualTo("{\"name\":\"value\"}"); 98 | assertThat(request.getHeader("Content-Type")).isEqualTo("application/json; charset=UTF-8"); 99 | } 100 | 101 | @Test public void anImplementation() throws Exception { 102 | server.enqueue(new MockResponse().setBody("{\"theName\":\"value\"}")); 103 | 104 | AnImplementation response = service.anImplementation(new AnImplementation("value")); 105 | assertThat(response.theName).isEqualTo("value"); 106 | 107 | RecordedRequest request = server.takeRequest(); 108 | assertThat(request.getBody().readUtf8()).isEqualTo("{\"theName\":\"value\"}"); 109 | assertThat(request.getHeader("Content-Type")).isEqualTo("application/json; charset=UTF-8"); 110 | } 111 | 112 | @Test public void serializeUsesConfiguration() throws Exception { 113 | server.enqueue(new MockResponse().setBody("{}")); 114 | 115 | service.anImplementation(new AnImplementation(null)); 116 | 117 | RecordedRequest request = server.takeRequest(); 118 | assertThat(request.getBody().readUtf8()).isEqualTo("{}"); // Null value was not serialized. 119 | assertThat(request.getHeader("Content-Type")).isEqualTo("application/json; charset=UTF-8"); 120 | } 121 | 122 | @Test public void deserializeUsesConfiguration() { 123 | server.enqueue(new MockResponse().setBody("{/* a comment! */}")); 124 | 125 | AnImplementation response = service.anImplementation(new AnImplementation("value")); 126 | assertThat(response.getName()).isNull(); 127 | } 128 | } 129 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | # SPDX-License-Identifier: Apache-2.0 19 | # 20 | 21 | ############################################################################## 22 | # 23 | # Gradle start up script for POSIX generated by Gradle. 24 | # 25 | # Important for running: 26 | # 27 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 28 | # noncompliant, but you have some other compliant shell such as ksh or 29 | # bash, then to run this script, type that shell name before the whole 30 | # command line, like: 31 | # 32 | # ksh Gradle 33 | # 34 | # Busybox and similar reduced shells will NOT work, because this script 35 | # requires all of these POSIX shell features: 36 | # * functions; 37 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 38 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 39 | # * compound commands having a testable exit status, especially «case»; 40 | # * various built-in commands including «command», «set», and «ulimit». 41 | # 42 | # Important for patching: 43 | # 44 | # (2) This script targets any POSIX shell, so it avoids extensions provided 45 | # by Bash, Ksh, etc; in particular arrays are avoided. 46 | # 47 | # The "traditional" practice of packing multiple parameters into a 48 | # space-separated string is a well documented source of bugs and security 49 | # problems, so this is (mostly) avoided, by progressively accumulating 50 | # options in "$@", and eventually passing that to Java. 51 | # 52 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 53 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 54 | # see the in-line comments for details. 55 | # 56 | # There are tweaks for specific operating systems such as AIX, CygWin, 57 | # Darwin, MinGW, and NonStop. 58 | # 59 | # (3) This script is generated from the Groovy template 60 | # https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 61 | # within the Gradle project. 62 | # 63 | # You can find Gradle at https://github.com/gradle/gradle/. 64 | # 65 | ############################################################################## 66 | 67 | # Attempt to set APP_HOME 68 | 69 | # Resolve links: $0 may be a link 70 | app_path=$0 71 | 72 | # Need this for daisy-chained symlinks. 73 | while 74 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 75 | [ -h "$app_path" ] 76 | do 77 | ls=$( ls -ld "$app_path" ) 78 | link=${ls#*' -> '} 79 | case $link in #( 80 | /*) app_path=$link ;; #( 81 | *) app_path=$APP_HOME$link ;; 82 | esac 83 | done 84 | 85 | # This is normally unused 86 | # shellcheck disable=SC2034 87 | APP_BASE_NAME=${0##*/} 88 | # Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) 89 | APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit 90 | 91 | # Use the maximum available, or set MAX_FD != -1 to use that value. 92 | MAX_FD=maximum 93 | 94 | warn () { 95 | echo "$*" 96 | } >&2 97 | 98 | die () { 99 | echo 100 | echo "$*" 101 | echo 102 | exit 1 103 | } >&2 104 | 105 | # OS specific support (must be 'true' or 'false'). 106 | cygwin=false 107 | msys=false 108 | darwin=false 109 | nonstop=false 110 | case "$( uname )" in #( 111 | CYGWIN* ) cygwin=true ;; #( 112 | Darwin* ) darwin=true ;; #( 113 | MSYS* | MINGW* ) msys=true ;; #( 114 | NONSTOP* ) nonstop=true ;; 115 | esac 116 | 117 | 118 | 119 | # Determine the Java command to use to start the JVM. 120 | if [ -n "$JAVA_HOME" ] ; then 121 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 122 | # IBM's JDK on AIX uses strange locations for the executables 123 | JAVACMD=$JAVA_HOME/jre/sh/java 124 | else 125 | JAVACMD=$JAVA_HOME/bin/java 126 | fi 127 | if [ ! -x "$JAVACMD" ] ; then 128 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 129 | 130 | Please set the JAVA_HOME variable in your environment to match the 131 | location of your Java installation." 132 | fi 133 | else 134 | JAVACMD=java 135 | if ! command -v java >/dev/null 2>&1 136 | then 137 | die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 138 | 139 | Please set the JAVA_HOME variable in your environment to match the 140 | location of your Java installation." 141 | fi 142 | fi 143 | 144 | # Increase the maximum file descriptors if we can. 145 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 146 | case $MAX_FD in #( 147 | max*) 148 | # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. 149 | # shellcheck disable=SC2039,SC3045 150 | MAX_FD=$( ulimit -H -n ) || 151 | warn "Could not query maximum file descriptor limit" 152 | esac 153 | case $MAX_FD in #( 154 | '' | soft) :;; #( 155 | *) 156 | # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. 157 | # shellcheck disable=SC2039,SC3045 158 | ulimit -n "$MAX_FD" || 159 | warn "Could not set maximum file descriptor limit to $MAX_FD" 160 | esac 161 | fi 162 | 163 | # Collect all arguments for the java command, stacking in reverse order: 164 | # * args from the command line 165 | # * the main class name 166 | # * -classpath 167 | # * -D...appname settings 168 | # * --module-path (only if needed) 169 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 170 | 171 | # For Cygwin or MSYS, switch paths to Windows format before running java 172 | if "$cygwin" || "$msys" ; then 173 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 174 | 175 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 176 | 177 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 178 | for arg do 179 | if 180 | case $arg in #( 181 | -*) false ;; # don't mess with options #( 182 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 183 | [ -e "$t" ] ;; #( 184 | *) false ;; 185 | esac 186 | then 187 | arg=$( cygpath --path --ignore --mixed "$arg" ) 188 | fi 189 | # Roll the args list around exactly as many times as the number of 190 | # args, so each arg winds up back in the position where it started, but 191 | # possibly modified. 192 | # 193 | # NB: a `for` loop captures its iteration list before it begins, so 194 | # changing the positional parameters here affects neither the number of 195 | # iterations, nor the values presented in `arg`. 196 | shift # remove old arg 197 | set -- "$@" "$arg" # push replacement arg 198 | done 199 | fi 200 | 201 | 202 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 203 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 204 | 205 | # Collect all arguments for the java command: 206 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, 207 | # and any embedded shellness will be escaped. 208 | # * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be 209 | # treated as '${Hostname}' itself on the command line. 210 | 211 | set -- \ 212 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 213 | -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ 214 | "$@" 215 | 216 | # Stop when "xargs" is not available. 217 | if ! command -v xargs >/dev/null 2>&1 218 | then 219 | die "xargs is not available" 220 | fi 221 | 222 | # Use "xargs" to parse quoted args. 223 | # 224 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 225 | # 226 | # In Bash we could simply go: 227 | # 228 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 229 | # set -- "${ARGS[@]}" "$@" 230 | # 231 | # but POSIX shell has neither arrays nor command substitution, so instead we 232 | # post-process each arg (as a line of input to sed) to backslash-escape any 233 | # character that might be a shell metacharacter, then use eval to reverse 234 | # that process (while maintaining the separation between arguments), and wrap 235 | # the whole thing up as a single "set" statement. 236 | # 237 | # This will of course break if any of these variables contains a newline or 238 | # an unmatched quote. 239 | # 240 | 241 | eval "set -- $( 242 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 243 | xargs -n1 | 244 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 245 | tr '\n' ' ' 246 | )" '"$@"' 247 | 248 | exec "$JAVACMD" "$@" 249 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /retrofit2-synchronous-adapter/src/test/java/com/jaredsburrows/retrofit2/adapter/synchronous/SynchronousCallTest.java: -------------------------------------------------------------------------------- 1 | package com.jaredsburrows.retrofit2.adapter.synchronous; 2 | 3 | import static okhttp3.mockwebserver.SocketPolicy.DISCONNECT_DURING_RESPONSE_BODY; 4 | import static com.google.common.truth.Truth.assertThat; 5 | import static org.junit.Assert.fail; 6 | import static org.mockito.Mockito.spy; 7 | import static org.mockito.Mockito.verifyNoMoreInteractions; 8 | 9 | import java.io.IOException; 10 | import java.lang.annotation.Annotation; 11 | import java.lang.reflect.Type; 12 | import java.util.concurrent.atomic.AtomicInteger; 13 | import javax.annotation.Nonnull; 14 | import javax.annotation.Nullable; 15 | import okhttp3.MediaType; 16 | import okhttp3.OkHttpClient; 17 | import okhttp3.RequestBody; 18 | import okhttp3.ResponseBody; 19 | import okhttp3.mockwebserver.MockResponse; 20 | import okhttp3.mockwebserver.MockWebServer; 21 | import okhttp3.mockwebserver.SocketPolicy; 22 | import okio.Buffer; 23 | import okio.BufferedSource; 24 | import okio.ForwardingSource; 25 | import okio.Okio; 26 | import org.junit.Rule; 27 | import org.junit.Test; 28 | import retrofit2.Converter; 29 | import retrofit2.HttpException; 30 | import retrofit2.Response; 31 | import retrofit2.Retrofit; 32 | import retrofit2.helpers.StringConverterFactory; 33 | import retrofit2.http.Body; 34 | import retrofit2.http.GET; 35 | import retrofit2.http.POST; 36 | import retrofit2.http.Path; 37 | import retrofit2.http.Streaming; 38 | 39 | /** 40 | * This test does not use {@link retrofit2.Call} and uses the {@link SynchronousCallAdapterFactory} 41 | * instead. 42 | * From: https://github.com/square/retrofit/blob/d51805b9af79d631b43b5e8b85d12581989b1d49/retrofit/java-test/src/test/java/retrofit2/CallTest.java#L53 43 | */ 44 | public final class SynchronousCallTest { 45 | @Rule public final MockWebServer server = new MockWebServer(); 46 | 47 | interface Service { 48 | @GET("/") String getString(); 49 | 50 | @GET("/") ResponseBody getBody(); 51 | 52 | @GET("/") @Streaming ResponseBody getStreamingBody(); 53 | 54 | @POST("/") String postString(@Body String body); 55 | 56 | @POST("/{a}") String postRequestBody(@Path("a") Object a); 57 | 58 | @GET("/") Response getStringResponse(); 59 | 60 | @GET("/") Response getResponseBodyResponse(); 61 | } 62 | 63 | @Test public void http200Sync() { 64 | Retrofit retrofit = new Retrofit.Builder() 65 | .baseUrl(server.url("/")) 66 | .addConverterFactory(new StringConverterFactory()) 67 | .addCallAdapterFactory(SynchronousCallAdapterFactory.create()) // Add synchronous adapter 68 | .build(); 69 | Service example = retrofit.create(Service.class); 70 | 71 | server.enqueue(new MockResponse().setBody("Hi")); 72 | 73 | String response = example.getString(); 74 | assertThat(response).isEqualTo("Hi"); 75 | } 76 | 77 | @Test public void http404Sync() { 78 | Retrofit retrofit = new Retrofit.Builder() 79 | .baseUrl(server.url("/")) 80 | .addConverterFactory(new StringConverterFactory()) 81 | .addCallAdapterFactory(SynchronousCallAdapterFactory.create()) // Add synchronous adapter 82 | .build(); 83 | Service example = retrofit.create(Service.class); 84 | 85 | server.enqueue(new MockResponse().setResponseCode(404).setBody("Hi")); 86 | 87 | try { 88 | String response = example.getString(); 89 | assertThat(response).isEqualTo("Hi"); 90 | fail(); 91 | } catch (Exception e) { 92 | assertThat(e) 93 | .isInstanceOf(HttpException.class); 94 | assertThat(e) 95 | .hasMessageThat().isEqualTo("HTTP 404 Client Error"); 96 | } 97 | } 98 | 99 | @Test public void transportProblemSync() { 100 | Retrofit retrofit = new Retrofit.Builder() 101 | .baseUrl(server.url("/")) 102 | .addConverterFactory(new StringConverterFactory()) 103 | .addCallAdapterFactory(SynchronousCallAdapterFactory.create()) // Add synchronous adapter 104 | .build(); 105 | Service example = retrofit.create(Service.class); 106 | 107 | server.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.DISCONNECT_AT_START)); 108 | 109 | try { 110 | example.getString(); 111 | fail(); 112 | } catch (Exception ignored) { 113 | } 114 | } 115 | 116 | @Test public void conversionProblemOutgoingSync() { 117 | Retrofit retrofit = new Retrofit.Builder() 118 | .baseUrl(server.url("/")) 119 | .addConverterFactory(new StringConverterFactory() { 120 | @Override 121 | public Converter requestBodyConverter(Type type, 122 | Annotation[] parameterAnnotations, Annotation[] methodAnnotations, 123 | Retrofit retrofit) { 124 | return (Converter) value -> { 125 | throw new UnsupportedOperationException("I am broken!"); 126 | }; 127 | } 128 | }) 129 | .addCallAdapterFactory(SynchronousCallAdapterFactory.create()) // Add synchronous adapter 130 | .build(); 131 | Service example = retrofit.create(Service.class); 132 | 133 | try { 134 | example.postString("Hi"); 135 | fail(); 136 | } catch (UnsupportedOperationException e) { 137 | assertThat(e).hasMessageThat().isEqualTo("I am broken!"); 138 | } 139 | } 140 | 141 | @Test public void conversionProblemIncomingSync() { 142 | Retrofit retrofit = new Retrofit.Builder() 143 | .baseUrl(server.url("/")) 144 | .addConverterFactory(new StringConverterFactory() { 145 | @Override 146 | public Converter responseBodyConverter(Type type, 147 | Annotation[] annotations, Retrofit retrofit) { 148 | return (Converter) value -> { 149 | throw new UnsupportedOperationException("I am broken!"); 150 | }; 151 | } 152 | }) 153 | .addCallAdapterFactory(SynchronousCallAdapterFactory.create()) // Add synchronous adapter 154 | .build(); 155 | Service example = retrofit.create(Service.class); 156 | 157 | server.enqueue(new MockResponse().setBody("Hi")); 158 | 159 | try { 160 | example.postString("Hi"); 161 | fail(); 162 | } catch (UnsupportedOperationException e) { 163 | assertThat(e).hasMessageThat().isEqualTo("I am broken!"); 164 | } 165 | } 166 | 167 | @Test public void requestBeforeExecuteCreates() { 168 | Retrofit retrofit = new Retrofit.Builder() 169 | .baseUrl(server.url("/")) 170 | .addConverterFactory(new StringConverterFactory()) 171 | .addCallAdapterFactory(SynchronousCallAdapterFactory.create()) // Add synchronous adapter 172 | .build(); 173 | Service service = retrofit.create(Service.class); 174 | 175 | server.enqueue(new MockResponse()); 176 | 177 | AtomicInteger writeCount = new AtomicInteger(); 178 | Object a = new Object() { 179 | @Override public String toString() { 180 | writeCount.incrementAndGet(); 181 | return "Hello"; 182 | } 183 | }; 184 | 185 | service.postRequestBody(a); 186 | assertThat(writeCount.get()).isEqualTo(1); 187 | } 188 | 189 | @Test public void requestThrowingBeforeExecuteFailsExecute() { 190 | Retrofit retrofit = new Retrofit.Builder() 191 | .baseUrl(server.url("/")) 192 | .addConverterFactory(new StringConverterFactory()) 193 | .addCallAdapterFactory(SynchronousCallAdapterFactory.create()) // Add synchronous adapter 194 | .build(); 195 | Service service = retrofit.create(Service.class); 196 | 197 | server.enqueue(new MockResponse()); 198 | 199 | AtomicInteger writeCount = new AtomicInteger(); 200 | Object a = new Object() { 201 | @Override public String toString() { 202 | writeCount.incrementAndGet(); 203 | throw new RuntimeException("Broken!"); 204 | } 205 | }; 206 | 207 | try { 208 | service.postRequestBody(a); 209 | fail(); 210 | } catch (RuntimeException e) { 211 | assertThat(e).hasMessageThat().isEqualTo("Broken!"); 212 | } 213 | assertThat(writeCount.get()).isEqualTo(1); 214 | } 215 | 216 | @Test public void requestAfterExecuteThrowingAlsoThrows() { 217 | Retrofit retrofit = new Retrofit.Builder() 218 | .baseUrl(server.url("/")) 219 | .addConverterFactory(new StringConverterFactory()) 220 | .addCallAdapterFactory(SynchronousCallAdapterFactory.create()) // Add synchronous adapter 221 | .build(); 222 | Service service = retrofit.create(Service.class); 223 | 224 | server.enqueue(new MockResponse()); 225 | 226 | AtomicInteger writeCount = new AtomicInteger(); 227 | Object a = new Object() { 228 | @Override public String toString() { 229 | writeCount.incrementAndGet(); 230 | throw new RuntimeException("Broken!"); 231 | } 232 | }; 233 | 234 | try { 235 | service.postRequestBody(a); 236 | fail(); 237 | } catch (RuntimeException e) { 238 | assertThat(e).hasMessageThat().isEqualTo("Broken!"); 239 | } 240 | assertThat(writeCount.get()).isEqualTo(1); 241 | } 242 | 243 | @Test public void conversionProblemIncomingMaskedByConverterIsUnwrapped() { 244 | // MWS has no way to trigger IOExceptions during the response body so use an interceptor. 245 | OkHttpClient client = new OkHttpClient.Builder() // 246 | .addInterceptor(chain -> { 247 | okhttp3.Response response = chain.proceed(chain.request()); 248 | ResponseBody body = response.body(); 249 | BufferedSource source = Okio.buffer(new ForwardingSource(body.source()) { 250 | @Override public long read(@Nonnull Buffer sink, long byteCount) throws IOException { 251 | throw new IOException("cause"); 252 | } 253 | }); 254 | body = create(body.contentType(), body.contentLength(), source); 255 | return response.newBuilder().body(body).build(); 256 | }).build(); 257 | 258 | Retrofit retrofit = new Retrofit.Builder() 259 | .baseUrl(server.url("/")) 260 | .client(client) 261 | .addConverterFactory(new StringConverterFactory() { 262 | @Override 263 | public Converter responseBodyConverter(Type type, 264 | Annotation[] annotations, Retrofit retrofit) { 265 | return (Converter) value -> { 266 | try { 267 | return value.string(); 268 | } catch (IOException e) { 269 | // Some serialization libraries mask transport problems in runtime exceptions. Bad! 270 | throw new RuntimeException("wrapper", e); 271 | } 272 | }; 273 | } 274 | }) 275 | .addCallAdapterFactory(SynchronousCallAdapterFactory.create()) // Add synchronous adapter 276 | .build(); 277 | Service example = retrofit.create(Service.class); 278 | 279 | server.enqueue(new MockResponse().setBody("Hi")); 280 | 281 | try { 282 | example.getString(); 283 | fail(); 284 | } catch (Exception e) { 285 | assertThat(e).hasMessageThat().contains("cause"); 286 | } 287 | } 288 | 289 | @Test public void http204SkipsConverter() { 290 | Converter converter = spy(new Converter() { 291 | @Override public String convert(@Nonnull ResponseBody value) throws IOException { 292 | return value.string(); 293 | } 294 | }); 295 | Retrofit retrofit = new Retrofit.Builder() 296 | .baseUrl(server.url("/")) 297 | .addConverterFactory(new StringConverterFactory() { 298 | @Override 299 | public Converter responseBodyConverter(Type type, 300 | Annotation[] annotations, Retrofit retrofit) { 301 | return converter; 302 | } 303 | }) 304 | .addCallAdapterFactory(SynchronousCallAdapterFactory.create()) // Add synchronous adapter 305 | .build(); 306 | Service example = retrofit.create(Service.class); 307 | 308 | server.enqueue(new MockResponse().setStatus("HTTP/1.1 204 Nothin")); 309 | 310 | String response = example.getString(); 311 | assertThat(response).isNull(); 312 | verifyNoMoreInteractions(converter); 313 | } 314 | 315 | @Test public void http205SkipsConverter() { 316 | Converter converter = spy(new Converter() { 317 | @Override public String convert(@Nonnull ResponseBody value) throws IOException { 318 | return value.string(); 319 | } 320 | }); 321 | Retrofit retrofit = new Retrofit.Builder() 322 | .baseUrl(server.url("/")) 323 | .addConverterFactory(new StringConverterFactory() { 324 | @Override 325 | public Converter responseBodyConverter(Type type, 326 | Annotation[] annotations, Retrofit retrofit) { 327 | return converter; 328 | } 329 | }) 330 | .addCallAdapterFactory(SynchronousCallAdapterFactory.create()) // Add synchronous adapter 331 | .build(); 332 | Service example = retrofit.create(Service.class); 333 | 334 | server.enqueue(new MockResponse().setStatus("HTTP/1.1 205 Nothin")); 335 | 336 | String response = example.getString(); 337 | assertThat(response).isNull(); 338 | verifyNoMoreInteractions(converter); 339 | } 340 | 341 | @Test public void successfulRequestResponseWhenMimeTypeMissing() { 342 | Retrofit retrofit = new Retrofit.Builder() 343 | .baseUrl(server.url("/")) 344 | .addConverterFactory(new StringConverterFactory()) 345 | .addCallAdapterFactory(SynchronousCallAdapterFactory.create()) // Add synchronous adapter 346 | .build(); 347 | Service example = retrofit.create(Service.class); 348 | 349 | server.enqueue(new MockResponse().setBody("Hi").removeHeader("Content-Type")); 350 | 351 | String response = example.getString(); 352 | assertThat(response).isEqualTo("Hi"); 353 | } 354 | 355 | @Test public void responseBody() throws IOException { 356 | Retrofit retrofit = new Retrofit.Builder() 357 | .baseUrl(server.url("/")) 358 | .addConverterFactory(new StringConverterFactory()) 359 | .addCallAdapterFactory(SynchronousCallAdapterFactory.create()) // Add synchronous adapter 360 | .build(); 361 | Service example = retrofit.create(Service.class); 362 | 363 | server.enqueue(new MockResponse().setBody("1234")); 364 | 365 | ResponseBody response = example.getBody(); 366 | assertThat(response.string()).isEqualTo("1234"); 367 | } 368 | 369 | @Test public void responseBodyBuffers() { 370 | Retrofit retrofit = new Retrofit.Builder() 371 | .baseUrl(server.url("/")) 372 | .addConverterFactory(new StringConverterFactory()) 373 | .addCallAdapterFactory(SynchronousCallAdapterFactory.create()) // Add synchronous adapter 374 | .build(); 375 | Service example = retrofit.create(Service.class); 376 | 377 | server.enqueue(new MockResponse() 378 | .setBody("1234") 379 | .setSocketPolicy(DISCONNECT_DURING_RESPONSE_BODY)); 380 | 381 | // When buffering we will detect all socket problems before returning the Response. 382 | try { 383 | example.getBody(); 384 | fail(); 385 | } catch (Exception e) { 386 | assertThat(e).hasMessageThat().contains("unexpected end of stream"); 387 | } 388 | } 389 | 390 | @Test public void responseBodyStreams() { 391 | Retrofit retrofit = new Retrofit.Builder() 392 | .baseUrl(server.url("/")) 393 | .addConverterFactory(new StringConverterFactory()) 394 | .addCallAdapterFactory(SynchronousCallAdapterFactory.create()) // Add synchronous adapter 395 | .build(); 396 | Service example = retrofit.create(Service.class); 397 | 398 | server.enqueue(new MockResponse() 399 | .setBody("1234") 400 | .setSocketPolicy(DISCONNECT_DURING_RESPONSE_BODY)); 401 | 402 | // When streaming we only detect socket problems as the ResponseBody is read. 403 | try { 404 | example.getStreamingBody().string(); 405 | fail(); 406 | } catch (IOException e) { 407 | assertThat(e).hasMessageThat().contains("unexpected end of stream"); 408 | } 409 | } 410 | 411 | @Test public void emptyResponse() { 412 | Retrofit retrofit = new Retrofit.Builder() 413 | .baseUrl(server.url("/")) 414 | .addConverterFactory(new StringConverterFactory()) 415 | .addCallAdapterFactory(SynchronousCallAdapterFactory.create()) // Add synchronous adapter 416 | .build(); 417 | Service example = retrofit.create(Service.class); 418 | 419 | server.enqueue(new MockResponse().setBody("").addHeader("Content-Type", "text/stringy")); 420 | 421 | String response = example.getString(); 422 | assertThat(response).isEmpty(); 423 | } 424 | 425 | @SuppressWarnings("deprecation") 426 | private static ResponseBody create(@Nullable MediaType mediaType, Long length, 427 | BufferedSource source) { 428 | return ResponseBody.create(mediaType, length, source); 429 | } 430 | } 431 | --------------------------------------------------------------------------------