├── .gitignore ├── CHANGELOG.md ├── LICENSE ├── README.md ├── app ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src │ └── main │ ├── AndroidManifest.xml │ ├── java │ └── com.jaychang.sac │ │ └── demo │ │ ├── ApiClient.kt │ │ ├── GithubApi.kt │ │ ├── MainActivity.kt │ │ └── User.kt │ └── res │ ├── layout │ └── activity_main.xml │ ├── mipmap-hdpi │ └── ic_launcher.png │ ├── mipmap-mdpi │ └── ic_launcher.png │ ├── mipmap-xhdpi │ └── ic_launcher.png │ ├── mipmap-xxhdpi │ └── ic_launcher.png │ ├── mipmap-xxxhdpi │ └── ic_launcher.png │ ├── raw │ ├── get_repo.json │ ├── get_users.json │ └── get_users_error.json │ └── values │ ├── colors.xml │ ├── strings.xml │ └── styles.xml ├── build.gradle ├── gradle.properties ├── gradle ├── dependencies.gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── library-jsonparser-gson ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src │ └── main │ ├── AndroidManifest.xml │ └── java │ └── com │ └── jaychang │ └── sac │ └── jsonparser │ └── gson │ └── GsonJsonParser.kt ├── library-jsonparser-moshi ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src │ └── main │ ├── AndroidManifest.xml │ └── java │ └── com │ └── jaychang │ └── sac │ └── jsonparser │ └── moshi │ └── MoshiJsonParser.kt ├── library ├── build.gradle ├── proguard-rules.pro └── src │ └── main │ ├── AndroidManifest.xml │ └── java │ └── com │ └── jaychang │ └── sac │ ├── ApiManager.kt │ ├── CertificatePin.kt │ ├── ContextProvider.kt │ ├── Error.kt │ ├── ErrorConsumer.kt │ ├── JsonParser.kt │ ├── SimpleApiClient.kt │ ├── SimpleApiError.kt │ ├── SimpleApiResult.kt │ ├── SimpleExtension.kt │ ├── annotation │ ├── KeyPathResponse.kt │ ├── MockResponse.kt │ └── WrappedResponse.java │ ├── calladapter │ ├── MockResponseAdapterFactory.kt │ └── ObserveOnCallAdapterFactory.kt │ ├── converter │ ├── FileConverterFactory.kt │ ├── KeyPathResponseConverterFactory.kt │ └── WrappedResponseConverterFactory.kt │ ├── interceptor │ ├── HeaderInterceptor.kt │ └── ParameterInterceptor.kt │ └── util │ ├── Mime.kt │ └── Utils.kt └── settings.gradle /.gitignore: -------------------------------------------------------------------------------- 1 | # Created by .ignore support plugin (hsz.mobi) 2 | ### Android template 3 | # Built application files 4 | *.apk 5 | *.ap_ 6 | 7 | # Files for the ART/Dalvik VM 8 | *.dex 9 | 10 | # Java class files 11 | *.class 12 | 13 | # Generated files 14 | bin/ 15 | gen/ 16 | out/ 17 | 18 | # Gradle files 19 | .gradle/ 20 | build/ 21 | 22 | # Local configuration file (sdk path, etc) 23 | local.properties 24 | 25 | # Proguard folder generated by Eclipse 26 | proguard/ 27 | 28 | # Log Files 29 | *.log 30 | 31 | # Android Studio Navigation editor temp files 32 | .navigation/ 33 | 34 | # Android Studio captures folder 35 | captures/ 36 | 37 | # Intellij 38 | *.iml 39 | .idea/workspace.xml 40 | .idea/tasks.xml 41 | .idea/gradle.xml 42 | .idea/dictionaries 43 | .idea/libraries 44 | 45 | # Keystore files 46 | *.jks 47 | 48 | # External native build folder generated in Android Studio 2.2 and later 49 | .externalNativeBuild 50 | 51 | # Google Services (e.g. APIs or Firebase) 52 | google-services.json 53 | 54 | # Freeline 55 | freeline.py 56 | freeline/ 57 | freeline_project_description.json 58 | 59 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | ## Change Log 2 | 3 | ### Version 2.3.0 (1 June 2018) 4 | - Support other rx return types (i.e. `Flowable`, `Single`, `Maybe`, `Completable`) 5 | - Rename `autoCancel` to `autoDispose` 6 | 7 | ### Version 2.2.0 (27 May 2018) 8 | - Now the library doesn't depend on gson to parse data 9 | - Add `GsonJsonParser` and `MoshiJsonParser` 10 | 11 | ### Version 2.1.0 (6 May 2018) 12 | - Remove Uri-to-MultipartBody feature 13 | - Rename some files and class members 14 | 15 | ### Version 1.11.0 (20 Oct 2017) 16 | - New: Add `autoCancel(LifecycleOwner, Lifecycle.Event)` for cancelling call until specific event occurs 17 | - Fix: keypath parsing issue 18 | 19 | ### Version 1.10.0 (20 Oct 2017) 20 | - Api changes: `SimpleApiClient.Config.isMockDataEnabled` is renamed to `SimpleApiClient.Config.isMockResponseEnabled` 21 | 22 | ### Version 1.9.0 (15 Oct 2017) 23 | - New: Add `@ResponseKeyPath` for successful response parsing 24 | - New: Add `errorMessageKeyPath` for error response parsing 25 | - Api changes: `@Image` is refactored to `@MultiPart` which add mime type parameter 26 | - Fix: Mock reponse parsing now will not throw error when use `@Unwrap` 27 | 28 | ### Version 1.8.0 (9 Oct 2017) 29 | - Api changes: Demote `ApiClientConfig` to `SimpleApiClient.Config` 30 | 31 | ### Version 1.7.0 (9 Oct 2017) 32 | - Api changes: Error model type should be set via `SimpleApierrorClass` 33 | 34 | ### Version 1.6.2 (8 Oct 2017) 35 | - Fix: No default parameter value for retry delaySeconds 36 | 37 | ### Version 1.6.1 (8 Oct 2017) 38 | - Fix: Wrong wording 39 | 40 | ### Version 1.6.0 (8 Oct 2017) 41 | - New: Support custom JSON parser 42 | 43 | ### Version 1.5.0 (7 Oct 2017) 44 | - New: Support mock response status 45 | 46 | ### Version 1.4.1 (7 Oct 2017) 47 | - Fix: Return correct error for status code 500..599 48 | 49 | ### Version 1.4.0 (6 Oct 2017) 50 | - New: Data mocking support 51 | 52 | ### Version 1.3.0 (5 Oct 2017) 53 | - Fix: `observe()` now return `Cancellable` 54 | 55 | ### Version 1.2.0 (5 Oct 2017) 56 | - Fix: Rename `autoDispose()` to `autoCancel()` 57 | 58 | ### Version 1.1.0 (4 Oct 2017) 59 | - New: Add `enableStetho`, `logLevel` and `certificatePins` configs 60 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # SimpleApiClient 2 | [![Download](https://api.bintray.com/packages/jaychang0917/maven/simpleapiclient/images/download.svg) ](https://bintray.com/jaychang0917/maven/simpleapiclient/_latestVersion) 3 | [![Android Weekly](http://img.shields.io/badge/Android%20Weekly-%23277-2CB3E5.svg)](http://androidweekly.net/issues/issue-277) 4 | 5 | A configurable api client based on Retrofit2 and RxJava2 for android 6 | 7 | ## Table of Contents 8 | * [Basic Usage](#basic_usage) 9 | * [Unwrap Response by KeyPath](#unwrap_keypath) 10 | * [Unwrap Response by Wrapper Class](#unwrap_class) 11 | * [Serial / Concurrent Calls](#serial_parallel_calls) 12 | * [Retry Interval / Exponential backoff](#retry) 13 | * [Call Cancellation](#call_cancel) 14 | * [Mock Response](#mock_response) 15 | 16 | ## Installation 17 | In your app level build.gradle : 18 | 19 | ```java 20 | dependencies { 21 | implementation 'com.jaychang:simpleapiclient:2.3.0' 22 | // if you use gson 23 | implementation 'com.jaychang:simpleapiclient-jsonparser-gson:2.3.0' 24 | // if you use moshi 25 | implementation 'com.jaychang:simpleapiclient-jsonparser-moshi:2.3.0' 26 | } 27 | ``` 28 | 29 | --- 30 | 31 | ## Basic Usage 32 | ### Step 1 33 | Config the api client and use it to create your api. 34 | ```java 35 | interface GithubApi { 36 | 37 | companion object { 38 | fun create() : GithubApi = 39 | SimpleApiClient.create { 40 | baseUrl = "https://api.github.com" 41 | 42 | defaultParameters = mapOf() 43 | defaultHeaders = mapOf() 44 | connectTimeout = TimeUnit.MINUTES.toMillis(1) 45 | readTimeout = TimeUnit.MINUTES.toMillis(1) 46 | writeTimeout = TimeUnit.MINUTES.toMillis(1) 47 | logLevel = LogLevel.BASIC // default NONE 48 | isMockResponseEnabled = true // default false 49 | certificatePins = listOf( 50 | CertificatePin(hostname = "api.foo.com", sha1PublicKeyHash = "0beec7b5ea3f0fdbc95d0dd47f3c5bc275da8a33"), 51 | CertificatePin(hostname = "api.bar.com", sha256PublicKeyHash = "fcde2b2edba56bf408601fb721fe9b5c338d10ee429ea04fae5511b68fbf8fb9") 52 | ) 53 | 54 | interceptors = listOf() 55 | networkInterceptors = listOf() 56 | httpClient = OkHttpClient.Builder().build() // your own http client 57 | 58 | jsonParser = MoshiJsonParser() 59 | errorClass = ApiError::class // should be conformed to SimpleApiError 60 | errorMessageKeyPath = "meta.message" 61 | errorHandler = { error -> 62 | // you can centralize the handling of general error here 63 | when (error) { 64 | is AuthenticationError -> {...} 65 | is ClientError -> {...} 66 | is ServerError -> {...} 67 | is NetworkError -> {...} 68 | is SSLError -> {...} 69 | } 70 | } 71 | } 72 | } 73 | 74 | @GET("/search/users") 75 | fun getUsers(@Query("q") query: String): Single> 76 | 77 | } 78 | ```` 79 | 80 | ### Step 2 81 | Use `observe()` to enqueue the call, do your stuff in corresponding parameter block. All blocks are run on android main thread by default and they are optional. 82 | ```kotlin 83 | githubApi.getUsers("google") 84 | .observe( 85 | onStart = { println("show loading") }, 86 | onEnd = { println("hide loading") }, 87 | onSuccess = { println(it) }, 88 | onError = { println(it.message) } 89 | ) 90 | ``` 91 | 92 | ## Unwrap Response by KeyPath 93 | Sometimes the api response includes metadata that we don't need, but in order to map the response we create a wrapper class and make the function return that wrapper class. 94 | This approach leaks the implementation of service to calling code. 95 | 96 | Assuming the response json looks like the following: 97 | ```xml 98 | { 99 | total_count: 33909, 100 | incomplete_results: false, 101 | foo: { 102 | bar: { 103 | items: [ 104 | { 105 | login: "jaychang0917", 106 | ... 107 | } 108 | ... 109 | ] 110 | } 111 | } 112 | } 113 | ``` 114 | And you only want the `items` part, use `@KeyPathResponse("keypath")` annotation to indicate which part of response you want. 115 | ```kotlin 116 | @GET("/search/users") 117 | @KeyPathResponse("foo.bar.items") 118 | fun getUsers(@Query("q") query: String): Single> 119 | ``` 120 | 121 | Similarly, unwrap the error response by setting the `errorMessageKeyPath` of `SimpleApiClient.Config` 122 | 123 | ## Unwrap Response by Wrapper Class 124 | An alternative solution is that you can create a wrapper class that conforming `SimpleApiResult`, and use `@WrappedResponse(class)` to indicate that you want an unwrapped response of that wrapper class. 125 | 126 | ```kotlin 127 | class ApiResult: SimpleApiResult { 128 | ... 129 | } 130 | 131 | @GET("/search/users") 132 | @WrappedResponse(ApiResult::class) 133 | fun getUsers(@Query("q") query: String): Single> 134 | ``` 135 | 136 | ## Serial / Concurrent Calls 137 | ### Serial 138 | ```kotlin 139 | githubApi.foo() 140 | .then { foo -> githubApi.bar(foo.name) } 141 | .observe(...) 142 | ``` 143 | 144 | ### Serial then Concurrent 145 | ```kotlin 146 | githubApi.foo() 147 | .then { foo -> githubApi.bar(foo.name) } 148 | .thenAll( bar -> 149 | githubApi.baz(bar.name), 150 | githubApi.qux(bar.name) 151 | ) 152 | .observe(...) 153 | ``` 154 | 155 | ### Concurrent 156 | ```kotlin 157 | SimpleApiClient.all( 158 | githubApi.foo(), 159 | githubApi.bar() 160 | ).observe(...) 161 | ``` 162 | 163 | ### Concurrent then Serial 164 | ```kotlin 165 | SimpleApiClient.all( 166 | githubApi.foo(), 167 | githubApi.bar() 168 | ).then { array -> // the return type is Array, you should cast them, e.g. val users = array[0] as List 169 | githubApi.baz() 170 | }.observe(...) 171 | ``` 172 | 173 | ## Retry Interval / Exponential backoff 174 | ```kotlin 175 | githubApi.getUsers("google") 176 | .retryInterval(maxRetryCount = 3, delaySeconds = 5) // retry up to 3 times, each time delays 5 seconds 177 | .retryExponential(maxRetryCount = 3, delaySeconds = 5) // retry up to 3 times, each time delays 5^n seconds, where n = {1,2,3} 178 | .observe(...) 179 | ``` 180 | 181 | ## Call Cancellation 182 | ### Auto Call Cancellation 183 | The api call will be cancelled automatically in corresponding lifecycle callback. For instance, an api call is made in `onStart()`, it be will cancelled automatically in `onStop`. 184 | 185 | ```kotlin 186 | githubApi.getUsers("google") 187 | .autoDispose(this) 188 | .observe(...) 189 | ``` 190 | ### Cancel call manually 191 | ```kotlin 192 | val call = githubApi.getUsers("google").observe(...) 193 | 194 | call.dispose() 195 | ``` 196 | 197 | ## Mock Response 198 | To enable response mocking, set `SimpleApiClient.Config.isMockResponseEnabled` to `true`. 199 | 200 | ### Mock sample json data 201 | To make the api return a successful response with provided json 202 | ```kotlin 203 | @GET("/repos/{user}/{repo}") 204 | @MockResponse(R.raw.get_repo) 205 | fun getRepo(@Path("user") user: String, @Path("repo") repo: String): Single 206 | ``` 207 | 208 | ### Mock status 209 | To make the api return a client side error with provided json 210 | ```kotlin 211 | @GET("/repos/{user}/{repo}") 212 | @MockResponse(json = R.raw.get_repo_error, status = Status.CLIENT_ERROR) 213 | fun getRepo(@Path("user") user: String, @Path("repo") repo: String): Single 214 | ``` 215 | `json` parameter of `MockResponse` is optional, you can set the status only, then you receive empty string. 216 | 217 | Possible `Status` values: 218 | ```kotlin 219 | enum class Status { 220 | SUCCESS, AUTHENTICATION_ERROR, CLIENT_ERROR, SERVER_ERROR, NETWORK_ERROR, SSL_ERROR 221 | } 222 | ``` 223 | To mock a response with success status only, you should return `Completable`. 224 | ```kotlin 225 | @DELETE("/repo/{id}}") 226 | @MockResponse(status = Status.SUCCESS) 227 | fun deleteRepo(@Path("id") id: String): Completable 228 | ``` 229 | 230 | ## License 231 | ``` 232 | Copyright 2017 Jay Chang 233 | 234 | Licensed under the Apache License, Version 2.0 (the "License"); 235 | you may not use this file except in compliance with the License. 236 | You may obtain a copy of the License at 237 | 238 | http://www.apache.org/licenses/LICENSE-2.0 239 | 240 | Unless required by applicable law or agreed to in writing, software 241 | distributed under the License is distributed on an "AS IS" BASIS, 242 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 243 | See the License for the specific language governing permissions and 244 | limitations under the License. 245 | ``` 246 | -------------------------------------------------------------------------------- /app/.gitignore: -------------------------------------------------------------------------------- 1 | # Created by .ignore support plugin (hsz.mobi) 2 | ### Android template 3 | # Built application files 4 | *.apk 5 | *.ap_ 6 | 7 | # Files for the ART/Dalvik VM 8 | *.dex 9 | 10 | # Java class files 11 | *.class 12 | 13 | # Generated files 14 | bin/ 15 | gen/ 16 | out/ 17 | 18 | # Gradle files 19 | .gradle/ 20 | build/ 21 | 22 | # Local configuration file (sdk path, etc) 23 | local.properties 24 | 25 | # Proguard folder generated by Eclipse 26 | proguard/ 27 | 28 | # Log Files 29 | *.log 30 | 31 | # Android Studio Navigation editor temp files 32 | .navigation/ 33 | 34 | # Android Studio captures folder 35 | captures/ 36 | 37 | # IntelliJ 38 | *.iml 39 | .idea/workspace.xml 40 | .idea/tasks.xml 41 | .idea/gradle.xml 42 | .idea/dictionaries 43 | .idea/libraries 44 | 45 | # Keystore files 46 | # Uncomment the following line if you do not want to check your keystore files in. 47 | #*.jks 48 | 49 | # External native build folder generated in Android Studio 2.2 and later 50 | .externalNativeBuild 51 | 52 | # Google Services (e.g. APIs or Firebase) 53 | google-services.json 54 | 55 | # Freeline 56 | freeline.py 57 | freeline/ 58 | freeline_project_description.json 59 | 60 | -------------------------------------------------------------------------------- /app/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | apply plugin: 'kotlin-android' 3 | apply plugin: 'kotlin-kapt' 4 | 5 | android { 6 | compileSdkVersion deps.build.compileSdkVersion 7 | buildToolsVersion deps.build.buildToolsVersion 8 | defaultConfig { 9 | applicationId "com.jaychang.sac.demo" 10 | minSdkVersion deps.build.minSdkVersion 11 | targetSdkVersion deps.build.targetSdkVersion 12 | versionCode 1 13 | versionName "1.0" 14 | } 15 | buildTypes { 16 | release { 17 | minifyEnabled false 18 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 19 | } 20 | } 21 | packagingOptions { 22 | exclude 'META-INF/rxjava.properties' 23 | } 24 | lintOptions { 25 | abortOnError false 26 | } 27 | } 28 | 29 | dependencies { 30 | implementation fileTree(include: ['*.jar'], dir: 'libs') 31 | implementation deps.kotlin.stdlib 32 | implementation deps.support.appcompat 33 | implementation project(':library') 34 | implementation project(':library-jsonparser-gson') 35 | implementation project(':library-jsonparser-moshi') 36 | } 37 | -------------------------------------------------------------------------------- /app/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in /Users/jaychang/Library/Android/sdk/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | 12 | # If your project uses WebView create JS, uncomment the following 13 | # and specify the fully qualified class name to the JavaScript interface 14 | # class: 15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 16 | # public *; 17 | #} 18 | 19 | # Uncomment this to preserve the line number information for 20 | # debugging stack traces. 21 | #-keepattributes SourceFile,LineNumberTable 22 | 23 | # If you keep the line number information, uncomment this to 24 | # hide the original source file name. 25 | #-renamesourcefileattribute SourceFile 26 | -------------------------------------------------------------------------------- /app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /app/src/main/java/com.jaychang.sac/demo/ApiClient.kt: -------------------------------------------------------------------------------- 1 | package com.jaychang.sac.demo 2 | 3 | object ApiClient { 4 | val githubApi = GithubApi.create() 5 | } -------------------------------------------------------------------------------- /app/src/main/java/com.jaychang.sac/demo/GithubApi.kt: -------------------------------------------------------------------------------- 1 | package com.jaychang.sac.demo 2 | 3 | import com.jaychang.sac.* 4 | import com.jaychang.sac.annotation.KeyPathResponse 5 | import com.jaychang.sac.annotation.MockResponse 6 | import com.jaychang.sac.jsonparser.moshi.MoshiJsonParser 7 | import com.squareup.moshi.Json 8 | import io.reactivex.Single 9 | import retrofit2.http.GET 10 | import retrofit2.http.Query 11 | import java.util.concurrent.TimeUnit 12 | 13 | class ApiResult : SimpleApiResult { 14 | @Json(name = "items") 15 | override lateinit var result: T 16 | } 17 | 18 | class ApiError : SimpleApiError { 19 | @Json(name = "message") 20 | override lateinit var message: String 21 | } 22 | 23 | interface GithubApi { 24 | 25 | companion object { 26 | fun create(): GithubApi = 27 | SimpleApiClient.create { 28 | baseUrl = "https://api.github.com" 29 | defaultParameters = mapOf() 30 | defaultHeaders = mapOf() 31 | connectTimeout = TimeUnit.MINUTES.toMillis(1) 32 | readTimeout = TimeUnit.MINUTES.toMillis(1) 33 | writeTimeout = TimeUnit.MINUTES.toMillis(1) 34 | logLevel = LogLevel.BASIC // default: NONE 35 | certificatePins = listOf( 36 | CertificatePin(hostname = "api.foo.com", sha1PublicKeyHash = "0beec7b5ea3f0fdbc95d0dd47f3c5bc275da8a33"), 37 | CertificatePin(hostname = "api.bar.com", sha256PublicKeyHash = "fcde2b2edba56bf408601fb721fe9b5c338d10ee429ea04fae5511b68fbf8fb9") 38 | ) 39 | 40 | interceptors = listOf() 41 | networkInterceptors = listOf() 42 | //httpClient = OkHttpClient.Builder().build() 43 | 44 | errorMessageKeyPath = "message" 45 | //errorClass = ApiError::class 46 | isMockResponseEnabled = true // default: false 47 | 48 | jsonParser = MoshiJsonParser() 49 | errorHandler = { error -> 50 | when (error) { 51 | is AuthenticationError -> {} 52 | is ClientError -> {} 53 | is ServerError -> {} 54 | is NetworkError -> {} 55 | is SSLError -> {} 56 | } 57 | } 58 | } 59 | } 60 | 61 | @GET("/search/users") 62 | @KeyPathResponse("foo.bar.items") 63 | // @WrappedResponse(ApiResult::class) 64 | @MockResponse(R.raw.get_users) 65 | fun getUsers(@Query("q") query: String): Single> 66 | } 67 | -------------------------------------------------------------------------------- /app/src/main/java/com.jaychang.sac/demo/MainActivity.kt: -------------------------------------------------------------------------------- 1 | package com.jaychang.sac.demo 2 | 3 | import android.os.Bundle 4 | import android.support.v7.app.AppCompatActivity 5 | import com.jaychang.sac.autoDispose 6 | import com.jaychang.sac.observe 7 | 8 | class MainActivity : AppCompatActivity() { 9 | 10 | override fun onCreate(savedInstanceState: Bundle?) { 11 | super.onCreate(savedInstanceState) 12 | setContentView(R.layout.activity_main) 13 | 14 | ApiClient.githubApi.getUsers("google") 15 | .autoDispose(this) 16 | .observe( 17 | onStart = { println("show loading") }, 18 | onEnd = { println("hide loading") }, 19 | onSuccess = { println("success: $it") }, 20 | onError = { println("error: ${it.message}") } 21 | ) 22 | } 23 | } -------------------------------------------------------------------------------- /app/src/main/java/com.jaychang.sac/demo/User.kt: -------------------------------------------------------------------------------- 1 | package com.jaychang.sac.demo 2 | 3 | import com.squareup.moshi.Json 4 | 5 | data class User( 6 | @Json(name = "login") 7 | val name: String 8 | ) -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 2 | 8 | 9 |