├── .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 | [ ](https://bintray.com/jaychang0917/maven/simpleapiclient/_latestVersion)
3 | [](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 |
15 |
16 |
17 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jaychang0917/SimpleApiClient/45a688a6f4f1cc346fe534ecc348d54bb257977c/app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jaychang0917/SimpleApiClient/45a688a6f4f1cc346fe534ecc348d54bb257977c/app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jaychang0917/SimpleApiClient/45a688a6f4f1cc346fe534ecc348d54bb257977c/app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jaychang0917/SimpleApiClient/45a688a6f4f1cc346fe534ecc348d54bb257977c/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jaychang0917/SimpleApiClient/45a688a6f4f1cc346fe534ecc348d54bb257977c/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/raw/get_repo.json:
--------------------------------------------------------------------------------
1 |
2 | {
3 | "id": 105370527,
4 | "name": "sample repo",
5 | "full_name": "jaychang0917/SimpleApiClient",
6 | "owner": {
7 | "login": "jaychang0917",
8 | "id": 5347535,
9 | "avatar_url": "https://avatars2.githubusercontent.com/u/5347535?v=4",
10 | "gravatar_id": "",
11 | "url": "https://api.github.com/users/jaychang0917",
12 | "html_url": "https://github.com/jaychang0917",
13 | "followers_url": "https://api.github.com/users/jaychang0917/followers",
14 | "following_url": "https://api.github.com/users/jaychang0917/following{/other_user}",
15 | "gists_url": "https://api.github.com/users/jaychang0917/gists{/gist_id}",
16 | "starred_url": "https://api.github.com/users/jaychang0917/starred{/owner}{/repo}",
17 | "subscriptions_url": "https://api.github.com/users/jaychang0917/subscriptions",
18 | "organizations_url": "https://api.github.com/users/jaychang0917/orgs",
19 | "repos_url": "https://api.github.com/users/jaychang0917/repos",
20 | "events_url": "https://api.github.com/users/jaychang0917/events{/privacy}",
21 | "received_events_url": "https://api.github.com/users/jaychang0917/received_events",
22 | "type": "User",
23 | "site_admin": false
24 | },
25 | "private": false,
26 | "html_url": "https://github.com/jaychang0917/SimpleApiClient",
27 | "description": "A Retrofit extension written in kotlin",
28 | "fork": false,
29 | "url": "https://api.github.com/repos/jaychang0917/SimpleApiClient",
30 | "forks_url": "https://api.github.com/repos/jaychang0917/SimpleApiClient/forks",
31 | "keys_url": "https://api.github.com/repos/jaychang0917/SimpleApiClient/keys{/key_id}",
32 | "collaborators_url": "https://api.github.com/repos/jaychang0917/SimpleApiClient/collaborators{/collaborator}",
33 | "teams_url": "https://api.github.com/repos/jaychang0917/SimpleApiClient/teams",
34 | "hooks_url": "https://api.github.com/repos/jaychang0917/SimpleApiClient/hooks",
35 | "issue_events_url": "https://api.github.com/repos/jaychang0917/SimpleApiClient/issues/events{/number}",
36 | "events_url": "https://api.github.com/repos/jaychang0917/SimpleApiClient/events",
37 | "assignees_url": "https://api.github.com/repos/jaychang0917/SimpleApiClient/assignees{/user}",
38 | "branches_url": "https://api.github.com/repos/jaychang0917/SimpleApiClient/branches{/branch}",
39 | "tags_url": "https://api.github.com/repos/jaychang0917/SimpleApiClient/tags",
40 | "blobs_url": "https://api.github.com/repos/jaychang0917/SimpleApiClient/git/blobs{/sha}",
41 | "git_tags_url": "https://api.github.com/repos/jaychang0917/SimpleApiClient/git/tags{/sha}",
42 | "git_refs_url": "https://api.github.com/repos/jaychang0917/SimpleApiClient/git/refs{/sha}",
43 | "trees_url": "https://api.github.com/repos/jaychang0917/SimpleApiClient/git/trees{/sha}",
44 | "statuses_url": "https://api.github.com/repos/jaychang0917/SimpleApiClient/statuses/{sha}",
45 | "languages_url": "https://api.github.com/repos/jaychang0917/SimpleApiClient/languages",
46 | "stargazers_url": "https://api.github.com/repos/jaychang0917/SimpleApiClient/stargazers",
47 | "contributors_url": "https://api.github.com/repos/jaychang0917/SimpleApiClient/contributors",
48 | "subscribers_url": "https://api.github.com/repos/jaychang0917/SimpleApiClient/subscribers",
49 | "subscription_url": "https://api.github.com/repos/jaychang0917/SimpleApiClient/subscription",
50 | "commits_url": "https://api.github.com/repos/jaychang0917/SimpleApiClient/commits{/sha}",
51 | "git_commits_url": "https://api.github.com/repos/jaychang0917/SimpleApiClient/git/commits{/sha}",
52 | "comments_url": "https://api.github.com/repos/jaychang0917/SimpleApiClient/comments{/number}",
53 | "issue_comment_url": "https://api.github.com/repos/jaychang0917/SimpleApiClient/issues/comments{/number}",
54 | "contents_url": "https://api.github.com/repos/jaychang0917/SimpleApiClient/contents/{+path}",
55 | "compare_url": "https://api.github.com/repos/jaychang0917/SimpleApiClient/compare/{base}...{head}",
56 | "merges_url": "https://api.github.com/repos/jaychang0917/SimpleApiClient/merges",
57 | "archive_url": "https://api.github.com/repos/jaychang0917/SimpleApiClient/{archive_format}{/ref}",
58 | "downloads_url": "https://api.github.com/repos/jaychang0917/SimpleApiClient/downloads",
59 | "issues_url": "https://api.github.com/repos/jaychang0917/SimpleApiClient/issues{/number}",
60 | "pulls_url": "https://api.github.com/repos/jaychang0917/SimpleApiClient/pulls{/number}",
61 | "milestones_url": "https://api.github.com/repos/jaychang0917/SimpleApiClient/milestones{/number}",
62 | "notifications_url": "https://api.github.com/repos/jaychang0917/SimpleApiClient/notifications{?since,all,participating}",
63 | "labels_url": "https://api.github.com/repos/jaychang0917/SimpleApiClient/labels{/name}",
64 | "releases_url": "https://api.github.com/repos/jaychang0917/SimpleApiClient/releases{/id}",
65 | "deployments_url": "https://api.github.com/repos/jaychang0917/SimpleApiClient/deployments",
66 | "created_at": "2017-09-30T13:07:25Z",
67 | "updated_at": "2017-10-07T07:17:09Z",
68 | "pushed_at": "2017-10-07T05:25:30Z",
69 | "git_url": "git://github.com/jaychang0917/SimpleApiClient.git",
70 | "ssh_url": "git@github.com:jaychang0917/SimpleApiClient.git",
71 | "clone_url": "https://github.com/jaychang0917/SimpleApiClient.git",
72 | "svn_url": "https://github.com/jaychang0917/SimpleApiClient",
73 | "homepage": "",
74 | "size": 164,
75 | "stargazers_count": 50,
76 | "watchers_count": 50,
77 | "language": "Kotlin",
78 | "has_issues": true,
79 | "has_projects": true,
80 | "has_downloads": true,
81 | "has_wiki": true,
82 | "has_pages": false,
83 | "forks_count": 4,
84 | "mirror_url": null,
85 | "open_issues_count": 0,
86 | "forks": 4,
87 | "open_issues": 0,
88 | "watchers": 50,
89 | "default_branch": "master",
90 | "network_count": 4,
91 | "subscribers_count": 3
92 | }
93 |
--------------------------------------------------------------------------------
/app/src/main/res/raw/get_users.json:
--------------------------------------------------------------------------------
1 |
2 | {
3 | "total_count": 34210,
4 | "incomplete_results": false,
5 | "foo": {
6 | "bar": {
7 | "items": [
8 | {
9 | "login": "sample_user",
10 | "id": 965580,
11 | "avatar_url": "https://avatars1.githubusercontent.com/u/965580?v=4",
12 | "gravatar_id": "",
13 | "url": "https://api.github.com/users/jay",
14 | "html_url": "https://github.com/jay",
15 | "followers_url": "https://api.github.com/users/jay/followers",
16 | "following_url": "https://api.github.com/users/jay/following{/other_user}",
17 | "gists_url": "https://api.github.com/users/jay/gists{/gist_id}",
18 | "starred_url": "https://api.github.com/users/jay/starred{/owner}{/repo}",
19 | "subscriptions_url": "https://api.github.com/users/jay/subscriptions",
20 | "organizations_url": "https://api.github.com/users/jay/orgs",
21 | "repos_url": "https://api.github.com/users/jay/repos",
22 | "events_url": "https://api.github.com/users/jay/events{/privacy}",
23 | "received_events_url": "https://api.github.com/users/jay/received_events",
24 | "type": "User",
25 | "site_admin": false,
26 | "score": 86.388336
27 | },
28 | {
29 | "login": "jayschwa",
30 | "id": 475017,
31 | "avatar_url": "https://avatars1.githubusercontent.com/u/475017?v=4",
32 | "gravatar_id": "",
33 | "url": "https://api.github.com/users/jayschwa",
34 | "html_url": "https://github.com/jayschwa",
35 | "followers_url": "https://api.github.com/users/jayschwa/followers",
36 | "following_url": "https://api.github.com/users/jayschwa/following{/other_user}",
37 | "gists_url": "https://api.github.com/users/jayschwa/gists{/gist_id}",
38 | "starred_url": "https://api.github.com/users/jayschwa/starred{/owner}{/repo}",
39 | "subscriptions_url": "https://api.github.com/users/jayschwa/subscriptions",
40 | "organizations_url": "https://api.github.com/users/jayschwa/orgs",
41 | "repos_url": "https://api.github.com/users/jayschwa/repos",
42 | "events_url": "https://api.github.com/users/jayschwa/events{/privacy}",
43 | "received_events_url": "https://api.github.com/users/jayschwa/received_events",
44 | "type": "User",
45 | "site_admin": false,
46 | "score": 40.0574
47 | }
48 | ]
49 | }
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/app/src/main/res/raw/get_users_error.json:
--------------------------------------------------------------------------------
1 | {
2 | "status": 10000,
3 | "message_en": "sample error: /search/users",
4 | "message_zht": "示範錯誤:/search/users"
5 | }
--------------------------------------------------------------------------------
/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #3F51B5
4 | #303F9F
5 | #FF4081
6 |
7 |
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | SimpleApiClient
3 |
4 |
--------------------------------------------------------------------------------
/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/build.gradle:
--------------------------------------------------------------------------------
1 | // Top-level build file where you can add configuration options common to all sub-projects/modules.
2 |
3 | buildscript {
4 | apply from: 'gradle/dependencies.gradle'
5 |
6 | repositories {
7 | mavenCentral()
8 | jcenter()
9 | google()
10 | }
11 |
12 | dependencies {
13 | classpath deps.build.gradlePlugins.android
14 | classpath deps.build.gradlePlugins.github
15 | classpath deps.build.gradlePlugins.kotlin
16 | // NOTE: Do not place your application dependencies here; they belong
17 | // in the individual module build.gradle files
18 | }
19 | }
20 |
21 | allprojects {
22 | repositories {
23 | mavenCentral()
24 | jcenter()
25 | google()
26 | }
27 | }
28 |
29 | task clean(type: Delete) {
30 | delete rootProject.buildDir
31 | }
32 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 |
3 | # IDE (e.g. Android Studio) users:
4 | # Gradle settings configured through the IDE *will override*
5 | # any settings specified in this file.
6 |
7 | # For more details on how to configure your build environment visit
8 | # http://www.gradle.org/docs/current/userguide/build_environment.html
9 |
10 | # Specifies the JVM arguments used for the daemon process.
11 | # The setting is particularly useful for tweaking memory settings.
12 | org.gradle.jvmargs=-Xmx1536m
13 |
14 | # When configured, Gradle will run in incubating parallel mode.
15 | # This option should only be used create decoupled projects. More details, visit
16 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
17 | # org.gradle.parallel=true
--------------------------------------------------------------------------------
/gradle/dependencies.gradle:
--------------------------------------------------------------------------------
1 | def versions = [
2 | kotlin : '1.2.21',
3 | support: '27.1.1',
4 | dagger2: '2.11',
5 | retrofit2: '2.4.0',
6 | moshi: '1.6.0',
7 | rxLifecycle: '2.2.1'
8 | ]
9 |
10 | def build = [
11 | buildToolsVersion: '27.0.3',
12 | compileSdkVersion: 27,
13 | minSdkVersion: 14,
14 | targetSdkVersion: 27,
15 |
16 | gradlePlugins: [
17 | android: 'com.android.tools.build:gradle:3.0.1',
18 | kotlin: "org.jetbrains.kotlin:kotlin-gradle-plugin:${versions.kotlin}",
19 | github: 'com.github.dcendents:android-maven-gradle-plugin:1.5',
20 | bintray: 'com.novoda:bintray-release:0.8.0'
21 | ]
22 | ]
23 |
24 | def kotlin = [
25 | stdlib: "org.jetbrains.kotlin:kotlin-stdlib:${versions.kotlin}",
26 | extensions: "org.jetbrains.kotlin:kotlin-android-extensions-runtime:${versions.kotlin}"
27 | ]
28 |
29 | def support = [
30 | appcompat: "com.android.support:appcompat-v7:${versions.support}"
31 | ]
32 |
33 | def moshi = [
34 | core: "com.squareup.moshi:moshi:${versions.moshi}",
35 | kotlin: "com.squareup.moshi:moshi-kotlin:${versions.moshi}"
36 | ]
37 |
38 | def retrofit2 = [
39 | core: "com.squareup.retrofit2:retrofit:${versions.retrofit2}",
40 | converterGson: "com.squareup.retrofit2:converter-gson:${versions.retrofit2}",
41 | converterMoshi: "com.squareup.retrofit2:converter-moshi:${versions.retrofit2}",
42 | adapterRxJava2: "com.squareup.retrofit2:adapter-rxjava2:${versions.retrofit2}"
43 | ]
44 |
45 | def rxJava2 = 'io.reactivex.rxjava2:rxjava:2.1.3'
46 |
47 | def rxAndroid = 'io.reactivex.rxjava2:rxandroid:2.0.1'
48 |
49 | def okhttp3 = [
50 | logging: 'com.squareup.okhttp3:logging-interceptor:3.8.0'
51 | ]
52 |
53 | def gson = 'com.google.code.gson:gson:2.8.1'
54 |
55 | def dagger2 = [
56 | core: "com.google.dagger:dagger:${versions.dagger2}",
57 | compiler: "com.google.dagger:dagger-compiler:${versions.dagger2}",
58 | androidSupport: "com.google.dagger:dagger-android-support:${versions.dagger2}",
59 | androidProcessor: "com.google.dagger:dagger-android-processor:${versions.dagger2}"
60 | ]
61 |
62 | def rxLifecycle = [
63 | core: "com.trello.rxlifecycle2:rxlifecycle:${versions.rxLifecycle}",
64 | kotlin: "com.trello.rxlifecycle2:rxlifecycle-android-lifecycle-kotlin:${versions.rxLifecycle}"
65 | ]
66 |
67 | ext.deps = [
68 | "build": build,
69 | "kotlin": kotlin,
70 | "support": support,
71 | "versions": versions,
72 | "rxJava2": rxJava2,
73 | "rxAndroid": rxAndroid,
74 | "moshi": moshi,
75 | "retrofit2": retrofit2,
76 | "okhttp3": okhttp3,
77 | "gson": gson,
78 | "dagger2": dagger2,
79 | "rxLifecycle": rxLifecycle
80 | ]
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jaychang0917/SimpleApiClient/45a688a6f4f1cc346fe534ecc348d54bb257977c/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Wed Sep 27 22:54:29 HKT 2017
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 | distributionUrl=https\://services.gradle.org/distributions/gradle-4.1-all.zip
7 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
10 | DEFAULT_JVM_OPTS=""
11 |
12 | APP_NAME="Gradle"
13 | APP_BASE_NAME=`basename "$0"`
14 |
15 | # Use the maximum available, or set MAX_FD != -1 to use that value.
16 | MAX_FD="maximum"
17 |
18 | warn ( ) {
19 | echo "$*"
20 | }
21 |
22 | die ( ) {
23 | echo
24 | echo "$*"
25 | echo
26 | exit 1
27 | }
28 |
29 | # OS specific support (must be 'true' or 'false').
30 | cygwin=false
31 | msys=false
32 | darwin=false
33 | case "`uname`" in
34 | CYGWIN* )
35 | cygwin=true
36 | ;;
37 | Darwin* )
38 | darwin=true
39 | ;;
40 | MINGW* )
41 | msys=true
42 | ;;
43 | esac
44 |
45 | # Attempt to set APP_HOME
46 | # Resolve links: $0 may be a link
47 | PRG="$0"
48 | # Need this for relative symlinks.
49 | while [ -h "$PRG" ] ; do
50 | ls=`ls -ld "$PRG"`
51 | link=`expr "$ls" : '.*-> \(.*\)$'`
52 | if expr "$link" : '/.*' > /dev/null; then
53 | PRG="$link"
54 | else
55 | PRG=`dirname "$PRG"`"/$link"
56 | fi
57 | done
58 | SAVED="`pwd`"
59 | cd "`dirname \"$PRG\"`/" >/dev/null
60 | APP_HOME="`pwd -P`"
61 | cd "$SAVED" >/dev/null
62 |
63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
64 |
65 | # Determine the Java command to use to start the JVM.
66 | if [ -n "$JAVA_HOME" ] ; then
67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
68 | # IBM's JDK on AIX uses strange locations for the executables
69 | JAVACMD="$JAVA_HOME/jre/sh/java"
70 | else
71 | JAVACMD="$JAVA_HOME/bin/java"
72 | fi
73 | if [ ! -x "$JAVACMD" ] ; then
74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
75 |
76 | Please set the JAVA_HOME variable in your environment to match the
77 | location of your Java installation."
78 | fi
79 | else
80 | JAVACMD="java"
81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
82 |
83 | Please set the JAVA_HOME variable in your environment to match the
84 | location of your Java installation."
85 | fi
86 |
87 | # Increase the maximum file descriptors if we can.
88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
89 | MAX_FD_LIMIT=`ulimit -H -n`
90 | if [ $? -eq 0 ] ; then
91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
92 | MAX_FD="$MAX_FD_LIMIT"
93 | fi
94 | ulimit -n $MAX_FD
95 | if [ $? -ne 0 ] ; then
96 | warn "Could not set maximum file descriptor limit: $MAX_FD"
97 | fi
98 | else
99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
100 | fi
101 | fi
102 |
103 | # For Darwin, add options to specify how the application appears in the dock
104 | if $darwin; then
105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
106 | fi
107 |
108 | # For Cygwin, switch paths to Windows format before running java
109 | if $cygwin ; then
110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
112 | JAVACMD=`cygpath --unix "$JAVACMD"`
113 |
114 | # We build the pattern for arguments to be converted via cygpath
115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
116 | SEP=""
117 | for dir in $ROOTDIRSRAW ; do
118 | ROOTDIRS="$ROOTDIRS$SEP$dir"
119 | SEP="|"
120 | done
121 | OURCYGPATTERN="(^($ROOTDIRS))"
122 | # Add a user-defined pattern to the cygpath arguments
123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
125 | fi
126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
127 | i=0
128 | for arg in "$@" ; do
129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
131 |
132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
134 | else
135 | eval `echo args$i`="\"$arg\""
136 | fi
137 | i=$((i+1))
138 | done
139 | case $i in
140 | (0) set -- ;;
141 | (1) set -- "$args0" ;;
142 | (2) set -- "$args0" "$args1" ;;
143 | (3) set -- "$args0" "$args1" "$args2" ;;
144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
150 | esac
151 | fi
152 |
153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
154 | function splitJvmOpts() {
155 | JVM_OPTS=("$@")
156 | }
157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
159 |
160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
161 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables create windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
12 | set DEFAULT_JVM_OPTS=
13 |
14 | set DIRNAME=%~dp0
15 | if "%DIRNAME%" == "" set DIRNAME=.
16 | set APP_BASE_NAME=%~n0
17 | set APP_HOME=%DIRNAME%
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto create
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto create
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :create
49 | @rem Get command-line arguments, handling Windowz variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 | if "%@eval[2+2]" == "4" goto 4NT_args
53 |
54 | :win9xME_args
55 | @rem Slurp the command line arguments.
56 | set CMD_LINE_ARGS=
57 | set _SKIP=2
58 |
59 | :win9xME_args_slurp
60 | if "x%~1" == "x" goto execute
61 |
62 | set CMD_LINE_ARGS=%*
63 | goto execute
64 |
65 | :4NT_args
66 | @rem Get arguments from the 4NT Shell from JP Software
67 | set CMD_LINE_ARGS=%$
68 |
69 | :execute
70 | @rem Setup the command line
71 |
72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
73 |
74 | @rem Execute Gradle
75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
76 |
77 | :end
78 | @rem End local scope for the variables create windows NT shell
79 | if "%ERRORLEVEL%"=="0" goto mainEnd
80 |
81 | :fail
82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
83 | rem the _cmd.exe /c_ return code!
84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
85 | exit /b 1
86 |
87 | :mainEnd
88 | if "%OS%"=="Windows_NT" endlocal
89 |
90 | :omega
91 |
--------------------------------------------------------------------------------
/library-jsonparser-gson/.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 |
--------------------------------------------------------------------------------
/library-jsonparser-gson/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.library'
2 | apply plugin: 'kotlin-android'
3 | apply plugin: 'com.novoda.bintray-release'
4 |
5 | buildscript {
6 | repositories {
7 | jcenter()
8 | }
9 | dependencies {
10 | classpath deps.build.gradlePlugins.kotlin
11 | classpath deps.build.gradlePlugins.bintray
12 | }
13 | }
14 |
15 | android {
16 | compileSdkVersion deps.build.compileSdkVersion
17 | buildToolsVersion deps.build.buildToolsVersion
18 | defaultConfig {
19 | minSdkVersion deps.build.minSdkVersion
20 | targetSdkVersion deps.build.targetSdkVersion
21 | versionCode 1
22 | versionName "1.0"
23 | }
24 | buildTypes {
25 | release {
26 | minifyEnabled false
27 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
28 | }
29 | }
30 | }
31 |
32 | dependencies {
33 | compileOnly project(':library')
34 | implementation deps.kotlin.stdlib
35 | api deps.retrofit2.converterGson
36 | api deps.gson
37 | }
38 |
39 | publish {
40 | userOrg = 'jaychang0917'
41 | groupId = 'com.jaychang'
42 | artifactId = 'simpleapiclient-jsonparser-gson'
43 | publishVersion = '2.3.0'
44 | desc = 'A configurable api client based on Retrofit2 and RxJava2 for android.'
45 | website = 'https://github.com/jaychang0917/SimpleApiClient'
46 | }
47 |
--------------------------------------------------------------------------------
/library-jsonparser-gson/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
22 |
--------------------------------------------------------------------------------
/library-jsonparser-gson/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------
/library-jsonparser-gson/src/main/java/com/jaychang/sac/jsonparser/gson/GsonJsonParser.kt:
--------------------------------------------------------------------------------
1 | package com.jaychang.sac.jsonparser.gson
2 |
3 | import com.google.gson.*
4 | import retrofit2.Converter
5 | import retrofit2.converter.gson.GsonConverterFactory
6 | import java.lang.reflect.Type
7 |
8 | class GsonJsonParser : com.jaychang.sac.JsonParser {
9 |
10 | private var gson = Gson()
11 |
12 | override fun getConverterFactory(): Converter.Factory {
13 | return GsonConverterFactory.create(gson)
14 | }
15 |
16 | override fun parse(json: String, typeOfT: Type, keyPath: String?): T {
17 | return if (keyPath == null) {
18 | gson.fromJson(json, typeOfT)
19 | } else {
20 | createGson(typeOfT, keyPath).fromJson(json, typeOfT)
21 | }
22 | }
23 |
24 | override fun update(type: Type, keyPath: String) {
25 | gson = createGson(type, keyPath)
26 | }
27 |
28 | private fun createGson(type: Type, keyPath: String): Gson {
29 | val deserializer = KeyPathDeserializer(keyPath)
30 | return GsonBuilder().registerTypeAdapter(type, deserializer).create()
31 | }
32 |
33 | private class KeyPathDeserializer(private val keyPath: String) : JsonDeserializer {
34 | override fun deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): Any {
35 | val parts = keyPath.split(".")
36 | var jsonObject = json.asJsonObject
37 | var jsonElement: JsonElement = jsonObject[parts[0]]
38 | for (part in parts) {
39 | jsonElement = jsonObject[part]
40 | if (jsonElement is JsonObject) {
41 | jsonObject = jsonElement.asJsonObject
42 | }
43 | }
44 | return Gson().fromJson(jsonElement, typeOfT)
45 | }
46 | }
47 |
48 | }
49 |
--------------------------------------------------------------------------------
/library-jsonparser-moshi/.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 |
--------------------------------------------------------------------------------
/library-jsonparser-moshi/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.library'
2 | apply plugin: 'kotlin-android'
3 | apply plugin: 'com.novoda.bintray-release'
4 |
5 | buildscript {
6 | repositories {
7 | jcenter()
8 | }
9 | dependencies {
10 | classpath deps.build.gradlePlugins.kotlin
11 | classpath deps.build.gradlePlugins.bintray
12 | }
13 | }
14 |
15 | android {
16 | compileSdkVersion deps.build.compileSdkVersion
17 | buildToolsVersion deps.build.buildToolsVersion
18 | defaultConfig {
19 | minSdkVersion deps.build.minSdkVersion
20 | targetSdkVersion deps.build.targetSdkVersion
21 | versionCode 1
22 | versionName "1.0"
23 | }
24 | buildTypes {
25 | release {
26 | minifyEnabled false
27 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
28 | }
29 | }
30 | }
31 |
32 | dependencies {
33 | compileOnly project(':library')
34 | implementation deps.kotlin.stdlib
35 | api deps.retrofit2.converterMoshi
36 | api deps.moshi.core
37 | api deps.moshi.kotlin
38 | }
39 |
40 | publish {
41 | userOrg = 'jaychang0917'
42 | groupId = 'com.jaychang'
43 | artifactId = 'simpleapiclient-jsonparser-moshi'
44 | publishVersion = '2.3.0'
45 | desc = 'A configurable api client based on Retrofit2 and RxJava2 for android.'
46 | website = 'https://github.com/jaychang0917/SimpleApiClient'
47 | }
48 |
--------------------------------------------------------------------------------
/library-jsonparser-moshi/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
22 |
--------------------------------------------------------------------------------
/library-jsonparser-moshi/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------
/library-jsonparser-moshi/src/main/java/com/jaychang/sac/jsonparser/moshi/MoshiJsonParser.kt:
--------------------------------------------------------------------------------
1 | package com.jaychang.sac.jsonparser.moshi
2 |
3 | import com.jaychang.sac.JsonParser
4 | import com.squareup.moshi.JsonAdapter
5 | import com.squareup.moshi.JsonReader
6 | import com.squareup.moshi.JsonWriter
7 | import com.squareup.moshi.Moshi
8 | import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
9 | import retrofit2.Converter
10 | import retrofit2.converter.moshi.MoshiConverterFactory
11 | import java.lang.reflect.Type
12 |
13 | class MoshiJsonParser: JsonParser {
14 | private var parser = Moshi.Builder().add(KotlinJsonAdapterFactory()).build()
15 |
16 | override fun getConverterFactory(): Converter.Factory = MoshiConverterFactory.create(parser)
17 |
18 | override fun parse(json: String, typeOfT: Type, keyPath: String?): T {
19 | return if (keyPath == null) {
20 | parser.adapter(typeOfT).fromJson(json)!!
21 | } else {
22 | createParser(keyPath).adapter(typeOfT).fromJson(json)!!
23 | }
24 | }
25 |
26 | override fun update(type: Type, keyPath: String) {
27 | parser = createParser(keyPath)
28 | }
29 |
30 | private fun createParser(keyPath: String): Moshi {
31 | return Moshi.Builder().add(KeyPathJsonAdapterFactory(keyPath)).add(KotlinJsonAdapterFactory()).build()
32 | }
33 |
34 | private class KeyPathJsonAdapterFactory(val keyPath: String): JsonAdapter.Factory {
35 | override fun create(type: Type, annotations: MutableSet?, moshi: Moshi?): JsonAdapter<*>? {
36 | return KeyPathJsonAdapter(type, keyPath)
37 | }
38 | }
39 |
40 | private class KeyPathJsonAdapter(val type: Type, val keyPath: String): JsonAdapter() {
41 | override fun toJson(writer: JsonWriter, value: Any?) = Unit
42 |
43 | override fun fromJson(reader: JsonReader): Any {
44 | val map = reader.readJsonValue() as Map<*, *>
45 | val moshi = Moshi.Builder().add(KotlinJsonAdapterFactory()).build()
46 | var jsonObject = map
47 | val parts = keyPath.split(".")
48 | var jsonElement = jsonObject[parts[0]]
49 | for (part in parts) {
50 | jsonElement = jsonObject[part]
51 | if (jsonElement is Map<*,*>) {
52 | jsonObject = jsonElement
53 | }
54 | }
55 | return moshi.adapter(type).fromJsonValue(jsonElement)!!
56 | }
57 | }
58 | }
--------------------------------------------------------------------------------
/library/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.library'
2 | apply plugin: 'kotlin-android'
3 | apply plugin: 'com.novoda.bintray-release'
4 |
5 | buildscript {
6 | repositories {
7 | jcenter()
8 | }
9 | dependencies {
10 | classpath deps.build.gradlePlugins.bintray
11 | }
12 | }
13 |
14 | android {
15 | compileSdkVersion deps.build.compileSdkVersion
16 | buildToolsVersion deps.build.buildToolsVersion
17 | defaultConfig {
18 | minSdkVersion deps.build.minSdkVersion
19 | targetSdkVersion deps.build.targetSdkVersion
20 | versionCode 1
21 | versionName "1.0"
22 | }
23 | buildTypes {
24 | release {
25 | minifyEnabled false
26 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
27 | }
28 | }
29 | }
30 |
31 | dependencies {
32 | implementation deps.support.appcompat
33 | implementation deps.kotlin.stdlib
34 | api deps.rxJava2
35 | api deps.rxAndroid
36 | api deps.retrofit2.core
37 | api deps.retrofit2.adapterRxJava2
38 | api deps.okhttp3.logging
39 | implementation deps.gson
40 | implementation deps.rxLifecycle.core
41 | implementation deps.rxLifecycle.kotlin
42 | }
43 |
44 | publish {
45 | userOrg = 'jaychang0917'
46 | groupId = 'com.jaychang'
47 | artifactId = 'simpleapiclient'
48 | publishVersion = '2.3.0'
49 | desc = 'A configurable api client based on Retrofit2 and RxJava2 for android.'
50 | website = 'https://github.com/jaychang0917/SimpleApiClient'
51 | }
52 |
--------------------------------------------------------------------------------
/library/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 |
--------------------------------------------------------------------------------
/library/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
3 |
4 |
5 |
6 |
7 |
12 |
13 |
14 |
--------------------------------------------------------------------------------
/library/src/main/java/com/jaychang/sac/ApiManager.kt:
--------------------------------------------------------------------------------
1 | package com.jaychang.sac
2 |
3 | import android.annotation.SuppressLint
4 | import android.content.Context
5 | import com.jaychang.sac.calladapter.MockResponseAdapterFactory
6 | import com.jaychang.sac.calladapter.ObserveOnCallAdapterFactory
7 | import com.jaychang.sac.converter.KeyPathResponseConverterFactory
8 | import com.jaychang.sac.converter.WrappedResponseConverterFactory
9 | import com.jaychang.sac.interceptor.HeaderInterceptor
10 | import com.jaychang.sac.interceptor.ParameterInterceptor
11 | import io.reactivex.android.schedulers.AndroidSchedulers
12 | import io.reactivex.exceptions.CompositeException
13 | import io.reactivex.plugins.RxJavaPlugins
14 | import io.reactivex.schedulers.Schedulers
15 | import okhttp3.CertificatePinner
16 | import okhttp3.OkHttpClient
17 | import okhttp3.logging.HttpLoggingInterceptor
18 | import retrofit2.Retrofit
19 | import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
20 | import java.util.concurrent.TimeUnit
21 | import kotlin.reflect.KClass
22 |
23 | @SuppressLint("StaticFieldLeak")
24 | object ApiManager {
25 | internal var errorClass: KClass? = null
26 | internal var errorMessageKeyPath: String? = null
27 | internal lateinit var context: Context
28 | internal lateinit var jsonParser: JsonParser
29 |
30 | fun init(config: SimpleApiClient.Config): Retrofit {
31 | this.jsonParser = config.jsonParser ?: throw IllegalArgumentException("jsonParser cannot be null")
32 | this.errorClass = config.errorClass
33 | this.errorMessageKeyPath = config.errorMessageKeyPath
34 |
35 | RxJavaPlugins.setErrorHandler {
36 | when (it){
37 | is CompositeException -> {
38 | if (it.exceptions.size >= 2) {
39 | config.errorHandler?.invoke(it.exceptions[1])
40 | } else {
41 | config.errorHandler?.invoke(it.exceptions[0])
42 | }
43 | }
44 | }
45 | }
46 |
47 | return createRetrofit(config, createOkHttpClient(config))
48 | }
49 |
50 | private fun createOkHttpClient(config: SimpleApiClient.Config): OkHttpClient {
51 | val builder = OkHttpClient.Builder()
52 |
53 | if (config.logLevel != LogLevel.NONE) {
54 | val httpLoggingInterceptor = HttpLoggingInterceptor()
55 | httpLoggingInterceptor.level = config.logLevel
56 | builder.addInterceptor(httpLoggingInterceptor)
57 | }
58 |
59 | config.defaultParameters?.let {
60 | builder.addInterceptor(ParameterInterceptor(it))
61 | }
62 |
63 | config.defaultHeaders?.let {
64 | builder.addInterceptor(HeaderInterceptor(it))
65 | }
66 |
67 | config.networkInterceptors?.forEach {
68 | builder.addNetworkInterceptor(it)
69 | }
70 |
71 | config.interceptors?.forEach {
72 | builder.addInterceptor(it)
73 | }
74 |
75 | config.certificatePins?.let {
76 | if (it.isEmpty()) {
77 | return@let
78 | }
79 | val pinBuilder = CertificatePinner.Builder()
80 | for (pin in it) {
81 | pin.sha1PublicKeyHash?.let {
82 | pinBuilder.add(pin.hostname, pin.toString())
83 | }
84 | pin.sha256PublicKeyHash?.let {
85 | pinBuilder.add(pin.hostname, pin.toString())
86 | }
87 | }
88 | builder.certificatePinner(pinBuilder.build())
89 | }
90 |
91 | builder
92 | .connectTimeout(config.connectTimeout, TimeUnit.MILLISECONDS)
93 | .readTimeout(config.readTimeout, TimeUnit.MILLISECONDS)
94 | .writeTimeout(config.writeTimeout, TimeUnit.MILLISECONDS)
95 |
96 | return config.httpClient ?: builder.build()
97 | }
98 |
99 | private fun createRetrofit(config: SimpleApiClient.Config, client: OkHttpClient): Retrofit {
100 | return Retrofit.Builder()
101 | .baseUrl(config.baseUrl).client(client)
102 | .addConverterFactory(KeyPathResponseConverterFactory.create(jsonParser))
103 | .addConverterFactory(WrappedResponseConverterFactory.create())
104 | .addConverterFactory(jsonParser.getConverterFactory())
105 | .addCallAdapterFactory(MockResponseAdapterFactory.create(config.isMockResponseEnabled, context, jsonParser))
106 | .addCallAdapterFactory(ObserveOnCallAdapterFactory.create(AndroidSchedulers.mainThread()))
107 | .addCallAdapterFactory(RxJava2CallAdapterFactory.createWithScheduler(Schedulers.io()))
108 | .build()
109 | }
110 | }
--------------------------------------------------------------------------------
/library/src/main/java/com/jaychang/sac/CertificatePin.kt:
--------------------------------------------------------------------------------
1 | package com.jaychang.sac
2 |
3 | class CertificatePin(val hostname: String,
4 | val sha1PublicKeyHash: String? = null,
5 | val sha256PublicKeyHash: String? = null) {
6 | override fun toString(): String {
7 | return when {
8 | sha1PublicKeyHash != null -> "sha1/$sha1PublicKeyHash"
9 | sha256PublicKeyHash != null -> "sha256/$sha256PublicKeyHash"
10 | else -> throw IllegalArgumentException("You must enter `sha1PublicKeyHash` or `sha256PublicKeyHash`")
11 | }
12 | }
13 | }
--------------------------------------------------------------------------------
/library/src/main/java/com/jaychang/sac/ContextProvider.kt:
--------------------------------------------------------------------------------
1 | package com.jaychang.sac
2 |
3 | import android.content.ContentProvider
4 | import android.content.ContentValues
5 | import android.database.Cursor
6 | import android.net.Uri
7 |
8 | class ContextProvider : ContentProvider() {
9 | override fun onCreate(): Boolean {
10 | ApiManager.context = context.applicationContext
11 | return true
12 | }
13 |
14 | override fun insert(p0: Uri?, p1: ContentValues?): Uri? = null
15 |
16 | override fun query(p0: Uri?, p1: Array?, p2: String?, p3: Array?, p4: String?): Cursor? = null
17 |
18 | override fun update(p0: Uri?, p1: ContentValues?, p2: String?, p3: Array?): Int = 0
19 |
20 | override fun delete(p0: Uri?, p1: String?, p2: Array?): Int = 0
21 |
22 | override fun getType(p0: Uri?): String? = null
23 | }
--------------------------------------------------------------------------------
/library/src/main/java/com/jaychang/sac/Error.kt:
--------------------------------------------------------------------------------
1 | package com.jaychang.sac
2 |
3 | sealed class Error : Throwable()
4 | class AuthenticationError(val code: Int, override val message: String) : Error()
5 | class ClientError(val code: Int, override val message: String) : Error()
6 | class ServerError(val code: Int, override val message: String) : Error()
7 | class NetworkError(val source: Throwable) : Error()
8 | class SSLError(val source: Throwable) : Error()
--------------------------------------------------------------------------------
/library/src/main/java/com/jaychang/sac/ErrorConsumer.kt:
--------------------------------------------------------------------------------
1 | package com.jaychang.sac
2 |
3 | import io.reactivex.functions.Consumer
4 | import retrofit2.HttpException
5 | import java.net.UnknownHostException
6 | import javax.net.ssl.SSLPeerUnverifiedException
7 | import kotlin.properties.Delegates
8 |
9 | internal class ErrorConsumer(private val handler: (Throwable) -> Unit) : Consumer {
10 | override fun accept(error: T) {
11 | var result: Throwable by Delegates.notNull()
12 | when (error) {
13 | is HttpException -> {
14 | val code = error.response().code()
15 | val errorJson = error.response().errorBody()?.string()
16 | var message = ""
17 | if (!errorJson.isNullOrEmpty()) {
18 | if (ApiManager.errorClass != null) {
19 | message = (ApiManager.jsonParser.parse(errorJson!!, ApiManager.errorClass!!.java) as SimpleApiError).message
20 | } else if (ApiManager.errorMessageKeyPath != null) {
21 | message = ApiManager.jsonParser.parse(errorJson!!, String::class.java, ApiManager.errorMessageKeyPath!!)
22 | }
23 | }
24 | when (code) {
25 | 401, 403 -> result = AuthenticationError(code = code, message = message)
26 | in 400..499 -> result = ClientError(code = code, message = message)
27 | in 500..599 -> result = ServerError(code = code, message = message)
28 | }
29 | }
30 | is UnknownHostException -> {
31 | result = NetworkError(source = error)
32 | }
33 | is SSLPeerUnverifiedException -> {
34 | result = SSLError(source = error)
35 | }
36 | else -> {
37 | result = error
38 | }
39 | }
40 | handler(result)
41 |
42 | throw result
43 | }
44 | }
--------------------------------------------------------------------------------
/library/src/main/java/com/jaychang/sac/JsonParser.kt:
--------------------------------------------------------------------------------
1 | package com.jaychang.sac
2 |
3 | import retrofit2.Converter
4 | import java.lang.reflect.Type
5 |
6 | interface JsonParser {
7 | fun getConverterFactory(): Converter.Factory
8 |
9 | fun parse(json: String, typeOfT: Type, keyPath: String? = null): T
10 |
11 | /**
12 | * Update the parser to deserialize response by keyPath
13 | * */
14 | fun update(type: Type, keyPath: String) {
15 | }
16 | }
--------------------------------------------------------------------------------
/library/src/main/java/com/jaychang/sac/SimpleApiClient.kt:
--------------------------------------------------------------------------------
1 | package com.jaychang.sac
2 |
3 | import io.reactivex.Observable
4 | import okhttp3.Interceptor
5 | import okhttp3.OkHttpClient
6 | import okhttp3.logging.HttpLoggingInterceptor
7 | import java.util.concurrent.TimeUnit
8 | import kotlin.reflect.KClass
9 |
10 | typealias LogLevel = HttpLoggingInterceptor.Level
11 |
12 | open class SimpleApiClient {
13 | data class Config(
14 | var baseUrl: String = "",
15 | var connectTimeout: Long = TimeUnit.MINUTES.toMillis(1),
16 | var readTimeout: Long = TimeUnit.MINUTES.toMillis(1),
17 | var writeTimeout: Long = TimeUnit.MINUTES.toMillis(1),
18 | var defaultHeaders: Map? = null,
19 | var defaultParameters: Map? = null,
20 | var certificatePins: List? = null,
21 | var logLevel: LogLevel = LogLevel.NONE,
22 | var networkInterceptors: List? = null,
23 | var interceptors: List? = null,
24 | var httpClient: OkHttpClient? = null,
25 | var isMockResponseEnabled: Boolean = false,
26 | var errorClass: KClass? = null,
27 | var errorMessageKeyPath: String? = null,
28 | var errorHandler: ((Throwable) -> Unit)? = null,
29 | var jsonParser: JsonParser? = null
30 | )
31 |
32 | companion object {
33 | @JvmStatic
34 | inline fun create(init: Config.() -> Unit): Api {
35 | val config = Config()
36 | config.init()
37 | return ApiManager.init(config).create(Api::class.java)
38 | }
39 |
40 | @JvmStatic
41 | fun all(vararg calls: Observable<*>): Observable> {
42 | return Observable.zip(calls.asIterable(), { objects -> objects })
43 | }
44 | }
45 | }
--------------------------------------------------------------------------------
/library/src/main/java/com/jaychang/sac/SimpleApiError.kt:
--------------------------------------------------------------------------------
1 | package com.jaychang.sac
2 |
3 | interface SimpleApiError {
4 | val message: String
5 | }
6 |
--------------------------------------------------------------------------------
/library/src/main/java/com/jaychang/sac/SimpleApiResult.kt:
--------------------------------------------------------------------------------
1 | package com.jaychang.sac
2 |
3 | interface SimpleApiResult {
4 | val result : T
5 | }
6 |
--------------------------------------------------------------------------------
/library/src/main/java/com/jaychang/sac/SimpleExtension.kt:
--------------------------------------------------------------------------------
1 | @file:JvmName("SimpleApiClientEx")
2 |
3 | package com.jaychang.sac
4 |
5 | import android.arch.lifecycle.Lifecycle
6 | import android.arch.lifecycle.LifecycleOwner
7 | import com.jaychang.sac.util.Utils
8 | import com.trello.rxlifecycle2.android.lifecycle.kotlin.bindToLifecycle
9 | import com.trello.rxlifecycle2.android.lifecycle.kotlin.bindUntilEvent
10 | import io.reactivex.*
11 | import io.reactivex.disposables.Disposable
12 | import io.reactivex.functions.Action
13 | import io.reactivex.functions.BiFunction
14 | import io.reactivex.functions.Consumer
15 | import okhttp3.MediaType
16 | import okhttp3.MultipartBody
17 | import okhttp3.RequestBody
18 | import org.reactivestreams.Publisher
19 | import java.io.File
20 | import java.util.concurrent.TimeUnit
21 |
22 | fun Observable.then(mapper: (T) -> ObservableSource): Observable {
23 | return flatMap(mapper)
24 | }
25 |
26 | fun Flowable.then(mapper: (T) -> Publisher): Flowable {
27 | return flatMap(mapper)
28 | }
29 |
30 | fun Single.then(mapper: (T) -> SingleSource): Single {
31 | return flatMap(mapper)
32 | }
33 |
34 | fun Maybe.then(mapper: (T) -> MaybeSource): Maybe {
35 | return flatMap(mapper)
36 | }
37 |
38 |
39 | fun Observable.thenAll(vararg calls: ObservableSource<*>): Observable> {
40 | return flatMap {
41 | Observable.zip(calls.asIterable(), { objects -> objects })
42 | }
43 | }
44 |
45 | fun Flowable.thenAll(vararg calls: Publisher<*>): Flowable> {
46 | return flatMap {
47 | Flowable.zip(calls.asIterable(), { objects -> objects })
48 | }
49 | }
50 |
51 | fun Single.thenAll(vararg calls: SingleSource<*>): Single> {
52 | return flatMap {
53 | Single.zip(calls.asIterable(), { objects -> objects })
54 | }
55 | }
56 |
57 | fun Maybe.thenAll(vararg calls: MaybeSource<*>): Maybe> {
58 | return flatMap {
59 | Maybe.zip(calls.asIterable(), { objects -> objects })
60 | }
61 | }
62 |
63 |
64 | fun Observable.retryExponential(maxRetryCount: Int = Int.MAX_VALUE, delaySeconds: Long): Observable {
65 | return retryWhen { error ->
66 | error
67 | .zipWith(Observable.range(1, maxRetryCount + 1), BiFunction { throwable: Throwable, retryCount: Int -> (throwable to retryCount) })
68 | .flatMap { pair ->
69 | if (pair.second == maxRetryCount + 1) {
70 | Observable.error(pair.first)
71 | } else {
72 | Observable.timer(Math.pow(delaySeconds.toDouble(), pair.second.toDouble()).toLong(), TimeUnit.SECONDS)
73 | }
74 | }
75 | }
76 | }
77 |
78 | fun Flowable.retryExponential(maxRetryCount: Int = Int.MAX_VALUE, delaySeconds: Long): Flowable {
79 | return retryWhen { error ->
80 | error
81 | .zipWith(Flowable.range(1, maxRetryCount + 1), BiFunction { throwable: Throwable, retryCount: Int -> (throwable to retryCount) })
82 | .flatMap { pair ->
83 | if (pair.second == maxRetryCount + 1) {
84 | Flowable.error(pair.first)
85 | } else {
86 | Flowable.timer(Math.pow(delaySeconds.toDouble(), pair.second.toDouble()).toLong(), TimeUnit.SECONDS)
87 | }
88 | }
89 | }
90 | }
91 |
92 | fun Single.retryExponential(maxRetryCount: Int = Int.MAX_VALUE, delaySeconds: Long): Single {
93 | return retryWhen { error ->
94 | error
95 | .zipWith(Flowable.range(1, maxRetryCount + 1), BiFunction { throwable: Throwable, retryCount: Int -> (throwable to retryCount) })
96 | .flatMap { pair ->
97 | if (pair.second == maxRetryCount + 1) {
98 | Flowable.error(pair.first)
99 | } else {
100 | Flowable.timer(Math.pow(delaySeconds.toDouble(), pair.second.toDouble()).toLong(), TimeUnit.SECONDS)
101 | }
102 | }
103 | }
104 | }
105 |
106 | fun Maybe.retryExponential(maxRetryCount: Int = Int.MAX_VALUE, delaySeconds: Long): Maybe {
107 | return retryWhen { error ->
108 | error
109 | .zipWith(Flowable.range(1, maxRetryCount + 1), BiFunction { throwable: Throwable, retryCount: Int -> (throwable to retryCount) })
110 | .flatMap { pair ->
111 | if (pair.second == maxRetryCount + 1) {
112 | Flowable.error(pair.first)
113 | } else {
114 | Flowable.timer(Math.pow(delaySeconds.toDouble(), pair.second.toDouble()).toLong(), TimeUnit.SECONDS)
115 | }
116 | }
117 | }
118 | }
119 |
120 |
121 | fun Observable.retryInterval(maxRetryCount: Int = Int.MAX_VALUE, delaySeconds: Long): Observable {
122 | return retryWhen { error ->
123 | error
124 | .zipWith(Observable.range(1, maxRetryCount + 1), BiFunction { throwable: Throwable, retryCount: Int -> (throwable to retryCount) })
125 | .flatMap { pair ->
126 | if (pair.second == maxRetryCount + 1) {
127 | Observable.error(pair.first)
128 | } else {
129 | Observable.timer(delaySeconds, TimeUnit.SECONDS)
130 | }
131 | }
132 | }
133 | }
134 |
135 | fun Flowable.retryInterval(maxRetryCount: Int = Int.MAX_VALUE, delaySeconds: Long): Flowable {
136 | return retryWhen { error ->
137 | error
138 | .zipWith(Flowable.range(1, maxRetryCount + 1), BiFunction { throwable: Throwable, retryCount: Int -> (throwable to retryCount) })
139 | .flatMap { pair ->
140 | if (pair.second == maxRetryCount + 1) {
141 | Flowable.error(pair.first)
142 | } else {
143 | Flowable.timer(delaySeconds, TimeUnit.SECONDS)
144 | }
145 | }
146 | }
147 | }
148 |
149 | fun Single.retryInterval(maxRetryCount: Int = Int.MAX_VALUE, delaySeconds: Long): Single {
150 | return retryWhen { error ->
151 | error
152 | .zipWith(Flowable.range(1, maxRetryCount + 1), BiFunction { throwable: Throwable, retryCount: Int -> (throwable to retryCount) })
153 | .flatMap { pair ->
154 | if (pair.second == maxRetryCount + 1) {
155 | Flowable.error(pair.first)
156 | } else {
157 | Flowable.timer(delaySeconds, TimeUnit.SECONDS)
158 | }
159 | }
160 | }
161 | }
162 |
163 | fun Maybe.retryInterval(maxRetryCount: Int = Int.MAX_VALUE, delaySeconds: Long): Maybe {
164 | return retryWhen { error ->
165 | error
166 | .zipWith(Flowable.range(1, maxRetryCount + 1), BiFunction { throwable: Throwable, retryCount: Int -> (throwable to retryCount) })
167 | .flatMap { pair ->
168 | if (pair.second == maxRetryCount + 1) {
169 | Flowable.error(pair.first)
170 | } else {
171 | Flowable.timer(delaySeconds, TimeUnit.SECONDS)
172 | }
173 | }
174 | }
175 | }
176 |
177 |
178 | fun Observable.autoCancel(lifecycleOwner: LifecycleOwner, untilEvent: Lifecycle.Event? = null): Observable {
179 | return if (untilEvent != null) {
180 | bindUntilEvent(lifecycleOwner, untilEvent)
181 | } else {
182 | bindToLifecycle(lifecycleOwner)
183 | }
184 | }
185 |
186 | fun Flowable.autoCancel(lifecycleOwner: LifecycleOwner, untilEvent: Lifecycle.Event? = null): Flowable {
187 | return if (untilEvent != null) {
188 | bindUntilEvent(lifecycleOwner, untilEvent)
189 | } else {
190 | bindToLifecycle(lifecycleOwner)
191 | }
192 | }
193 |
194 | fun Single.autoDispose(lifecycleOwner: LifecycleOwner, untilEvent: Lifecycle.Event? = null): Single {
195 | return if (untilEvent != null) {
196 | bindUntilEvent(lifecycleOwner, untilEvent)
197 | } else {
198 | bindToLifecycle(lifecycleOwner)
199 | }
200 | }
201 |
202 | fun Maybe.autoDispose(lifecycleOwner: LifecycleOwner, untilEvent: Lifecycle.Event? = null): Maybe {
203 | return if (untilEvent != null) {
204 | bindUntilEvent(lifecycleOwner, untilEvent)
205 | } else {
206 | bindToLifecycle(lifecycleOwner)
207 | }
208 | }
209 |
210 | fun Completable.autoDispose(lifecycleOwner: LifecycleOwner, untilEvent: Lifecycle.Event? = null): Completable {
211 | return if (untilEvent != null) {
212 | bindUntilEvent(lifecycleOwner, untilEvent)
213 | } else {
214 | bindToLifecycle(lifecycleOwner)
215 | }
216 | }
217 |
218 |
219 | fun Observable.observe(onStart: () -> Unit = {}, onEnd: () -> Unit = {}, onSuccess: (T) -> Unit = {}, onError: (Throwable) -> Unit = {}): Disposable {
220 | return doOnSubscribe { onStart() }.doFinally { onEnd() }
221 | .subscribe(Consumer { onSuccess(it) }, ErrorConsumer(onError))
222 | }
223 |
224 | fun Flowable.observe(onStart: () -> Unit = {}, onEnd: () -> Unit = {}, onSuccess: (T) -> Unit = {}, onError: (Throwable) -> Unit = {}): Disposable {
225 | return doOnSubscribe { onStart() }.doFinally { onEnd() }
226 | .subscribe(Consumer { onSuccess(it) }, ErrorConsumer(onError))
227 | }
228 |
229 | fun Single.observe(onStart: () -> Unit = {}, onEnd: () -> Unit = {}, onSuccess: (T) -> Unit = {}, onError: (Throwable) -> Unit = {}): Disposable {
230 | return doOnSubscribe { onStart() }.doFinally { onEnd() }
231 | .subscribe(Consumer { onSuccess(it) }, ErrorConsumer(onError))
232 | }
233 |
234 | fun Maybe.observe(onStart: () -> Unit = {}, onEnd: () -> Unit = {}, onSuccess: (T) -> Unit = {}, onError: (Throwable) -> Unit = {}): Disposable {
235 | return doOnSubscribe { onStart() }.doFinally { onEnd() }
236 | .subscribe(Consumer { onSuccess(it) }, ErrorConsumer(onError))
237 | }
238 |
239 | fun Completable.observe(onStart: () -> Unit = {}, onEnd: () -> Unit = {}, onSuccess: () -> Unit = {}, onError: (Throwable) -> Unit = {}): Disposable {
240 | return doOnSubscribe { onStart() }.doFinally { onEnd() }
241 | .subscribe(Action { onSuccess() }, ErrorConsumer(onError))
242 | }
243 |
244 | fun File.toMultipartBodyPart(paramName: String, mimeType: String = Utils.getMimeType(this)) {
245 | MultipartBody.Part.createFormData(paramName, name, RequestBody.create(MediaType.parse(mimeType), this))
246 | }
--------------------------------------------------------------------------------
/library/src/main/java/com/jaychang/sac/annotation/KeyPathResponse.kt:
--------------------------------------------------------------------------------
1 | package com.jaychang.sac.annotation
2 |
3 | @Target(AnnotationTarget.FUNCTION)
4 | annotation class KeyPathResponse(val value: String)
--------------------------------------------------------------------------------
/library/src/main/java/com/jaychang/sac/annotation/MockResponse.kt:
--------------------------------------------------------------------------------
1 | package com.jaychang.sac.annotation
2 |
3 | import android.support.annotation.RawRes
4 |
5 | enum class Status {
6 | SUCCESS, AUTHENTICATION_ERROR, CLIENT_ERROR, SERVER_ERROR, NETWORK_ERROR, SSL_ERROR
7 | }
8 |
9 | annotation class MockResponse(@RawRes val json: Int = -1, val status: Status = Status.SUCCESS)
--------------------------------------------------------------------------------
/library/src/main/java/com/jaychang/sac/annotation/WrappedResponse.java:
--------------------------------------------------------------------------------
1 | package com.jaychang.sac.annotation;
2 |
3 | import com.jaychang.sac.SimpleApiResult;
4 |
5 | import java.lang.annotation.ElementType;
6 | import java.lang.annotation.Target;
7 |
8 | // kotlin do not support: `annotation class Unwrap(val value: KClass>)`
9 | @Target(ElementType.METHOD)
10 | public @interface WrappedResponse {
11 | Class extends SimpleApiResult> value();
12 | }
--------------------------------------------------------------------------------
/library/src/main/java/com/jaychang/sac/calladapter/MockResponseAdapterFactory.kt:
--------------------------------------------------------------------------------
1 | package com.jaychang.sac.calladapter
2 |
3 | import android.content.Context
4 | import com.google.gson.reflect.TypeToken
5 | import com.jaychang.sac.JsonParser
6 | import com.jaychang.sac.SimpleApiResult
7 | import com.jaychang.sac.annotation.MockResponse
8 | import com.jaychang.sac.annotation.Status.*
9 | import com.jaychang.sac.annotation.WrappedResponse
10 | import com.jaychang.sac.util.Utils
11 | import io.reactivex.*
12 | import io.reactivex.android.schedulers.AndroidSchedulers
13 | import io.reactivex.schedulers.Schedulers
14 | import okhttp3.MediaType
15 | import okhttp3.ResponseBody
16 | import retrofit2.*
17 | import java.lang.reflect.ParameterizedType
18 | import java.lang.reflect.Type
19 | import java.net.UnknownHostException
20 | import javax.net.ssl.SSLPeerUnverifiedException
21 |
22 | internal class MockResponseAdapterFactory(private val isEnabled: Boolean, private val context: Context, private val jsonParser: JsonParser) : CallAdapter.Factory() {
23 | companion object {
24 | fun create(isEnabled: Boolean, context: Context, jsonParser: JsonParser): MockResponseAdapterFactory {
25 | return MockResponseAdapterFactory(isEnabled, context, jsonParser)
26 | }
27 | }
28 |
29 | override fun get(type: Type, annotations: Array, retrofit: Retrofit): CallAdapter<*, *>? {
30 | val rawType = getRawType(type)
31 |
32 | val isObservable = rawType === Observable::class.java
33 | val isFlowable = rawType === Flowable::class.java
34 | val isSingle = rawType === Single::class.java
35 | val isMaybe = rawType === Maybe::class.java
36 | val isCompletable = rawType === Completable::class.java
37 |
38 | if (!isObservable && !isFlowable && !isSingle && !isMaybe && !isCompletable) {
39 | return null
40 | }
41 |
42 | if (annotations.none { it is MockResponse } || !isEnabled) {
43 | return null
44 | }
45 |
46 | val mockResponse = annotations.find { it is MockResponse } as MockResponse
47 | val status = mockResponse.status
48 |
49 | if (status == SUCCESS) {
50 | return SuccessCallAdapter(type, annotations, mockResponse, isObservable, isFlowable, isSingle, isMaybe, isCompletable)
51 | }
52 |
53 | return ErrorStatusCallAdapter(type, mockResponse, isObservable, isFlowable, isSingle, isMaybe, isCompletable)
54 | }
55 |
56 | inner class SuccessCallAdapter(type: Type,
57 | annotations: Array,
58 | private val mockAnnotation: MockResponse,
59 | private val isObservable: Boolean,
60 | private val isFlowable: Boolean,
61 | private val isSingle: Boolean,
62 | private val isMaybe: Boolean,
63 | private val isCompletable: Boolean) : CallAdapter {
64 | private var apiResultType: Type? = null
65 |
66 | init {
67 | if (!isCompletable) {
68 | val dataType = (type as ParameterizedType).actualTypeArguments[0]
69 | apiResultType = if (annotations.any { it is WrappedResponse }) {
70 | val wrappedType = annotations.find { it is WrappedResponse } as WrappedResponse
71 | TypeToken.getParameterized(wrappedType.value.java, dataType).type
72 | } else {
73 | dataType
74 | }
75 | }
76 | }
77 |
78 | override fun adapt(call: Call?): Any? {
79 | val callable = {
80 | if (mockAnnotation.json == -1 || isCompletable) {
81 | Unit
82 | } else {
83 | val json = Utils.toText(context, mockAnnotation.json)
84 | val data = jsonParser.parse(json, apiResultType!!)
85 | if (data is SimpleApiResult) {
86 | data.result
87 | } else {
88 | data
89 | }
90 | }
91 | }
92 | return when {
93 | isObservable -> Observable.fromCallable(callable).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
94 | isFlowable -> Flowable.fromCallable(callable).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
95 | isSingle -> Single.fromCallable(callable).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
96 | isMaybe -> Maybe.fromCallable(callable).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
97 | isCompletable -> Completable.complete().subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
98 | else -> throw IllegalArgumentException("Unsupported type")
99 | }
100 | }
101 |
102 | override fun responseType(): Type {
103 | return if (isCompletable) Unit::class.java else apiResultType!!
104 | }
105 | }
106 |
107 | inner class ErrorStatusCallAdapter(private val type: Type,
108 | private val mockResponse: MockResponse,
109 | private val isObservable: Boolean,
110 | private val isFlowable: Boolean,
111 | private val isSingle: Boolean,
112 | private val isMaybe: Boolean,
113 | private val isCompletable: Boolean) : CallAdapter {
114 | override fun adapt(call: Call?): Any? {
115 | fun error(code: Int? = null, exception: Exception? = null) : Throwable {
116 | if (code != null) {
117 | val message = if (mockResponse.json != -1) {
118 | Utils.toText(context, mockResponse.json)
119 | } else {
120 | ""
121 | }
122 | val response = Response.error(code, ResponseBody.create(MediaType.parse("application/json"), message))
123 | return HttpException(response)
124 | }
125 | return exception!!
126 | }
127 |
128 | fun errorSource(code: Int? = null, exception: Exception? = null): Any {
129 | return when {
130 | isObservable -> Observable.error { error(code, exception) }.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
131 | isFlowable -> Flowable.error { error(code, exception) }.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
132 | isSingle -> Single.error { error(code, exception) }.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
133 | isMaybe -> Maybe.error { error(code, exception) }.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
134 | isCompletable -> Completable.error { error(code, exception) }.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
135 | else -> throw IllegalArgumentException("Unsupported type")
136 | }
137 | }
138 |
139 | return when (mockResponse.status) {
140 | AUTHENTICATION_ERROR -> { errorSource(code = 403) }
141 | CLIENT_ERROR -> { errorSource(code = 400)}
142 | SERVER_ERROR -> { errorSource(code = 500) }
143 | NETWORK_ERROR -> { errorSource(exception = UnknownHostException()) }
144 | SSL_ERROR -> { errorSource(exception = SSLPeerUnverifiedException("mock ssl error")) }
145 | else -> throw IllegalArgumentException("Unsupported type")
146 | }
147 | }
148 |
149 | override fun responseType(): Type {
150 | return type
151 | }
152 | }
153 | }
--------------------------------------------------------------------------------
/library/src/main/java/com/jaychang/sac/calladapter/ObserveOnCallAdapterFactory.kt:
--------------------------------------------------------------------------------
1 | package com.jaychang.sac.calladapter
2 |
3 | import io.reactivex.*
4 | import retrofit2.Call
5 | import retrofit2.CallAdapter
6 | import retrofit2.Retrofit
7 | import java.lang.reflect.Type
8 |
9 |
10 | internal class ObserveOnCallAdapterFactory(private val scheduler: Scheduler) : CallAdapter.Factory() {
11 | companion object {
12 | fun create(scheduler: Scheduler): ObserveOnCallAdapterFactory {
13 | return ObserveOnCallAdapterFactory(scheduler)
14 | }
15 | }
16 |
17 | override fun get(returnType: Type, annotations: Array, retrofit: Retrofit): CallAdapter<*, *>? {
18 | val rawType = getRawType(returnType)
19 |
20 | val isObservable = rawType === Observable::class.java
21 | val isFlowable = rawType === Flowable::class.java
22 | val isSingle = rawType === Single::class.java
23 | val isMaybe = rawType === Maybe::class.java
24 | val isCompletable = rawType === Completable::class.java
25 |
26 | if (!isObservable && !isFlowable && !isSingle && !isMaybe && !isCompletable) {
27 | return null
28 | }
29 |
30 | val delegate = retrofit.nextCallAdapter(this, returnType, annotations)
31 |
32 | return ObserveOnCallAdapter(delegate, scheduler, isObservable, isFlowable, isSingle, isMaybe, isCompletable)
33 | }
34 | }
35 |
36 | internal class ObserveOnCallAdapter(private val delegate: CallAdapter,
37 | private val scheduler: Scheduler,
38 | private val isObservable: Boolean,
39 | private val isFlowable: Boolean,
40 | private val isSingle: Boolean,
41 | private val isMaybe: Boolean,
42 | private val isCompletable: Boolean): CallAdapter {
43 | override fun adapt(call: Call): Any? {
44 | val result = delegate.adapt(call)
45 | return when {
46 | isObservable -> (result as Observable<*>).observeOn(scheduler)
47 | isFlowable -> (result as Flowable<*>).observeOn(scheduler)
48 | isSingle -> (result as Single<*>).observeOn(scheduler)
49 | isMaybe -> (result as Maybe<*>).observeOn(scheduler)
50 | isCompletable -> (result as Completable).observeOn(scheduler)
51 | else -> throw IllegalArgumentException("Unsupported type")
52 | }
53 | }
54 |
55 | override fun responseType(): Type {
56 | return delegate.responseType()
57 | }
58 | }
--------------------------------------------------------------------------------
/library/src/main/java/com/jaychang/sac/converter/FileConverterFactory.kt:
--------------------------------------------------------------------------------
1 | package com.jaychang.sac.converter
2 |
3 | import com.jaychang.sac.util.Utils
4 | import okhttp3.MediaType
5 | import okhttp3.MultipartBody
6 | import okhttp3.RequestBody
7 | import retrofit2.Converter
8 | import retrofit2.Retrofit
9 | import retrofit2.http.Part
10 | import java.io.File
11 | import java.lang.reflect.ParameterizedType
12 | import java.lang.reflect.Type
13 |
14 | class FileConverterFactory : Converter.Factory() {
15 | companion object {
16 | @JvmStatic
17 | fun create(): FileConverterFactory {
18 | return FileConverterFactory()
19 | }
20 | }
21 |
22 | override fun requestBodyConverter(type: Type, parameterAnnotations: Array, methodAnnotations: Array, retrofit: Retrofit): Converter<*, RequestBody>? {
23 | val isFileType = isFileType(type)
24 | val isListOfFileType = isListOfFileType(type)
25 |
26 | if (!isFileType && !isListOfFileType) {
27 | return null
28 | }
29 |
30 | val annotation = parameterAnnotations.find { annotation -> annotation is Part } as Part
31 |
32 | return Converter { value ->
33 | when {
34 | isFileType -> createMultipartBody(listOf(value as File), annotation)
35 | else -> createMultipartBody(value as Iterable, annotation)
36 | }
37 | }
38 | }
39 |
40 | private fun isFileType(type: Type): Boolean {
41 | return type == File::class.java
42 | }
43 |
44 | private fun isListOfFileType(type: Type): Boolean {
45 | val rawType = getRawType(type)
46 |
47 | val isList = Iterable::class.java.isAssignableFrom(rawType)
48 |
49 | val isParameterizedType = type is ParameterizedType
50 |
51 | if (isList && isParameterizedType) {
52 | val innerType = getParameterUpperBound(0, type as ParameterizedType)
53 | return isFileType(innerType)
54 | }
55 |
56 | return false
57 | }
58 |
59 | private fun createMultipartBody(list: Iterable, part: Part): RequestBody {
60 | val parts = list.map {
61 | val file = File(it.path)
62 | MultipartBody.Part.createFormData(part.value, file.name, RequestBody.create(MediaType.parse(Utils.getMimeType(file)), file))
63 | }
64 |
65 | val builder = MultipartBody.Builder()
66 |
67 | builder.setType(MultipartBody.FORM)
68 |
69 | parts.forEach { builder.addPart(it) }
70 |
71 | return builder.build()
72 | }
73 | }
--------------------------------------------------------------------------------
/library/src/main/java/com/jaychang/sac/converter/KeyPathResponseConverterFactory.kt:
--------------------------------------------------------------------------------
1 | package com.jaychang.sac.converter
2 |
3 | import com.jaychang.sac.JsonParser
4 | import com.jaychang.sac.annotation.KeyPathResponse
5 | import okhttp3.ResponseBody
6 | import retrofit2.Converter
7 | import retrofit2.Retrofit
8 | import java.lang.reflect.Type
9 |
10 | class KeyPathResponseConverterFactory(private val jsonParser: JsonParser) : Converter.Factory() {
11 | companion object {
12 | @JvmStatic
13 | fun create(jsonParser: JsonParser): KeyPathResponseConverterFactory {
14 | return KeyPathResponseConverterFactory(jsonParser)
15 | }
16 | }
17 |
18 | override fun responseBodyConverter(type: Type, annotations: Array, retrofit: Retrofit): Converter? {
19 | // if the response type is not annotated @ResponseKeyPath, delegate to next converter
20 | if (annotations.none { it is KeyPathResponse }) {
21 | return null
22 | }
23 |
24 | val keyPath = annotations.find { it is KeyPathResponse } as KeyPathResponse
25 | val value = keyPath.value
26 | if (value.isBlank() || value.split(".").isEmpty()) {
27 | return null
28 | }
29 |
30 | jsonParser.update(type, value)
31 |
32 | return Converter { body ->
33 | jsonParser.parse(body.string(), type)
34 | }
35 | }
36 | }
--------------------------------------------------------------------------------
/library/src/main/java/com/jaychang/sac/converter/WrappedResponseConverterFactory.kt:
--------------------------------------------------------------------------------
1 | package com.jaychang.sac.converter
2 |
3 | import com.google.gson.reflect.TypeToken
4 | import com.jaychang.sac.SimpleApiResult
5 | import com.jaychang.sac.annotation.WrappedResponse
6 | import okhttp3.ResponseBody
7 | import retrofit2.Converter
8 | import retrofit2.Retrofit
9 | import java.lang.reflect.Type
10 |
11 | class WrappedResponseConverterFactory : Converter.Factory() {
12 | companion object {
13 | @JvmStatic
14 | fun create(): WrappedResponseConverterFactory {
15 | return WrappedResponseConverterFactory()
16 | }
17 | }
18 |
19 | override fun responseBodyConverter(type: Type, annotations: Array, retrofit: Retrofit): Converter? {
20 | // if the response type is not annotated @Unwrap, delegate to next converter
21 | if (annotations.none { it is WrappedResponse }) {
22 | return null
23 | }
24 |
25 | val wrappedType = annotations.find { it is WrappedResponse } as WrappedResponse
26 |
27 | val apiResultType = TypeToken.getParameterized(wrappedType.value.java, type).type
28 |
29 | val delegate: Converter = retrofit.nextResponseBodyConverter(this, apiResultType, annotations)
30 |
31 | return Converter { body ->
32 | (delegate.convert(body) as SimpleApiResult).result
33 | }
34 | }
35 | }
--------------------------------------------------------------------------------
/library/src/main/java/com/jaychang/sac/interceptor/HeaderInterceptor.kt:
--------------------------------------------------------------------------------
1 | package com.jaychang.sac.interceptor
2 |
3 | import okhttp3.Interceptor
4 | import okhttp3.Response
5 |
6 | class HeaderInterceptor(private val headers: Map) : Interceptor {
7 | override fun intercept(chain: Interceptor.Chain): Response {
8 | val oldRequest = chain.request()
9 | val builder = oldRequest.newBuilder()
10 | headers.forEach { (key, value) ->
11 | builder.addHeader(key, value)
12 | }
13 | val newRequest = builder.build()
14 | return chain.proceed(newRequest)
15 | }
16 | }
--------------------------------------------------------------------------------
/library/src/main/java/com/jaychang/sac/interceptor/ParameterInterceptor.kt:
--------------------------------------------------------------------------------
1 | package com.jaychang.sac.interceptor
2 |
3 | import okhttp3.Interceptor
4 | import okhttp3.Response
5 |
6 | class ParameterInterceptor(private val params: Map) : Interceptor {
7 | override fun intercept(chain: Interceptor.Chain): Response {
8 | val oldRequest = chain.request()
9 | val builder = oldRequest.url().newBuilder()
10 | params.forEach { (key, value) ->
11 | builder.addQueryParameter(key, value)
12 | }
13 | val newRequest = oldRequest.newBuilder().url(builder.build()).build()
14 | return chain.proceed(newRequest)
15 | }
16 | }
--------------------------------------------------------------------------------
/library/src/main/java/com/jaychang/sac/util/Mime.kt:
--------------------------------------------------------------------------------
1 | package com.jaychang.sac.util
2 |
3 | class Mime {
4 | enum class Text(name: String) {
5 | PLAIN("plain"), HTML("html"), CSS("css"), JAVASCRIPT("javascript")
6 | }
7 | enum class Image(name: String) {
8 | GIF("gif"), PNG("png"), JPEG("jpeg"), BMP("bmp"), WEBP("webp")
9 | }
10 | enum class Audio(name: String) {
11 | MIDI("midi"), MPEG("mpeg"), WEBM("webm"), OGG("ogg"), WAV("wav")
12 | }
13 | enum class Video(name: String) {
14 | WEBM("webm"), OGG("ogg")
15 | }
16 | enum class Application(name: String) {
17 | OCTET_STREAM("octet_stream"), PDF("pdf"), PKCS12("pkcs12"), VND_MSPOWERPOINT("vnd.mspowerpoint"), XHTML_XML("xhtml+xml"), XML("xml")
18 | }
19 | }
--------------------------------------------------------------------------------
/library/src/main/java/com/jaychang/sac/util/Utils.kt:
--------------------------------------------------------------------------------
1 | package com.jaychang.sac.util
2 |
3 | import android.content.Context
4 | import android.webkit.MimeTypeMap
5 | import java.io.BufferedReader
6 | import java.io.File
7 | import java.io.InputStreamReader
8 | import java.io.StringWriter
9 |
10 |
11 |
12 | internal object Utils {
13 |
14 | fun toText(context: Context, file: Int): String {
15 | val inputStream = context.resources.openRawResource(file)
16 | val writer = StringWriter()
17 | val buffer = CharArray(1024)
18 | inputStream.use { input ->
19 | val reader = BufferedReader(InputStreamReader(input, "UTF-8"))
20 | var line: Int = -1
21 | while ({ line = reader.read(buffer); line }() != -1) {
22 | writer.write(buffer, 0, line)
23 | }
24 | }
25 | return writer.toString()
26 | }
27 |
28 | fun getMimeType(file: File): String {
29 | var type: String? = null
30 | val extension = MimeTypeMap.getFileExtensionFromUrl(file.path)
31 | if (extension != null) {
32 | type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension)
33 | }
34 | println("getMimeType: $type")
35 | return type ?: "*/*"
36 | }
37 | }
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':app', ':library', ':library-jsonparser-gson', ':library-jsonparser-moshi'
2 |
--------------------------------------------------------------------------------