├── .gitignore ├── .idea ├── caches │ └── build_file_checksums.ser ├── codeStyles │ └── Project.xml ├── gradle.xml ├── misc.xml ├── modules.xml ├── runConfigurations.xml └── vcs.xml ├── LICENSE ├── README.md ├── build.gradle ├── glin ├── .gitignore ├── build.gradle └── src │ └── main │ └── java │ └── org │ └── loader │ └── glin │ ├── Callback.java │ ├── Context.java │ ├── Glin.java │ ├── Params.java │ ├── RawResult.java │ ├── Result.java │ ├── annotation │ ├── Arg.java │ ├── DEL.java │ ├── GET.java │ ├── JSON.java │ ├── POST.java │ ├── PUT.java │ ├── Path.java │ └── ShouldCache.java │ ├── cache │ ├── DefaultCacheProvider.java │ └── ICacheProvider.java │ ├── call │ ├── Call.java │ ├── DelCall.java │ ├── GetCall.java │ ├── JsonCall.java │ ├── PostCall.java │ └── PutCall.java │ ├── chan │ ├── ChanNode.java │ ├── GlobalChanNode.java │ └── LogChanNode.java │ ├── client │ ├── IClient.java │ └── IRequest.java │ ├── factory │ ├── CallFactory.java │ └── ParserFactory.java │ ├── helper │ ├── ClientHelper.java │ ├── Helper.java │ ├── LogHelper.java │ └── SerializeHelper.java │ ├── interceptor │ └── IResultInterceptor.java │ ├── parser │ └── Parser.java │ └── utils │ └── Pair.java ├── glinsample ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src │ ├── androidTest │ └── java │ │ └── org │ │ └── loader │ │ └── glinsample │ │ └── ExampleInstrumentedTest.java │ ├── main │ ├── AndroidManifest.xml │ ├── java │ │ └── org │ │ │ └── loader │ │ │ └── glinsample │ │ │ ├── App.java │ │ │ ├── MainActivity.java │ │ │ ├── api │ │ │ └── Api.java │ │ │ ├── bean │ │ │ └── UserInfo.java │ │ │ ├── chan │ │ │ ├── CheckEnvChanNode.java │ │ │ ├── EndChanNode.java │ │ │ ├── UserIdChanNode.java │ │ │ └── UserNameChanNode.java │ │ │ └── utils │ │ │ ├── Net.java │ │ │ └── Parsers.java │ └── 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 │ │ ├── values-w820dp │ │ └── dimens.xml │ │ └── values │ │ ├── colors.xml │ │ ├── dimens.xml │ │ ├── strings.xml │ │ └── styles.xml │ └── test │ └── java │ └── org │ └── loader │ └── glinsample │ └── ExampleUnitTest.java ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── okclient ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src │ └── main │ ├── AndroidManifest.xml │ ├── java │ └── org │ │ └── loader │ │ └── okclient │ │ └── OkClient.java │ └── res │ └── values │ └── strings.xml └── settings.gradle /.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | .gradle 3 | /local.properties 4 | /.idea/workspace.xml 5 | /.idea/libraries 6 | .DS_Store 7 | /build 8 | /captures 9 | .externalNativeBuild 10 | -------------------------------------------------------------------------------- /.idea/caches/build_file_checksums.ser: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qibin0506/Glin/42f8eff35cb25373efb9436d27decc5f5209e2ad/.idea/caches/build_file_checksums.ser -------------------------------------------------------------------------------- /.idea/codeStyles/Project.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 15 | 16 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | -------------------------------------------------------------------------------- /.idea/gradle.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 19 | 20 | -------------------------------------------------------------------------------- /.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 17 | 27 | 28 | 29 | 30 | 31 | 32 | 34 | -------------------------------------------------------------------------------- /.idea/modules.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /.idea/runConfigurations.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 11 | 12 | -------------------------------------------------------------------------------- /.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /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 | # Glin 2 | 3 | Glin, 一款灵活支持中间件的Java&Android动态代理网络框架 4 | 5 | ### 功能列表 6 |    1. 默认支持GET, POST, DELETE, PUT请求方式 7 | 8 |    2. 默认支持JSON Body请求方式 9 | 10 |    3. 可自定义请求客户端 11 | 12 |    4. 可扩展请求方式 13 | 14 |    5. 支持中间件 15 | 16 |    6. 支持Path替换 17 | 18 |    7. 支持数据缓存 19 | 20 |    8. more... 21 | 22 | ### 升级日志 23 | 24 | 25 | v3.2 26 | 27 |        1. 修复使用@POST请求,无参数时系统崩溃错误 28 | 29 |        2. 删除默认序列化函数异常的日志打印 30 |     31 | 32 | v3.1 33 | 34 |        1. 新增:`Call`添加rewriteUrl方法,可用于在中间件中重写请求的URL 35 | 36 |        2. 新增:添加全局中间件`GlobalChanNode`,GlobalChanNode支持添加多个`ChanNode`, 只需按照顺序添加即可 37 | 38 |        3. 修改:现在日志中间件改用`GlobalChanNode`提供支持修改日志全局中间件方式:logChanNode -> globalChanNode(GlobalChanNode before, GlobalChanNode after) 39 | 40 |        4. glinsample适配Glin3.1, 添加权限处理 41 |         42 | 43 | v3.0 44 |        1. 支持更加灵活的中间件cancel机制,cancel支持自定义code和message 45 | 46 | 47 | v2.3 48 |        1. 支持中间件 49 | 50 |        2. 添加@Path注解 51 | 52 |        3. 默认添加日志中间件 53 | 54 |        4. 添加Context上下文 55 | 56 | ### 使用教程 57 | 58 | #### 获取 Glin 59 | 在你的gradle中添加如下compile 60 | ``` java 61 | compile 'org.loader:glin:3.2' 62 | ``` 63 | 如果你不想花时间定制网络请求方式, 可使用我提供的OkClient, 添加方法如下 64 | ``` java 65 | compile 'org.loader:glin-okclient:3.2' 66 | ``` 67 | **注意: 如果使用Glin3.0, glin-okclient就必须使用2.3以上** 68 | 69 | #### 自定义解析类 70 | 1. 通过继承`Parser`类来实现项目的数据解析类, 通常情况下需要实体类和列表类解析两种 71 | 2. 通过继承`ParserFactory`将上面实现的两个解析类告诉Glin 72 | 73 | 例子: 74 | ``` java 75 | // CommParser.java 76 | public class CommParser extends Parser { 77 | 78 | public CommParser(String key) { 79 | super(key); 80 | } 81 | 82 | @Override 83 | public Result parse(Class klass, NetResult netResult) { 84 | Result result = new Result<>(); 85 | try { 86 | JSONObject baseObject = JSON.parseObject(netResult.getResponse()); 87 | if (baseObject.containsKey("message")) { 88 | result.setMessage(baseObject.getString("message"));// message always get 89 | } 90 | 91 | result.setCode(baseObject.getIntValue("code")); 92 | result.setObj(result.getCode()); 93 | result.ok(baseObject.getBooleanValue("ok")); 94 | if (result.isOK()) { // ok true 95 | if (baseObject.containsKey(mKey)) { 96 | T t = baseObject.getObject(mKey, klass); 97 | result.setResult(t); 98 | } 99 | } 100 | } catch (Exception e) { 101 | e.printStackTrace(); 102 | result.setMessage("error"); 103 | } 104 | return result; 105 | } 106 | } 107 | ``` 108 | 109 | ``` java 110 | // ListParser.java 111 | public class ListParser extends Parser { 112 | 113 | public ListParser(String key) { 114 | super(key); 115 | } 116 | 117 | @Override 118 | public Result parse(Class klass, NetResult netResult) { 119 | Result result = new Result<>(); 120 | try { 121 | JSONObject baseObject = JSON.parseObject(netResult.getResponse()); 122 | if (baseObject.containsKey("message")) { 123 | result.setMessage(baseObject.getString("message"));// message always get 124 | } 125 | 126 | res.setCode(baseObject.getIntValue("code")); 127 | result.setObj(res.getCode()); 128 | result.ok(baseObject.getBooleanValue("ok")); 129 | if (result.isOK()) { // ok true 130 | if (baseObject.containsKey(mKey)) { 131 | JSONArray arr = baseObject.getJSONArray(mKey); 132 | T t = (T) baseObject.parseArray(arr.toString(), klass); 133 | result.setResult(t); 134 | } 135 | } 136 | } catch (Exception e) { 137 | e.printStackTrace(); 138 | result.setMessage("error"); 139 | } 140 | 141 | return result; 142 | } 143 | } 144 | ``` 145 | 146 | ``` java 147 | // FastJsonParserFactory 148 | public class FastJsonParserFactory implements ParserFactory { 149 | 150 | @Override 151 | public Parser getParser() { 152 | return new CommParser("data"); 153 | } 154 | 155 | @Override 156 | public Parser getListParser() { 157 | return new ListParser("data"); 158 | } 159 | } 160 | ``` 161 | 162 | #### 配置Glin 163 | ``` java 164 | private static final LogHelper.LogPrinter logPrinter = new LogHelper.LogPrinter() { 165 | @Override 166 | public void print(String tag, String content) { 167 | Log.d(tag, content); 168 | } 169 | }; 170 | 171 | //.... 172 | 173 | // request Log 174 | LogChanNode beforeLog = new LogChanNode(true, printer); 175 | // response log 176 | LogChanNode afterLog = new LogChanNode(true, printer); 177 | 178 | // Global Chan Node before request 179 | GlobalChanNode before = new GlobalChanNode(beforeLog/*, others...*/); 180 | // Global Chan Node after response 181 | GlobalChanNode after = new GlobalChanNode(afterLog/*, others...*/); 182 | 183 | Glin glin = new Glin.Builder() 184 | .client(new OkClient()) 185 |    .baseUrl("http://exampile.com") // the basic url 186 |    .globalChanNode(before, after) 187 | .parserFactory(new FastJsonParserFactory()) // your parser factory 188 | .cacheProvider(new DefaultCacheProvider(Environment.getExternalStorageDirectory() + "/test/", 2000)) // use default cacheProvider 189 | .timeout(10000) // timeout in ms 190 | .build(); 191 | ``` 192 | 193 | #### 创建网络访问接口 194 | ``` java 195 | public interface UserApi { 196 | // use @ShouldCache, Glin will cache the lastest response 197 | // the key of cache is your url and params 198 | @ShouldCache 199 | @POST("/users/list") 200 | Call list(@Arg("name") String userName); 201 | } 202 | ``` 203 | 204 | #### 访问网络 205 | ``` java 206 | UserApi api = glin.create(UserApi.class, getClass().getName()); 207 | Call call = api.list("qibin"); 208 | call.enqueue(new Callback() { 209 | @Override 210 | public void onResponse(Result result) { 211 | if (result.isOK()) { 212 | Toast.makeText(MainActivity.this, result.getResult().getName(), Toast.LENGTH_SHORT).show(); 213 | }else { 214 | Toast.makeText(MainActivity.this, result.getMessage(), Toast.LENGTH_SHORT).show(); 215 | } 216 | } 217 | }); 218 | ``` 219 | 220 | ### 高级用法 221 | 222 | ### get 请求 223 | 224 | ``` java 225 | @GET("/info") 226 | Call getUser(@Arg("username") String name); 227 | ``` 228 | 229 | ### post 请求 230 | 231 | ``` java 232 | @POST("/info") 233 | Call getUser(@Arg("username") String name); 234 | ``` 235 | 236 | ### delete 请求 237 | 238 | ``` java 239 | @DEL("/info") 240 | Call deleteUser(@Arg("username") String name); 241 | ``` 242 | 243 | ### put 请求 244 | 245 | ``` java 246 |    @PUT("/info") 247 | Call putUser(@Arg("username") String name); 248 | ``` 249 | 250 | 251 | ### json 请求 252 | 253 | ``` java 254 |    @JSON("/info") 255 | Call getUser(String name); 256 | ``` 257 | 258 | ### 添加 url path 259 | 260 | ``` java 261 |    @GET("/info/{:name}/{:age}") 262 | Call getUser(@Path("name") String name, @Path("age") int age); 263 | ``` 264 | 265 | ### 中间件支持 266 | 267 | 提供全局中间件支持(`GlobalChanNode.java`)和日志中间件(`LogChanNode.java`) 268 | 269 | #### 自定义中间件 270 | 271 | 继承ChanNode类, 实现自定义中间件, 实现run(Context ctx)方法, 在run方法里调用next()方法使流程继续. 272 | 273 | 如果想使用全局中间件,可在`GlobalChanNode`的构造中添加`ChanNode`, 可参考`glinsample`. 274 | 275 | 通过调用Call的before(ChanNode chanNode)方法设置请求前的中间件, 在调用before(ChanNode chanNode)后, 可通过使用一系列的next(ChanNode chanNode)方法设置请求前的中间件. 276 | 通过调用Call的after(ChanNode chanNode)方法设置请求后的中间件, 在调用after(ChanNode chanNode)后, 可通过使用一系列的next(ChanNode chanNode)方法设置请求后的中间件. 277 | 278 | 在中间件中,在网络请求未发起之前, 如果想要修改参数, 可使用`ctx.getCall().getParams()`进行参数修改. 279 | 280 | 例子(该例子实现了请求前检查用户id, 如果不存在, 则请求用户id接口, 然后发起请求获取用户信息, 最后检查用户信息) 281 | 282 | ``` java 283 | // 检查用户id的中间件 284 | class UserIdChanNode extends ChanNode { 285 | @Override 286 | public void run(Context ctx) { 287 |        // 如果uid存在, 则继续流程 288 |        if (SpUtils.get("uid") != null) { 289 | next(); 290 | return; 291 | } 292 | 293 |        glin.create(Api.class, tag).uid().enqueue(new Callback() { 294 | @Override 295 | public void onResponse(Result result) { 296 | // save uid 297 |                // 省略成功判断 298 |                SpUtils.put("uid", reuslt.getResult().getUid()); 299 | next(); 300 | } 301 | }); 302 | } 303 | } 304 | ``` 305 | 306 | ``` java 307 | // 检查用户信息中间件 308 | class UserInfoChanNode extends ChanNode { 309 | @Override 310 | public void run(Context ctx) { 311 |        if (SpUtils.get("user_name") == null) { 312 | sendUserName(); 313 |            next(); 314 |            return; 315 | } 316 |        // 调用cancel方法会中断流程 317 |        //cancel(); 318 | cancel(4000, "no user name") 319 | } 320 | } 321 | ``` 322 | 323 | ``` java 324 | // 使用中间件 325 | Call call = glin.create(Api.class, tag).userInfo(); 326 | call.before(new UserIdChanNode()).next(new OtherBeforeChanNode()) 327 | .after(new UserInfoChanNode()).next(new OtherAfterChanNode()) 328 | .enqueue(new Callback() { 329 | @Override 330 | public void onResponse(Result result) { 331 |                //  处理结果 332 |            } 333 | }); 334 | ``` 335 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | // Top-level build file where you can add configuration options common to all sub-projects/modules. 2 | 3 | buildscript { 4 | repositories { 5 | jcenter() 6 | } 7 | dependencies { 8 | classpath 'com.android.tools.build:gradle:2.3.3' 9 | 10 | // NOTE: Do not place your application dependencies here; they belong 11 | // in the individual module build.gradle files 12 | } 13 | } 14 | 15 | allprojects { 16 | repositories { 17 | jcenter() 18 | } 19 | } 20 | 21 | task clean(type: Delete) { 22 | delete rootProject.buildDir 23 | } 24 | -------------------------------------------------------------------------------- /glin/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /glin/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'java' 2 | 3 | dependencies { 4 | compile fileTree(dir: 'libs', include: ['*.jar']) 5 | } 6 | 7 | sourceCompatibility = "1.7" 8 | targetCompatibility = "1.7" -------------------------------------------------------------------------------- /glin/src/main/java/org/loader/glin/Callback.java: -------------------------------------------------------------------------------- 1 | package org.loader.glin; 2 | 3 | import org.loader.glin.chan.ChanNode; 4 | 5 | /** 6 | * Created by qibin on 2016/7/13. 7 | */ 8 | 9 | public abstract class Callback { 10 | 11 | private Context mContext; 12 | private ChanNode mAfterChanNode; 13 | 14 | public final void attach(Context ctx, ChanNode afterChanNode) { 15 | mContext = ctx; 16 | mAfterChanNode = afterChanNode; 17 | } 18 | 19 | public final void afterResponse(Result result, RawResult rawResult) { 20 | mContext.setRawResult(rawResult); 21 | mContext.setResult(result); 22 | 23 | if (mAfterChanNode != null) { 24 | mAfterChanNode.exec(mContext); 25 | } 26 | } 27 | 28 | public abstract void onResponse(Result result); 29 | } 30 | 31 | -------------------------------------------------------------------------------- /glin/src/main/java/org/loader/glin/Context.java: -------------------------------------------------------------------------------- 1 | package org.loader.glin; 2 | 3 | import org.loader.glin.call.Call; 4 | 5 | /** 6 | * Created by qibin on 2016/7/13. 7 | */ 8 | 9 | public class Context { 10 | private Call call; 11 | private Result result; 12 | private RawResult rawResult; 13 | 14 | public Context() {} 15 | 16 | public Context(Call call) { 17 | this.call = call; 18 | } 19 | 20 | public Call getCall() { 21 | return call; 22 | } 23 | 24 | public void setCall(Call call) { 25 | this.call = call; 26 | } 27 | 28 | public Result getResult() { 29 | return result; 30 | } 31 | 32 | public void setResult(Result result) { 33 | this.result = result; 34 | } 35 | 36 | public RawResult getRawResult() { 37 | return rawResult; 38 | } 39 | 40 | public void setRawResult(RawResult rawResult) { 41 | this.rawResult = rawResult; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /glin/src/main/java/org/loader/glin/Glin.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Glin, A retrofit like network framework
3 | * 4 | * Usage:
5 | * 1. write your client and parser, config glin 6 | * Glin glin = new Glin.Builder() 7 | .client(new OkClient()) 8 | .baseUrl("http://192.168.201.39") 9 | .debug(true) 10 | .parserFactory(new FastJsonParserFactory()) 11 | .timeout(10000) 12 | .build(); 13 | * 14 | * 2. create an interface 15 | * public interface UserBiz { 16 | @POST("/users/list") 17 | Call list(@Arg("name") String userName); 18 | } 19 | * 20 | * 3. request the network and callback 21 | * UserBiz biz = glin.create(UserBiz.class, getClass().getName()); 22 | * Call call = biz.list("qibin"); 23 | call.enqueue(new Callback() { 24 | @Override 25 | public void onResponse(Result result) { 26 | if (result.isOK()) { 27 | Toast.makeText(MainActivity.this, result.getResult().getName(), Toast.LENGTH_SHORT).show(); 28 | }else { 29 | Toast.makeText(MainActivity.this, result.getMessage(), Toast.LENGTH_SHORT).show(); 30 | } 31 | } 32 | }); 33 | */ 34 | package org.loader.glin; 35 | 36 | import org.loader.glin.annotation.Arg; 37 | import org.loader.glin.annotation.JSON; 38 | import org.loader.glin.annotation.Path; 39 | import org.loader.glin.annotation.ShouldCache; 40 | import org.loader.glin.cache.ICacheProvider; 41 | import org.loader.glin.call.Call; 42 | import org.loader.glin.chan.GlobalChanNode; 43 | import org.loader.glin.chan.LogChanNode; 44 | import org.loader.glin.client.IClient; 45 | import org.loader.glin.factory.CallFactory; 46 | import org.loader.glin.factory.ParserFactory; 47 | import org.loader.glin.interceptor.IResultInterceptor; 48 | import org.loader.glin.utils.Pair; 49 | 50 | import java.lang.annotation.Annotation; 51 | import java.lang.reflect.Constructor; 52 | import java.lang.reflect.InvocationHandler; 53 | import java.lang.reflect.Method; 54 | import java.lang.reflect.Proxy; 55 | import java.util.HashMap; 56 | import java.util.Iterator; 57 | 58 | /** 59 | * Created by qibin on 2016/7/13. 60 | */ 61 | 62 | public class Glin { 63 | private Builder mBuilder; 64 | private CallFactory mCallFactory; 65 | 66 | private Glin(Builder builder) { 67 | mBuilder = builder; 68 | mCallFactory = new CallFactory(); 69 | } 70 | 71 | @SuppressWarnings("unchecked") 72 | public T create(Class klass, Object tag) { 73 | return (T) Proxy.newProxyInstance(klass.getClassLoader(), 74 | new Class[] {klass}, new Handler(tag)); 75 | } 76 | 77 | public void cancel(String tag) { 78 | mBuilder.client.cancel(tag); 79 | } 80 | 81 | public void register(Class key, Class value) { 82 | mCallFactory.register(key, value); 83 | } 84 | 85 | class Handler implements InvocationHandler { 86 | private Object mTag; 87 | 88 | public Handler(Object tag) { 89 | mTag = tag; 90 | } 91 | 92 | @Override 93 | public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { 94 | Class key = null; 95 | String path = null; 96 | 97 | HashMap, Class> mapping = mCallFactory.get(); 98 | Class item; 99 | Annotation anno; 100 | for (Iterator> iterator = mapping.keySet().iterator(); 101 | iterator.hasNext();) { 102 | item = iterator.next(); 103 | if (method.isAnnotationPresent(item)) { 104 | key = item; 105 | anno = method.getAnnotation(item); 106 | path = (String) anno.getClass().getDeclaredMethod("value").invoke(anno); 107 | break; 108 | } 109 | } 110 | 111 | if (key == null) { 112 | throw new UnsupportedOperationException("cannot find annotations"); 113 | } 114 | 115 | Class callKlass = mCallFactory.get(key); 116 | if (callKlass == null) { 117 | throw new UnsupportedOperationException("cannot find calls"); 118 | } 119 | 120 | boolean shouldCache = method.isAnnotationPresent(ShouldCache.class); 121 | 122 | Pair pair = new Pair<>(justUrl(path), new Params()); 123 | params(pair, method, args); 124 | 125 | Constructor constructor = callKlass.getConstructor(IClient.class, 126 | String.class, Params.class, Object.class, boolean.class); 127 | 128 | Call call = constructor.newInstance(mBuilder.client, pair.first, pair.second, 129 | mTag, shouldCache); 130 | 131 | call.setGlobalChanNode(mBuilder.beforeGlobalChanNode, mBuilder.afterGlobalChanNode); 132 | 133 | return call; 134 | } 135 | 136 | private String justUrl(String path) { 137 | String url = mBuilder.baseUrl == null ? "" : mBuilder.baseUrl; 138 | path = path == null ? "" : path; 139 | if (isFullUrl(path)) { url = path;} 140 | else { url += path;} 141 | return url; 142 | } 143 | 144 | private boolean isFullUrl(String url) { 145 | if (url == null || url.length() == 0) { return false;} 146 | if (url.toLowerCase().startsWith("http://")) { return true;} 147 | if (url.toLowerCase().startsWith("https://")) {return true;} 148 | return false; 149 | } 150 | 151 | private void params(Pair pair, Method method, Object[] args) { 152 | if (args == null || args.length == 0) { 153 | return; 154 | } 155 | 156 | // method.getParameterAnnotations.length always equals args.length 157 | Annotation[][] paramsAnno = method.getParameterAnnotations(); 158 | // if (method.isAnnotationPresent(JSON.class)) { 159 | // params.add(Params.DEFAULT_JSON_KEY, args[0]); 160 | // return params; 161 | // } 162 | 163 | int length = paramsAnno.length; 164 | for (int i = 0; i < length; i++) { 165 | if (paramsAnno[i].length == 0) { 166 | // there is no annotation on this param, 167 | // so, maybe it is a json value when the method is JSON annotation presented 168 | if (method.isAnnotationPresent(JSON.class)) { 169 | pair.second.add(Params.DEFAULT_JSON_KEY, args[i]); 170 | } 171 | } else { 172 | if (paramsAnno[i][0] instanceof Arg) { 173 | pair.second.add(((Arg)paramsAnno[i][0]).value(), args[i]); 174 | } else if (paramsAnno[i][0] instanceof Path) { 175 | pair.first = pair.first.replaceAll("\\{:"+((Path)paramsAnno[i][0]).value()+"\\}", 176 | args[i].toString()); 177 | } 178 | } 179 | } 180 | } 181 | } 182 | 183 | public static class Builder { 184 | 185 | private IClient client; 186 | private String baseUrl; 187 | 188 | private GlobalChanNode beforeGlobalChanNode; 189 | private GlobalChanNode afterGlobalChanNode; 190 | 191 | public Builder() { 192 | 193 | } 194 | 195 | public Builder baseUrl(String baseUrl) { 196 | this.baseUrl = baseUrl; 197 | return this; 198 | } 199 | 200 | public Builder client(IClient client) { 201 | this.client = client; 202 | return this; 203 | } 204 | 205 | public Builder globalChanNode(GlobalChanNode before, GlobalChanNode after) { 206 | this.beforeGlobalChanNode = before; 207 | this.afterGlobalChanNode = after; 208 | return this; 209 | } 210 | 211 | public Builder parserFactory(ParserFactory factory) { 212 | if (this.client == null) { 213 | throw new UnsupportedOperationException("invoke client method first"); 214 | } 215 | this.client.parserFactory(factory); 216 | return this; 217 | } 218 | 219 | public Builder cacheProvider(ICacheProvider cacheProvider) { 220 | if (this.client == null) { 221 | throw new UnsupportedOperationException("invoke client method first"); 222 | } 223 | this.client.cacheProvider(cacheProvider); 224 | return this; 225 | } 226 | 227 | public Builder timeout(long ms) { 228 | if (this.client == null) { 229 | throw new UnsupportedOperationException("invoke client method first"); 230 | } 231 | this.client.timeout(ms); 232 | return this; 233 | } 234 | 235 | public Builder resultInterceptor(IResultInterceptor interceptor) { 236 | if (this.client == null) { 237 | throw new UnsupportedOperationException("invoke client method first"); 238 | } 239 | this.client.resultInterceptor(interceptor); 240 | return this; 241 | } 242 | 243 | public Glin build() { 244 | return new Glin(this); 245 | } 246 | } 247 | } 248 | -------------------------------------------------------------------------------- /glin/src/main/java/org/loader/glin/Params.java: -------------------------------------------------------------------------------- 1 | package org.loader.glin; 2 | 3 | import java.io.File; 4 | import java.util.Iterator; 5 | import java.util.LinkedHashMap; 6 | import java.util.Map; 7 | 8 | /** 9 | * Created by qibin on 2016/7/13. 10 | */ 11 | 12 | public class Params { 13 | 14 | public static final String DEFAULT_JSON_KEY = "json"; 15 | 16 | private LinkedHashMap mParams; 17 | private LinkedHashMap mFiles; 18 | 19 | public Params() { 20 | mParams = new LinkedHashMap<>(); 21 | mFiles = new LinkedHashMap<>(); 22 | } 23 | 24 | public Params(String key, Object value) { 25 | this(); 26 | add(key, value); 27 | } 28 | 29 | public Params add(String key, Object value) { 30 | if (key == null) { return this;} 31 | if (value == null) { mParams.put(key, null);} 32 | else if (value instanceof File) { mFiles.put(key, (File) value);} 33 | else { mParams.put(key, value.toString());} 34 | return this; 35 | } 36 | 37 | public LinkedHashMap get() { 38 | return mParams; 39 | } 40 | 41 | public String getParams(String key) { 42 | return mParams.get(key); 43 | } 44 | 45 | public File getFile(String key) { 46 | return mFiles.get(key); 47 | } 48 | 49 | public LinkedHashMap files() { 50 | return mFiles; 51 | } 52 | 53 | public void remove(String key) { 54 | if (mParams.containsKey(key)) { mParams.remove(key);} 55 | if (mFiles.containsKey(key)) { mFiles.remove(key);} 56 | } 57 | 58 | public String encode() { 59 | String query = null; 60 | for (Map.Entry entry : mParams.entrySet()) { 61 | if (query == null) { query = entry.getKey() + "=" + entry.getValue();} 62 | else { query += "&" + entry.getKey() + "=" + entry.getValue();} 63 | } 64 | 65 | return query; 66 | } 67 | 68 | public Iterator iterator() { 69 | return mParams.keySet().iterator(); 70 | } 71 | 72 | public Iterator fileIterator() { 73 | return mFiles.keySet().iterator(); 74 | } 75 | 76 | public boolean isEmpty() { 77 | return mParams.isEmpty() && mFiles.isEmpty(); 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /glin/src/main/java/org/loader/glin/RawResult.java: -------------------------------------------------------------------------------- 1 | package org.loader.glin; 2 | 3 | /** 4 | * Created by qibin on 2016/10/17. 5 | */ 6 | 7 | public class RawResult { 8 | private int statusCode; 9 | private String message; 10 | private String response; 11 | 12 | public RawResult() {} 13 | 14 | public RawResult(int statusCode, String message, String response) { 15 | this.statusCode = statusCode; 16 | this.message = message; 17 | this.response = response; 18 | } 19 | 20 | public int getStatusCode() { 21 | return statusCode; 22 | } 23 | 24 | public void setStatusCode(int statusCode) { 25 | this.statusCode = statusCode; 26 | } 27 | 28 | public String getMessage() { 29 | return message; 30 | } 31 | 32 | public void setMessage(String message) { 33 | this.message = message; 34 | } 35 | 36 | public String getResponse() { 37 | return response; 38 | } 39 | 40 | public void setResponse(String response) { 41 | this.response = response; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /glin/src/main/java/org/loader/glin/Result.java: -------------------------------------------------------------------------------- 1 | package org.loader.glin; 2 | 3 | /** 4 | * Created by qibin on 2016/7/13. 5 | */ 6 | 7 | public class Result { 8 | private boolean ok; 9 | private String message; 10 | private T result; 11 | private int code; 12 | private Object obj; 13 | private boolean isCache; 14 | 15 | public boolean isOK() { 16 | return ok; 17 | } 18 | 19 | public void ok(boolean ok) { 20 | this.ok = ok; 21 | } 22 | 23 | public String getMessage() { 24 | return message; 25 | } 26 | 27 | public void setMessage(String mMessage) { 28 | this.message = mMessage; 29 | } 30 | 31 | public T getResult() { 32 | return result; 33 | } 34 | 35 | public void setResult(T mResult) { 36 | this.result = mResult; 37 | } 38 | 39 | public int getCode() { 40 | return code; 41 | } 42 | 43 | public void setCode(int code) { 44 | this.code = code; 45 | } 46 | 47 | public Object getObj() { 48 | return obj; 49 | } 50 | 51 | public void setObj(Object obj) { 52 | this.obj = obj; 53 | } 54 | 55 | public V assertGetObj() { 56 | return (V) getObj(); 57 | } 58 | 59 | public boolean isCache() { 60 | return isCache; 61 | } 62 | 63 | public void setCache(boolean cache) { 64 | isCache = cache; 65 | } 66 | 67 | @Override 68 | public String toString() { 69 | StringBuilder sb = new StringBuilder(); 70 | sb.append("ok: ").append(ok).append("\n"); 71 | sb.append("message: ").append(message).append("\n"); 72 | sb.append("obj: ").append(obj).append("\n"); 73 | sb.append("result: ").append(result).append("\n"); 74 | sb.append("code: ").append(code).append("\n"); 75 | sb.append("is_cache: ").append(isCache); 76 | 77 | return sb.toString(); 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /glin/src/main/java/org/loader/glin/annotation/Arg.java: -------------------------------------------------------------------------------- 1 | package org.loader.glin.annotation; 2 | 3 | import java.lang.annotation.ElementType; 4 | import java.lang.annotation.Retention; 5 | import java.lang.annotation.RetentionPolicy; 6 | import java.lang.annotation.Target; 7 | 8 | /** 9 | * Created by qibin on 2016/7/13. 10 | */ 11 | 12 | @Target(ElementType.PARAMETER) 13 | @Retention(RetentionPolicy.RUNTIME) 14 | public @interface Arg { 15 | String value(); 16 | } 17 | -------------------------------------------------------------------------------- /glin/src/main/java/org/loader/glin/annotation/DEL.java: -------------------------------------------------------------------------------- 1 | package org.loader.glin.annotation; 2 | 3 | import java.lang.annotation.ElementType; 4 | import java.lang.annotation.Retention; 5 | import java.lang.annotation.RetentionPolicy; 6 | import java.lang.annotation.Target; 7 | 8 | /** 9 | * Created by qibin on 2016/7/14. 10 | */ 11 | 12 | @Target(ElementType.METHOD) 13 | @Retention(RetentionPolicy.RUNTIME) 14 | public @interface DEL { 15 | String value(); 16 | } 17 | -------------------------------------------------------------------------------- /glin/src/main/java/org/loader/glin/annotation/GET.java: -------------------------------------------------------------------------------- 1 | package org.loader.glin.annotation; 2 | 3 | import java.lang.annotation.ElementType; 4 | import java.lang.annotation.Retention; 5 | import java.lang.annotation.RetentionPolicy; 6 | import java.lang.annotation.Target; 7 | 8 | /** 9 | * Created by qibin on 2016/7/13. 10 | */ 11 | 12 | @Target(ElementType.METHOD) 13 | @Retention(RetentionPolicy.RUNTIME) 14 | public @interface GET { 15 | String value(); 16 | } 17 | -------------------------------------------------------------------------------- /glin/src/main/java/org/loader/glin/annotation/JSON.java: -------------------------------------------------------------------------------- 1 | package org.loader.glin.annotation; 2 | 3 | import java.lang.annotation.ElementType; 4 | import java.lang.annotation.Retention; 5 | import java.lang.annotation.RetentionPolicy; 6 | import java.lang.annotation.Target; 7 | 8 | /** 9 | * Created by qibin on 2016/7/13. 10 | */ 11 | 12 | @Target(ElementType.METHOD) 13 | @Retention(RetentionPolicy.RUNTIME) 14 | public @interface JSON { 15 | String value(); 16 | } 17 | -------------------------------------------------------------------------------- /glin/src/main/java/org/loader/glin/annotation/POST.java: -------------------------------------------------------------------------------- 1 | package org.loader.glin.annotation; 2 | 3 | import java.lang.annotation.ElementType; 4 | import java.lang.annotation.Retention; 5 | import java.lang.annotation.RetentionPolicy; 6 | import java.lang.annotation.Target; 7 | 8 | /** 9 | * Created by qibin on 2016/7/13. 10 | */ 11 | 12 | @Target(ElementType.METHOD) 13 | @Retention(RetentionPolicy.RUNTIME) 14 | public @interface POST { 15 | String value(); 16 | } 17 | -------------------------------------------------------------------------------- /glin/src/main/java/org/loader/glin/annotation/PUT.java: -------------------------------------------------------------------------------- 1 | package org.loader.glin.annotation; 2 | 3 | import java.lang.annotation.ElementType; 4 | import java.lang.annotation.Retention; 5 | import java.lang.annotation.RetentionPolicy; 6 | import java.lang.annotation.Target; 7 | 8 | /** 9 | * Created by qibin on 2016/7/14. 10 | */ 11 | 12 | @Target(ElementType.METHOD) 13 | @Retention(RetentionPolicy.RUNTIME) 14 | public @interface PUT { 15 | String value(); 16 | } 17 | -------------------------------------------------------------------------------- /glin/src/main/java/org/loader/glin/annotation/Path.java: -------------------------------------------------------------------------------- 1 | package org.loader.glin.annotation; 2 | 3 | import java.lang.annotation.ElementType; 4 | import java.lang.annotation.Retention; 5 | import java.lang.annotation.RetentionPolicy; 6 | import java.lang.annotation.Target; 7 | 8 | /** 9 | * Created by qibin on 17-7-2. 10 | */ 11 | 12 | @Target(ElementType.PARAMETER) 13 | @Retention(RetentionPolicy.RUNTIME) 14 | public @interface Path { 15 | String value(); 16 | } 17 | -------------------------------------------------------------------------------- /glin/src/main/java/org/loader/glin/annotation/ShouldCache.java: -------------------------------------------------------------------------------- 1 | package org.loader.glin.annotation; 2 | 3 | import java.lang.annotation.ElementType; 4 | import java.lang.annotation.Retention; 5 | import java.lang.annotation.RetentionPolicy; 6 | import java.lang.annotation.Target; 7 | 8 | @Target(ElementType.METHOD) 9 | @Retention(RetentionPolicy.RUNTIME) 10 | public @interface ShouldCache { 11 | } 12 | -------------------------------------------------------------------------------- /glin/src/main/java/org/loader/glin/cache/DefaultCacheProvider.java: -------------------------------------------------------------------------------- 1 | package org.loader.glin.cache; 2 | 3 | import org.loader.glin.RawResult; 4 | import org.loader.glin.Result; 5 | import org.loader.glin.helper.Helper; 6 | import org.loader.glin.helper.SerializeHelper; 7 | 8 | import java.io.File; 9 | import java.io.IOException; 10 | 11 | public class DefaultCacheProvider implements ICacheProvider { 12 | 13 | private static final String SUFFIX = ".gc"; 14 | 15 | private String mCachePath; 16 | private long mMaxCacheSize; 17 | 18 | public DefaultCacheProvider(String cachePath, long maxCacheSize) { 19 | mCachePath = cachePath.endsWith("/") ? cachePath : cachePath + "/"; 20 | mMaxCacheSize = maxCacheSize; 21 | 22 | File cache = new File(mCachePath); 23 | if (!cache.exists()) { 24 | for (int i = 0; i < 3;i++) { 25 | if (cache.mkdirs()) { break;} 26 | } 27 | } 28 | } 29 | 30 | /** 31 | * {@inheritDoc} 32 | */ 33 | @Override 34 | public Result get(String key, Class klass, boolean isList) { 35 | T cacheResult = SerializeHelper.unSerialize(mCachePath, key + SUFFIX); 36 | if (cacheResult == null) { return null;} 37 | 38 | Result result = new Result<>(); 39 | result.ok(true); 40 | result.setMessage(""); 41 | result.setResult(cacheResult); 42 | result.setObj(200); 43 | result.setCache(true); 44 | 45 | return result; 46 | } 47 | 48 | /** 49 | * {@inheritDoc} 50 | */ 51 | @Override 52 | public void put(String key, RawResult netResult, Result result) { 53 | checkCacheSize(); 54 | SerializeHelper.serialize(mCachePath, key + SUFFIX, result.getResult()); 55 | } 56 | 57 | /** 58 | * {@inheritDoc} 59 | */ 60 | @Override 61 | public String getKey(String url, String params) { 62 | String cacheName = url + (params == null ? "" : params); 63 | cacheName = Helper.md5(cacheName); 64 | return cacheName == null ? "" : cacheName; 65 | } 66 | 67 | private void checkCacheSize() { 68 | File dir = new File(mCachePath); 69 | File[] files = dir.listFiles(); 70 | 71 | long size = 0L; 72 | for (File item : files) { 73 | size += item.length(); 74 | } 75 | 76 | if (mMaxCacheSize <= size) { 77 | clearAllCache(files); 78 | } 79 | } 80 | 81 | private void clearAllCache(File[] files) { 82 | TAG: 83 | for (File file : files) { 84 | for (int i = 0; i < 3; i++) { 85 | if (file.delete()) {continue TAG;} 86 | } 87 | } 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /glin/src/main/java/org/loader/glin/cache/ICacheProvider.java: -------------------------------------------------------------------------------- 1 | package org.loader.glin.cache; 2 | 3 | import org.loader.glin.RawResult; 4 | import org.loader.glin.Result; 5 | 6 | public interface ICacheProvider { 7 | /** 8 | * get cache by key of {@link #getKey(String, String)} 9 | * @param key key 10 | * @param klass type of data struct, see also {@link org.loader.glin.helper.Helper} 11 | * @param isList is result a List 12 | * @return cache data 13 | */ 14 | Result get(String key, Class klass, boolean isList); 15 | 16 | /** 17 | * cache data 18 | * @param key see {@link #getKey(String, String)} 19 | * @param netResult the origin result 20 | * @param result parsed result 21 | */ 22 | void put(String key, RawResult netResult, Result result); 23 | 24 | /** 25 | * provide the key 26 | * @param url the request url 27 | * @param params the request params, maybe key1=value1&key2=value2 while your request is POST, maybe null while your request is GET, maybe json string while your request is POST Json 28 | * @return 29 | */ 30 | String getKey(String url, String params); 31 | } 32 | -------------------------------------------------------------------------------- /glin/src/main/java/org/loader/glin/call/Call.java: -------------------------------------------------------------------------------- 1 | package org.loader.glin.call; 2 | 3 | import org.loader.glin.Callback; 4 | import org.loader.glin.Context; 5 | import org.loader.glin.Params; 6 | import org.loader.glin.Result; 7 | import org.loader.glin.chan.ChanNode; 8 | import org.loader.glin.chan.GlobalChanNode; 9 | import org.loader.glin.chan.LogChanNode; 10 | import org.loader.glin.client.IClient; 11 | 12 | import java.util.LinkedHashMap; 13 | import java.util.LinkedList; 14 | 15 | /** 16 | * Created by qibin on 2016/7/13. 17 | */ 18 | 19 | public abstract class Call { 20 | 21 | public static final int DEF_HTTP_CODE_CHAN_CANCELED = 468; 22 | public static final String DEF_MSG_CHAN_CANCELED = "chan canceled"; 23 | 24 | protected String mUrl; 25 | protected Params mParams; 26 | protected LinkedHashMap mHeaders; 27 | 28 | protected IClient mClient; 29 | protected Object mTag; 30 | 31 | protected boolean shouldCache; 32 | 33 | private ChanNode mBeforeChanNode; 34 | private ChanNode mAfterChanNode; 35 | 36 | private GlobalChanNode mBeforeGlobalChanNode; 37 | private GlobalChanNode mAfterGlobalChanNode; 38 | 39 | private Callback mCallback; 40 | 41 | public Call(IClient client, String url, 42 | Params params, Object tag, 43 | boolean cache) { 44 | mClient = client; 45 | mUrl = url; 46 | mParams = params; 47 | mTag = tag; 48 | shouldCache = cache; 49 | } 50 | 51 | public Call before(ChanNode chanNode) { 52 | if (mBeforeChanNode == null) { 53 | mBeforeChanNode = chanNode; 54 | chanNode.beforeCall(true); 55 | } else { 56 | next(chanNode, mBeforeChanNode); 57 | } 58 | 59 | return this; 60 | } 61 | 62 | public Call after(ChanNode chanNode) { 63 | if (mAfterChanNode == null) { 64 | mAfterChanNode = chanNode; 65 | chanNode.beforeCall(false); 66 | } else { 67 | next(chanNode, mAfterChanNode); 68 | } 69 | return this; 70 | } 71 | 72 | public Call next(ChanNode chanNode) { 73 | ChanNode current = mAfterChanNode == null ? mBeforeChanNode : mAfterChanNode; 74 | return next(chanNode, current); 75 | } 76 | 77 | private Call next(ChanNode chanNode, ChanNode header) { 78 | ChanNode current = header; 79 | 80 | if (current == null) { 81 | throw new RuntimeException("there is no before chans, please call before() first"); 82 | } 83 | 84 | while(current.nextChanNode() != null) { 85 | current = current.nextChanNode(); 86 | } 87 | 88 | current.nextChanNode(chanNode); 89 | chanNode.beforeCall(current.isBeforeCall()); 90 | 91 | return this; 92 | } 93 | 94 | public void enqueue(Callback callback) { 95 | mCallback = callback; 96 | 97 | if (mBeforeGlobalChanNode != null) { 98 | before(mBeforeGlobalChanNode); 99 | } 100 | 101 | if (mAfterGlobalChanNode != null) { 102 | ChanNode after = mAfterChanNode; 103 | mAfterChanNode = mAfterGlobalChanNode; 104 | mAfterChanNode.nextChanNode(after); 105 | } 106 | 107 | Context ctx = new Context(this); 108 | callback.attach(ctx, mAfterChanNode); 109 | 110 | if (mBeforeChanNode != null) { 111 | mBeforeChanNode.exec(ctx); 112 | return; 113 | } 114 | 115 | exec(callback); 116 | } 117 | 118 | public void exec() { exec(mCallback);} 119 | 120 | public abstract void exec(Callback callback); 121 | 122 | public void cancel(int code, String msg) { 123 | if (mCallback != null) { 124 | Result result = new Result<>(); 125 | result.ok(false); 126 | result.setCode(code); 127 | result.setMessage(msg); 128 | mCallback.onResponse(result); 129 | } 130 | } 131 | 132 | public void setGlobalChanNode(GlobalChanNode before, GlobalChanNode after) { 133 | mBeforeGlobalChanNode = before; 134 | mAfterGlobalChanNode = after; 135 | 136 | if (mBeforeGlobalChanNode != null) { 137 | mBeforeGlobalChanNode.beforeCall(true); 138 | } 139 | 140 | if (mAfterGlobalChanNode != null) { 141 | mAfterGlobalChanNode.beforeCall(false); 142 | } 143 | } 144 | 145 | public Call header(LinkedHashMap headers) { 146 | mHeaders = headers; 147 | return this; 148 | } 149 | 150 | public Call shouldCache(boolean cache) { 151 | shouldCache = cache; 152 | return this; 153 | } 154 | 155 | public Call rewriteUrl(String url) { 156 | mUrl = url; 157 | return this; 158 | } 159 | 160 | public LinkedHashMap getHeaders() { 161 | return mHeaders; 162 | } 163 | 164 | public Params getParams() { 165 | return mParams; 166 | } 167 | 168 | public String getUrl() { 169 | return mUrl; 170 | } 171 | 172 | public boolean shouldCache() { 173 | return shouldCache; 174 | } 175 | } 176 | -------------------------------------------------------------------------------- /glin/src/main/java/org/loader/glin/call/DelCall.java: -------------------------------------------------------------------------------- 1 | package org.loader.glin.call; 2 | 3 | import org.loader.glin.Callback; 4 | import org.loader.glin.Params; 5 | import org.loader.glin.client.IClient; 6 | 7 | /** 8 | * Created by qibin on 2016/7/14. 9 | */ 10 | 11 | public class DelCall extends Call { 12 | 13 | public DelCall(IClient client, String url, 14 | Params params, Object tag, 15 | boolean cache) { 16 | super(client, url, params, tag, cache); 17 | } 18 | 19 | @Override 20 | public void exec(Callback callback) { 21 | mClient.delete(mUrl, mHeaders, mTag, shouldCache, callback); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /glin/src/main/java/org/loader/glin/call/GetCall.java: -------------------------------------------------------------------------------- 1 | package org.loader.glin.call; 2 | 3 | import org.loader.glin.Callback; 4 | import org.loader.glin.Params; 5 | import org.loader.glin.client.IClient; 6 | 7 | /** 8 | * Created by qibin on 2016/7/13. 9 | */ 10 | 11 | public class GetCall extends Call { 12 | 13 | public GetCall(IClient client, String url, 14 | Params params, Object tag, 15 | boolean cache) { 16 | super(client, url, params, tag, cache); 17 | } 18 | 19 | @Override 20 | public void exec(final Callback callback) { 21 | String query = mParams.encode(); 22 | 23 | String url = mUrl; 24 | if (query != null) { 25 | if (url.contains("?")) { url = url + "&" + query;} 26 | else { url = url + "?" + query;} 27 | } 28 | 29 | mClient.get(url, mHeaders, mTag, shouldCache, callback); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /glin/src/main/java/org/loader/glin/call/JsonCall.java: -------------------------------------------------------------------------------- 1 | package org.loader.glin.call; 2 | 3 | import org.loader.glin.Callback; 4 | import org.loader.glin.Params; 5 | import org.loader.glin.client.IClient; 6 | 7 | /** 8 | * Created by qibin on 2016/7/13. 9 | */ 10 | 11 | public class JsonCall extends Call { 12 | 13 | public JsonCall(IClient client, String url, 14 | Params params, Object tag, 15 | boolean cache) { 16 | super(client, url, params, tag, cache); 17 | } 18 | 19 | @Override 20 | public void exec(final Callback callback) { 21 | String json = mParams.getParams(Params.DEFAULT_JSON_KEY); 22 | if (json == null) { 23 | throw new UnsupportedOperationException("cannot find json"); 24 | } 25 | mClient.post(mUrl, mHeaders, mParams.getParams(Params.DEFAULT_JSON_KEY), mTag, shouldCache, callback); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /glin/src/main/java/org/loader/glin/call/PostCall.java: -------------------------------------------------------------------------------- 1 | package org.loader.glin.call; 2 | 3 | import org.loader.glin.Callback; 4 | import org.loader.glin.Params; 5 | import org.loader.glin.client.IClient; 6 | 7 | /** 8 | * Created by qibin on 2016/7/13. 9 | */ 10 | 11 | public class PostCall extends Call { 12 | 13 | public PostCall(IClient client, String url, 14 | Params params, Object tag, 15 | boolean cache) { 16 | super(client, url, params, tag, cache); 17 | } 18 | 19 | @Override 20 | public void exec(final Callback callback) { 21 | mClient.post(mUrl, mHeaders, mParams, mTag, shouldCache, callback); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /glin/src/main/java/org/loader/glin/call/PutCall.java: -------------------------------------------------------------------------------- 1 | package org.loader.glin.call; 2 | 3 | import org.loader.glin.Callback; 4 | import org.loader.glin.Params; 5 | import org.loader.glin.client.IClient; 6 | 7 | /** 8 | * Created by qibin on 2016/7/14. 9 | */ 10 | 11 | public class PutCall extends Call { 12 | 13 | public PutCall(IClient client, String url, 14 | Params params, Object tag, 15 | boolean cache) { 16 | super(client, url, params, tag, cache); 17 | } 18 | 19 | @Override 20 | public void exec(Callback callback) { 21 | mClient.put(mUrl, mHeaders, mParams, mTag, shouldCache, callback); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /glin/src/main/java/org/loader/glin/chan/ChanNode.java: -------------------------------------------------------------------------------- 1 | package org.loader.glin.chan; 2 | 3 | import org.loader.glin.Context; 4 | import org.loader.glin.call.Call; 5 | 6 | /** 7 | * Created by qibin on 2016/7/13. 8 | */ 9 | 10 | public abstract class ChanNode { 11 | private ChanNode mNext; 12 | private Context mContext; 13 | 14 | private boolean beforeCall; 15 | 16 | public final void beforeCall(boolean invoke) { 17 | beforeCall = invoke; 18 | } 19 | 20 | public final boolean isBeforeCall() { 21 | return beforeCall; 22 | } 23 | 24 | public final void exec(Context ctx) { 25 | mContext = ctx; 26 | run(ctx); 27 | } 28 | 29 | public final ChanNode nextChanNode() { 30 | return mNext; 31 | } 32 | 33 | public final void nextChanNode(ChanNode chanNode) { 34 | mNext = chanNode; 35 | } 36 | 37 | protected final void next() { 38 | if (mNext != null) { 39 | mNext.exec(mContext); 40 | return; 41 | } 42 | 43 | if (beforeCall) { mContext.getCall().exec();} 44 | } 45 | 46 | protected final void cancel() { 47 | cancel(Call.DEF_HTTP_CODE_CHAN_CANCELED); 48 | } 49 | 50 | protected final void cancel(int code) { 51 | cancel(code, Call.DEF_MSG_CHAN_CANCELED); 52 | } 53 | 54 | protected final void cancel(int code, String msg) { 55 | mNext = null; 56 | if (beforeCall) { 57 | mContext.getCall().cancel(code, msg); 58 | } 59 | } 60 | 61 | public abstract void run(Context ctx); 62 | } 63 | -------------------------------------------------------------------------------- /glin/src/main/java/org/loader/glin/chan/GlobalChanNode.java: -------------------------------------------------------------------------------- 1 | package org.loader.glin.chan; 2 | 3 | import org.loader.glin.Context; 4 | 5 | /** 6 | *

File Note

7 | * Created by qibin on 2017/11/13. 8 | */ 9 | 10 | public class GlobalChanNode extends ChanNode { 11 | 12 | private ChanNode[] mGlobalChanNodes; 13 | 14 | public GlobalChanNode(ChanNode ...chanNodes) { 15 | mGlobalChanNodes = chanNodes; 16 | } 17 | 18 | @Override 19 | public void run(Context ctx) { 20 | ChanNode[] globalChanNodes = mGlobalChanNodes; 21 | 22 | if (globalChanNodes == null) { return;} 23 | for (ChanNode item : globalChanNodes) { 24 | if (item == null) { continue;} 25 | 26 | item.beforeCall(isBeforeCall()); 27 | item.exec(ctx); 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /glin/src/main/java/org/loader/glin/chan/LogChanNode.java: -------------------------------------------------------------------------------- 1 | package org.loader.glin.chan; 2 | 3 | import org.loader.glin.Context; 4 | import org.loader.glin.helper.LogHelper; 5 | 6 | import java.io.File; 7 | import java.util.LinkedHashMap; 8 | import java.util.Map; 9 | import java.util.regex.Matcher; 10 | import java.util.regex.Pattern; 11 | 12 | /** 13 | * Created by qibin on 2016/7/13. 14 | */ 15 | 16 | public class LogChanNode extends ChanNode implements Cloneable { 17 | 18 | private boolean isDebug; 19 | private LogHelper.LogPrinter mLogPrinter; 20 | 21 | public LogChanNode(boolean debug, LogHelper.LogPrinter printer) { 22 | isDebug = debug; 23 | mLogPrinter = printer; 24 | } 25 | 26 | @Override 27 | public void run(Context ctx) { 28 | if (isBeforeCall()) { 29 | prntRequestLog(ctx); 30 | }else { 31 | prntResponseLog(ctx); 32 | // do not call next(), when result is cache 33 | if (ctx.getResult().isCache()) { return;} 34 | } 35 | next(); 36 | } 37 | 38 | private void prntResponseLog(Context ctx) { 39 | if (!isDebug) { return;} 40 | 41 | StringBuilder builder = new StringBuilder(); 42 | builder.append("================== Glin Start Response ==================\n\n"); 43 | 44 | if (ctx.getResult().isCache()) { 45 | builder.append(" is cache-> true \n") 46 | .append(" use cache-> ") 47 | .append(ctx.getCall().getUrl()) 48 | .append("\n"); 49 | } else { 50 | builder.append(" is cache-> false \n"); 51 | builder.append(" status code-> ").append(ctx.getRawResult().getStatusCode()).append("\n"); 52 | builder.append(" message-> ").append(ctx.getRawResult().getMessage()).append("\n"); 53 | builder.append(" response-> ").append(ctx.getRawResult().getResponse()).append("\n"); 54 | 55 | if (ctx.getCall().shouldCache()) { 56 | builder.append(" cache result-> ").append(ctx.getCall().getUrl()).append("\n"); 57 | } 58 | } 59 | 60 | builder.append("\n================== Glin End Response =================="); 61 | 62 | mLogPrinter.print("Glin", builder.toString()); 63 | 64 | } 65 | 66 | private void prntRequestLog(Context ctx) { 67 | if (!isDebug) { return;} 68 | 69 | StringBuilder builder = new StringBuilder(); 70 | builder.append("================== Glin Start Request ==================\n\n"); 71 | 72 | builder.append(" url-> ").append(ctx.getCall().getUrl()).append("\n"); 73 | builder.append(" method-> ").append(ctx.getCall().getClass().getSimpleName()).append("\n"); 74 | 75 | if (!ctx.getCall().getParams().isEmpty()) { 76 | builder.append(" params-> \n"); 77 | LinkedHashMap map = ctx.getCall().getParams().get(); 78 | for (Map.Entry entry : map.entrySet()) { 79 | String value = entry.getValue(); 80 | if (value == null) { continue;} 81 | builder.append(" \t").append(entry.getKey()).append(":").append(value).append("\n"); 82 | } 83 | } 84 | 85 | if (!ctx.getCall().getParams().files().isEmpty()) { 86 | builder.append(" files-> \n"); 87 | LinkedHashMap files = ctx.getCall().getParams().files(); 88 | for (Map.Entry entry : files.entrySet()) { 89 | File file = entry.getValue(); 90 | if (file == null) { continue;} 91 | builder.append(" \t").append(entry.getKey()).append(":") 92 | .append(file.getName()).append("\n"); 93 | } 94 | } 95 | 96 | if (ctx.getCall().getHeaders() != null && !ctx.getCall().getHeaders().isEmpty()) { 97 | builder.append(" header-> \n"); 98 | for(Map.Entry entry : ctx.getCall().getHeaders().entrySet()) { 99 | builder.append(" \t").append(entry.getKey()).append(":") 100 | .append(entry.getValue()).append("\n"); 101 | } 102 | } 103 | 104 | builder.append("\n================== Glin End Request =================="); 105 | mLogPrinter.print("Glin", builder.toString()); 106 | } 107 | 108 | @Override 109 | public LogChanNode clone() throws CloneNotSupportedException { 110 | return (LogChanNode) super.clone(); 111 | } 112 | } 113 | -------------------------------------------------------------------------------- /glin/src/main/java/org/loader/glin/client/IClient.java: -------------------------------------------------------------------------------- 1 | package org.loader.glin.client; 2 | 3 | import org.loader.glin.cache.ICacheProvider; 4 | import org.loader.glin.factory.ParserFactory; 5 | import org.loader.glin.interceptor.IResultInterceptor; 6 | 7 | import java.util.LinkedHashMap; 8 | 9 | /** 10 | * Created by qibin on 2016/7/13. 11 | */ 12 | 13 | public interface IClient extends IRequest { 14 | 15 | void cancel(final Object tag); 16 | 17 | void parserFactory(ParserFactory factory); 18 | 19 | LinkedHashMap headers(); 20 | 21 | void resultInterceptor(IResultInterceptor interceptor); 22 | 23 | void cacheProvider(ICacheProvider provider); 24 | 25 | void timeout(long ms); 26 | } 27 | -------------------------------------------------------------------------------- /glin/src/main/java/org/loader/glin/client/IRequest.java: -------------------------------------------------------------------------------- 1 | package org.loader.glin.client; 2 | 3 | import org.loader.glin.Callback; 4 | import org.loader.glin.Params; 5 | 6 | import java.util.LinkedHashMap; 7 | 8 | /** 9 | * Created by qibin on 2016/8/29. 10 | */ 11 | 12 | public interface IRequest { 13 | 14 | void get(final String url, final LinkedHashMap header, final Object tag, 15 | final boolean shouldCache, final Callback callback); 16 | 17 | void post(final String url, final LinkedHashMap header, final Params params, 18 | final Object tag, final boolean shouldCache, final Callback callback); 19 | 20 | void post(final String url, final LinkedHashMap header, final String json, 21 | final Object tag, final boolean shouldCache, final Callback callback); 22 | 23 | void put(final String url, final LinkedHashMap header, final Params params, 24 | final Object tag, final boolean shouldCache, final Callback callback); 25 | 26 | void put(final String url, final LinkedHashMap header, final String json, 27 | final Object tag, final boolean shouldCache, final Callback callback); 28 | 29 | void delete(final String url, final LinkedHashMap header, 30 | final Object tag, final boolean shouldCache, final Callback callback); 31 | } 32 | -------------------------------------------------------------------------------- /glin/src/main/java/org/loader/glin/factory/CallFactory.java: -------------------------------------------------------------------------------- 1 | package org.loader.glin.factory; 2 | 3 | import org.loader.glin.annotation.DEL; 4 | import org.loader.glin.annotation.GET; 5 | import org.loader.glin.annotation.JSON; 6 | import org.loader.glin.annotation.POST; 7 | import org.loader.glin.annotation.PUT; 8 | import org.loader.glin.call.Call; 9 | import org.loader.glin.call.DelCall; 10 | import org.loader.glin.call.GetCall; 11 | import org.loader.glin.call.JsonCall; 12 | import org.loader.glin.call.PostCall; 13 | import org.loader.glin.call.PutCall; 14 | 15 | import java.lang.annotation.Annotation; 16 | import java.util.HashMap; 17 | 18 | /** 19 | * Created by qibin on 2016/7/13. 20 | */ 21 | 22 | public class CallFactory { 23 | 24 | private HashMap, Class> mMapping = new HashMap<>(); 25 | 26 | public CallFactory() { 27 | autoRegist(); 28 | } 29 | 30 | private void autoRegist() { 31 | register(JSON.class, JsonCall.class); 32 | register(GET.class, GetCall.class); 33 | register(POST.class, PostCall.class); 34 | register(PUT.class, PutCall.class); 35 | register(DEL.class, DelCall.class); 36 | } 37 | 38 | public void register(Class key, Class value) { 39 | mMapping.put(key, value); 40 | } 41 | 42 | public Class get(Class key) { 43 | return mMapping.get(key); 44 | } 45 | 46 | public HashMap, Class> get() { 47 | return mMapping; 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /glin/src/main/java/org/loader/glin/factory/ParserFactory.java: -------------------------------------------------------------------------------- 1 | package org.loader.glin.factory; 2 | 3 | import org.loader.glin.parser.Parser; 4 | 5 | /** 6 | * Created by qibin on 2016/7/13. 7 | */ 8 | 9 | public interface ParserFactory { 10 | Parser getParser(); 11 | Parser getListParser(); 12 | } 13 | -------------------------------------------------------------------------------- /glin/src/main/java/org/loader/glin/helper/ClientHelper.java: -------------------------------------------------------------------------------- 1 | package org.loader.glin.helper; 2 | 3 | import org.loader.glin.Callback; 4 | import org.loader.glin.RawResult; 5 | import org.loader.glin.Result; 6 | import org.loader.glin.cache.ICacheProvider; 7 | import org.loader.glin.factory.ParserFactory; 8 | import org.loader.glin.interceptor.IResultInterceptor; 9 | 10 | import java.util.List; 11 | 12 | /** 13 | * ClientHelper, useful when you convert response, cache your data and intercept your callback 14 | */ 15 | public final class ClientHelper { 16 | 17 | private ParserFactory mParserFactory; 18 | private ICacheProvider mCacheProvider; 19 | private IResultInterceptor mResultInterceptor; 20 | 21 | public ClientHelper parserFactory(ParserFactory parserFactory) { 22 | mParserFactory = parserFactory; 23 | return this; 24 | } 25 | 26 | public ClientHelper cacheProvider(ICacheProvider cacheProvider) { 27 | mCacheProvider = cacheProvider; 28 | return this; 29 | } 30 | 31 | public ClientHelper resultInterceptor(IResultInterceptor resultInterceptor) { 32 | mResultInterceptor = resultInterceptor; 33 | return this; 34 | } 35 | 36 | /** 37 | * convert the http response to Result 38 | * @param callback 39 | * @param netResult 40 | * @param 41 | * @return return the result 42 | */ 43 | public Result parseResponse(Callback callback, RawResult netResult) { 44 | final Class callbackKlass = callback.getClass(); 45 | final Class dataKlass = Helper.getType(callbackKlass); 46 | final boolean resultTypeIsArray = resultTypeIsArray(dataKlass); 47 | 48 | Result result; 49 | if (resultTypeIsArray) { 50 | Class klass = Helper.getDeepType(callbackKlass); 51 | result = mParserFactory.getListParser().parse(klass, netResult); 52 | } else { 53 | result = mParserFactory.getParser().parse(dataKlass, netResult); 54 | } 55 | 56 | return result; 57 | } 58 | 59 | /** 60 | * generate cache key 61 | * @param url 62 | * @param params 63 | * @return return key of cache 64 | */ 65 | public String getCacheKey(String url, String params) { 66 | return mCacheProvider == null ? null : mCacheProvider.getKey(url, params); 67 | } 68 | 69 | /** 70 | * use cache 71 | * @param shouldCache 72 | * @param cacheKey 73 | * @param callback 74 | * @param 75 | * @return return the cache Result, if no cache was found return null 76 | */ 77 | public Result useCache(boolean shouldCache, String cacheKey, Callback callback) { 78 | final Class callbackKlass = callback.getClass(); 79 | final Class dataKlass = Helper.getType(callbackKlass); 80 | final boolean resultTypeIsArray = resultTypeIsArray(dataKlass); 81 | if (shouldCache && mCacheProvider != null) { 82 | // data struct or List.class 83 | Result result; 84 | if (resultTypeIsArray) { 85 | Class klass = Helper.getDeepType(callbackKlass); 86 | result = mCacheProvider.get(cacheKey, klass, true); 87 | }else { 88 | result = mCacheProvider.get(cacheKey, dataKlass, false); 89 | } 90 | 91 | if (result != null && result.isOK()) { 92 | return result; 93 | } 94 | } 95 | 96 | return null; 97 | } 98 | 99 | /** 100 | * cache your response if should cache 101 | * @param shouldCache 102 | * @param cacheKey 103 | * @param result 104 | * @param netResult 105 | * @param 106 | * @return return true if cache ok, otherwise return false 107 | */ 108 | public boolean cache(boolean shouldCache, String cacheKey, Result result, 109 | RawResult netResult) { 110 | if (shouldCache && mCacheProvider != null && result.isOK()) { 111 | mCacheProvider.put(cacheKey, netResult, result); 112 | return true; 113 | } 114 | return false; 115 | } 116 | 117 | /** 118 | * testing should intercept callback 119 | * @param result 120 | * @param 121 | * @return return true if should intercept your callback, otherwise return false 122 | */ 123 | public boolean shouldInterceptResult(final Result result) { 124 | return mResultInterceptor != null && mResultInterceptor.intercept(result); 125 | } 126 | 127 | private boolean resultTypeIsArray(Class dataKlass) { 128 | return List.class.isAssignableFrom(dataKlass); 129 | } 130 | } 131 | -------------------------------------------------------------------------------- /glin/src/main/java/org/loader/glin/helper/Helper.java: -------------------------------------------------------------------------------- 1 | package org.loader.glin.helper; 2 | 3 | import java.lang.reflect.ParameterizedType; 4 | import java.lang.reflect.Type; 5 | import java.math.BigInteger; 6 | import java.security.MessageDigest; 7 | 8 | /** 9 | * Created by qibin on 2016/7/13. 10 | */ 11 | 12 | public class Helper { 13 | public static Class getType(Class klass) { 14 | Type type = generateType(klass); 15 | 16 | if (type != null) { 17 | if (type instanceof ParameterizedType) { 18 | type = ((ParameterizedType) type).getRawType(); 19 | } 20 | return (Class) type; 21 | } 22 | return null; 23 | } 24 | 25 | public static Class getDeepType(Class klass) { 26 | Type type = generateType(klass); 27 | if (type != null && type instanceof ParameterizedType) { 28 | ParameterizedType parameterizedType = (ParameterizedType) type; 29 | return (Class) parameterizedType.getActualTypeArguments()[0]; 30 | } 31 | return null; 32 | } 33 | 34 | public static Type generateType(Class klass) { 35 | Type type = klass.getGenericSuperclass(); 36 | if (type instanceof ParameterizedType) { 37 | ParameterizedType paramType = (ParameterizedType) type; 38 | Type[] actualTypes = paramType.getActualTypeArguments(); 39 | if (actualTypes != null && actualTypes.length > 0) { 40 | return actualTypes[0]; 41 | } 42 | } 43 | 44 | return null; 45 | } 46 | 47 | public static String md5(String str) { 48 | try { 49 | MessageDigest md = MessageDigest.getInstance("MD5"); 50 | md.update(str.getBytes()); 51 | return new BigInteger(1, md.digest()).toString(16); 52 | } catch (Exception e) { 53 | e.printStackTrace(); 54 | } 55 | 56 | return str; 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /glin/src/main/java/org/loader/glin/helper/LogHelper.java: -------------------------------------------------------------------------------- 1 | package org.loader.glin.helper; 2 | 3 | /** 4 | * Created by qibin on 2016/7/13. 5 | */ 6 | public class LogHelper { 7 | private boolean isDebugMode; 8 | private LogPrinter mLogPrinter; 9 | private StringBuilder mLogAppender; 10 | 11 | public static LogHelper get(boolean debug, LogPrinter logPrinter) { 12 | LogHelper helper = new LogHelper(logPrinter); 13 | helper.isDebugMode(debug); 14 | return helper; 15 | } 16 | 17 | private LogHelper(LogPrinter logPrinter) { 18 | mLogPrinter = logPrinter; 19 | } 20 | 21 | public void isDebugMode(boolean debug) { 22 | isDebugMode = debug; 23 | } 24 | 25 | public boolean isDebugMode() { 26 | return isDebugMode; 27 | } 28 | 29 | public StringBuilder getLogAppender() { 30 | if (mLogAppender == null) { 31 | mLogAppender = new StringBuilder(); 32 | } 33 | return mLogAppender; 34 | } 35 | 36 | public void print() { 37 | if (!isDebugMode || mLogAppender == null || mLogAppender.length() == 0) { return;} 38 | print(mLogAppender.toString()); 39 | } 40 | 41 | public void print(String content) { 42 | if (!isDebugMode) { return;} 43 | 44 | mLogPrinter.print("Glin", "*******************--BEGIN--*******************"); 45 | mLogPrinter.print("Glin", content); 46 | mLogPrinter.print("Glin", "********************--END--********************"); 47 | } 48 | 49 | public interface LogPrinter { 50 | void print(String tag, String content); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /glin/src/main/java/org/loader/glin/helper/SerializeHelper.java: -------------------------------------------------------------------------------- 1 | package org.loader.glin.helper; 2 | 3 | import java.io.File; 4 | import java.io.FileInputStream; 5 | import java.io.FileOutputStream; 6 | import java.io.IOException; 7 | import java.io.ObjectInputStream; 8 | import java.io.ObjectOutputStream; 9 | import java.io.Serializable; 10 | 11 | public class SerializeHelper { 12 | 13 | public static T unSerialize(String path, String name) { 14 | checkPath(path); 15 | ObjectInputStream ois = null; 16 | try { 17 | ois = new ObjectInputStream(new FileInputStream(path + name)); 18 | Object obj = ois.readObject(); 19 | return (T) obj; 20 | } catch (IOException e) { 21 | // empty 22 | } catch (ClassNotFoundException e) { 23 | // empty 24 | } finally { 25 | if (ois != null) { 26 | try { 27 | ois.close(); 28 | } catch (IOException e) { 29 | // empty 30 | } 31 | } 32 | } 33 | return null; 34 | } 35 | 36 | public static void serialize(String path, String name, Object obj) { 37 | checkPath(path); 38 | if (!(obj instanceof Serializable)) { return;} 39 | ObjectOutputStream oos = null; 40 | try { 41 | oos = new ObjectOutputStream(new FileOutputStream(path + name)); 42 | oos.writeObject(obj); 43 | oos.flush(); 44 | } catch (IOException e) { 45 | e.printStackTrace(); 46 | } finally { 47 | if (oos != null) { 48 | try { 49 | oos.close(); 50 | } catch (IOException e) { 51 | e.printStackTrace(); 52 | } 53 | } 54 | } 55 | } 56 | 57 | private static void checkPath(String path) { 58 | File pathFile = new File(path); 59 | if (!pathFile.exists()) { 60 | pathFile.mkdirs(); 61 | } 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /glin/src/main/java/org/loader/glin/interceptor/IResultInterceptor.java: -------------------------------------------------------------------------------- 1 | package org.loader.glin.interceptor; 2 | 3 | 4 | import org.loader.glin.Result; 5 | 6 | /** 7 | * Created by qibin on 2016/8/20. 8 | */ 9 | 10 | public interface IResultInterceptor { 11 | /** 12 | * 是否拦截结果 13 | * @param result 14 | * @return true callback不会执行 15 | */ 16 | boolean intercept(Result result); 17 | } 18 | -------------------------------------------------------------------------------- /glin/src/main/java/org/loader/glin/parser/Parser.java: -------------------------------------------------------------------------------- 1 | package org.loader.glin.parser; 2 | 3 | import org.loader.glin.RawResult; 4 | import org.loader.glin.Result; 5 | 6 | /** 7 | * Created by qibin on 2016/7/13. 8 | */ 9 | 10 | public abstract class Parser { 11 | public String mKey; 12 | 13 | public Parser() { 14 | 15 | } 16 | 17 | public Parser(String key) { 18 | mKey = key; 19 | } 20 | 21 | /** 22 | * 23 | * @param klass the class of data struct 24 | * @param netResult 25 | * @param 26 | * @return 27 | */ 28 | public abstract Result parse(Class klass, RawResult netResult); 29 | } 30 | -------------------------------------------------------------------------------- /glin/src/main/java/org/loader/glin/utils/Pair.java: -------------------------------------------------------------------------------- 1 | package org.loader.glin.utils; 2 | 3 | /** 4 | * Created by qibin on 17-7-2. 5 | */ 6 | 7 | public class Pair { 8 | public F first; 9 | public S second; 10 | 11 | public Pair(F f, S s) { 12 | first = f; 13 | second = s; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /glinsample/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /glinsample/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | 3 | android { 4 | compileSdkVersion 25 5 | buildToolsVersion "25.0.2" 6 | 7 | defaultConfig { 8 | applicationId "org.loader.glinsample" 9 | minSdkVersion 9 10 | targetSdkVersion 25 11 | versionCode 1 12 | versionName "1.0" 13 | 14 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" 15 | 16 | } 17 | buildTypes { 18 | release { 19 | minifyEnabled false 20 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 21 | } 22 | } 23 | } 24 | 25 | dependencies { 26 | compile fileTree(dir: 'libs', include: ['*.jar']) 27 | androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', { 28 | exclude group: 'com.android.support', module: 'support-annotations' 29 | }) 30 | compile 'com.android.support:appcompat-v7:25.3.1' 31 | testCompile 'junit:junit:4.12' 32 | 33 | compile 'org.loader:glin-okclient:3.2' 34 | compile 'com.alibaba:fastjson:1.1.56.android' 35 | } 36 | -------------------------------------------------------------------------------- /glinsample/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 D:\android-sdk\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 with 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 | -------------------------------------------------------------------------------- /glinsample/src/androidTest/java/org/loader/glinsample/ExampleInstrumentedTest.java: -------------------------------------------------------------------------------- 1 | package org.loader.glinsample; 2 | 3 | import android.content.Context; 4 | import android.support.test.InstrumentationRegistry; 5 | import android.support.test.runner.AndroidJUnit4; 6 | 7 | import org.junit.Test; 8 | import org.junit.runner.RunWith; 9 | 10 | import static org.junit.Assert.*; 11 | 12 | /** 13 | * Instrumentation test, which will execute on an Android device. 14 | * 15 | * @see Testing documentation 16 | */ 17 | @RunWith(AndroidJUnit4.class) 18 | public class ExampleInstrumentedTest { 19 | @Test 20 | public void useAppContext() throws Exception { 21 | // Context of the app under test. 22 | Context appContext = InstrumentationRegistry.getTargetContext(); 23 | 24 | assertEquals("org.loader.glinsample", appContext.getPackageName()); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /glinsample/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | 8 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /glinsample/src/main/java/org/loader/glinsample/App.java: -------------------------------------------------------------------------------- 1 | package org.loader.glinsample; 2 | 3 | import android.app.Application; 4 | 5 | public class App extends Application { 6 | 7 | private static App app; 8 | 9 | @Override 10 | public void onCreate() { 11 | super.onCreate(); 12 | app = this; 13 | } 14 | 15 | public static App get() { 16 | return app; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /glinsample/src/main/java/org/loader/glinsample/MainActivity.java: -------------------------------------------------------------------------------- 1 | package org.loader.glinsample; 2 | 3 | import android.Manifest; 4 | import android.content.DialogInterface; 5 | import android.content.Intent; 6 | import android.content.SharedPreferences; 7 | import android.content.pm.PackageManager; 8 | import android.net.Uri; 9 | import android.provider.Settings; 10 | import android.support.annotation.NonNull; 11 | import android.support.v4.app.ActivityCompat; 12 | import android.support.v4.content.ContextCompat; 13 | import android.support.v7.app.AlertDialog; 14 | import android.support.v7.app.AppCompatActivity; 15 | import android.os.Bundle; 16 | import android.view.View; 17 | import android.widget.TextView; 18 | import android.widget.Toast; 19 | 20 | import org.loader.glin.Callback; 21 | import org.loader.glin.Result; 22 | import org.loader.glin.call.Call; 23 | import org.loader.glinsample.api.Api; 24 | import org.loader.glinsample.bean.UserInfo; 25 | import org.loader.glinsample.chan.CheckEnvChanNode; 26 | import org.loader.glinsample.chan.EndChanNode; 27 | import org.loader.glinsample.chan.UserIdChanNode; 28 | import org.loader.glinsample.chan.UserNameChanNode; 29 | import org.loader.glinsample.utils.Net; 30 | 31 | public class MainActivity extends AppCompatActivity implements View.OnClickListener { 32 | 33 | private TextView mInfoTextView; 34 | private boolean canClick; 35 | 36 | @Override 37 | protected void onCreate(Bundle savedInstanceState) { 38 | super.onCreate(savedInstanceState); 39 | setContentView(R.layout.activity_main); 40 | 41 | mInfoTextView = (TextView) findViewById(R.id.info); 42 | mInfoTextView.setOnClickListener(this); 43 | 44 | if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) 45 | == PackageManager.PERMISSION_GRANTED) { 46 | canClick = true; 47 | } 48 | } 49 | 50 | @Override 51 | public void onClick(View v) { 52 | if (!canClick) { 53 | ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1000); 54 | return; 55 | } 56 | 57 | final SharedPreferences sp = App.get().getSharedPreferences("sp", 58 | android.content.Context.MODE_PRIVATE); 59 | 60 | String uid = sp.getString("uid", ""); 61 | String name = sp.getString("name", ""); 62 | 63 | Call call = Net.get().create(Api.class, getClass().getName()).info(uid, name); 64 | 65 | call.before(new CheckEnvChanNode()) 66 | .next(new UserIdChanNode()) 67 | .next(new UserNameChanNode()) 68 | .after(new EndChanNode()) 69 | .enqueue(new Callback() { 70 | @Override 71 | public void onResponse(Result result) { 72 | if (result.isOK()) { 73 | String uid = result.getResult().getId(); 74 | String name = result.getResult().getName(); 75 | int age = result.getResult().getAge(); 76 | Toast.makeText(MainActivity.this, uid + ";" + name + ";" + age, Toast.LENGTH_SHORT).show(); 77 | } else { 78 | Toast.makeText(MainActivity.this, "code:" + result.getCode() + ",msg:" + result.getMessage(), 79 | Toast.LENGTH_SHORT).show(); 80 | } 81 | } 82 | }); 83 | } 84 | 85 | @Override 86 | public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { 87 | super.onRequestPermissionsResult(requestCode, permissions, grantResults); 88 | if (requestCode != 1000) { return;} 89 | 90 | if (grantResults.length <= 0) { return;} 91 | 92 | if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { 93 | canClick = true; 94 | onClick(null); 95 | return; 96 | } 97 | 98 | if (!ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { 99 | new AlertDialog.Builder(this) 100 | .setTitle("NOTICE") 101 | .setMessage("PLZ Grant me permission!!") 102 | .setPositiveButton("Grant", new DialogInterface.OnClickListener() { 103 | @Override 104 | public void onClick(DialogInterface dialog, int which) { 105 | Uri packageURI = Uri.parse("package:" + getPackageName()); 106 | Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packageURI); 107 | startActivity(intent); 108 | } 109 | }).setNegativeButton("Cancel", null).show(); 110 | } 111 | } 112 | } 113 | -------------------------------------------------------------------------------- /glinsample/src/main/java/org/loader/glinsample/api/Api.java: -------------------------------------------------------------------------------- 1 | package org.loader.glinsample.api; 2 | 3 | import org.loader.glin.annotation.Arg; 4 | import org.loader.glin.annotation.GET; 5 | import org.loader.glin.annotation.POST; 6 | import org.loader.glin.annotation.Path; 7 | import org.loader.glin.annotation.ShouldCache; 8 | import org.loader.glin.call.Call; 9 | import org.loader.glinsample.bean.UserInfo; 10 | 11 | public interface Api { 12 | 13 | @GET("/user/{:path}/") 14 | Call uid(@Path("path") String path); 15 | 16 | @ShouldCache 17 | @POST("/user/info/") 18 | Call info(@Arg("uid") String id, @Arg("name") String name); 19 | } 20 | -------------------------------------------------------------------------------- /glinsample/src/main/java/org/loader/glinsample/bean/UserInfo.java: -------------------------------------------------------------------------------- 1 | package org.loader.glinsample.bean; 2 | 3 | import java.io.Serializable; 4 | 5 | public class UserInfo implements Serializable { 6 | private String id; 7 | private String name; 8 | private int age; 9 | 10 | public String getId() { 11 | return id; 12 | } 13 | 14 | public void setId(String id) { 15 | this.id = id; 16 | } 17 | 18 | public String getName() { 19 | return name; 20 | } 21 | 22 | public void setName(String name) { 23 | this.name = name; 24 | } 25 | 26 | public int getAge() { 27 | return age; 28 | } 29 | 30 | public void setAge(int age) { 31 | this.age = age; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /glinsample/src/main/java/org/loader/glinsample/chan/CheckEnvChanNode.java: -------------------------------------------------------------------------------- 1 | package org.loader.glinsample.chan; 2 | 3 | import android.util.Log; 4 | 5 | import org.loader.glin.Context; 6 | import org.loader.glin.chan.ChanNode; 7 | 8 | public class CheckEnvChanNode extends ChanNode { 9 | 10 | @Override 11 | public void run(Context ctx) { 12 | // ctx.getCall().rewriteUrl("http://baidu.com"); 13 | Log.d("Glin", "CheckEnvChanNode"); 14 | next(); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /glinsample/src/main/java/org/loader/glinsample/chan/EndChanNode.java: -------------------------------------------------------------------------------- 1 | package org.loader.glinsample.chan; 2 | 3 | import android.util.Log; 4 | 5 | import org.loader.glin.Context; 6 | import org.loader.glin.chan.ChanNode; 7 | 8 | public class EndChanNode extends ChanNode { 9 | 10 | @Override 11 | public void run(Context ctx) { 12 | // do nothing 13 | Log.d("Glin", "EndChanNode do nothing"); 14 | next(); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /glinsample/src/main/java/org/loader/glinsample/chan/UserIdChanNode.java: -------------------------------------------------------------------------------- 1 | package org.loader.glinsample.chan; 2 | 3 | import android.content.SharedPreferences; 4 | import android.text.TextUtils; 5 | import android.util.Log; 6 | 7 | import org.loader.glin.Callback; 8 | import org.loader.glin.Context; 9 | import org.loader.glin.Result; 10 | import org.loader.glin.chan.ChanNode; 11 | import org.loader.glinsample.App; 12 | import org.loader.glinsample.api.Api; 13 | import org.loader.glinsample.bean.UserInfo; 14 | import org.loader.glinsample.utils.Net; 15 | 16 | public class UserIdChanNode extends ChanNode { 17 | 18 | @Override 19 | public void run(final Context ctx) { 20 | final SharedPreferences sp = App.get().getSharedPreferences("sp", 21 | android.content.Context.MODE_PRIVATE); 22 | 23 | Log.d("Glin", "UserIdChanNode"); 24 | 25 | if (!TextUtils.isEmpty(sp.getString("uid", null))) { 26 | next(); 27 | return; 28 | } 29 | 30 | Net.get().create(Api.class, getClass().getName()).uid("id").enqueue(new Callback() { 31 | @Override 32 | public void onResponse(Result result) { 33 | if (result.isOK()) { 34 | // refresh uid param 35 | ctx.getCall().getParams().add("uid", result.getResult().getId()); 36 | sp.edit().putString("uid", result.getResult().getId()).apply(); 37 | 38 | next(); 39 | } else { 40 | cancel(4000, "no uid"); 41 | } 42 | } 43 | }); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /glinsample/src/main/java/org/loader/glinsample/chan/UserNameChanNode.java: -------------------------------------------------------------------------------- 1 | package org.loader.glinsample.chan; 2 | 3 | import android.content.SharedPreferences; 4 | import android.text.TextUtils; 5 | import android.util.Log; 6 | 7 | import org.loader.glin.Callback; 8 | import org.loader.glin.Context; 9 | import org.loader.glin.Result; 10 | import org.loader.glin.chan.ChanNode; 11 | import org.loader.glinsample.App; 12 | import org.loader.glinsample.api.Api; 13 | import org.loader.glinsample.bean.UserInfo; 14 | import org.loader.glinsample.utils.Net; 15 | 16 | public class UserNameChanNode extends ChanNode { 17 | 18 | @Override 19 | public void run(final Context ctx) { 20 | 21 | Log.d("Glin", "UserNameChanNode"); 22 | 23 | final SharedPreferences sp = App.get().getSharedPreferences("sp", 24 | android.content.Context.MODE_PRIVATE); 25 | 26 | if (!TextUtils.isEmpty(sp.getString("name", null))) { 27 | next(); 28 | return; 29 | } 30 | 31 | Net.get().create(Api.class, getClass().getName()).uid("name").enqueue(new Callback() { 32 | @Override 33 | public void onResponse(Result result) { 34 | if (result.isOK()) { 35 | // refresh name param 36 | ctx.getCall().getParams().add("name", result.getResult().getName()); 37 | sp.edit().putString("name", result.getResult().getName()).apply(); 38 | 39 | next(); 40 | } else { 41 | cancel(5000, "no username"); 42 | } 43 | } 44 | }); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /glinsample/src/main/java/org/loader/glinsample/utils/Net.java: -------------------------------------------------------------------------------- 1 | package org.loader.glinsample.utils; 2 | 3 | import android.os.Environment; 4 | import android.util.Log; 5 | 6 | import org.loader.glin.Glin; 7 | import org.loader.glin.cache.DefaultCacheProvider; 8 | import org.loader.glin.chan.GlobalChanNode; 9 | import org.loader.glin.chan.LogChanNode; 10 | import org.loader.glin.helper.LogHelper; 11 | import org.loader.okclient.OkClient; 12 | 13 | public class Net { 14 | 15 | private static final LogHelper.LogPrinter printer = new LogHelper.LogPrinter() { 16 | @Override 17 | public void print(String tag, String content) { 18 | Log.d(tag, content); 19 | } 20 | }; 21 | 22 | private static Glin glin; 23 | 24 | public static Glin get() { 25 | if (glin == null) { 26 | String cachePath = Environment.getExternalStorageDirectory() + "/cache"; 27 | 28 | LogChanNode beforeLog = new LogChanNode(true, printer); 29 | LogChanNode afterLog = new LogChanNode(true, printer); 30 | 31 | GlobalChanNode before = new GlobalChanNode(beforeLog); 32 | GlobalChanNode after = new GlobalChanNode(afterLog); 33 | 34 | glin = new Glin.Builder() 35 | .baseUrl("http://103.50.253.220:8891") 36 | .client(new OkClient()) 37 | .globalChanNode(before, after) 38 | .parserFactory(new Parsers()) 39 | .cacheProvider(new DefaultCacheProvider(cachePath, 1024*1024L)) 40 | .timeout(5000L) 41 | .build(); 42 | } 43 | 44 | return glin; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /glinsample/src/main/java/org/loader/glinsample/utils/Parsers.java: -------------------------------------------------------------------------------- 1 | package org.loader.glinsample.utils; 2 | 3 | import com.alibaba.fastjson.JSON; 4 | import com.alibaba.fastjson.JSONObject; 5 | 6 | import org.loader.glin.RawResult; 7 | import org.loader.glin.Result; 8 | import org.loader.glin.factory.ParserFactory; 9 | import org.loader.glin.parser.Parser; 10 | 11 | public class Parsers implements ParserFactory { 12 | 13 | @Override 14 | public Parser getParser() { 15 | return new Parser() { 16 | @Override 17 | public Result parse(Class klass, RawResult netResult) { 18 | Result result = new Result<>(); 19 | try { 20 | JSONObject baseObject = JSON.parseObject(netResult.getResponse()); 21 | if (baseObject.getBoolean("ok")) { 22 | if (baseObject.containsKey("data")) { 23 | T t = baseObject.getObject("data", klass); 24 | result.setResult(t); 25 | result.ok(true); 26 | return result; 27 | } 28 | } 29 | 30 | throw new Exception(); 31 | } catch (Exception e) { 32 | e.printStackTrace(); 33 | result.ok(false); 34 | result.setMessage("error"); 35 | } 36 | return result; 37 | } 38 | }; 39 | } 40 | 41 | @Override 42 | public Parser getListParser() { 43 | // empty 44 | return null; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /glinsample/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 2 | 12 | 13 | 18 | 19 | -------------------------------------------------------------------------------- /glinsample/src/main/res/mipmap-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qibin0506/Glin/42f8eff35cb25373efb9436d27decc5f5209e2ad/glinsample/src/main/res/mipmap-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /glinsample/src/main/res/mipmap-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qibin0506/Glin/42f8eff35cb25373efb9436d27decc5f5209e2ad/glinsample/src/main/res/mipmap-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /glinsample/src/main/res/mipmap-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qibin0506/Glin/42f8eff35cb25373efb9436d27decc5f5209e2ad/glinsample/src/main/res/mipmap-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /glinsample/src/main/res/mipmap-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qibin0506/Glin/42f8eff35cb25373efb9436d27decc5f5209e2ad/glinsample/src/main/res/mipmap-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /glinsample/src/main/res/mipmap-xxxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qibin0506/Glin/42f8eff35cb25373efb9436d27decc5f5209e2ad/glinsample/src/main/res/mipmap-xxxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /glinsample/src/main/res/values-w820dp/dimens.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 64dp 6 | 7 | -------------------------------------------------------------------------------- /glinsample/src/main/res/values/colors.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | #3F51B5 4 | #303F9F 5 | #FF4081 6 | 7 | -------------------------------------------------------------------------------- /glinsample/src/main/res/values/dimens.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 16dp 4 | 16dp 5 | 6 | -------------------------------------------------------------------------------- /glinsample/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | GlinSample 3 | 4 | -------------------------------------------------------------------------------- /glinsample/src/main/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /glinsample/src/test/java/org/loader/glinsample/ExampleUnitTest.java: -------------------------------------------------------------------------------- 1 | package org.loader.glinsample; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.junit.Assert.*; 6 | 7 | /** 8 | * Example local unit test, which will execute on the development machine (host). 9 | * 10 | * @see Testing documentation 11 | */ 12 | public class ExampleUnitTest { 13 | @Test 14 | public void addition_isCorrect() throws Exception { 15 | assertEquals(4, 2 + 2); 16 | } 17 | } -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | ## Project-wide Gradle settings. 2 | # 3 | # For more details on how to configure your build environment visit 4 | # http://www.gradle.org/docs/current/userguide/build_environment.html 5 | # 6 | # Specifies the JVM arguments used for the daemon process. 7 | # The setting is particularly useful for tweaking memory settings. 8 | # Default value: -Xmx1024m -XX:MaxPermSize=256m 9 | # org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8 10 | # 11 | # When configured, Gradle will run in incubating parallel mode. 12 | # This option should only be used with decoupled projects. More details, visit 13 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects 14 | # org.gradle.parallel=true 15 | #Wed Sep 20 14:39:27 CST 2017 16 | #systemProp.http.proxyHost=127.0.0.1 17 | org.gradle.jvmargs=-Xmx1536m 18 | #systemProp.http.proxyPort=1080 19 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qibin0506/Glin/42f8eff35cb25373efb9436d27decc5f5209e2ad/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Mon Nov 13 10:09:22 CST 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-3.3-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 with 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 init 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 init 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 | :init 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 with 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 | -------------------------------------------------------------------------------- /okclient/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /okclient/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.library' 2 | 3 | android { 4 | compileSdkVersion 25 5 | buildToolsVersion "25.0.0" 6 | 7 | defaultConfig { 8 | minSdkVersion 9 9 | targetSdkVersion 25 10 | versionCode 8 11 | versionName "3.2" 12 | 13 | } 14 | buildTypes { 15 | release { 16 | minifyEnabled false 17 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 18 | } 19 | } 20 | 21 | lintOptions { 22 | abortOnError false 23 | } 24 | } 25 | 26 | dependencies { 27 | compile fileTree(dir: 'libs', include: ['*.jar']) 28 | 29 | compile 'com.squareup.okhttp3:okhttp:3.4.1' 30 | compile 'com.squareup.okio:okio:1.9.0' 31 | 32 | compile 'org.loader:glin:3.2' 33 | } -------------------------------------------------------------------------------- /okclient/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 D:\android-sdk\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 with 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 | -------------------------------------------------------------------------------- /okclient/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 5 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /okclient/src/main/java/org/loader/okclient/OkClient.java: -------------------------------------------------------------------------------- 1 | package org.loader.okclient; 2 | 3 | import android.os.Handler; 4 | import android.os.Looper; 5 | 6 | import org.loader.glin.Callback; 7 | import org.loader.glin.Params; 8 | import org.loader.glin.RawResult; 9 | import org.loader.glin.Result; 10 | import org.loader.glin.cache.ICacheProvider; 11 | import org.loader.glin.client.IClient; 12 | import org.loader.glin.factory.ParserFactory; 13 | import org.loader.glin.helper.ClientHelper; 14 | import org.loader.glin.interceptor.IResultInterceptor; 15 | 16 | import java.io.File; 17 | import java.io.IOException; 18 | import java.security.SecureRandom; 19 | import java.security.cert.CertificateException; 20 | import java.security.cert.X509Certificate; 21 | import java.util.LinkedHashMap; 22 | import java.util.Map; 23 | import java.util.concurrent.TimeUnit; 24 | 25 | import javax.net.ssl.HostnameVerifier; 26 | import javax.net.ssl.SSLContext; 27 | import javax.net.ssl.SSLSession; 28 | import javax.net.ssl.TrustManager; 29 | import javax.net.ssl.X509TrustManager; 30 | 31 | import okhttp3.Call; 32 | import okhttp3.Headers; 33 | import okhttp3.MediaType; 34 | import okhttp3.MultipartBody; 35 | import okhttp3.OkHttpClient; 36 | import okhttp3.Request; 37 | import okhttp3.RequestBody; 38 | import okhttp3.Response; 39 | 40 | /** 41 | * Created by qibin on 2016/7/13. 42 | */ 43 | 44 | public class OkClient implements IClient { 45 | public static final String MSG_ERROR_HTTP = "msg_error_http:okhttp"; 46 | private static final long DEFAULT_TIME_OUT = 5000; 47 | 48 | private OkHttpClient mClient; 49 | private Handler mHandler; 50 | 51 | private ClientHelper mClientHelper; 52 | 53 | private long mTimeOut = DEFAULT_TIME_OUT; 54 | 55 | public OkClient() { 56 | mClient = buildClient(); 57 | mClientHelper = new ClientHelper(); 58 | } 59 | 60 | private OkHttpClient buildClient() { 61 | OkHttpClient.Builder builder = new OkHttpClient.Builder(); 62 | try { 63 | SSLContext sc = SSLContext.getInstance("SSL"); 64 | sc.init(null, new TrustManager[]{new X509TrustManager() { 65 | @Override 66 | public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { 67 | } 68 | 69 | @Override 70 | public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { 71 | } 72 | 73 | @Override 74 | public X509Certificate[] getAcceptedIssuers() { 75 | X509Certificate[] x509Certificates = new X509Certificate[0]; 76 | return x509Certificates; 77 | } 78 | }}, new SecureRandom()); 79 | 80 | builder.sslSocketFactory(sc.getSocketFactory()); 81 | builder.hostnameVerifier(new HostnameVerifier() { 82 | @Override 83 | public boolean verify(String hostname, SSLSession session) { 84 | return true; 85 | } 86 | }); 87 | } catch (Exception e) { 88 | e.printStackTrace(); 89 | } 90 | 91 | return builder.build(); 92 | } 93 | 94 | @Override 95 | public void get(String url, final LinkedHashMap header, 96 | Object tag, boolean shouldCache, Callback callback) { 97 | final Request request = new Request.Builder().url(url).build(); 98 | call(request, header, null, callback, tag, shouldCache); 99 | } 100 | 101 | @Override 102 | public void post(String url, final LinkedHashMap header, 103 | Params params, Object tag, boolean shouldCache, Callback callback) { 104 | RequestBody builder = createRequestBody(params); 105 | Request request = new Request.Builder().url(url).post(builder).build(); 106 | call(request, header, params.encode(), callback, tag, shouldCache); 107 | } 108 | 109 | @Override 110 | public void post(String url, final LinkedHashMap header, 111 | String json, Object tag, boolean shouldCache, final Callback callback) { 112 | Request request = new Request.Builder().url(url).post(createJsonBody(json)).build(); 113 | call(request, header, json, callback, tag, shouldCache); 114 | } 115 | 116 | @Override 117 | public void put(String url, final LinkedHashMap header, 118 | Params params, Object tag, boolean shouldCache, Callback callback) { 119 | RequestBody builder = createRequestBody(params); 120 | Request request = new Request.Builder().url(url).put(builder).build(); 121 | call(request, header, params.encode(), callback, tag, shouldCache); 122 | } 123 | 124 | @Override 125 | public void put(String url, final LinkedHashMap header, 126 | String json, Object tag, boolean shouldCache, Callback callback) { 127 | Request request = new Request.Builder().url(url).put(createJsonBody(json)).build(); 128 | call(request, header, json, callback, tag, shouldCache); 129 | } 130 | 131 | @Override 132 | public void delete(String url, final LinkedHashMap header, 133 | Object tag, boolean shouldCache, Callback callback) { 134 | final Request request = new Request.Builder().url(url).delete().build(); 135 | call(request, header, null, callback, tag, shouldCache); 136 | } 137 | 138 | @SuppressWarnings("unchecked") 139 | private void call(Request request, final LinkedHashMap header, 140 | final String params, final Callback callback, final Object tag, 141 | final boolean shouldCache) { 142 | final String cacheKey = mClientHelper.getCacheKey(request.url().toString(), params); 143 | 144 | Result result = mClientHelper.useCache(shouldCache, cacheKey, callback); 145 | if (result != null) { 146 | callback.onResponse(result); 147 | callback.afterResponse(result, null); 148 | } 149 | 150 | LinkedHashMap map = (header != null && !header.isEmpty()) 151 | ? header : headers(); 152 | Request.Builder builder = request.newBuilder(); 153 | builder.tag(tag); 154 | 155 | if (map != null && !map.isEmpty()) { 156 | for (Map.Entry entry : map.entrySet()) { 157 | String value = entry.getValue(); 158 | if(value == null) { continue;} 159 | builder.addHeader(entry.getKey(), value); 160 | } 161 | } 162 | request = builder.build(); 163 | final Call call = cloneClient().newCall(request); 164 | call.enqueue(new okhttp3.Callback() { 165 | @Override 166 | public void onFailure(Call call, IOException e) { 167 | Result result = new Result<>(); 168 | result.ok(false); 169 | result.setCode(0); 170 | result.setObj(0); 171 | result.setMessage(MSG_ERROR_HTTP); 172 | 173 | callback(call, callback, result, new RawResult(0, e.getMessage(), "")); 174 | } 175 | 176 | @Override 177 | public void onResponse(final Call call, Response response) throws IOException { 178 | if (!response.isSuccessful()) { 179 | Result res = new Result<>(); 180 | res.ok(false); 181 | res.setCode(response.code()); 182 | res.setObj(response.code()); 183 | res.setMessage(MSG_ERROR_HTTP); 184 | 185 | callback(call, callback, res, new RawResult(response.code(), response.message(), "")); 186 | return; 187 | } 188 | 189 | String resp = ""; 190 | try { 191 | resp = response.body().string(); 192 | } catch (Exception e) { 193 | e.printStackTrace(); 194 | } 195 | 196 | RawResult rawResult = new RawResult(response.code(), response.message(), resp); 197 | Result res = mClientHelper.parseResponse(callback, rawResult); 198 | 199 | callback(call, callback, res, rawResult); 200 | 201 | if (mClientHelper.cache(shouldCache, cacheKey, res, rawResult)) { 202 | // empty 203 | } 204 | } 205 | }); 206 | } 207 | 208 | private void callback(final Call call, final Callback callback, 209 | final Result result, 210 | final RawResult rawResult) { 211 | if(Looper.myLooper() == Looper.getMainLooper()) { 212 | realCallback(call, callback, result, rawResult); 213 | }else { 214 | getHandler().post(new Runnable() { 215 | @Override 216 | public void run() { realCallback(call, callback, result, rawResult);} 217 | }); 218 | } 219 | } 220 | 221 | private void realCallback(Call call, Callback callback, Result result, 222 | RawResult rawResult) { 223 | if (!call.isCanceled()) { 224 | if (!mClientHelper.shouldInterceptResult(result)) { 225 | callback.onResponse(result); 226 | } 227 | } 228 | 229 | callback.afterResponse(result, rawResult); 230 | } 231 | 232 | private RequestBody createRequestBody(Params params) { 233 | if (params.isEmpty()) { 234 | return MultipartBody.create(null, ""); 235 | } 236 | 237 | MultipartBody.Builder builder = new MultipartBody.Builder() 238 | .setType(MultipartBody.FORM); 239 | 240 | LinkedHashMap map = params.get(); 241 | for(Map.Entry entry : map.entrySet()) { 242 | String value = entry.getValue(); 243 | if(value == null) { continue;} 244 | 245 | builder.addPart(Headers.of("Content-Disposition", 246 | "form-data; name=\""+ entry.getKey() +"\""), 247 | RequestBody.create(null, value)); 248 | } 249 | 250 | LinkedHashMap files = params.files(); 251 | for(Map.Entry entry : files.entrySet()) { 252 | File file = entry.getValue(); 253 | if(file == null) { continue;} 254 | 255 | builder.addPart(Headers.of("Content-Disposition", 256 | "form-data; name=\"" + entry.getKey() + "\";filename=\""+ file.getName() +"\""), 257 | RequestBody.create(MediaType.parse("application/octet-stream"), file)); 258 | } 259 | 260 | return builder.build(); 261 | } 262 | 263 | private RequestBody createJsonBody(String json) { 264 | return RequestBody.create(MediaType.parse("application/json;charset=utf-8"), json); 265 | } 266 | 267 | @Override 268 | public void cancel(Object tag) { 269 | for (Call call : mClient.dispatcher().queuedCalls()) { 270 | if (tag.equals(call.request().tag())) { 271 | call.cancel(); 272 | } 273 | } 274 | 275 | for (Call call : mClient.dispatcher().runningCalls()) { 276 | if (tag.equals(call.request().tag())) { 277 | call.cancel(); 278 | } 279 | } 280 | } 281 | 282 | @Override 283 | public void parserFactory(ParserFactory factory) { 284 | mClientHelper.parserFactory(factory); 285 | } 286 | 287 | @Override 288 | public void cacheProvider(ICacheProvider provider) { 289 | mClientHelper.cacheProvider(provider); 290 | } 291 | 292 | @Override 293 | public void resultInterceptor(IResultInterceptor interceptor) { 294 | mClientHelper.resultInterceptor(interceptor); 295 | } 296 | 297 | @Override 298 | public void timeout(long ms) { 299 | mTimeOut = ms; 300 | } 301 | 302 | @Override 303 | public LinkedHashMap headers() { 304 | return null; 305 | } 306 | 307 | private Handler getHandler() { 308 | if(mHandler == null) { mHandler = new Handler(Looper.getMainLooper());} 309 | return mHandler; 310 | } 311 | 312 | private OkHttpClient cloneClient() { 313 | return mClient.newBuilder() 314 | .connectTimeout(mTimeOut, TimeUnit.MILLISECONDS) 315 | // .readTimeout(mTimeOut, TimeUnit.MILLISECONDS) 316 | // .writeTimeout(mTimeOut, TimeUnit.MILLISECONDS) 317 | .build(); 318 | } 319 | } 320 | -------------------------------------------------------------------------------- /okclient/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | OkClient 3 | 4 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | include ':glin',':okclient', ':glinsample' --------------------------------------------------------------------------------