├── .gitignore
├── LICENSE.txt
├── README.md
├── app
├── .gitignore
├── build.gradle
├── proguard-rules.pro
└── src
│ ├── androidTest
│ └── java
│ │ └── net
│ │ └── lateralview
│ │ └── simplerestclienthandler
│ │ └── ApplicationTest.java
│ └── main
│ ├── AndroidManifest.xml
│ └── java
│ └── net
│ └── lateralview
│ └── simplerestclienthandler
│ ├── RestClientManager.java
│ ├── base
│ ├── BaseArrayJsonRequest.java
│ ├── BaseJsonRequest.java
│ ├── BaseMultipartJsonArrayRequest.java
│ ├── BaseMultipartJsonRequest.java
│ ├── HttpErrorException.java
│ ├── ICallbackTypes.java
│ ├── MultipartRequest.java
│ ├── RequestCallbacks.java
│ ├── RequestFutureHandler.java
│ └── RequestHandler.java
│ ├── gson
│ ├── AnnotationExclusionStrategy.java
│ └── Exclude.java
│ ├── helper
│ ├── BundleJSONConverter.java
│ ├── FileManager.java
│ ├── MultipartEntity.java
│ ├── ParametersJSONObject.java
│ ├── ReflectionHelper.java
│ └── VolleyHelper.java
│ └── log
│ └── RequestLoggingHelper.java
├── build.gradle
├── gradle.properties
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
└── settings.gradle
/.gitignore:
--------------------------------------------------------------------------------
1 | # Built application files
2 | *.apk
3 | *.ap_
4 |
5 | # Files for the Dalvik VM
6 | *.dex
7 |
8 | # Java class files
9 | *.class
10 |
11 | # Generated files
12 | bin/
13 | gen/
14 |
15 | # Gradle files
16 | .gradle/
17 | build/
18 | /*/build/
19 |
20 | # Local configuration file (sdk path, etc)
21 | local.properties
22 |
23 | # Proguard folder generated by Eclipse
24 | proguard/
25 |
26 | # Log Files
27 | *.log
28 |
29 | # OSX files
30 | .DS_Store
31 |
32 | # Android Studio
33 | *.iml
34 | .idea
35 |
36 | # Windows files
37 | Thumbs.db
--------------------------------------------------------------------------------
/LICENSE.txt:
--------------------------------------------------------------------------------
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 | SimpleRESTClientHandler
2 | ===========
3 | [](https://android-arsenal.com/details/1/3209)
4 |
5 | SimpleRESTClientHandler is an Open Source Android library that allows developers to easily make request to a REST server usign VOLLEY and GSON.
6 | Using GSON as dependency SimpleRESTClientHandler parse the responses automatically to the Model of your interest.
7 |
8 | Setup
9 | -----
10 |
11 | ```groovy
12 | dependencies {
13 | compile 'julianfalcionelli:SimpleRESTClientHandler:1.2'
14 | }
15 | ```
16 |
17 |
18 | ### Initialize the service
19 |
20 | Initialize the RestClientManager in your Application class in the #onCreate() method.
21 |
22 | ```java
23 | RestClientManager.initialize(getApplicationContext()).enableDebugLog(true);
24 | ```
25 |
26 | The `enableDebugLog` method allows you too see the request information in the console.
27 |
28 | Remember to have the Internet Permission in the manifest
29 |
30 | ```xml
31 |
32 | ```
33 |
34 | Simple Example
35 | -----
36 |
37 | ### JSON Request
38 | To make a request that returns a JSON object you need to call the `makeJsonRequest` after obtaining RestClientManager instance.
39 | Required parameters are the request method (POST, GET, PUT, DELETE), the URL of the server endpoint, and RequestHanlder object.
40 |
41 | You can also pass new headers to the request in a `Map ` as an Authorization header.
42 | We also recommend spending a tag request to cancel the specific request for some reasons.
43 |
44 | ```java
45 | RestClientManager.getInstance().makeJsonRequest(Request.Method.POST, url,
46 | new RequestHandler<>(new RequestCallbacks() {
47 | @Override
48 | public void onRequestSuccess(ResponseModel response) {
49 |
50 | }
51 |
52 | @Override
53 | public void onRequestError(ErrorModel error) {
54 |
55 | }
56 | }, parameters));
57 | ```
58 |
59 | To create an instance of `Request Handler` you need to spend a instance of `Request Callbacks`. This class has two types, the model answer at the first set and the second type defines the model error. If you do not want to analyze the response or error just pass a `Object` in each of the types.
60 |
61 | Remember that the classes passed to the `Request Callbacks` object must be use GSON, where each of the values assigned to GSON must correspond to the parameters sent by the server.
62 |
63 | The `Request Callbacks` object has four methods:
64 |
65 | - `onRequestStart`: This method is always executed before the request is made.
66 | - `onRequestSuccess`: It is obligatory to overwrite. This method will be execute if the request is successfull (HTTP Status = 200)
67 | - `onRequestError`: It is obligatory to overwrite. This method will be execute if the request failed (HTTP Status != 200)
68 | - `onRequestFinish`: This method is always executed after the request is made, independently if the request failed or not.
69 |
70 | You can pass to the `Request Handler` object the parameters. The parameters can be a bundle or any object that use GSON, and automatically the library will parse the object to a valid json.
71 |
72 | ### JSON Array Request
73 | To make a request that returns a JSON Array you need to call the `makeJsonArrayRequest`.
74 |
75 | ```java
76 | RestClientManager.getInstance().makeJsonArrayRequest(Request.Method.GET, url,
77 | new RequestHandler<>(new RequestCallbacks, ErrorModel>() {
78 | @Override
79 | public void onRequestSuccess(List response) {
80 |
81 | }
82 |
83 | @Override
84 | public void onRequestError(ErrorModel error) {
85 |
86 | }
87 | }, parameters));
88 | ```
89 |
90 | ### Multipart Request
91 | To make a mutipart request call the `makeMultipartJsonRequest` method if the response is a JSONObject or call the `makeMultipartJsonArrayRequest` method if the response is a JSON Array.
92 |
93 | To pass files to the RequestHandler call the `setFileParameters` method passing a `Map` where the key represent the file identifier and the value the file path in the device.
94 |
95 | - makeMultipartJsonRequest
96 |
97 | ```java
98 | RestClientManager.getInstance().makeMultipartJsonRequest(Request.Method.POST, url,
99 | new RequestHandler<>(new RequestCallbacks() {
100 | @Override
101 | public void onRequestSuccess(ResponseModel response) {
102 |
103 | }
104 |
105 | @Override
106 | public void onRequestError(ErrorModel error) {
107 |
108 | }
109 | }, parameters).setFileParameters(filesMap));
110 | ```
111 |
112 | - makeMultipartJsonArrayRequest
113 |
114 | ```java
115 | RestClientManager.getInstance().makeMultipartJsonArrayRequest(Request.Method.GET, url,
116 | new RequestHandler<>(new RequestCallbacks, ErrorModel>() {
117 | @Override
118 | public void onRequestSuccess(List response) {
119 |
120 | }
121 |
122 | @Override
123 | public void onRequestError(ErrorModel error) {
124 |
125 | }
126 | }, parameters).setFileParameters(filesMap));
127 | ```
128 |
129 | News
130 | -----
131 | - Synchronous Calls via Future Request
132 | - Now Support Multipart Requests!
133 | - Gson extension to exclude parameters in the serialization process (`@Exclude`)
134 |
135 | License
136 | -----
137 | Copyright 2016 Julián Falcionelli
138 |
139 | Licensed under the Apache License, Version 2.0 (the "License");
140 | you may not use this file except in compliance with the License.
141 | You may obtain a copy of the License at
142 |
143 | http://www.apache.org/licenses/LICENSE-2.0
144 |
145 | Unless required by applicable law or agreed to in writing, software
146 | distributed under the License is distributed on an "AS IS" BASIS,
147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
148 | See the License for the specific language governing permissions and
149 | limitations under the License.
150 |
--------------------------------------------------------------------------------
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.library'
2 |
3 | def RELEASE_VERSION = "1.2"
4 |
5 | android {
6 | compileSdkVersion 23
7 | buildToolsVersion "23.0.2"
8 |
9 | defaultConfig {
10 | minSdkVersion 16
11 | targetSdkVersion 23
12 | versionCode 2
13 | versionName RELEASE_VERSION
14 | }
15 | buildTypes {
16 | release {
17 | minifyEnabled false
18 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
19 | }
20 | }
21 | }
22 |
23 | dependencies {
24 | compile fileTree(dir: 'libs', include: ['*.jar'])
25 | compile 'com.android.support:appcompat-v7:23.1.1'
26 | compile 'com.android.volley:volley:1.0.0'
27 | compile 'com.google.code.gson:gson:2.4'
28 | compile 'org.apache.tika:tika-core:1.4'
29 | }
30 |
31 | ext {
32 | PUBLISH_GROUP_ID = 'julianfalcionelli'
33 | PUBLISH_ARTIFACT_ID = 'SimpleRESTClientHandler'
34 | PUBLISH_VERSION = RELEASE_VERSION
35 | }
36 |
37 | apply from: 'https://raw.githubusercontent.com/blundell/release-android-library/master/android-release-aar.gradle'
--------------------------------------------------------------------------------
/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in C:\Users\Julián\AppData\Local\Android\sdk1/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 |
--------------------------------------------------------------------------------
/app/src/androidTest/java/net/lateralview/simplerestclienthandler/ApplicationTest.java:
--------------------------------------------------------------------------------
1 | package net.lateralview.simplerestclienthandler;
2 |
3 | import android.app.Application;
4 | import android.test.ApplicationTestCase;
5 |
6 | /**
7 | * Testing Fundamentals
8 | */
9 | public class ApplicationTest extends ApplicationTestCase
10 | {
11 | public ApplicationTest()
12 | {
13 | super(Application.class);
14 | }
15 | }
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/app/src/main/java/net/lateralview/simplerestclienthandler/RestClientManager.java:
--------------------------------------------------------------------------------
1 | package net.lateralview.simplerestclienthandler;
2 |
3 | import android.content.Context;
4 |
5 | import com.android.volley.DefaultRetryPolicy;
6 | import com.android.volley.Request;
7 | import com.android.volley.RequestQueue;
8 | import com.android.volley.ResponseDelivery;
9 | import com.android.volley.toolbox.Volley;
10 |
11 | import net.lateralview.simplerestclienthandler.base.BaseArrayJsonRequest;
12 | import net.lateralview.simplerestclienthandler.base.BaseJsonRequest;
13 | import net.lateralview.simplerestclienthandler.base.BaseMultipartJsonArrayRequest;
14 | import net.lateralview.simplerestclienthandler.base.BaseMultipartJsonRequest;
15 | import net.lateralview.simplerestclienthandler.base.RequestFutureHandler;
16 | import net.lateralview.simplerestclienthandler.base.RequestHandler;
17 | import net.lateralview.simplerestclienthandler.helper.VolleyHelper;
18 |
19 | import java.util.Map;
20 |
21 | public class RestClientManager
22 | {
23 | public static final String TAG = RestClientManager.class.getSimpleName();
24 | public static boolean sDebugLog = false;
25 | private static RestClientManager sInstance;
26 | private final RequestQueue mRequestQueue;
27 | private final Context mContext;
28 |
29 | private RestClientManager(Context context)
30 | {
31 | mContext = context;
32 | mRequestQueue = Volley.newRequestQueue(context);
33 | }
34 |
35 | /**
36 | * Method used to create a queue that uses a custom response delivery.
37 | *
38 | * @param context the context the manager will use to create de queue (Use application context in the application initialization)
39 | * @param responseDelivery this can be used to execute calls in a worker or a main thread. Be careful with it's usage since it can generate a blocking thread and this can lead to a poor performance of your app.
40 | * Consider using a SingleThreadExecutor to perform Async tests in your unit testing clases.
41 | *
42 | * Example: new ExecutorDelivery(Executors.newSingleThreadExecutor())
43 | */
44 | private RestClientManager(Context context, ResponseDelivery responseDelivery)
45 | {
46 | mContext = context;
47 | mRequestQueue = VolleyHelper.newRequestQueue(mContext, responseDelivery);
48 | }
49 |
50 | public static RestClientManager getInstance()
51 | {
52 | if (sInstance == null)
53 | {
54 | throw new UnsupportedOperationException("You must call RestClientManager.Initialize before using RestClient classes");
55 | }
56 | return sInstance;
57 | }
58 |
59 | public static RestClientManager initialize(Context context)
60 | {
61 | sInstance = new RestClientManager(context);
62 |
63 | return sInstance;
64 | }
65 |
66 | public static RestClientManager initialize(Context context, ResponseDelivery responseDelivery)
67 | {
68 | sInstance = new RestClientManager(context, responseDelivery);
69 |
70 | return sInstance;
71 | }
72 |
73 | public RestClientManager enableDebugLog(boolean enable)
74 | {
75 | sDebugLog = enable;
76 |
77 | return getInstance();
78 | }
79 |
80 | private void addToRequestQueue(Request req, String tag)
81 | {
82 | mRequestQueue.add(normalizeRequest(req, tag));
83 | }
84 |
85 | private Request normalizeRequest(Request req, String tag)
86 | {
87 | //to avoid time out
88 | req.setRetryPolicy(new DefaultRetryPolicy(
89 | 50000,
90 | DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
91 | DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
92 |
93 | req.setTag(tag != null ? tag : TAG);
94 |
95 | return req;
96 | }
97 |
98 | public void cancelPendingRequests(Object tag)
99 | {
100 | mRequestQueue.cancelAll(tag);
101 | }
102 |
103 | public Context getContext()
104 | {
105 | return mContext;
106 | }
107 |
108 | /*
109 | For request that return JSONObject
110 | */
111 | public void makeJsonRequest(int method, String url, RequestHandler requestHandler)
112 | {
113 | makeJsonRequest(method, url, requestHandler, null, null);
114 | }
115 |
116 | public void makeJsonRequest(int method, String url, RequestHandler requestHandler, String tag)
117 | {
118 | makeJsonRequest(method, url, requestHandler, null, tag);
119 | }
120 |
121 | public void makeJsonRequest(int method, String url, RequestHandler requestHandler, Map headers)
122 | {
123 | makeJsonRequest(method, url, requestHandler, headers, null);
124 | }
125 |
126 | public void makeJsonRequest(int method, String url, RequestHandler requestHandler, Map headers, String tag)
127 | {
128 | addToRequestQueue(new BaseJsonRequest(method, url, requestHandler.getParameters(), requestHandler.getResponseSuccessListener(), requestHandler.getResponseErrorListener(), headers), tag);
129 | }
130 |
131 | /*
132 | For request that return JSONArray
133 | */
134 | public void makeJsonArrayRequest(int method, String url, RequestHandler requestHandler)
135 | {
136 | makeJsonArrayRequest(method, url, requestHandler, null, null);
137 | }
138 |
139 | public void makeJsonArrayRequest(int method, String url, RequestHandler requestHandler, String tag)
140 | {
141 | makeJsonArrayRequest(method, url, requestHandler, null, tag);
142 | }
143 |
144 | public void makeJsonArrayRequest(int method, String url, RequestHandler requestHandler, Map headers)
145 | {
146 | makeJsonArrayRequest(method, url, requestHandler, headers, null);
147 | }
148 |
149 | public void makeJsonArrayRequest(int method, String url, RequestHandler requestHandler, Map headers, String tag)
150 | {
151 | addToRequestQueue(new BaseArrayJsonRequest(method, url, requestHandler.getParameters(), requestHandler.getArrayResponseSuccessListener(), requestHandler.getResponseErrorListener(), headers), tag);
152 | }
153 |
154 | /*
155 | For multipart request that return JSONObject
156 | */
157 | public void makeMultipartJsonRequest(int method, String url, RequestHandler requestHandler)
158 | {
159 | makeMultipartJsonRequest(method, url, requestHandler, null, null);
160 | }
161 |
162 | public void makeMultipartJsonRequest(int method, String url, RequestHandler requestHandler, String tag)
163 | {
164 | makeMultipartJsonRequest(method, url, requestHandler, null, tag);
165 | }
166 |
167 | public void makeMultipartJsonRequest(int method, String url, RequestHandler requestHandler, Map headers)
168 | {
169 | makeMultipartJsonRequest(method, url, requestHandler, headers, null);
170 | }
171 |
172 | public void makeMultipartJsonRequest(int method, String url, RequestHandler requestHandler, Map headers, String tag)
173 | {
174 | addToRequestQueue(new BaseMultipartJsonRequest(method, url, requestHandler.getParameters(), requestHandler.getFileParameters(), requestHandler.getResponseSuccessListener(), requestHandler.getResponseErrorListener(), headers), tag);
175 | }
176 |
177 | /*
178 | For multipart request that return JSONArray
179 | */
180 | public void makeMultipartJsonArrayRequest(int method, String url, RequestHandler requestHandler)
181 | {
182 | makeMultipartJsonArrayRequest(method, url, requestHandler, null, null);
183 | }
184 |
185 | public void makeMultipartJsonArrayRequest(int method, String url, RequestHandler requestHandler, String tag)
186 | {
187 | makeMultipartJsonArrayRequest(method, url, requestHandler, null, tag);
188 | }
189 |
190 | public void makeMultipartJsonArrayRequest(int method, String url, RequestHandler requestHandler, Map headers)
191 | {
192 | makeMultipartJsonArrayRequest(method, url, requestHandler, headers, null);
193 | }
194 |
195 | public void makeMultipartJsonArrayRequest(int method, String url, RequestHandler requestHandler, Map headers, String tag)
196 | {
197 | addToRequestQueue(new BaseMultipartJsonArrayRequest(method, url, requestHandler.getParameters(), requestHandler.getFileParameters(), requestHandler.getArrayResponseSuccessListener(), requestHandler.getResponseErrorListener(), headers), tag);
198 | }
199 |
200 |
201 | //------- Future Request ------//
202 |
203 | /*
204 | For request that return JSONObject
205 | */
206 | public Object makeJsonRequest(int method, String url, RequestFutureHandler requestHandler)
207 | {
208 | return makeJsonRequest(method, url, requestHandler, null, null);
209 | }
210 |
211 | public Object makeJsonRequest(int method, String url, RequestFutureHandler requestHandler, String tag)
212 | {
213 | return makeJsonRequest(method, url, requestHandler, null, tag);
214 | }
215 |
216 | public Object makeJsonRequest(int method, String url, RequestFutureHandler requestHandler, Map headers)
217 | {
218 | return makeJsonRequest(method, url, requestHandler, headers, null);
219 | }
220 |
221 | public Object makeJsonRequest(int method, String url, RequestFutureHandler requestHandler, Map headers, String tag)
222 | {
223 | addToRequestQueue(new BaseJsonRequest(method, url, requestHandler.getParameters(), requestHandler.getRequestFuture(), requestHandler.getRequestFuture(), headers), tag);
224 | return requestHandler.call();
225 | }
226 |
227 | /*
228 | For request that return JSONArray
229 | */
230 | public Object makeJsonArrayRequest(int method, String url, RequestFutureHandler requestHandler)
231 | {
232 | return makeJsonArrayRequest(method, url, requestHandler, null, null);
233 | }
234 |
235 | public Object makeJsonArrayRequest(int method, String url, RequestFutureHandler requestHandler, String tag)
236 | {
237 | return makeJsonArrayRequest(method, url, requestHandler, null, tag);
238 | }
239 |
240 | public Object makeJsonArrayRequest(int method, String url, RequestFutureHandler requestHandler, Map headers)
241 | {
242 | return makeJsonArrayRequest(method, url, requestHandler, headers, null);
243 | }
244 |
245 | public Object makeJsonArrayRequest(int method, String url, RequestFutureHandler requestHandler, Map headers, String tag)
246 | {
247 | addToRequestQueue(new BaseArrayJsonRequest(method, url, requestHandler.getParameters(), requestHandler.getRequestFuture(), requestHandler.getRequestFuture(), headers), tag);
248 | return requestHandler.call();
249 | }
250 |
251 | /*
252 | For multipart request that return JSONObject
253 | */
254 | public Object makeMultipartJsonRequest(int method, String url, RequestFutureHandler requestHandler)
255 | {
256 | return makeMultipartJsonRequest(method, url, requestHandler, null, null);
257 | }
258 |
259 | public Object makeMultipartJsonRequest(int method, String url, RequestFutureHandler requestHandler, String tag)
260 | {
261 | return makeMultipartJsonRequest(method, url, requestHandler, null, tag);
262 | }
263 |
264 | public Object makeMultipartJsonRequest(int method, String url, RequestFutureHandler requestHandler, Map headers)
265 | {
266 | return makeMultipartJsonRequest(method, url, requestHandler, headers, null);
267 | }
268 |
269 | public Object makeMultipartJsonRequest(int method, String url, RequestFutureHandler requestHandler, Map headers, String tag)
270 | {
271 | addToRequestQueue(new BaseMultipartJsonRequest(method, url, requestHandler.getParameters(), requestHandler.getFileParameters(), requestHandler.getRequestFuture(), requestHandler.getRequestFuture(), headers), tag);
272 | return requestHandler.call();
273 | }
274 |
275 | /*
276 | For multipart request that return JSONArray
277 | */
278 | public Object makeMultipartJsonArrayRequest(int method, String url, RequestFutureHandler requestHandler)
279 | {
280 | return makeMultipartJsonArrayRequest(method, url, requestHandler, null, null);
281 | }
282 |
283 | public Object makeMultipartJsonArrayRequest(int method, String url, RequestFutureHandler requestHandler, String tag)
284 | {
285 | return makeMultipartJsonArrayRequest(method, url, requestHandler, null, tag);
286 | }
287 |
288 | public Object makeMultipartJsonArrayRequest(int method, String url, RequestFutureHandler requestHandler, Map headers)
289 | {
290 | return makeMultipartJsonArrayRequest(method, url, requestHandler, headers, null);
291 | }
292 |
293 | public Object makeMultipartJsonArrayRequest(int method, String url, RequestFutureHandler requestHandler, Map headers, String tag)
294 | {
295 | addToRequestQueue(new BaseMultipartJsonArrayRequest(method, url, requestHandler.getParameters(), requestHandler.getFileParameters(), requestHandler.getRequestFuture(), requestHandler.getRequestFuture(), headers), tag);
296 | return requestHandler.call();
297 | }
298 | }
299 |
--------------------------------------------------------------------------------
/app/src/main/java/net/lateralview/simplerestclienthandler/base/BaseArrayJsonRequest.java:
--------------------------------------------------------------------------------
1 | package net.lateralview.simplerestclienthandler.base;
2 |
3 | import android.util.Log;
4 |
5 | import com.android.volley.AuthFailureError;
6 | import com.android.volley.NetworkResponse;
7 | import com.android.volley.ParseError;
8 | import com.android.volley.Response;
9 | import com.android.volley.VolleyError;
10 | import com.android.volley.toolbox.HttpHeaderParser;
11 | import com.android.volley.toolbox.JsonRequest;
12 |
13 | import net.lateralview.simplerestclienthandler.RestClientManager;
14 | import net.lateralview.simplerestclienthandler.log.RequestLoggingHelper;
15 |
16 | import org.json.JSONArray;
17 | import org.json.JSONException;
18 | import org.json.JSONObject;
19 |
20 | import java.io.UnsupportedEncodingException;
21 | import java.util.HashMap;
22 | import java.util.Map;
23 |
24 |
25 | public class BaseArrayJsonRequest extends JsonRequest
26 | {
27 | protected static String TAG = BaseArrayJsonRequest.class.getSimpleName();
28 |
29 | protected Map mHeaders = new HashMap<>();
30 |
31 | /**
32 | * @param method HTTP method type (POST, PUT, DELETE or GET)
33 | * @param url Full URL for the request
34 | * @param parameters JSONObject with required and optional parameters
35 | * @param listener Listener to handle request successful response
36 | * @param errorListener Listener to handle request error response
37 | */
38 | public BaseArrayJsonRequest(int method, String url, JSONObject parameters, Response.Listener listener, Response.ErrorListener errorListener, Map headers)
39 | {
40 | super(method, url, parameters != null ? parameters.toString() : null, listener, errorListener);
41 |
42 | if (headers != null)
43 | {
44 | mHeaders.putAll(headers);
45 | }
46 |
47 | if (RestClientManager.sDebugLog)
48 | {
49 | Log.i(TAG, RequestLoggingHelper.getRequestText(this));
50 | }
51 | }
52 |
53 | @Override
54 | public Map getHeaders() throws AuthFailureError
55 | {
56 | return mHeaders;
57 | }
58 |
59 | @Override
60 | protected Response parseNetworkResponse(NetworkResponse response)
61 | {
62 | try
63 | {
64 | String jsonString =
65 | new String(response.data, HttpHeaderParser.parseCharset(response.headers));
66 | return Response.success(new JSONArray(jsonString),
67 | HttpHeaderParser.parseCacheHeaders(response));
68 | } catch (UnsupportedEncodingException e)
69 | {
70 | return Response.error(new ParseError(e));
71 | } catch (JSONException je)
72 | {
73 | return Response.error(new ParseError(je));
74 | }
75 | }
76 |
77 | @Override
78 | public String getBodyContentType()
79 | {
80 | return "application/json";
81 | }
82 |
83 | @Override
84 | public void deliverError(VolleyError error)
85 | {
86 | if (RestClientManager.sDebugLog)
87 | {
88 | Log.i(TAG, RequestLoggingHelper.getRequestErrorText(this, error));
89 | }
90 |
91 | super.deliverError(error);
92 | }
93 |
94 | @Override
95 | protected void deliverResponse(JSONArray response)
96 | {
97 | if (RestClientManager.sDebugLog)
98 | {
99 | Log.i(TAG, RequestLoggingHelper.getRequestResponseText(this, response));
100 | }
101 | super.deliverResponse(response);
102 | }
103 | }
--------------------------------------------------------------------------------
/app/src/main/java/net/lateralview/simplerestclienthandler/base/BaseJsonRequest.java:
--------------------------------------------------------------------------------
1 | package net.lateralview.simplerestclienthandler.base;
2 |
3 | import android.util.Log;
4 |
5 | import com.android.volley.AuthFailureError;
6 | import com.android.volley.NetworkResponse;
7 | import com.android.volley.ParseError;
8 | import com.android.volley.Response;
9 | import com.android.volley.VolleyError;
10 | import com.android.volley.toolbox.HttpHeaderParser;
11 | import com.android.volley.toolbox.JsonObjectRequest;
12 |
13 | import net.lateralview.simplerestclienthandler.RestClientManager;
14 | import net.lateralview.simplerestclienthandler.log.RequestLoggingHelper;
15 |
16 | import org.json.JSONException;
17 | import org.json.JSONObject;
18 |
19 | import java.io.UnsupportedEncodingException;
20 | import java.util.HashMap;
21 | import java.util.Map;
22 |
23 |
24 | public class BaseJsonRequest extends JsonObjectRequest
25 | {
26 | protected static String TAG = BaseJsonRequest.class.getSimpleName();
27 |
28 | protected Map mHeaders = new HashMap<>();
29 |
30 | /**
31 | * @param method HTTP method type (POST, PUT, DELETE or GET)
32 | * @param url Full URL for the request
33 | * @param parameters JSONObject with required and optional parameters
34 | * @param listener Listener to handle request successful response
35 | * @param errorListener Listener to handle request error response
36 | */
37 | public BaseJsonRequest(int method, String url, JSONObject parameters, Response.Listener listener, Response.ErrorListener errorListener, Map headers)
38 | {
39 | super(method, url, parameters, listener, errorListener);
40 |
41 | if (headers != null)
42 | {
43 | mHeaders.putAll(headers);
44 | }
45 |
46 | if (RestClientManager.sDebugLog)
47 | {
48 | Log.i(TAG, RequestLoggingHelper.getRequestText(this));
49 | }
50 | }
51 |
52 | @Override
53 | public Map getHeaders() throws AuthFailureError
54 | {
55 | return mHeaders;
56 | }
57 |
58 | @Override
59 | protected Response parseNetworkResponse(NetworkResponse response)
60 | {
61 | try
62 | {
63 | String jsonString = new String(response.data,
64 | HttpHeaderParser.parseCharset(response.headers));
65 | //Allow null
66 | if (jsonString == null || jsonString.length() == 0)
67 | {
68 | return Response.success(null, HttpHeaderParser.parseCacheHeaders(response));
69 | }
70 | return Response.success(new JSONObject(jsonString),
71 | HttpHeaderParser.parseCacheHeaders(response));
72 | } catch (UnsupportedEncodingException e)
73 | {
74 | return Response.error(new ParseError(e));
75 | } catch (JSONException je)
76 | {
77 | return Response.error(new ParseError(je));
78 | }
79 | }
80 |
81 | @Override
82 | public String getBodyContentType()
83 | {
84 | return "application/json";
85 | }
86 |
87 | @Override
88 | public void deliverError(VolleyError error)
89 | {
90 | if (RestClientManager.sDebugLog)
91 | {
92 | Log.i(TAG, RequestLoggingHelper.getRequestErrorText(this, error));
93 | }
94 | super.deliverError(error);
95 | }
96 |
97 | @Override
98 | protected void deliverResponse(JSONObject response)
99 | {
100 | if (RestClientManager.sDebugLog)
101 | {
102 | Log.i(TAG, RequestLoggingHelper.getRequestResponseText(this, response));
103 | }
104 | super.deliverResponse(response);
105 | }
106 | }
--------------------------------------------------------------------------------
/app/src/main/java/net/lateralview/simplerestclienthandler/base/BaseMultipartJsonArrayRequest.java:
--------------------------------------------------------------------------------
1 | package net.lateralview.simplerestclienthandler.base;
2 |
3 | import com.android.volley.NetworkResponse;
4 | import com.android.volley.ParseError;
5 | import com.android.volley.Response;
6 | import com.android.volley.toolbox.HttpHeaderParser;
7 |
8 | import org.json.JSONArray;
9 | import org.json.JSONException;
10 | import org.json.JSONObject;
11 |
12 | import java.io.UnsupportedEncodingException;
13 | import java.util.Map;
14 |
15 | public class BaseMultipartJsonArrayRequest extends MultipartRequest
16 | {
17 | public BaseMultipartJsonArrayRequest(int method, String url, JSONObject parameters, Map fileParameters, Response.Listener listener, Response.ErrorListener errorListener, Map headers)
18 | {
19 | super(method, url, parameters, fileParameters, headers, listener, errorListener);
20 | }
21 |
22 | @Override
23 | protected Response parseNetworkResponse(NetworkResponse response)
24 | {
25 | try
26 | {
27 | String jsonString = new String(response.data,
28 | HttpHeaderParser.parseCharset(response.headers, PROTOCOL_CHARSET));
29 | return Response.success(new JSONArray(jsonString),
30 | HttpHeaderParser.parseCacheHeaders(response));
31 | } catch (UnsupportedEncodingException e)
32 | {
33 | return Response.error(new ParseError(e));
34 | } catch (JSONException je)
35 | {
36 | return Response.error(new ParseError(je));
37 | }
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/app/src/main/java/net/lateralview/simplerestclienthandler/base/BaseMultipartJsonRequest.java:
--------------------------------------------------------------------------------
1 | package net.lateralview.simplerestclienthandler.base;
2 |
3 | import com.android.volley.NetworkResponse;
4 | import com.android.volley.ParseError;
5 | import com.android.volley.Response;
6 | import com.android.volley.toolbox.HttpHeaderParser;
7 |
8 | import org.json.JSONException;
9 | import org.json.JSONObject;
10 |
11 | import java.io.UnsupportedEncodingException;
12 | import java.util.Map;
13 |
14 | public class BaseMultipartJsonRequest extends MultipartRequest
15 | {
16 | public BaseMultipartJsonRequest(int method, String url, JSONObject parameters, Map fileParameters, Response.Listener listener, Response.ErrorListener errorListener, Map headers)
17 | {
18 | super(method, url, parameters, fileParameters, headers, listener, errorListener);
19 | }
20 |
21 | @Override
22 | protected Response parseNetworkResponse(NetworkResponse response)
23 | {
24 | try
25 | {
26 | String jsonString = new String(response.data,
27 | HttpHeaderParser.parseCharset(response.headers, PROTOCOL_CHARSET));
28 | return Response.success(new JSONObject(jsonString),
29 | HttpHeaderParser.parseCacheHeaders(response));
30 | } catch (UnsupportedEncodingException e)
31 | {
32 | return Response.error(new ParseError(e));
33 | } catch (JSONException je)
34 | {
35 | return Response.error(new ParseError(je));
36 | }
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/app/src/main/java/net/lateralview/simplerestclienthandler/base/HttpErrorException.java:
--------------------------------------------------------------------------------
1 | package net.lateralview.simplerestclienthandler.base;
2 |
3 | /**
4 | * Created by julianfalcionelli on 1/16/17.
5 | */
6 | public class HttpErrorException extends RuntimeException
7 | {
8 | private Object error;
9 |
10 | public HttpErrorException(Object error)
11 | {
12 | this.error = error;
13 | }
14 |
15 | public Object getError()
16 | {
17 | return error;
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/app/src/main/java/net/lateralview/simplerestclienthandler/base/ICallbackTypes.java:
--------------------------------------------------------------------------------
1 | package net.lateralview.simplerestclienthandler.base;
2 |
3 | import java.lang.reflect.Type;
4 |
5 | /**
6 | * Created by julianfalcionelli on 11/11/16.
7 | */
8 | public interface ICallbackTypes
9 | {
10 | Type getResponseType();
11 | Type getErrorType();
12 | }
13 |
--------------------------------------------------------------------------------
/app/src/main/java/net/lateralview/simplerestclienthandler/base/MultipartRequest.java:
--------------------------------------------------------------------------------
1 | package net.lateralview.simplerestclienthandler.base;
2 |
3 | import android.util.Log;
4 |
5 | import com.android.volley.AuthFailureError;
6 | import com.android.volley.Request;
7 | import com.android.volley.Response;
8 | import com.android.volley.VolleyError;
9 |
10 | import net.lateralview.simplerestclienthandler.RestClientManager;
11 | import net.lateralview.simplerestclienthandler.helper.MultipartEntity;
12 | import net.lateralview.simplerestclienthandler.helper.ParametersJSONObject;
13 | import net.lateralview.simplerestclienthandler.log.RequestLoggingHelper;
14 |
15 | import org.json.JSONObject;
16 |
17 | import java.util.HashMap;
18 | import java.util.Map;
19 |
20 | public abstract class MultipartRequest extends Request
21 | {
22 | protected static final String TAG = MultipartRequest.class.getSimpleName();
23 | protected static final String PROTOCOL_CHARSET = "utf-8";
24 |
25 | private final Response.Listener mListener;
26 |
27 | protected Map mHeaders = new HashMap<>();
28 | protected String mMimeType;
29 | protected MultipartEntity mMultipartEntity;
30 |
31 | public MultipartRequest(int method, String url, JSONObject parameters, Map fileParameters, Map headers, Response.Listener listener, Response.ErrorListener errorListener)
32 | {
33 | super(method, url, errorListener);
34 |
35 | mListener = listener;
36 |
37 | if (headers != null)
38 | {
39 | mHeaders.putAll(headers);
40 | }
41 |
42 | mMultipartEntity = new MultipartEntity(fileParameters, ParametersJSONObject.toMap(parameters));
43 |
44 | mMimeType = "multipart/form-data;boundary=" + mMultipartEntity.getBoundary();
45 |
46 | if (RestClientManager.sDebugLog)
47 | {
48 | Log.i(TAG, RequestLoggingHelper.getMultipartRequestText(this, parameters));
49 | }
50 | }
51 |
52 | @Override
53 | public String getBodyContentType()
54 | {
55 | return mMimeType;
56 | }
57 |
58 | @Override
59 | public Map getHeaders() throws AuthFailureError
60 | {
61 | return mHeaders;
62 | }
63 |
64 | @Override
65 | public byte[] getBody() throws AuthFailureError
66 | {
67 | return mMultipartEntity.build();
68 | }
69 |
70 | @Override
71 | public void deliverError(VolleyError error)
72 | {
73 | if (RestClientManager.sDebugLog)
74 | {
75 | Log.i(TAG, RequestLoggingHelper.getRequestErrorText(this, error));
76 | }
77 |
78 | super.deliverError(error);
79 | }
80 |
81 | @Override
82 | protected void deliverResponse(T response)
83 | {
84 | if (RestClientManager.sDebugLog)
85 | {
86 | Log.i(TAG, RequestLoggingHelper.getRequestResponseText(this, response.toString()));
87 | }
88 |
89 | if (mListener != null)
90 | {
91 | mListener.onResponse(response);
92 | }
93 | }
94 | }
95 |
--------------------------------------------------------------------------------
/app/src/main/java/net/lateralview/simplerestclienthandler/base/RequestCallbacks.java:
--------------------------------------------------------------------------------
1 | package net.lateralview.simplerestclienthandler.base;
2 |
3 | public abstract class RequestCallbacks
4 | {
5 | protected void onRequestStart()
6 | {
7 | }
8 |
9 | protected abstract void onRequestSuccess(R response);
10 |
11 | protected abstract void onRequestError(E error);
12 |
13 | protected void onRequestFinish()
14 | {
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/app/src/main/java/net/lateralview/simplerestclienthandler/base/RequestFutureHandler.java:
--------------------------------------------------------------------------------
1 | package net.lateralview.simplerestclienthandler.base;
2 |
3 | import android.os.Bundle;
4 | import android.support.annotation.NonNull;
5 | import android.util.Log;
6 |
7 | import com.android.volley.ServerError;
8 | import com.android.volley.VolleyError;
9 | import com.android.volley.toolbox.RequestFuture;
10 | import com.google.gson.Gson;
11 | import com.google.gson.GsonBuilder;
12 |
13 | import net.lateralview.simplerestclienthandler.gson.AnnotationExclusionStrategy;
14 | import net.lateralview.simplerestclienthandler.helper.BundleJSONConverter;
15 |
16 | import org.json.JSONArray;
17 | import org.json.JSONObject;
18 |
19 | import java.lang.reflect.Type;
20 | import java.util.Map;
21 |
22 |
23 | public class RequestFutureHandler
24 | {
25 | protected static final String TAG = RequestFutureHandler.class.getSimpleName();
26 |
27 | public static Type sServerErrorClass;
28 |
29 | private Type mToClassType, mErrorClassType;
30 | private Object mObjectParameter;
31 | private Bundle mBundleParameters = new Bundle();
32 | private Map mFileParameters;
33 | private RequestFuture mCallbacks;
34 |
35 | public static void setServerErrorClass(Class serverErrorClass)
36 | {
37 | sServerErrorClass = serverErrorClass;
38 | }
39 |
40 | public RequestFutureHandler(Type responseClass, Type errorClass)
41 | {
42 | mToClassType = responseClass;
43 | mErrorClassType = errorClass;
44 |
45 | initializeRequestHandler();
46 | }
47 |
48 | public RequestFutureHandler(Type responseClass)
49 | {
50 | this(responseClass, sServerErrorClass);
51 | }
52 |
53 | public RequestFutureHandler(Type responseClass, Object parameters)
54 | {
55 | this(responseClass, sServerErrorClass, parameters);
56 | }
57 |
58 | public RequestFutureHandler(Type responseClass, Bundle parameters)
59 | {
60 | this(responseClass, sServerErrorClass, parameters);
61 | }
62 |
63 | public RequestFutureHandler(Type responseClass, Type errorClass, Object parameters)
64 | {
65 | this(responseClass, errorClass);
66 | mObjectParameter = parameters;
67 | }
68 |
69 | public RequestFutureHandler(Type responseClass, Type errorClass, @NonNull Bundle parameters)
70 | {
71 | this(responseClass, errorClass);
72 | mBundleParameters = parameters;
73 | }
74 |
75 | private void initializeRequestHandler()
76 | {
77 | mCallbacks = RequestFuture.newFuture();
78 | }
79 |
80 | public RequestFuture getRequestFuture()
81 | {
82 | return mCallbacks;
83 | }
84 |
85 | public JSONObject getParameters()
86 | {
87 | JSONObject jsonObject = null;
88 |
89 | try
90 | {
91 | if (mObjectParameter != null)
92 | {
93 | jsonObject = new JSONObject(new GsonBuilder().setExclusionStrategies(new AnnotationExclusionStrategy()).create().toJson(mObjectParameter));
94 | } else
95 | {
96 | jsonObject = BundleJSONConverter.convertToJSON(mBundleParameters);
97 | }
98 | } catch (Exception e)
99 | {
100 | if (e.getMessage() != null)
101 | {
102 | Log.e(TAG, e.getMessage());
103 | }
104 | }
105 |
106 | return jsonObject;
107 | }
108 |
109 | public Object call()
110 | {
111 | Object response;
112 |
113 | try
114 | {
115 | response = mCallbacks.get();
116 | } catch (Exception e)
117 | {
118 | ServerError serverError = null;
119 |
120 | if (e.getCause() instanceof ServerError)
121 | {
122 | serverError = ((ServerError) e.getCause());
123 | }
124 |
125 | throw new HttpErrorException(parseError(serverError));
126 | }
127 |
128 | return parseResponse(response);
129 | }
130 |
131 | private Object parseResponse(Object response)
132 | {
133 | if (response instanceof JSONArray)
134 | {
135 | return parseJSONArrayResponse((JSONArray) response);
136 | }
137 |
138 | return parseJSONObject((JSONObject) response);
139 | }
140 |
141 | private Object parseJSONObject(JSONObject response)
142 | {
143 | Object objectResponse = response;
144 |
145 | if (response != null && !mToClassType.toString().equals(JSONObject.class.toString()))
146 | {
147 | try
148 | {
149 | objectResponse = new Gson().fromJson(response.toString(), mToClassType);
150 |
151 | } catch (Exception e)
152 | {
153 | if (e.getMessage() != null)
154 | {
155 | Log.e(TAG, e.getMessage());
156 | }
157 | }
158 | }
159 |
160 | return objectResponse;
161 | }
162 |
163 |
164 | private Object parseJSONArrayResponse(JSONArray response)
165 | {
166 | Object objectResponse = response;
167 |
168 | if (response != null && !mToClassType.toString().equals(JSONArray.class.toString()))
169 | {
170 | try
171 | {
172 | objectResponse = new Gson().fromJson(response.toString(), mToClassType);
173 |
174 | } catch (Exception e)
175 | {
176 | if (e.getMessage() != null)
177 | {
178 | Log.e(TAG, e.getMessage());
179 | }
180 | }
181 | }
182 |
183 | return objectResponse;
184 | }
185 |
186 | private Object parseError(VolleyError error)
187 | {
188 | Object errorObject = error;
189 |
190 | if (!mToClassType.toString().equals(VolleyError.class.toString()) &&
191 | error != null && error.networkResponse != null && error.networkResponse.data != null)
192 | {
193 | try
194 | {
195 | errorObject = mErrorClassType != null ? new Gson().fromJson(new String(error.networkResponse.data), mErrorClassType) : error;
196 | } catch (Exception e)
197 | {
198 | if (e.getMessage() != null)
199 | {
200 | Log.e(TAG, e.getMessage());
201 | }
202 | }
203 | }
204 |
205 | return errorObject;
206 | }
207 |
208 | public Map getFileParameters()
209 | {
210 | return mFileParameters;
211 | }
212 |
213 | public RequestFutureHandler setFileParameters(Map fileParameters)
214 | {
215 | mFileParameters = fileParameters;
216 | return this;
217 | }
218 | }
219 |
--------------------------------------------------------------------------------
/app/src/main/java/net/lateralview/simplerestclienthandler/base/RequestHandler.java:
--------------------------------------------------------------------------------
1 | package net.lateralview.simplerestclienthandler.base;
2 |
3 | import android.os.Bundle;
4 | import android.support.annotation.NonNull;
5 | import android.util.Log;
6 |
7 | import com.android.volley.Response;
8 | import com.android.volley.VolleyError;
9 | import com.google.gson.Gson;
10 | import com.google.gson.GsonBuilder;
11 |
12 | import net.lateralview.simplerestclienthandler.gson.AnnotationExclusionStrategy;
13 | import net.lateralview.simplerestclienthandler.helper.BundleJSONConverter;
14 | import net.lateralview.simplerestclienthandler.helper.ReflectionHelper;
15 |
16 | import org.json.JSONArray;
17 | import org.json.JSONObject;
18 |
19 | import java.lang.reflect.Type;
20 | import java.util.Map;
21 |
22 | public class RequestHandler
23 | {
24 | protected static final String TAG = RequestHandler.class.getSimpleName();
25 |
26 | private RequestCallbacks mRequestCallbacks;
27 | private Type mToClassType, mErrorClassType;
28 | private T mObjectParameter;
29 | private Bundle mBundleParameters;
30 | private Map mFileParameters;
31 |
32 | public RequestHandler(RequestCallbacks requestCallbacks, T parameter)
33 | {
34 | mObjectParameter = parameter;
35 |
36 | initializeRequestHandler(requestCallbacks);
37 | }
38 |
39 | public RequestHandler(RequestCallbacks requestCallbacks, @NonNull Bundle parameters)
40 | {
41 | mBundleParameters = parameters;
42 |
43 | initializeRequestHandler(requestCallbacks);
44 | }
45 |
46 | public RequestHandler(RequestCallbacks requestCallbacks)
47 | {
48 | this(requestCallbacks, new Bundle());
49 | }
50 |
51 | private void initializeRequestHandler(RequestCallbacks requestCallbacks)
52 | {
53 | mRequestCallbacks = requestCallbacks;
54 | mToClassType = getToClassFromRequestCallback();
55 | mErrorClassType = getErrorClassFromRequestCallback();
56 |
57 | callRequestCallbackStarted(requestCallbacks);
58 | }
59 |
60 | public Response.Listener getResponseSuccessListener()
61 | {
62 | return new Response.Listener()
63 | {
64 | @Override
65 | public void onResponse(JSONObject response)
66 | {
67 | requestJSONObjectResponseHandler(response);
68 | }
69 | };
70 | }
71 |
72 | public Response.Listener getArrayResponseSuccessListener()
73 | {
74 | return new Response.Listener()
75 | {
76 | @Override
77 | public void onResponse(JSONArray response)
78 | {
79 | requestJSONArrayResponseHandler(response);
80 | }
81 | };
82 | }
83 |
84 | public Response.ErrorListener getResponseErrorListener()
85 | {
86 | return new Response.ErrorListener()
87 | {
88 | public void onErrorResponse(VolleyError error)
89 | {
90 | requestErrorHandler(error);
91 | }
92 | };
93 | }
94 |
95 | public JSONObject getParameters()
96 | {
97 | JSONObject jsonObject = null;
98 |
99 | try
100 | {
101 | if (mObjectParameter != null)
102 | {
103 | jsonObject = new JSONObject(new GsonBuilder().setExclusionStrategies(new AnnotationExclusionStrategy()).create().toJson(mObjectParameter));
104 | } else
105 | {
106 | jsonObject = BundleJSONConverter.convertToJSON(mBundleParameters);
107 | }
108 | } catch (Exception e)
109 | {
110 | if (e.getMessage() != null)
111 | {
112 | Log.e(TAG, e.getMessage());
113 | }
114 | callRequestCallbackOnError(null);
115 | }
116 |
117 | return jsonObject;
118 | }
119 |
120 | private void callRequestCallbackOnSuccess(E responseParsedData)
121 | {
122 | if (mRequestCallbacks != null)
123 | {
124 | mRequestCallbacks.onRequestSuccess(responseParsedData);
125 | }
126 | }
127 |
128 | private void callRequestCallbackOnError(E errorObject)
129 | {
130 | if (mRequestCallbacks != null)
131 | {
132 | mRequestCallbacks.onRequestError(errorObject);
133 | }
134 | }
135 |
136 | private void callRequestCallbackFinished(RequestCallbacks requestCallbacks)
137 | {
138 | if (requestCallbacks != null)
139 | {
140 | requestCallbacks.onRequestFinish();
141 | }
142 | }
143 |
144 | private void callRequestCallbackStarted(RequestCallbacks requestCallbacks)
145 | {
146 | if (requestCallbacks != null)
147 | {
148 | requestCallbacks.onRequestStart();
149 | }
150 | }
151 |
152 | private Type getToClassFromRequestCallback()
153 | {
154 | if (mRequestCallbacks != null && mRequestCallbacks instanceof ICallbackTypes)
155 | {
156 | return ((ICallbackTypes) mRequestCallbacks).getResponseType();
157 | }
158 | else
159 | {
160 | return ReflectionHelper.getTypeArgument(mRequestCallbacks, 0);
161 | }
162 | }
163 |
164 | private Type getErrorClassFromRequestCallback()
165 | {
166 | if (mRequestCallbacks != null && mRequestCallbacks instanceof ICallbackTypes)
167 | {
168 | return ((ICallbackTypes) mRequestCallbacks).getErrorType();
169 | }
170 | else
171 | {
172 | return ReflectionHelper.getTypeArgument(mRequestCallbacks, 1);
173 | }
174 | }
175 |
176 | private void requestJSONObjectResponseHandler(JSONObject response)
177 | {
178 | callRequestCallbackFinished(mRequestCallbacks);
179 |
180 | if (response != null)
181 | {
182 | try
183 | {
184 | if (mToClassType != null && mToClassType.toString().equals(JSONObject.class.toString()))
185 | {
186 | callRequestCallbackOnSuccess(response);
187 | } else
188 | {
189 | callRequestCallbackOnSuccess(mToClassType != null ? new Gson().fromJson(response.toString(), mToClassType) : null);
190 | }
191 | } catch (Exception e)
192 | {
193 | if (e.getMessage() != null)
194 | {
195 | Log.e(TAG, e.getMessage());
196 | }
197 |
198 | callRequestCallbackOnError(null);
199 | }
200 | } else
201 | {
202 | callRequestCallbackOnError(null);
203 | }
204 | }
205 |
206 | private void requestJSONArrayResponseHandler(JSONArray response)
207 | {
208 | callRequestCallbackFinished(mRequestCallbacks);
209 |
210 | if (response != null)
211 | {
212 | try
213 | {
214 | if (mToClassType != null && mToClassType.toString().equals(JSONArray.class.toString()))
215 | {
216 | callRequestCallbackOnSuccess(response);
217 | } else
218 | {
219 | callRequestCallbackOnSuccess(mToClassType != null ? new Gson().fromJson(response.toString(), mToClassType) : null);
220 | }
221 | } catch (Exception e)
222 | {
223 | if (e.getMessage() != null)
224 | {
225 | Log.e(TAG, e.getMessage());
226 | }
227 |
228 | callRequestCallbackOnError(null);
229 | }
230 | } else
231 | {
232 | callRequestCallbackOnError(null);
233 | }
234 | }
235 |
236 | private void requestErrorHandler(VolleyError error)
237 | {
238 | callRequestCallbackFinished(mRequestCallbacks);
239 |
240 | if (mToClassType != null && mToClassType.toString().equals(VolleyError.class.toString()))
241 | {
242 | callRequestCallbackOnError(error);
243 | } else if (error != null && error.networkResponse != null && error.networkResponse.data != null)
244 | {
245 | try
246 | {
247 | callRequestCallbackOnError(mErrorClassType != null ? new Gson().fromJson(new String(error.networkResponse.data), mErrorClassType) : error);
248 | } catch (Exception e)
249 | {
250 | if (e.getMessage() != null)
251 | {
252 | Log.e(TAG, e.getMessage());
253 | }
254 | callRequestCallbackOnError(null);
255 | }
256 | } else
257 | {
258 | callRequestCallbackOnError(null);
259 | }
260 | }
261 |
262 | public Map getFileParameters()
263 | {
264 | return mFileParameters;
265 | }
266 |
267 | public RequestHandler setFileParameters(Map fileParameters)
268 | {
269 | mFileParameters = fileParameters;
270 | return this;
271 | }
272 | }
273 |
--------------------------------------------------------------------------------
/app/src/main/java/net/lateralview/simplerestclienthandler/gson/AnnotationExclusionStrategy.java:
--------------------------------------------------------------------------------
1 | package net.lateralview.simplerestclienthandler.gson;
2 |
3 | import com.google.gson.ExclusionStrategy;
4 | import com.google.gson.FieldAttributes;
5 |
6 | public class AnnotationExclusionStrategy implements ExclusionStrategy
7 | {
8 |
9 | @Override
10 | public boolean shouldSkipField(FieldAttributes f)
11 | {
12 | return f.getAnnotation(Exclude.class) != null;
13 | }
14 |
15 | @Override
16 | public boolean shouldSkipClass(Class> clazz)
17 | {
18 | return false;
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/app/src/main/java/net/lateralview/simplerestclienthandler/gson/Exclude.java:
--------------------------------------------------------------------------------
1 | package net.lateralview.simplerestclienthandler.gson;
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 | @Retention(RetentionPolicy.RUNTIME)
9 | @Target(ElementType.FIELD)
10 | public @interface Exclude
11 | {
12 | }
13 |
14 |
--------------------------------------------------------------------------------
/app/src/main/java/net/lateralview/simplerestclienthandler/helper/BundleJSONConverter.java:
--------------------------------------------------------------------------------
1 | package net.lateralview.simplerestclienthandler.helper;
2 |
3 | import android.os.Bundle;
4 |
5 | import org.json.JSONArray;
6 | import org.json.JSONException;
7 | import org.json.JSONObject;
8 |
9 | import java.util.ArrayList;
10 | import java.util.HashMap;
11 | import java.util.Iterator;
12 | import java.util.List;
13 | import java.util.Map;
14 |
15 | /**
16 | * A helper class that can round trip between JSON and Bundle objects that contains the types:
17 | * Boolean, Integer, Long, Double, String
18 | * If other types are found, an IllegalArgumentException is thrown.
19 | */
20 | public class BundleJSONConverter
21 | {
22 | private static final Map, Setter> SETTERS = new HashMap, Setter>();
23 |
24 | static
25 | {
26 | SETTERS.put(Boolean.class, new Setter()
27 | {
28 | public void setOnBundle(Bundle bundle, String key, Object value) throws JSONException
29 | {
30 | bundle.putBoolean(key, (Boolean) value);
31 | }
32 |
33 | public void setOnJSON(JSONObject json, String key, Object value) throws JSONException
34 | {
35 | json.put(key, value);
36 | }
37 | });
38 | SETTERS.put(Integer.class, new Setter()
39 | {
40 | public void setOnBundle(Bundle bundle, String key, Object value) throws JSONException
41 | {
42 | bundle.putInt(key, (Integer) value);
43 | }
44 |
45 | public void setOnJSON(JSONObject json, String key, Object value) throws JSONException
46 | {
47 | json.put(key, value);
48 | }
49 | });
50 | SETTERS.put(Long.class, new Setter()
51 | {
52 | public void setOnBundle(Bundle bundle, String key, Object value) throws JSONException
53 | {
54 | bundle.putLong(key, (Long) value);
55 | }
56 |
57 | public void setOnJSON(JSONObject json, String key, Object value) throws JSONException
58 | {
59 | json.put(key, value);
60 | }
61 | });
62 | SETTERS.put(Double.class, new Setter()
63 | {
64 | public void setOnBundle(Bundle bundle, String key, Object value) throws JSONException
65 | {
66 | bundle.putDouble(key, (Double) value);
67 | }
68 |
69 | public void setOnJSON(JSONObject json, String key, Object value) throws JSONException
70 | {
71 | json.put(key, value);
72 | }
73 | });
74 | SETTERS.put(String.class, new Setter()
75 | {
76 | public void setOnBundle(Bundle bundle, String key, Object value) throws JSONException
77 | {
78 | bundle.putString(key, (String) value);
79 | }
80 |
81 | public void setOnJSON(JSONObject json, String key, Object value) throws JSONException
82 | {
83 | json.put(key, value);
84 | }
85 | });
86 | SETTERS.put(String[].class, new Setter()
87 | {
88 | public void setOnBundle(Bundle bundle, String key, Object value) throws JSONException
89 | {
90 | throw new IllegalArgumentException("Unexpected type from JSON");
91 | }
92 |
93 | public void setOnJSON(JSONObject json, String key, Object value) throws JSONException
94 | {
95 | JSONArray jsonArray = new JSONArray();
96 | for (String stringValue : (String[]) value)
97 | {
98 | jsonArray.put(stringValue);
99 | }
100 | json.put(key, jsonArray);
101 | }
102 | });
103 |
104 | SETTERS.put(JSONArray.class, new Setter()
105 | {
106 | public void setOnBundle(Bundle bundle, String key, Object value) throws JSONException
107 | {
108 | JSONArray jsonArray = (JSONArray) value;
109 | ArrayList stringArrayList = new ArrayList();
110 | // Empty list, can't even figure out the type, assume an ArrayList
111 | if (jsonArray.length() == 0)
112 | {
113 | bundle.putStringArrayList(key, stringArrayList);
114 | return;
115 | }
116 |
117 | // Only strings are supported for now
118 | for (int i = 0; i < jsonArray.length(); i++)
119 | {
120 | Object current = jsonArray.get(i);
121 | if (current instanceof String)
122 | {
123 | stringArrayList.add((String) current);
124 | } else
125 | {
126 | throw new IllegalArgumentException("Unexpected type in an array: " + current.getClass());
127 | }
128 | }
129 | bundle.putStringArrayList(key, stringArrayList);
130 | }
131 |
132 | @Override
133 | public void setOnJSON(JSONObject json, String key, Object value) throws JSONException
134 | {
135 | throw new IllegalArgumentException("JSONArray's are not supported in bundles.");
136 | }
137 | });
138 | }
139 |
140 | public static JSONObject convertToJSON(Bundle bundle) throws JSONException
141 | {
142 | JSONObject json = new JSONObject();
143 |
144 | for (String key : bundle.keySet())
145 | {
146 | Object value = bundle.get(key);
147 | if (value == null)
148 | {
149 | // Null is not supported.
150 | continue;
151 | }
152 |
153 | // Special case List as getClass would not work, since List is an interface
154 | if (value instanceof List>)
155 | {
156 | JSONArray jsonArray = new JSONArray();
157 | @SuppressWarnings("unchecked")
158 | List listValue = (List) value;
159 | for (String stringValue : listValue)
160 | {
161 | jsonArray.put(stringValue);
162 | }
163 | json.put(key, jsonArray);
164 | continue;
165 | }
166 |
167 | // Special case Bundle as it's one way, on the return it will be JSONObject
168 | if (value instanceof Bundle)
169 | {
170 | json.put(key, convertToJSON((Bundle) value));
171 | continue;
172 | }
173 |
174 | Setter setter = SETTERS.get(value.getClass());
175 | if (setter == null)
176 | {
177 | throw new IllegalArgumentException("Unsupported type: " + value.getClass());
178 | }
179 | setter.setOnJSON(json, key, value);
180 | }
181 |
182 | return json;
183 | }
184 |
185 | public static Bundle convertToBundle(JSONObject jsonObject) throws JSONException
186 | {
187 | Bundle bundle = new Bundle();
188 | @SuppressWarnings("unchecked")
189 | Iterator jsonIterator = jsonObject.keys();
190 | while (jsonIterator.hasNext())
191 | {
192 | String key = jsonIterator.next();
193 | Object value = jsonObject.get(key);
194 | if (value == null || value == JSONObject.NULL)
195 | {
196 | // Null is not supported.
197 | continue;
198 | }
199 |
200 | // Special case JSONObject as it's one way, on the return it would be Bundle.
201 | if (value instanceof JSONObject)
202 | {
203 | bundle.putBundle(key, convertToBundle((JSONObject) value));
204 | continue;
205 | }
206 |
207 | Setter setter = SETTERS.get(value.getClass());
208 | if (setter == null)
209 | {
210 | throw new IllegalArgumentException("Unsupported type: " + value.getClass());
211 | }
212 | setter.setOnBundle(bundle, key, value);
213 | }
214 |
215 | return bundle;
216 | }
217 |
218 | public interface Setter
219 | {
220 | void setOnBundle(Bundle bundle, String key, Object value) throws JSONException;
221 |
222 | void setOnJSON(JSONObject json, String key, Object value) throws JSONException;
223 | }
224 | }
225 |
--------------------------------------------------------------------------------
/app/src/main/java/net/lateralview/simplerestclienthandler/helper/FileManager.java:
--------------------------------------------------------------------------------
1 | package net.lateralview.simplerestclienthandler.helper;
2 |
3 | import org.apache.tika.detect.DefaultDetector;
4 | import org.apache.tika.io.TikaInputStream;
5 | import org.apache.tika.metadata.Metadata;
6 | import org.apache.tika.mime.MimeTypes;
7 |
8 | import java.io.BufferedInputStream;
9 | import java.io.File;
10 | import java.io.FileInputStream;
11 | import java.io.IOException;
12 |
13 | public class FileManager
14 | {
15 | public File file;
16 |
17 | public FileManager(File file)
18 | {
19 | this.file = file;
20 | }
21 |
22 | public byte[] toByteArray() throws IOException
23 | {
24 | int size = (int) file.length();
25 | byte[] bytes = new byte[size];
26 |
27 | BufferedInputStream buf = new BufferedInputStream(new FileInputStream(file));
28 | buf.read(bytes, 0, bytes.length);
29 | buf.close();
30 |
31 | return bytes;
32 | }
33 |
34 | public String getMimeType() throws IOException
35 | {
36 | TikaInputStream tikaIS = null;
37 | try
38 | {
39 | tikaIS = TikaInputStream.get(file);
40 |
41 | return new DefaultDetector(MimeTypes.getDefaultMimeTypes()).detect(tikaIS, new Metadata()).toString();
42 | } finally
43 | {
44 | if (tikaIS != null)
45 | {
46 | tikaIS.close();
47 | }
48 | }
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/app/src/main/java/net/lateralview/simplerestclienthandler/helper/MultipartEntity.java:
--------------------------------------------------------------------------------
1 | package net.lateralview.simplerestclienthandler.helper;
2 |
3 | import com.android.volley.VolleyLog;
4 |
5 | import java.io.ByteArrayInputStream;
6 | import java.io.ByteArrayOutputStream;
7 | import java.io.DataOutputStream;
8 | import java.io.File;
9 | import java.io.IOException;
10 | import java.util.Map;
11 |
12 | public class MultipartEntity
13 | {
14 | public static final String TWO_HYPHENS = "--";
15 | public static final String LINE_END = "\r\n";
16 |
17 | private final String boundary = "apiclient-" + System.currentTimeMillis();
18 | private Map fileParams;
19 | private Map params;
20 |
21 | public MultipartEntity(Map fileParams, Map params)
22 | {
23 | this.fileParams = fileParams;
24 | this.params = params;
25 | }
26 |
27 | public String getBoundary()
28 | {
29 | return boundary;
30 | }
31 |
32 | public byte[] build()
33 | {
34 | ByteArrayOutputStream bos = new ByteArrayOutputStream();
35 | DataOutputStream dos = new DataOutputStream(bos);
36 |
37 | try
38 | {
39 | if (null != fileParams && !fileParams.isEmpty())
40 | {
41 | for (Map.Entry entry : fileParams.entrySet())
42 | {
43 | File file = new File(entry.getValue());
44 |
45 | FileManager fileManager = new FileManager(file);
46 |
47 | if (file.exists())
48 | {
49 | buildPart(dos, fileManager.toByteArray(), entry.getKey(), file.getName(), fileManager.getMimeType());
50 | }
51 | }
52 | }
53 |
54 | if (null != params)
55 | {
56 | for (Map.Entry entry : params.entrySet())
57 | {
58 | if (entry.getValue() != null)
59 | {
60 | buildTextPart(dos, entry.getKey(), entry.getValue());
61 | }
62 | }
63 | }
64 |
65 | dos.writeBytes(TWO_HYPHENS + boundary + TWO_HYPHENS);
66 |
67 | } catch (IOException e)
68 | {
69 | VolleyLog.e("buildMultipartEntity: " + e.toString());
70 | }
71 |
72 | return bos.toByteArray();
73 | }
74 |
75 | private void buildPart(DataOutputStream dataOutputStream, byte[] fileData, String fieldName, String fileName, String contentType) throws IOException
76 | {
77 | dataOutputStream.writeBytes(TWO_HYPHENS + boundary + LINE_END);
78 | dataOutputStream.writeBytes("Content-Type: " + contentType + LINE_END);
79 | dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"" + fieldName + "\"; filename=\"" + fileName + "\"" + LINE_END);
80 | dataOutputStream.writeBytes(LINE_END);
81 |
82 | ByteArrayInputStream fileInputStream = new ByteArrayInputStream(fileData);
83 | int bytesAvailable = fileInputStream.available();
84 |
85 | int maxBufferSize = 1024 * 1024;
86 | int bufferSize = Math.min(bytesAvailable, maxBufferSize);
87 | byte[] buffer = new byte[bufferSize];
88 |
89 | // read file and write it into form...
90 | int bytesRead = fileInputStream.read(buffer, 0, bufferSize);
91 |
92 | while (bytesRead > 0)
93 | {
94 | dataOutputStream.write(buffer, 0, bufferSize);
95 | bytesAvailable = fileInputStream.available();
96 | bufferSize = Math.min(bytesAvailable, maxBufferSize);
97 | bytesRead = fileInputStream.read(buffer, 0, bufferSize);
98 | }
99 |
100 | dataOutputStream.writeBytes(LINE_END);
101 | }
102 |
103 | private void buildTextPart(DataOutputStream dataOutputStream, String parameterName, String parameterValue) throws IOException
104 | {
105 | dataOutputStream.writeBytes(TWO_HYPHENS + boundary + LINE_END);
106 | dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"" + parameterName + "\"" + LINE_END);
107 | dataOutputStream.writeBytes("Content-Type: text/plain; charset=UTF-8" + LINE_END);
108 | dataOutputStream.writeBytes(LINE_END);
109 | dataOutputStream.write(parameterValue.getBytes("UTF-8"));
110 | dataOutputStream.writeBytes(LINE_END);
111 | }
112 | }
113 |
--------------------------------------------------------------------------------
/app/src/main/java/net/lateralview/simplerestclienthandler/helper/ParametersJSONObject.java:
--------------------------------------------------------------------------------
1 | package net.lateralview.simplerestclienthandler.helper;
2 |
3 | import com.google.gson.Gson;
4 |
5 | import org.json.JSONArray;
6 | import org.json.JSONException;
7 | import org.json.JSONObject;
8 |
9 | import java.util.HashMap;
10 | import java.util.Map;
11 |
12 | public class ParametersJSONObject extends JSONObject
13 | {
14 | public static JSONObject fromMap(Map parameters)
15 | {
16 | JSONObject b = new JSONObject();
17 |
18 | try
19 | {
20 | if (null != parameters)
21 | {
22 | for (String parameter : parameters.keySet())
23 | {
24 | b.put(parameter, parameters.get(parameter));
25 | }
26 | }
27 | } catch (JSONException e)
28 | {
29 | }
30 |
31 | return b;
32 | }
33 |
34 | public static Map toMap(JSONObject parameters)
35 | {
36 | Map params = new HashMap<>();
37 |
38 | if (parameters != null)
39 | {
40 | JSONArray names = parameters.names();
41 |
42 | try
43 | {
44 | if (null != names)
45 | {
46 | for (int i = 0; i < names.length(); i++)
47 | {
48 | params.put(names.getString(i), parameters.get(names.getString(i)).toString());
49 | }
50 | }
51 | } catch (JSONException e)
52 | {
53 | }
54 | }
55 |
56 | return params;
57 | }
58 |
59 | public static String getUrlQuery(JSONObject parameters)
60 | {
61 | StringBuilder urlParameters = new StringBuilder();
62 | Map parametersMap = toMap(parameters);
63 |
64 | if (parametersMap.size() > 0)
65 | {
66 | urlParameters.append("?");
67 | }
68 |
69 | for (String parameterName : parametersMap.keySet())
70 | {
71 | urlParameters.append(parameterName).append("=").append(parametersMap.get(parameterName).replace(" ", "%20")).append("&");
72 | }
73 |
74 | urlParameters.deleteCharAt(urlParameters.length() - 1);
75 |
76 | return urlParameters.toString();
77 | }
78 |
79 | public JSONObject putBoolean(String name, boolean value)
80 | {
81 | try
82 | {
83 | super.put(name, value);
84 | } catch (JSONException e)
85 | {
86 | }
87 | return this;
88 | }
89 |
90 | public JSONObject putDouble(String name, double value)
91 | {
92 | try
93 | {
94 | super.put(name, value);
95 | } catch (JSONException e)
96 | {
97 | }
98 | return this;
99 | }
100 |
101 | public JSONObject putInt(String name, int value)
102 | {
103 | try
104 | {
105 | super.put(name, value);
106 | } catch (JSONException e)
107 | {
108 | }
109 | return this;
110 | }
111 |
112 | public JSONObject putLong(String name, long value)
113 | {
114 | try
115 | {
116 | super.put(name, value);
117 | } catch (JSONException e)
118 | {
119 | }
120 | return this;
121 | }
122 |
123 | public JSONObject putString(String name, String value)
124 | {
125 | try
126 | {
127 | super.put(name, value);
128 | } catch (JSONException e)
129 | {
130 | }
131 | return this;
132 | }
133 |
134 | public JSONObject putObject(String name, Object value)
135 | {
136 | try
137 | {
138 | super.put(name, value);
139 | } catch (JSONException e)
140 | {
141 | }
142 | return this;
143 | }
144 |
145 | public JSONObject putOptObject(String name, Object value)
146 | {
147 | if (name == null || value == null)
148 | {
149 | return this;
150 | }
151 | return putObject(name, value);
152 | }
153 |
154 | public JSONObject putJSONArray(String name, JSONArray array)
155 | {
156 | putOptObject(name, array);
157 | return this;
158 | }
159 |
160 | public JSONObject putObjectArray(String name, Object[] objects)
161 | {
162 | JSONArray jsonArray = new JSONArray();
163 |
164 | for (Object object : objects)
165 | {
166 | try
167 | {
168 | jsonArray.put(new JSONObject(new Gson().toJson(object)));
169 | } catch (JSONException e)
170 | {
171 | }
172 | }
173 |
174 | putJSONArray(name, jsonArray);
175 |
176 | return this;
177 | }
178 | }
179 |
--------------------------------------------------------------------------------
/app/src/main/java/net/lateralview/simplerestclienthandler/helper/ReflectionHelper.java:
--------------------------------------------------------------------------------
1 | package net.lateralview.simplerestclienthandler.helper;
2 |
3 | import java.lang.reflect.ParameterizedType;
4 | import java.lang.reflect.Type;
5 |
6 | /**
7 | * Created by julianfalcionelli on 11/11/16.
8 | */
9 | public class ReflectionHelper
10 | {
11 | public static Type getTypeArgument(Object object, int position)
12 | {
13 | Type genericType = null;
14 |
15 | if (object != null)
16 | {
17 | try
18 | {
19 | genericType = ((ParameterizedType) object.getClass().getGenericSuperclass()).getActualTypeArguments()[position];
20 | }
21 | catch (Exception e)
22 | {
23 | //do nothing
24 | }
25 | }
26 |
27 | return genericType;
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/app/src/main/java/net/lateralview/simplerestclienthandler/helper/VolleyHelper.java:
--------------------------------------------------------------------------------
1 | package net.lateralview.simplerestclienthandler.helper;
2 |
3 | import android.content.Context;
4 |
5 | import com.android.volley.Network;
6 | import com.android.volley.RequestQueue;
7 | import com.android.volley.ResponseDelivery;
8 | import com.android.volley.toolbox.BasicNetwork;
9 | import com.android.volley.toolbox.DiskBasedCache;
10 | import com.android.volley.toolbox.HurlStack;
11 |
12 | import java.io.File;
13 |
14 | /**
15 | * Created by Joaquin on 8/3/16.
16 | */
17 | public class VolleyHelper
18 | {
19 | private static final String DEFAULT_CACHE_DIR = "volley";
20 |
21 | private static final int DEFAULT_NETWORK_THREAD_POOL_SIZE = 4;
22 |
23 | public static RequestQueue newRequestQueue(Context context, ResponseDelivery responseDelivery)
24 | {
25 | File cacheDir = new File(context.getCacheDir(), DEFAULT_CACHE_DIR);
26 |
27 | Network network = new BasicNetwork(new HurlStack());
28 |
29 | RequestQueue requestQueue = new RequestQueue(new DiskBasedCache(cacheDir), network, DEFAULT_NETWORK_THREAD_POOL_SIZE, responseDelivery);
30 |
31 | requestQueue.start();
32 |
33 | return requestQueue;
34 | }
35 | }
--------------------------------------------------------------------------------
/app/src/main/java/net/lateralview/simplerestclienthandler/log/RequestLoggingHelper.java:
--------------------------------------------------------------------------------
1 | package net.lateralview.simplerestclienthandler.log;
2 |
3 | import com.android.volley.AuthFailureError;
4 | import com.android.volley.Request;
5 | import com.android.volley.VolleyError;
6 |
7 | import org.json.JSONArray;
8 | import org.json.JSONObject;
9 |
10 | /**
11 | * Helper class to log requests information
12 | */
13 | public class RequestLoggingHelper
14 | {
15 | /**
16 | * Gets basic request information.
17 | *
18 | * @param request Request instance to retrieve information for logging
19 | * @return Message describing request, including Method type, URL and JSON body
20 | */
21 | public static String getRequestText(Request request)
22 | {
23 | StringBuilder msg = new StringBuilder();
24 |
25 | msg.append("New ").append(getMethodText(request.getMethod())).append(" request").append("\n");
26 | msg.append("URL: ").append(request.getUrl()).append("\n");
27 | try
28 | {
29 | msg.append("JSON: ").append(new String(request.getBody())).append("\n");
30 | } catch (AuthFailureError authFailureError)
31 | {
32 | authFailureError.printStackTrace();
33 | }
34 |
35 | return msg.toString();
36 | }
37 |
38 | public static String getMultipartRequestText(Request request, JSONObject stringParameters)
39 | {
40 | StringBuilder msg = new StringBuilder();
41 |
42 | msg.append("New ").append(getMethodText(request.getMethod())).append(" request").append("\n");
43 | msg.append("URL: ").append(request.getUrl()).append("\n");
44 |
45 | if (stringParameters != null)
46 | {
47 | msg.append("JSON: ").append(stringParameters.toString()).append("\n");
48 | }
49 |
50 | return msg.toString();
51 | }
52 |
53 | /**
54 | * Gets Request error information.
55 | *
56 | * @param request Request instance to retrieve information for logging
57 | * @param volleyError Error instance to retrieve information for logging
58 | * @return Message describing error, including Method type, URL, HTTP status and JSON response
59 | */
60 | public static String getRequestErrorText(Request request, VolleyError volleyError)
61 | {
62 | StringBuilder msg = new StringBuilder();
63 |
64 | msg.append(getMethodText(request.getMethod())).append(" request failed ").append("\n");
65 | msg.append("URL: ").append(request.getUrl()).append("\n");
66 |
67 | String statusCode = "unknown";
68 | String responseData = "unknown";
69 | if (volleyError.networkResponse != null)
70 | {
71 | statusCode = String.valueOf(volleyError.networkResponse.statusCode);
72 | responseData = new String(volleyError.networkResponse.data);
73 | }
74 |
75 | msg.append("HTTP status:").append(statusCode).append("\n");
76 | msg.append("Response:").append(new String(responseData)).append("\n");
77 |
78 | return msg.toString();
79 | }
80 |
81 | /**
82 | * Gets Request response information.
83 | *
84 | * @param request Request instance to retrieve information for logging
85 | * @param response Response instance to retrieve information for logging
86 | * @return Message describing response, including Method type, URL and JSON response
87 | */
88 | public static String getRequestResponseText(Request request, JSONArray response)
89 | {
90 | return getRequestResponseText(request, response.toString());
91 | }
92 |
93 | public static String getRequestResponseText(Request request, JSONObject response)
94 | {
95 | return getRequestResponseText(request, response.toString());
96 | }
97 |
98 | public static String getRequestResponseText(Request request, String response)
99 | {
100 | StringBuilder msg = new StringBuilder();
101 |
102 | msg.append(getMethodText(request.getMethod())).append(" request successful ").append("\n");
103 |
104 | msg.append("URL: ").append(request.getUrl()).append("\n");
105 |
106 | if (response != null)
107 | {
108 | msg.append("Response: ").append(response).append("\n");
109 | }
110 |
111 | return msg.toString();
112 | }
113 |
114 | public static String getMethodText(int method)
115 | {
116 | switch (method)
117 | {
118 | case Request.Method.POST:
119 | {
120 | return "POST";
121 | }
122 | case Request.Method.GET:
123 | {
124 | return "GET";
125 | }
126 | case Request.Method.PUT:
127 | {
128 | return "PUT";
129 | }
130 | case Request.Method.DELETE:
131 | {
132 | return "DELETE";
133 | }
134 | default:
135 | {
136 | return "OTHER";
137 | }
138 | }
139 | }
140 | }
141 |
--------------------------------------------------------------------------------
/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.1.2'
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 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 |
3 | # IDE (e.g. Android Studio) users:
4 | # Gradle settings configured through the IDE *will override*
5 | # any settings specified in this file.
6 |
7 | # For more details on how to configure your build environment visit
8 | # http://www.gradle.org/docs/current/userguide/build_environment.html
9 |
10 | # Specifies the JVM arguments used for the daemon process.
11 | # The setting is particularly useful for tweaking memory settings.
12 | # Default value: -Xmx10248m -XX:MaxPermSize=256m
13 | # org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
14 |
15 | # When configured, Gradle will run in incubating parallel mode.
16 | # This option should only be used with decoupled projects. More details, visit
17 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
18 | # org.gradle.parallel=true
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/julianfalcionelli/SimpleRESTClientHandler/0d83fe316856250cc16b2492c47319ddb07377c5/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Wed Aug 31 21:02:19 ART 2016
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-2.14.1-all.zip
7 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
10 | DEFAULT_JVM_OPTS=""
11 |
12 | APP_NAME="Gradle"
13 | APP_BASE_NAME=`basename "$0"`
14 |
15 | # Use the maximum available, or set MAX_FD != -1 to use that value.
16 | MAX_FD="maximum"
17 |
18 | warn ( ) {
19 | echo "$*"
20 | }
21 |
22 | die ( ) {
23 | echo
24 | echo "$*"
25 | echo
26 | exit 1
27 | }
28 |
29 | # OS specific support (must be 'true' or 'false').
30 | cygwin=false
31 | msys=false
32 | darwin=false
33 | case "`uname`" in
34 | CYGWIN* )
35 | cygwin=true
36 | ;;
37 | Darwin* )
38 | darwin=true
39 | ;;
40 | MINGW* )
41 | msys=true
42 | ;;
43 | esac
44 |
45 | # For Cygwin, ensure paths are in UNIX format before anything is touched.
46 | if $cygwin ; then
47 | [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
48 | fi
49 |
50 | # Attempt to set APP_HOME
51 | # Resolve links: $0 may be a link
52 | PRG="$0"
53 | # Need this for relative symlinks.
54 | while [ -h "$PRG" ] ; do
55 | ls=`ls -ld "$PRG"`
56 | link=`expr "$ls" : '.*-> \(.*\)$'`
57 | if expr "$link" : '/.*' > /dev/null; then
58 | PRG="$link"
59 | else
60 | PRG=`dirname "$PRG"`"/$link"
61 | fi
62 | done
63 | SAVED="`pwd`"
64 | cd "`dirname \"$PRG\"`/" >&-
65 | APP_HOME="`pwd -P`"
66 | cd "$SAVED" >&-
67 |
68 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
69 |
70 | # Determine the Java command to use to start the JVM.
71 | if [ -n "$JAVA_HOME" ] ; then
72 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
73 | # IBM's JDK on AIX uses strange locations for the executables
74 | JAVACMD="$JAVA_HOME/jre/sh/java"
75 | else
76 | JAVACMD="$JAVA_HOME/bin/java"
77 | fi
78 | if [ ! -x "$JAVACMD" ] ; then
79 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
80 |
81 | Please set the JAVA_HOME variable in your environment to match the
82 | location of your Java installation."
83 | fi
84 | else
85 | JAVACMD="java"
86 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
87 |
88 | Please set the JAVA_HOME variable in your environment to match the
89 | location of your Java installation."
90 | fi
91 |
92 | # Increase the maximum file descriptors if we can.
93 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
94 | MAX_FD_LIMIT=`ulimit -H -n`
95 | if [ $? -eq 0 ] ; then
96 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
97 | MAX_FD="$MAX_FD_LIMIT"
98 | fi
99 | ulimit -n $MAX_FD
100 | if [ $? -ne 0 ] ; then
101 | warn "Could not set maximum file descriptor limit: $MAX_FD"
102 | fi
103 | else
104 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
105 | fi
106 | fi
107 |
108 | # For Darwin, add options to specify how the application appears in the dock
109 | if $darwin; then
110 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
111 | fi
112 |
113 | # For Cygwin, switch paths to Windows format before running java
114 | if $cygwin ; then
115 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
116 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
117 |
118 | # We build the pattern for arguments to be converted via cygpath
119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
120 | SEP=""
121 | for dir in $ROOTDIRSRAW ; do
122 | ROOTDIRS="$ROOTDIRS$SEP$dir"
123 | SEP="|"
124 | done
125 | OURCYGPATTERN="(^($ROOTDIRS))"
126 | # Add a user-defined pattern to the cygpath arguments
127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
129 | fi
130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
131 | i=0
132 | for arg in "$@" ; do
133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
135 |
136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
138 | else
139 | eval `echo args$i`="\"$arg\""
140 | fi
141 | i=$((i+1))
142 | done
143 | case $i in
144 | (0) set -- ;;
145 | (1) set -- "$args0" ;;
146 | (2) set -- "$args0" "$args1" ;;
147 | (3) set -- "$args0" "$args1" "$args2" ;;
148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
154 | esac
155 | fi
156 |
157 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
158 | function splitJvmOpts() {
159 | JVM_OPTS=("$@")
160 | }
161 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
162 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
163 |
164 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
165 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':app'
2 |
--------------------------------------------------------------------------------