├── .gitignore
├── .gradle
├── 2.1
│ └── taskArtifacts
│ │ ├── cache.properties
│ │ ├── cache.properties.lock
│ │ ├── fileHashes.bin
│ │ ├── fileSnapshots.bin
│ │ ├── outputFileStates.bin
│ │ └── taskArtifacts.bin
└── 2.2.1
│ └── taskArtifacts
│ ├── cache.properties
│ ├── cache.properties.lock
│ ├── fileHashes.bin
│ ├── fileSnapshots.bin
│ ├── outputFileStates.bin
│ └── taskArtifacts.bin
├── .project
├── .settings
├── org.eclipse.core.resources.prefs
└── org.eclipse.m2e.core.prefs
├── LICENSE.txt
├── README.md
├── android-rest-client.iml
├── android-rest-lib-additions
├── .classpath
├── .gitignore
├── .project
├── .settings
│ ├── org.eclipse.core.resources.prefs
│ ├── org.eclipse.jdt.core.prefs
│ └── org.eclipse.m2e.core.prefs
├── android-rest-lib-additions.iml
├── build.gradle
├── gradle.properties
├── pom.xml
└── src
│ └── main
│ ├── AndroidManifest.xml
│ └── java
│ └── com
│ └── dg
│ └── libs
│ └── rest
│ └── parsers
│ ├── BaseJacksonMapperResponseParser.java
│ ├── FileHttpResponseParser.java
│ └── StringHttpResponseParser.java
├── android-rest-lib
├── .classpath
├── .gitignore
├── .project
├── .settings
│ ├── org.eclipse.core.resources.prefs
│ ├── org.eclipse.jdt.core.prefs
│ └── org.eclipse.m2e.core.prefs
├── android-rest-lib.iml
├── build.gradle
├── gradle.properties
├── pom.xml
├── proguard-rules.pro
└── src
│ └── main
│ ├── AndroidManifest.xml
│ └── java
│ └── com
│ └── dg
│ └── libs
│ └── rest
│ ├── HttpRequest.java
│ ├── RestClientConfiguration.java
│ ├── authentication
│ └── AuthenticationProvider.java
│ ├── callbacks
│ ├── ActivityBoundHttpCallback.java
│ ├── BoundCallback.java
│ ├── FragmentBoundHttpCallback.java
│ └── HttpCallback.java
│ ├── client
│ └── RequestMethod.java
│ ├── domain
│ └── ResponseStatus.java
│ ├── entities
│ ├── CountingInputStreamEntity.java
│ └── UnicodeBOMInputStream.java
│ ├── exceptions
│ ├── HttpException.java
│ └── ParseException.java
│ ├── handlers
│ ├── BackgroundThreadResponseHandler.java
│ ├── DefaultResponseStatusHandler.java
│ ├── ResponseHandler.java
│ ├── ResponseStatusHandler.java
│ └── UIThreadResponseHandler.java
│ ├── parsers
│ ├── HttpResponseParser.java
│ └── NoResponseParser.java
│ └── requests
│ ├── RequestBodyUtils.java
│ └── RestClientRequest.java
├── build.gradle
├── gradle-mvn-push.gradle
├── gradle.properties
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── parent.iml
├── pom.xml
├── rest-client-demo
├── .classpath
├── .gitignore
├── .project
├── .settings
│ ├── org.eclipse.jdt.core.prefs
│ └── org.eclipse.m2e.core.prefs
├── build.gradle
├── gradle.properties
├── lint.xml
├── pom.xml
├── proguard-project.txt
├── project.properties
├── rest-client-demo.iml
└── src
│ └── main
│ ├── AndroidManifest.xml
│ ├── java
│ └── com
│ │ └── dg
│ │ └── examples
│ │ └── restclientdemo
│ │ ├── MainActivity.java
│ │ ├── app
│ │ ├── App.java
│ │ └── TokenAuthenticationProvider.java
│ │ ├── communication
│ │ ├── RestConstants.java
│ │ ├── parsers
│ │ │ └── BlogsGoogleParser.java
│ │ └── requests
│ │ │ ├── BlogsGoogleRequest.java
│ │ │ ├── CustomHandlersRequest.java
│ │ │ └── PatchRequest.java
│ │ └── domain
│ │ ├── EntriesModel.java
│ │ ├── ResponseDataModel.java
│ │ └── ResponseModel.java
│ └── res
│ ├── drawable-hdpi
│ └── ic_launcher.png
│ ├── drawable-mdpi
│ └── ic_launcher.png
│ ├── drawable-xhdpi
│ └── ic_launcher.png
│ ├── layout
│ └── activity_main.xml
│ ├── menu
│ └── activity_main.xml
│ └── values
│ ├── strings.xml
│ └── styles.xml
└── settings.gradle
/.gitignore:
--------------------------------------------------------------------------------
1 | # built application files
2 | *.apk
3 | *.ap_
4 |
5 | # files for the dex VM
6 | *.dex
7 |
8 | # Java class files
9 | *.class
10 |
11 | # generated files
12 | bin/
13 | gen/
14 |
15 | # Local configuration file (sdk path, etc)
16 | local.properties
17 | .idea
18 | target/
19 | build/
--------------------------------------------------------------------------------
/.gradle/2.1/taskArtifacts/cache.properties:
--------------------------------------------------------------------------------
1 | #Tue Sep 30 12:08:11 CEST 2014
2 |
--------------------------------------------------------------------------------
/.gradle/2.1/taskArtifacts/cache.properties.lock:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/darko1002001/android-rest-client/3e58498ac831513de8094f72b320ef7c5861c3b0/.gradle/2.1/taskArtifacts/cache.properties.lock
--------------------------------------------------------------------------------
/.gradle/2.1/taskArtifacts/fileHashes.bin:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/darko1002001/android-rest-client/3e58498ac831513de8094f72b320ef7c5861c3b0/.gradle/2.1/taskArtifacts/fileHashes.bin
--------------------------------------------------------------------------------
/.gradle/2.1/taskArtifacts/fileSnapshots.bin:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/darko1002001/android-rest-client/3e58498ac831513de8094f72b320ef7c5861c3b0/.gradle/2.1/taskArtifacts/fileSnapshots.bin
--------------------------------------------------------------------------------
/.gradle/2.1/taskArtifacts/outputFileStates.bin:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/darko1002001/android-rest-client/3e58498ac831513de8094f72b320ef7c5861c3b0/.gradle/2.1/taskArtifacts/outputFileStates.bin
--------------------------------------------------------------------------------
/.gradle/2.1/taskArtifacts/taskArtifacts.bin:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/darko1002001/android-rest-client/3e58498ac831513de8094f72b320ef7c5861c3b0/.gradle/2.1/taskArtifacts/taskArtifacts.bin
--------------------------------------------------------------------------------
/.gradle/2.2.1/taskArtifacts/cache.properties:
--------------------------------------------------------------------------------
1 | #Wed Dec 10 10:50:04 CET 2014
2 |
--------------------------------------------------------------------------------
/.gradle/2.2.1/taskArtifacts/cache.properties.lock:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/darko1002001/android-rest-client/3e58498ac831513de8094f72b320ef7c5861c3b0/.gradle/2.2.1/taskArtifacts/cache.properties.lock
--------------------------------------------------------------------------------
/.gradle/2.2.1/taskArtifacts/fileHashes.bin:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/darko1002001/android-rest-client/3e58498ac831513de8094f72b320ef7c5861c3b0/.gradle/2.2.1/taskArtifacts/fileHashes.bin
--------------------------------------------------------------------------------
/.gradle/2.2.1/taskArtifacts/fileSnapshots.bin:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/darko1002001/android-rest-client/3e58498ac831513de8094f72b320ef7c5861c3b0/.gradle/2.2.1/taskArtifacts/fileSnapshots.bin
--------------------------------------------------------------------------------
/.gradle/2.2.1/taskArtifacts/outputFileStates.bin:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/darko1002001/android-rest-client/3e58498ac831513de8094f72b320ef7c5861c3b0/.gradle/2.2.1/taskArtifacts/outputFileStates.bin
--------------------------------------------------------------------------------
/.gradle/2.2.1/taskArtifacts/taskArtifacts.bin:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/darko1002001/android-rest-client/3e58498ac831513de8094f72b320ef7c5861c3b0/.gradle/2.2.1/taskArtifacts/taskArtifacts.bin
--------------------------------------------------------------------------------
/.project:
--------------------------------------------------------------------------------
1 |
2 |
3 | android-rest-client
4 |
5 |
6 |
7 |
8 |
9 | org.eclipse.m2e.core.maven2Builder
10 |
11 |
12 |
13 |
14 |
15 | org.eclipse.m2e.core.maven2Nature
16 |
17 |
18 |
--------------------------------------------------------------------------------
/.settings/org.eclipse.core.resources.prefs:
--------------------------------------------------------------------------------
1 | eclipse.preferences.version=1
2 | encoding/=UTF-8
3 |
--------------------------------------------------------------------------------
/.settings/org.eclipse.m2e.core.prefs:
--------------------------------------------------------------------------------
1 | activeProfiles=
2 | eclipse.preferences.version=1
3 | resolveWorkspaceProjects=true
4 | version=1
5 |
--------------------------------------------------------------------------------
/LICENSE.txt:
--------------------------------------------------------------------------------
1 |
2 | Apache License
3 | Version 2.0, January 2004
4 | http://www.apache.org/licenses/
5 |
6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7 |
8 | 1. Definitions.
9 |
10 | "License" shall mean the terms and conditions for use, reproduction,
11 | and distribution as defined by Sections 1 through 9 of this document.
12 |
13 | "Licensor" shall mean the copyright owner or entity authorized by
14 | the copyright owner that is granting the License.
15 |
16 | "Legal Entity" shall mean the union of the acting entity and all
17 | other entities that control, are controlled by, or are under common
18 | control with that entity. For the purposes of this definition,
19 | "control" means (i) the power, direct or indirect, to cause the
20 | direction or management of such entity, whether by contract or
21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
22 | outstanding shares, or (iii) beneficial ownership of such entity.
23 |
24 | "You" (or "Your") shall mean an individual or Legal Entity
25 | exercising permissions granted by this License.
26 |
27 | "Source" form shall mean the preferred form for making modifications,
28 | including but not limited to software source code, documentation
29 | source, and configuration files.
30 |
31 | "Object" form shall mean any form resulting from mechanical
32 | transformation or translation of a Source form, including but
33 | not limited to compiled object code, generated documentation,
34 | and conversions to other media types.
35 |
36 | "Work" shall mean the work of authorship, whether in Source or
37 | Object form, made available under the License, as indicated by a
38 | copyright notice that is included in or attached to the work
39 | (an example is provided in the Appendix below).
40 |
41 | "Derivative Works" shall mean any work, whether in Source or Object
42 | form, that is based on (or derived from) the Work and for which the
43 | editorial revisions, annotations, elaborations, or other modifications
44 | represent, as a whole, an original work of authorship. For the purposes
45 | of this License, Derivative Works shall not include works that remain
46 | separable from, or merely link (or bind by name) to the interfaces of,
47 | the Work and Derivative Works thereof.
48 |
49 | "Contribution" shall mean any work of authorship, including
50 | the original version of the Work and any modifications or additions
51 | to that Work or Derivative Works thereof, that is intentionally
52 | submitted to Licensor for inclusion in the Work by the copyright owner
53 | or by an individual or Legal Entity authorized to submit on behalf of
54 | the copyright owner. For the purposes of this definition, "submitted"
55 | means any form of electronic, verbal, or written communication sent
56 | to the Licensor or its representatives, including but not limited to
57 | communication on electronic mailing lists, source code control systems,
58 | and issue tracking systems that are managed by, or on behalf of, the
59 | Licensor for the purpose of discussing and improving the Work, but
60 | excluding communication that is conspicuously marked or otherwise
61 | designated in writing by the copyright owner as "Not a Contribution."
62 |
63 | "Contributor" shall mean Licensor and any individual or Legal Entity
64 | on behalf of whom a Contribution has been received by Licensor and
65 | subsequently incorporated within the Work.
66 |
67 | 2. Grant of Copyright License. Subject to the terms and conditions of
68 | this License, each Contributor hereby grants to You a perpetual,
69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70 | copyright license to reproduce, prepare Derivative Works of,
71 | publicly display, publicly perform, sublicense, and distribute the
72 | Work and such Derivative Works in Source or Object form.
73 |
74 | 3. Grant of Patent License. Subject to the terms and conditions of
75 | this License, each Contributor hereby grants to You a perpetual,
76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77 | (except as stated in this section) patent license to make, have made,
78 | use, offer to sell, sell, import, and otherwise transfer the Work,
79 | where such license applies only to those patent claims licensable
80 | by such Contributor that are necessarily infringed by their
81 | Contribution(s) alone or by combination of their Contribution(s)
82 | with the Work to which such Contribution(s) was submitted. If You
83 | institute patent litigation against any entity (including a
84 | cross-claim or counterclaim in a lawsuit) alleging that the Work
85 | or a Contribution incorporated within the Work constitutes direct
86 | or contributory patent infringement, then any patent licenses
87 | granted to You under this License for that Work shall terminate
88 | as of the date such litigation is filed.
89 |
90 | 4. Redistribution. You may reproduce and distribute copies of the
91 | Work or Derivative Works thereof in any medium, with or without
92 | modifications, and in Source or Object form, provided that You
93 | meet the following conditions:
94 |
95 | (a) You must give any other recipients of the Work or
96 | Derivative Works a copy of this License; and
97 |
98 | (b) You must cause any modified files to carry prominent notices
99 | stating that You changed the files; and
100 |
101 | (c) You must retain, in the Source form of any Derivative Works
102 | that You distribute, all copyright, patent, trademark, and
103 | attribution notices from the Source form of the Work,
104 | excluding those notices that do not pertain to any part of
105 | the Derivative Works; and
106 |
107 | (d) If the Work includes a "NOTICE" text file as part of its
108 | distribution, then any Derivative Works that You distribute must
109 | include a readable copy of the attribution notices contained
110 | within such NOTICE file, excluding those notices that do not
111 | pertain to any part of the Derivative Works, in at least one
112 | of the following places: within a NOTICE text file distributed
113 | as part of the Derivative Works; within the Source form or
114 | documentation, if provided along with the Derivative Works; or,
115 | within a display generated by the Derivative Works, if and
116 | wherever such third-party notices normally appear. The contents
117 | of the NOTICE file are for informational purposes only and
118 | do not modify the License. You may add Your own attribution
119 | notices within Derivative Works that You distribute, alongside
120 | or as an addendum to the NOTICE text from the Work, provided
121 | that such additional attribution notices cannot be construed
122 | as modifying the License.
123 |
124 | You may add Your own copyright statement to Your modifications and
125 | may provide additional or different license terms and conditions
126 | for use, reproduction, or distribution of Your modifications, or
127 | for any such Derivative Works as a whole, provided Your use,
128 | reproduction, and distribution of the Work otherwise complies with
129 | the conditions stated in this License.
130 |
131 | 5. Submission of Contributions. Unless You explicitly state otherwise,
132 | any Contribution intentionally submitted for inclusion in the Work
133 | by You to the Licensor shall be under the terms and conditions of
134 | this License, without any additional terms or conditions.
135 | Notwithstanding the above, nothing herein shall supersede or modify
136 | the terms of any separate license agreement you may have executed
137 | with Licensor regarding such Contributions.
138 |
139 | 6. Trademarks. This License does not grant permission to use the trade
140 | names, trademarks, service marks, or product names of the Licensor,
141 | except as required for reasonable and customary use in describing the
142 | origin of the Work and reproducing the content of the NOTICE file.
143 |
144 | 7. Disclaimer of Warranty. Unless required by applicable law or
145 | agreed to in writing, Licensor provides the Work (and each
146 | Contributor provides its Contributions) on an "AS IS" BASIS,
147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148 | implied, including, without limitation, any warranties or conditions
149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150 | PARTICULAR PURPOSE. You are solely responsible for determining the
151 | appropriateness of using or redistributing the Work and assume any
152 | risks associated with Your exercise of permissions under this License.
153 |
154 | 8. Limitation of Liability. In no event and under no legal theory,
155 | whether in tort (including negligence), contract, or otherwise,
156 | unless required by applicable law (such as deliberate and grossly
157 | negligent acts) or agreed to in writing, shall any Contributor be
158 | liable to You for damages, including any direct, indirect, special,
159 | incidental, or consequential damages of any character arising as a
160 | result of this License or out of the use or inability to use the
161 | Work (including but not limited to damages for loss of goodwill,
162 | work stoppage, computer failure or malfunction, or any and all
163 | other commercial damages or losses), even if such Contributor
164 | has been advised of the possibility of such damages.
165 |
166 | 9. Accepting Warranty or Additional Liability. While redistributing
167 | the Work or Derivative Works thereof, You may choose to offer,
168 | and charge a fee for, acceptance of support, warranty, indemnity,
169 | or other liability obligations and/or rights consistent with this
170 | License. However, in accepting such obligations, You may act only
171 | on Your own behalf and on Your sole responsibility, not on behalf
172 | of any other Contributor, and only if You agree to indemnify,
173 | defend, and hold each Contributor harmless for any liability
174 | incurred by, or claims asserted against, such Contributor by reason
175 | of your accepting any such warranty or additional liability.
176 |
177 | END OF TERMS AND CONDITIONS
178 |
179 | APPENDIX: How to apply the Apache License to your work.
180 |
181 | To apply the Apache License to your work, attach the following
182 | boilerplate notice, with the fields enclosed by brackets "[]"
183 | replaced with your own identifying information. (Don't include
184 | the brackets!) The text should be enclosed in the appropriate
185 | comment syntax for the file format. We also recommend that a
186 | file or class name and description of purpose be included on the
187 | same "printed page" as the copyright notice for easier
188 | identification within third-party archives.
189 |
190 | Copyright [yyyy] [name of copyright owner]
191 |
192 | Licensed under the Apache License, Version 2.0 (the "License");
193 | you may not use this file except in compliance with the License.
194 | You may obtain a copy of the License at
195 |
196 | http://www.apache.org/licenses/LICENSE-2.0
197 |
198 | Unless required by applicable law or agreed to in writing, software
199 | distributed under the License is distributed on an "AS IS" BASIS,
200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201 | See the License for the specific language governing permissions and
202 | limitations under the License.
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | [Follow to public page for more info](http://darko1002001.github.com/android-rest-client/)
2 |
3 | android-rest-client
4 | ===================
5 |
6 | A simple rest API client library
7 |
8 | Check for the latest version on [Maven Central](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22com.aranea-apps.android.libs%22%20AND%20a%3A%22android-rest%22)
9 |
10 |
11 |
12 | used libraries
13 | ================
14 |
15 | Main Rest client uses OKHTTP from square
16 | https://github.com/square/okhttp
17 |
18 | to provide HTTP layer compatibility across android OS versions and manufacturers
19 |
20 | Additions library uses:
21 |
22 |
23 | com.fasterxml.jackson.core
24 | jackson-core
25 | 2.3.0
26 |
27 |
28 | com.fasterxml.jackson.core
29 | jackson-annotations
30 | 2.3.0
31 |
32 |
33 | com.fasterxml.jackson.core
34 | jackson-databind
35 | 2.3.0
36 |
37 |
38 | commons-io
39 | commons-io
40 | 2.0.1
41 |
42 |
43 |
44 |
45 | Overview
46 | ================
47 |
48 | Can be used to run synchronous or asynchronous requests towards your API.
49 | There is a service class that handles request execution by 2 kinds of thread pools (choice can specified in the request implementation) either a single thread executor or a fixed size executor.
50 | Each of the executors is backed by a priority queue which means each individual request can have an execution priority set.
51 |
52 | You can also provide your own service class which will handle the requests, extend from the current ones etc...
53 |
54 | By default authorization is handled by setting an OAuth token in the header, but can be replaced with a custom implementation.
55 |
56 | Note: The process of getting an oauth token from the server is not a part of this library implementation and have to be set according to the specification for your webservice.
57 |
58 |
59 | Usage:
60 | ======
61 |
62 | Look at the demo project included in this repo for details.
63 |
64 | There is another sample project with an older version of android-rest-client found here:
65 | https://github.com/darko1002001/sync-notes-android
66 |
67 |
68 | ## Steps to setup the library
69 |
70 | 1. Import the lib project into your workspace and add it as a library project
71 | 2. Look into the demo project manifest and copy the definitions
72 | 3. Check the App.java class inside the Demo project on how to configure the library.
73 |
74 |
75 | ## Adding just the JAR files
76 |
77 | The library can be added inside /libs as a JAR. The dependencies include a version of Jackson for parsing JSON requests. you can use the regular jar
78 | and add your own parsers if the responses aren't JSON or you want to use a different library for parsing them.
79 |
80 | ## Manifest Declarations
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 | ## Configuration
91 |
92 | The library needs to be configured in a class extending Application (look into the demo project for specifics).
93 |
94 |
95 | RestClientConfiguration builder = new RestClientConfiguration.ConfigurationBuilder()
96 | .setAuthenticationProvider(new AuthenticationProvider() {
97 | @Override
98 | public void authenticateRequest(RestClientRequest client) {
99 | // YOu can add parameters or headers which will be attached to each request
100 | }
101 | })
102 | .create();
103 |
104 | RestClientConfiguration.init(this, builder);
105 |
106 | ## Note - If including this library with gradle will automatically merge your manifest with the one with the library. The lib is published as AAR.
107 |
108 |
109 | ## Calling requests (From the demo project)
110 |
111 | ```
112 |
113 | //----------------------------------
114 |
115 | TwitterService.getUsersTwitterRequest("android").setCallback(new HttpCallbackImplementation())
116 | .executeAsync();
117 |
118 | //----------------------------------
119 |
120 |
121 | // Callback returning your defined type
122 |
123 | private final class HttpCallbackImplementation implements HttpCallback {
124 |
125 | @Override
126 | public void onSuccess(UserModel responseData, ResponseStatus responseCode) {
127 | textViewResponse.setText(responseData.toString());
128 | }
129 |
130 | @Override
131 | public void onHttpError(ResponseStatus responseCode) {
132 | Toast.makeText(getApplicationContext(),
133 | responseCode.getStatusCode() + " " + responseCode.getStatusMessage(),
134 | Toast.LENGTH_LONG).show();
135 |
136 | }
137 | }
138 | ```
139 |
140 | Two callback methods are created each executing by default in the Android UI Thread so you don't have to implement the logic for switching back to UI from another thread.
141 |
142 |
143 | ## SDK that uses This library:
144 |
145 | Chute
146 | https://github.com/chute/Chute-SDK-V2-Android
147 |
148 |
149 |
150 | ## Use of Authentication Provider
151 |
152 | Look at the demo project to see how the Authentication Provider can be set. Use this if you need to define a custom logic
153 | (Parameters and/or headers that will be appended on each request). You can also specify a provider for individual requests.
154 |
155 |
156 | # Changelog:
157 |
158 | ## Release 2.2.0
159 |
160 | Updated version of OKHTTP to 2.+
161 | Changed the requests to RestClientRequest.class which handles all the request types.
162 | Added the option to run requests without a parser or a callback
163 | The callback can be set externally when creating the request
164 |
165 | ## Release 1.7.0
166 |
167 | Added RestClientConfiguration so all the global configuration is done through it.
168 |
169 | ## Release 1.6.0
170 |
171 | ### Breaking changes
172 |
173 | Added response status to success callback implementation
174 |
175 | ## Release 1.4.0
176 |
177 | Created a new project additions which now has some helper libraries and classes such as Jackson JSON parser, IOUtils from apache etc...
178 | Moved the async part (Service with executors) of the library to a new more general project on github not specific to just HTTP.
179 | HttpRequestStore.init(context) is now replaced with AsyncRunners.init(context) which will provide a wrapping layer around the code that should be initialized in the App class
180 | HttpRequest now extends Runnable interface
181 | Added the option to override a handleStatus method in BaseHttpRequestImpl to be able to do custom result handing based on the status (see demo for sample)
182 |
183 | ## Release 1.3.5
184 |
185 | Fix issue with add param with token provider
186 | Added socket timeout and connection timeout setters by calling `getClient().set...` inside any of the request classes.
187 |
188 | ## Release 1.3.0
189 |
190 | Added Entity body requests which are now the base class for the String body request.
191 | Opens options to add FileEntity body which enables you to upload streams from files.
192 | File Requests also include a progress listener which you can set if you want to track the progress.
193 | Added File Parser which save the response stream to a specified file location.
194 |
195 | ## Release 1.1.0
196 | Reworked the HttpRequestParser to return an InputStream instead of a String.
197 | Use StringResponseParser (extend or use directly) to get the input stream into a String
198 |
--------------------------------------------------------------------------------
/android-rest-client.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
--------------------------------------------------------------------------------
/android-rest-lib-additions/.classpath:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
--------------------------------------------------------------------------------
/android-rest-lib-additions/.gitignore:
--------------------------------------------------------------------------------
1 | # built application files
2 | *.apk
3 | *.ap_
4 |
5 | # files for the dex VM
6 | *.dex
7 |
8 | # Java class files
9 | *.class
10 |
11 | # generated files
12 | bin/
13 | gen/
14 |
15 | # Local configuration file (sdk path, etc)
16 | local.properties
17 | .idea
18 | build/
--------------------------------------------------------------------------------
/android-rest-lib-additions/.project:
--------------------------------------------------------------------------------
1 |
2 |
3 | android-rest-lib
4 |
5 |
6 |
7 |
8 |
9 | org.eclipse.jdt.core.javabuilder
10 |
11 |
12 |
13 |
14 | org.eclipse.m2e.core.maven2Builder
15 |
16 |
17 |
18 |
19 |
20 | org.eclipse.m2e.core.maven2Nature
21 | org.eclipse.jdt.core.javanature
22 |
23 |
24 |
--------------------------------------------------------------------------------
/android-rest-lib-additions/.settings/org.eclipse.core.resources.prefs:
--------------------------------------------------------------------------------
1 | eclipse.preferences.version=1
2 | encoding//src/main/java=UTF-8
3 | encoding//src/test/java=UTF-8
4 | encoding/=UTF-8
5 |
--------------------------------------------------------------------------------
/android-rest-lib-additions/.settings/org.eclipse.jdt.core.prefs:
--------------------------------------------------------------------------------
1 | #Thu Mar 29 11:59:14 CEST 2012
2 | eclipse.preferences.version=1
3 | org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
4 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6
5 | org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
6 | org.eclipse.jdt.core.compiler.compliance=1.6
7 | org.eclipse.jdt.core.compiler.debug.lineNumber=generate
8 | org.eclipse.jdt.core.compiler.debug.localVariable=generate
9 | org.eclipse.jdt.core.compiler.debug.sourceFile=generate
10 | org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
11 | org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
12 | org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning
13 | org.eclipse.jdt.core.compiler.source=1.6
14 |
--------------------------------------------------------------------------------
/android-rest-lib-additions/.settings/org.eclipse.m2e.core.prefs:
--------------------------------------------------------------------------------
1 | #Tue Dec 20 08:35:32 CET 2011
2 | activeProfiles=
3 | eclipse.preferences.version=1
4 | resolveWorkspaceProjects=true
5 | version=1
6 |
--------------------------------------------------------------------------------
/android-rest-lib-additions/android-rest-lib-additions.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 |
101 |
102 |
--------------------------------------------------------------------------------
/android-rest-lib-additions/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.library'
2 |
3 | android {
4 | compileSdkVersion Integer.parseInt(project.ANDROID_BUILD_SDK_VERSION)
5 | buildToolsVersion project.ANDROID_BUILD_TOOLS_VERSION
6 |
7 |
8 | defaultConfig {
9 | targetSdkVersion Integer.parseInt(project.ANDROID_BUILD_TARGET_SDK_VERSION)
10 | minSdkVersion Integer.parseInt(project.ANDROID_MIN_SDK_VERSION)
11 |
12 | buildTypes {
13 | release {
14 | minifyEnabled false
15 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
16 | }
17 | }
18 | }
19 |
20 | }
21 |
22 | dependencies {
23 | compile fileTree(dir: 'libs', include: ['*.jar'])
24 | compile project(":android-rest-lib")
25 | compile 'com.fasterxml.jackson.core:jackson-core:2.4.0'
26 | compile 'com.fasterxml.jackson.core:jackson-annotations:2.4.0'
27 | compile 'com.fasterxml.jackson.core:jackson-databind:2.4.0'
28 | compile 'commons-io:commons-io:2.4'
29 | }
30 | apply from: '../gradle-mvn-push.gradle'
31 |
--------------------------------------------------------------------------------
/android-rest-lib-additions/gradle.properties:
--------------------------------------------------------------------------------
1 | POM_NAME=Rest Client Android - Additions
2 | POM_ARTIFACT_ID=android-rest-additions
3 | PACKAGE_NAME=com.araneaapps.android.libs.androidrest.additions
4 | POM_PACKAGING=aar
--------------------------------------------------------------------------------
/android-rest-lib-additions/pom.xml:
--------------------------------------------------------------------------------
1 |
2 | 4.0.0
3 |
4 |
5 | com.aranea-apps.android.libs
6 | parent
7 | 1.7.1-SNAPSHOT
8 |
9 |
10 |
11 | android-rest-additions
12 | jar
13 | android-rest-lib-additions
14 | The additional parsers and classes for rest-lib
15 |
16 |
17 | The Apache Software License, Version 2.0
18 | http://www.apache.org/licenses/LICENSE-2.0.txt
19 | repo
20 |
21 |
22 |
23 |
24 |
25 | UTF-8
26 |
27 |
28 |
29 | com.aranea-apps.android.libs
30 | android-rest
31 | ${project.version}
32 |
33 |
34 | com.fasterxml.jackson.core
35 | jackson-core
36 | 2.4.0
37 |
38 |
39 | com.fasterxml.jackson.core
40 | jackson-annotations
41 | 2.4.0
42 |
43 |
44 | com.fasterxml.jackson.core
45 | jackson-databind
46 | 2.4.0
47 |
48 |
49 | commons-io
50 | commons-io
51 | 2.4
52 |
53 |
54 |
55 |
56 |
57 | org.apache.maven.plugins
58 | maven-compiler-plugin
59 | 2.3.2
60 |
61 | 1.6
62 | 1.6
63 |
64 |
65 |
66 | org.apache.maven.plugins
67 | maven-shade-plugin
68 | 1.4
69 |
70 |
71 | package
72 |
73 | shade
74 |
75 |
76 |
77 |
78 | ${artifactId}-${version}-with-dependencies
79 |
80 |
81 |
82 | org.apache.maven.plugins
83 | maven-source-plugin
84 |
85 |
86 | attach-sources
87 |
88 | jar
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
--------------------------------------------------------------------------------
/android-rest-lib-additions/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
4 |
5 |
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/android-rest-lib-additions/src/main/java/com/dg/libs/rest/parsers/BaseJacksonMapperResponseParser.java:
--------------------------------------------------------------------------------
1 | package com.dg.libs.rest.parsers;
2 |
3 | import com.fasterxml.jackson.databind.DeserializationFeature;
4 | import com.fasterxml.jackson.databind.ObjectMapper;
5 | import com.fasterxml.jackson.databind.SerializationFeature;
6 |
7 | public abstract class BaseJacksonMapperResponseParser implements HttpResponseParser {
8 |
9 | public static final String TAG = BaseJacksonMapperResponseParser.class.getSimpleName();
10 |
11 | public static ObjectMapper mapper = new ObjectMapper();
12 |
13 | static {
14 | mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
15 | mapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);
16 | mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true);
17 | mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
18 | }
19 |
20 | }
21 |
--------------------------------------------------------------------------------
/android-rest-lib-additions/src/main/java/com/dg/libs/rest/parsers/FileHttpResponseParser.java:
--------------------------------------------------------------------------------
1 | package com.dg.libs.rest.parsers;
2 |
3 | import org.apache.commons.io.IOUtils;
4 |
5 | import java.io.File;
6 | import java.io.FileOutputStream;
7 | import java.io.InputStream;
8 |
9 | public abstract class FileHttpResponseParser implements HttpResponseParser {
10 |
11 | private File outputFile;
12 |
13 | public FileHttpResponseParser(File outputFile) {
14 | super();
15 | this.outputFile = outputFile;
16 | }
17 |
18 | @Override
19 | public File parse(final InputStream responseStream) throws Exception {
20 | FileOutputStream outputStream = new FileOutputStream(outputFile);
21 | IOUtils.copy(responseStream, outputStream);
22 | return outputFile;
23 | }
24 |
25 | }
26 |
--------------------------------------------------------------------------------
/android-rest-lib-additions/src/main/java/com/dg/libs/rest/parsers/StringHttpResponseParser.java:
--------------------------------------------------------------------------------
1 | package com.dg.libs.rest.parsers;
2 |
3 | import org.apache.commons.io.IOUtils;
4 |
5 | import java.io.InputStream;
6 |
7 | /**
8 | * The {@link HttpResponseParser} interface has the responsibility to parse
9 | * responses from the server.
10 | *
11 | * @param
12 | * Parameter that indicates which object the parser returns. It can be
13 | * of any type.
14 | */
15 | public abstract class StringHttpResponseParser implements HttpResponseParser {
16 |
17 | /**
18 | * Do not override this method. Use the **abstract** {@link #parse(String)}
19 | *
20 | * This method is used for parsing text from the server. can be used for
21 | * anything that can be converted out of a string
22 | *
23 | * @param responseStream
24 | * The JSON string needed for parsing.
25 | * @return Object of any type returned by the parser.
26 | * @throws Exception
27 | * Thrown when various parsing errors occur.
28 | */
29 | @Override
30 | public T parse(final InputStream responseStream) throws Exception {
31 | return parse(IOUtils.toString(responseStream));
32 | }
33 |
34 | public abstract T parse(final String response) throws Exception;
35 | }
36 |
--------------------------------------------------------------------------------
/android-rest-lib/.classpath:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
--------------------------------------------------------------------------------
/android-rest-lib/.gitignore:
--------------------------------------------------------------------------------
1 | # built application files
2 | *.apk
3 | *.ap_
4 |
5 | # files for the dex VM
6 | *.dex
7 |
8 | # Java class files
9 | *.class
10 |
11 | # generated files
12 | bin/
13 | gen/
14 |
15 | # Local configuration file (sdk path, etc)
16 | local.properties
17 | .idea
18 | build/
--------------------------------------------------------------------------------
/android-rest-lib/.project:
--------------------------------------------------------------------------------
1 |
2 |
3 | android-rest-lib
4 |
5 |
6 |
7 |
8 |
9 | org.eclipse.jdt.core.javabuilder
10 |
11 |
12 |
13 |
14 | org.eclipse.m2e.core.maven2Builder
15 |
16 |
17 |
18 |
19 |
20 | org.eclipse.m2e.core.maven2Nature
21 | org.eclipse.jdt.core.javanature
22 |
23 |
24 |
--------------------------------------------------------------------------------
/android-rest-lib/.settings/org.eclipse.core.resources.prefs:
--------------------------------------------------------------------------------
1 | eclipse.preferences.version=1
2 | encoding//src/main/java=UTF-8
3 | encoding//src/test/java=UTF-8
4 | encoding/=UTF-8
5 |
--------------------------------------------------------------------------------
/android-rest-lib/.settings/org.eclipse.jdt.core.prefs:
--------------------------------------------------------------------------------
1 | #Thu Mar 29 11:59:14 CEST 2012
2 | eclipse.preferences.version=1
3 | org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
4 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6
5 | org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
6 | org.eclipse.jdt.core.compiler.compliance=1.6
7 | org.eclipse.jdt.core.compiler.debug.lineNumber=generate
8 | org.eclipse.jdt.core.compiler.debug.localVariable=generate
9 | org.eclipse.jdt.core.compiler.debug.sourceFile=generate
10 | org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
11 | org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
12 | org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning
13 | org.eclipse.jdt.core.compiler.source=1.6
14 |
--------------------------------------------------------------------------------
/android-rest-lib/.settings/org.eclipse.m2e.core.prefs:
--------------------------------------------------------------------------------
1 | #Tue Dec 20 08:35:32 CET 2011
2 | activeProfiles=
3 | eclipse.preferences.version=1
4 | resolveWorkspaceProjects=true
5 | version=1
6 |
--------------------------------------------------------------------------------
/android-rest-lib/android-rest-lib.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
--------------------------------------------------------------------------------
/android-rest-lib/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.library'
2 |
3 | android {
4 | compileSdkVersion Integer.parseInt(project.ANDROID_BUILD_SDK_VERSION)
5 | buildToolsVersion project.ANDROID_BUILD_TOOLS_VERSION
6 |
7 | defaultConfig {
8 | targetSdkVersion Integer.parseInt(project.ANDROID_BUILD_TARGET_SDK_VERSION)
9 | minSdkVersion Integer.parseInt(project.ANDROID_MIN_SDK_VERSION)
10 |
11 | buildTypes {
12 | release {
13 | minifyEnabled false
14 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
15 | }
16 | }
17 | }
18 | }
19 |
20 | dependencies {
21 | compile fileTree(dir: 'libs', include: ['*.jar'])
22 | compile 'com.squareup.okhttp:okhttp:2.3.0'
23 | compile 'com.squareup.okhttp:okhttp-apache:2.3.0'
24 | compile 'com.aranea-apps.android.libs:android-async-runners:1.0.4'
25 | androidTestCompile 'junit:junit:3.8.1'
26 | }
27 | apply from: '../gradle-mvn-push.gradle'
28 |
--------------------------------------------------------------------------------
/android-rest-lib/gradle.properties:
--------------------------------------------------------------------------------
1 | POM_NAME=Rest Client Android
2 | POM_ARTIFACT_ID=android-rest
3 | POM_PACKAGING=aar
4 | PACKAGE_NAME=com.araneaapps.android.libs.androidrest
--------------------------------------------------------------------------------
/android-rest-lib/pom.xml:
--------------------------------------------------------------------------------
1 |
2 | 4.0.0
3 |
4 |
5 | com.aranea-apps.android.libs
6 | parent
7 | 1.7.1-SNAPSHOT
8 |
9 |
10 |
11 | android-rest
12 | jar
13 | android-rest-lib
14 | This is a library for android for Making RestFul Requests
15 |
16 |
17 | The Apache Software License, Version 2.0
18 | http://www.apache.org/licenses/LICENSE-2.0.txt
19 | repo
20 |
21 |
22 |
23 | UTF-8
24 |
25 |
26 |
27 | junit
28 | junit
29 | 3.8.1
30 | test
31 |
32 |
33 | com.google.android
34 | android
35 | 2.2.1
36 | provided
37 |
38 |
39 | com.squareup.okhttp
40 | okhttp
41 | 1.6.0
42 |
43 |
44 | com.aranea-apps.android.libs
45 | android-logger
46 | 1.0.10
47 | jar
48 |
49 |
50 | com.aranea-apps.android.libs
51 | android-async-runners
52 | 1.0.1
53 | jar
54 |
55 |
56 |
57 |
58 |
59 | org.apache.maven.plugins
60 | maven-compiler-plugin
61 | 2.3.2
62 |
63 | 1.6
64 | 1.6
65 |
66 |
67 |
68 | org.apache.maven.plugins
69 | maven-shade-plugin
70 | 1.4
71 |
72 |
73 | package
74 |
75 | shade
76 |
77 |
78 |
79 |
80 | ${artifactId}-${version}-with-dependencies
81 |
82 |
83 |
84 | org.apache.maven.plugins
85 | maven-source-plugin
86 |
87 |
88 | attach-sources
89 |
90 | jar
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 |
--------------------------------------------------------------------------------
/android-rest-lib/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 /Applications/Android Studio.app/sdk/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
12 | # If your project uses WebView with JS, uncomment the following
13 | # and specify the fully qualified class name to the JavaScript interface
14 | # class:
15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
16 | # public *;
17 | #}
18 |
--------------------------------------------------------------------------------
/android-rest-lib/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
4 |
5 |
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/android-rest-lib/src/main/java/com/dg/libs/rest/HttpRequest.java:
--------------------------------------------------------------------------------
1 | package com.dg.libs.rest;
2 |
3 | /**
4 | * @author darko.grozdanovski The {@link HttpRequest} interface has the
5 | * responsibility to send a request object to the server which is used
6 | * for data exchange with the server behind the scenes. It contains
7 | * methods that run in threads.
8 | */
9 | public interface HttpRequest extends Runnable {
10 |
11 | /**
12 | * This method runs asynchronously in the same thread as the application and
13 | * launches a service for further server communication.
14 | */
15 | void executeAsync();
16 |
17 | /**
18 | * Calling this method will prevent the callback to be executed. Good for avoiding memory leaks if you bind callbacks with views that are a part of a
19 | * lifecycle of an activity or fragment.
20 | */
21 | void cancel();
22 |
23 | }
24 |
--------------------------------------------------------------------------------
/android-rest-lib/src/main/java/com/dg/libs/rest/RestClientConfiguration.java:
--------------------------------------------------------------------------------
1 | package com.dg.libs.rest;
2 |
3 | import android.content.Context;
4 |
5 | import com.araneaapps.android.libs.asyncrunners.models.AsyncRunners;
6 | import com.dg.libs.rest.authentication.AuthenticationProvider;
7 |
8 | public class RestClientConfiguration {
9 |
10 | private static Context applicationContext;
11 | private AuthenticationProvider authenticationProvider;
12 | int connectionTimeout;
13 | int readTimeout;
14 | int writeTimeout;
15 |
16 | private RestClientConfiguration(AuthenticationProvider authenticationProvider, int connectionTimeout, int readTimeout, int writeTimeout) {
17 | this.authenticationProvider = authenticationProvider;
18 | this.connectionTimeout = connectionTimeout;
19 | this.readTimeout = readTimeout;
20 | this.writeTimeout = writeTimeout;
21 | }
22 |
23 | private static RestClientConfiguration generateDefaultConfig() {
24 | return new ConfigurationBuilder().create();
25 | }
26 |
27 | private static RestClientConfiguration instance;
28 |
29 | public static void init(Context context) {
30 | applicationContext = context.getApplicationContext();
31 | AsyncRunners.init(applicationContext);
32 | instance = generateDefaultConfig();
33 | }
34 |
35 | public static void init(Context context, RestClientConfiguration restClientConfiguration) {
36 | applicationContext = context.getApplicationContext();
37 | AsyncRunners.init(applicationContext);
38 | instance = restClientConfiguration;
39 | }
40 |
41 | public static RestClientConfiguration get() {
42 | if (instance == null) {
43 | throw new IllegalStateException("You need to call Init on " + RestClientConfiguration.class + " First. Do it in your class extending application");
44 | }
45 | return instance;
46 | }
47 |
48 |
49 | public AuthenticationProvider getAuthenticationProvider() {
50 | return authenticationProvider;
51 | }
52 |
53 | public int getConnectionTimeout() {
54 | return connectionTimeout;
55 | }
56 |
57 | public int getReadTimeout() {
58 | return readTimeout;
59 | }
60 |
61 | public int getWriteTimeout() {
62 | return writeTimeout;
63 | }
64 |
65 | public Context getContext() {
66 | return applicationContext;
67 | }
68 |
69 | public static class ConfigurationBuilder {
70 | private AuthenticationProvider authenticationProvider;
71 | private int connectionTimeout = 10000;
72 | private int readTimeout = 20000;
73 | private int writeTimeout = 20000;
74 |
75 | public ConfigurationBuilder setAuthenticationProvider(AuthenticationProvider authenticationProvider) {
76 | this.authenticationProvider = authenticationProvider;
77 | return this;
78 | }
79 |
80 | public ConfigurationBuilder setConnectionTimeout(int connectionTimeout) {
81 | this.connectionTimeout = connectionTimeout;
82 | return this;
83 | }
84 |
85 | public ConfigurationBuilder setReadTimeout(int readTimeout) {
86 | this.readTimeout = readTimeout;
87 | return this;
88 | }
89 |
90 | public ConfigurationBuilder setWriteTimeout(int writeTimeout) {
91 | this.writeTimeout = writeTimeout;
92 | return this;
93 | }
94 |
95 | public RestClientConfiguration create() {
96 | return new RestClientConfiguration(authenticationProvider, connectionTimeout, readTimeout, writeTimeout);
97 | }
98 | }
99 | }
100 |
--------------------------------------------------------------------------------
/android-rest-lib/src/main/java/com/dg/libs/rest/authentication/AuthenticationProvider.java:
--------------------------------------------------------------------------------
1 | package com.dg.libs.rest.authentication;
2 |
3 | import com.dg.libs.rest.requests.RestClientRequest;
4 |
5 | public interface AuthenticationProvider {
6 |
7 | public void authenticateRequest(RestClientRequest restClientRequest);
8 | }
9 |
--------------------------------------------------------------------------------
/android-rest-lib/src/main/java/com/dg/libs/rest/callbacks/ActivityBoundHttpCallback.java:
--------------------------------------------------------------------------------
1 | package com.dg.libs.rest.callbacks;
2 |
3 | import android.app.Activity;
4 |
5 | import java.lang.ref.WeakReference;
6 |
7 | public class ActivityBoundHttpCallback extends BoundCallback {
8 |
9 | private static final String TAG = ActivityBoundHttpCallback.class.getSimpleName();
10 | WeakReference activityWeakReference;
11 |
12 | public ActivityBoundHttpCallback(Activity activity, HttpCallback callback) {
13 | super(callback);
14 | this.activityWeakReference = new WeakReference<>(activity);
15 | }
16 |
17 | @Override
18 | public boolean isRegistered() {
19 | Activity activity = activityWeakReference.get();
20 | return activity != null && activity.isFinishing() == false;
21 | }
22 |
23 | }
24 |
--------------------------------------------------------------------------------
/android-rest-lib/src/main/java/com/dg/libs/rest/callbacks/BoundCallback.java:
--------------------------------------------------------------------------------
1 | package com.dg.libs.rest.callbacks;
2 |
3 | import android.util.Log;
4 |
5 | import com.dg.libs.rest.domain.ResponseStatus;
6 |
7 | public class BoundCallback implements HttpCallback {
8 |
9 | private static final String TAG = BoundCallback.class.getSimpleName();
10 | private HttpCallback callback;
11 | private boolean isRegistered = true;
12 |
13 | public BoundCallback(HttpCallback callback) {
14 | this.callback = callback;
15 | }
16 |
17 | public void unregister() {
18 | isRegistered = false;
19 | }
20 |
21 | public boolean isRegistered() {
22 | return isRegistered;
23 | }
24 |
25 | @Override
26 | public void onSuccess(T responseData, ResponseStatus responseStatus) {
27 | if (isRegistered) {
28 | callback.onSuccess(responseData, responseStatus);
29 | } else {
30 | Log.d(TAG, "callback is unregistered, wont be called");
31 | }
32 | }
33 |
34 | @Override
35 | public void onHttpError(ResponseStatus responseStatus) {
36 | if (isRegistered) {
37 | callback.onHttpError(responseStatus);
38 | } else {
39 | Log.d(TAG, "callback is unregistered, wont be called");
40 | }
41 | }
42 |
43 | }
44 |
--------------------------------------------------------------------------------
/android-rest-lib/src/main/java/com/dg/libs/rest/callbacks/FragmentBoundHttpCallback.java:
--------------------------------------------------------------------------------
1 | package com.dg.libs.rest.callbacks;
2 |
3 | import android.annotation.TargetApi;
4 | import android.app.Fragment;
5 | import android.os.Build;
6 |
7 | import java.lang.ref.WeakReference;
8 |
9 | public class FragmentBoundHttpCallback extends BoundCallback {
10 |
11 | private static final String TAG = FragmentBoundHttpCallback.class.getSimpleName();
12 | WeakReference fragmentWeakReference;
13 |
14 | public FragmentBoundHttpCallback(Fragment fragment, HttpCallback callback) {
15 | super(callback);
16 | this.fragmentWeakReference = new WeakReference<>(fragment);
17 | }
18 |
19 | @TargetApi(Build.VERSION_CODES.HONEYCOMB)
20 | @Override
21 | public boolean isRegistered() {
22 | Fragment fragment = fragmentWeakReference.get();
23 | return fragment != null && fragment.isAdded() && fragment.isInLayout();
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/android-rest-lib/src/main/java/com/dg/libs/rest/callbacks/HttpCallback.java:
--------------------------------------------------------------------------------
1 | package com.dg.libs.rest.callbacks;
2 |
3 | import com.dg.libs.rest.domain.ResponseStatus;
4 |
5 | /**
6 | * The {@link HttpCallback} interface is used for HTTP request notification. It
7 | * contains methods that describe the error if the callback fails and return
8 | * response data if the callback succeeds.
9 | *
10 | * @param
11 | * Parameter that indicates which object the callback returns. It can
12 | * be of any type.
13 | */
14 | public interface HttpCallback {
15 |
16 | /**
17 | * This method shows that the callback successfully finished. It contains
18 | * response data which represents the return type of the callback.
19 | *
20 | * @param responseData
21 | * It can be of any type.
22 | */
23 | void onSuccess(T responseData, ResponseStatus responseStatus);
24 |
25 | /**
26 | * This method shows that the callback has failed due to server issue, no
27 | * connectivity or parser error
28 | *
29 | * @param responseStatus
30 | */
31 | void onHttpError(ResponseStatus responseStatus);
32 |
33 | }
34 |
--------------------------------------------------------------------------------
/android-rest-lib/src/main/java/com/dg/libs/rest/client/RequestMethod.java:
--------------------------------------------------------------------------------
1 | package com.dg.libs.rest.client;
2 |
3 | public enum RequestMethod {
4 | GET, POST, PUT, PATCH, DELETE;
5 | }
6 |
--------------------------------------------------------------------------------
/android-rest-lib/src/main/java/com/dg/libs/rest/domain/ResponseStatus.java:
--------------------------------------------------------------------------------
1 | package com.dg.libs.rest.domain;
2 |
3 | import org.apache.http.HttpStatus;
4 |
5 | public class ResponseStatus {
6 |
7 | public static final String TAG = ResponseStatus.class.getSimpleName();
8 |
9 | private int statusCode;
10 | private String statusMessage;
11 |
12 | public ResponseStatus(int statusCode, String statusMessage) {
13 | this.statusCode = statusCode;
14 | this.statusMessage = statusMessage;
15 | }
16 |
17 | public ResponseStatus() {
18 | }
19 |
20 | public int getStatusCode() {
21 | return statusCode;
22 | }
23 |
24 | public void setStatusCode(int statusCode) {
25 | this.statusCode = statusCode;
26 | }
27 |
28 | public String getStatusMessage() {
29 | return statusMessage;
30 | }
31 |
32 | public void setStatusMessage(String statusMessage) {
33 | this.statusMessage = statusMessage;
34 | }
35 |
36 | public static ResponseStatus getConnectionErrorStatus() {
37 | ResponseStatus status = new ResponseStatus();
38 | status.setStatusCode(HttpStatus.SC_REQUEST_TIMEOUT);
39 | status.setStatusMessage("HTTP Connection Error");
40 | return status;
41 | }
42 |
43 | public static ResponseStatus getParseErrorStatus() {
44 | ResponseStatus status = new ResponseStatus();
45 | status.setStatusCode(HttpStatus.SC_BAD_REQUEST);
46 | status.setStatusMessage("Parser Error");
47 | return status;
48 | }
49 |
50 | @Override
51 | public String toString() {
52 | StringBuilder builder = new StringBuilder();
53 | builder.append("ResponseStatus [statusCode=");
54 | builder.append(statusCode);
55 | builder.append(", statusMessage=");
56 | builder.append(statusMessage);
57 | builder.append("]");
58 | return builder.toString();
59 | }
60 |
61 | }
62 |
--------------------------------------------------------------------------------
/android-rest-lib/src/main/java/com/dg/libs/rest/entities/CountingInputStreamEntity.java:
--------------------------------------------------------------------------------
1 | package com.dg.libs.rest.entities;
2 |
3 | import java.io.IOException;
4 | import java.io.InputStream;
5 | import java.io.OutputStream;
6 |
7 | import org.apache.http.entity.InputStreamEntity;
8 |
9 | public class CountingInputStreamEntity extends InputStreamEntity {
10 |
11 | public interface UploadListener {
12 |
13 | public void onChange(long current);
14 | }
15 |
16 | private UploadListener listener;
17 |
18 | public CountingInputStreamEntity(final InputStream instream, final long length) {
19 | super(instream, length);
20 | }
21 |
22 | public void setUploadListener(final UploadListener listener) {
23 | this.listener = listener;
24 | }
25 |
26 | @Override
27 | public void writeTo(final OutputStream outstream) throws IOException {
28 | super.writeTo(new CountingOutputStream(outstream));
29 | }
30 |
31 | class CountingOutputStream extends OutputStream {
32 |
33 | private long counter = 0L;
34 | private final OutputStream outputStream;
35 |
36 | public CountingOutputStream(final OutputStream outputStream) {
37 | this.outputStream = outputStream;
38 | }
39 |
40 | @Override
41 | public void write(final byte[] buffer, final int offset, final int count)
42 | throws IOException {
43 | this.outputStream.write(buffer, offset, count);
44 | this.counter += count;
45 | if (listener != null) {
46 | listener.onChange(counter);
47 | }
48 | }
49 |
50 | @Override
51 | public void write(final int oneByte) throws IOException {
52 | this.outputStream.write(oneByte);
53 | counter++;
54 | if (listener != null) {
55 | // int percent = (int) ((counter * 100) / length);
56 | listener.onChange(counter);
57 | }
58 | }
59 | }
60 |
61 | }
62 |
--------------------------------------------------------------------------------
/android-rest-lib/src/main/java/com/dg/libs/rest/entities/UnicodeBOMInputStream.java:
--------------------------------------------------------------------------------
1 | package com.dg.libs.rest.entities;
2 |
3 | /* ____________________________________________________________________________
4 | *
5 | * File: UnicodeBOMInputStream.java
6 | * Author: Gregory Pakosz.
7 | * Date: 02 - November - 2005
8 | * ____________________________________________________________________________
9 | */
10 |
11 | import java.io.IOException;
12 | import java.io.InputStream;
13 | import java.io.PushbackInputStream;
14 |
15 | /**
16 | * The UnicodeBOMInputStream class wraps any
17 | * InputStream and detects the presence of any Unicode BOM (Byte
18 | * Order Mark) at its beginning, as defined by RFC 3629 - UTF-8, a
20 | * transformation format of ISO 10646
21 | *
22 | *
23 | * The Unicode FAQ
24 | * defines 5 types of BOMs:
25 | *
26 | *
27 | *
28 | *
29 | * 00 00 FE FF = UTF-32, big-endian
30 | *
31 | *
32 | *
33 | *
34 | *
35 | *
36 | * FF FE 00 00 = UTF-32, little-endian
37 | *
38 | *
39 | *
40 | *
41 | *
42 | *
43 | * FE FF = UTF-16, big-endian
44 | *
45 | *
46 | *
47 | *
48 | *
49 | *
50 | * FF FE = UTF-16, little-endian
51 | *
52 | *
53 | *
54 | *
55 | *
56 | *
57 | * EF BB BF = UTF-8
58 | *
59 | *
60 | *
61 | *
62 | *
63 | *
64 | *
65 | * Use the {@link #getBOM()} method to know whether a BOM has been detected or
66 | * not.
67 | *
68 | *
69 | * Use the {@link #skipBOM()} method to remove the detected BOM from the wrapped
70 | * InputStream object.
71 | *
72 | */
73 | public class UnicodeBOMInputStream extends InputStream {
74 |
75 | /**
76 | * Type safe enumeration class that describes the different types of Unicode
77 | * BOMs.
78 | */
79 | public static final class BOM {
80 |
81 | /**
82 | * NONE.
83 | */
84 | public static final BOM NONE = new BOM(new byte[] {}, "NONE");
85 |
86 | /**
87 | * UTF-8 BOM (EF BB BF).
88 | */
89 | public static final BOM UTF_8 = new BOM(
90 | new byte[] { (byte) 0xEF, (byte) 0xBB, (byte) 0xBF }, "UTF-8");
91 |
92 | /**
93 | * UTF-16, little-endian (FF FE).
94 | */
95 | public static final BOM UTF_16_LE = new BOM(new byte[] { (byte) 0xFF, (byte) 0xFE },
96 | "UTF-16 little-endian");
97 |
98 | /**
99 | * UTF-16, big-endian (FE FF).
100 | */
101 | public static final BOM UTF_16_BE = new BOM(new byte[] { (byte) 0xFE, (byte) 0xFF },
102 | "UTF-16 big-endian");
103 |
104 | /**
105 | * UTF-32, little-endian (FF FE 00 00).
106 | */
107 | public static final BOM UTF_32_LE = new BOM(new byte[] { (byte) 0xFF, (byte) 0xFE,
108 | (byte) 0x00, (byte) 0x00 }, "UTF-32 little-endian");
109 |
110 | /**
111 | * UTF-32, big-endian (00 00 FE FF).
112 | */
113 | public static final BOM UTF_32_BE = new BOM(new byte[] { (byte) 0x00, (byte) 0x00,
114 | (byte) 0xFE, (byte) 0xFF }, "UTF-32 big-endian");
115 |
116 | /**
117 | * Returns a String representation of this BOM
118 | * value.
119 | */
120 | @Override
121 | public final String toString() {
122 | return description;
123 | }
124 |
125 | /**
126 | * Returns the bytes corresponding to this BOM value.
127 | */
128 | public final byte[] getBytes() {
129 | final int length = bytes.length;
130 | final byte[] result = new byte[length];
131 |
132 | // Make a defensive copy
133 | System.arraycopy(bytes, 0, result, 0, length);
134 |
135 | return result;
136 | }
137 |
138 | private BOM(final byte bom[], final String description) {
139 | assert (bom != null) : "invalid BOM: null is not allowed";
140 | assert (description != null) : "invalid description: null is not allowed";
141 | assert (description.length() != 0) : "invalid description: empty string is not allowed";
142 |
143 | this.bytes = bom;
144 | this.description = description;
145 | }
146 |
147 | final byte bytes[];
148 | private final String description;
149 |
150 | } // BOM
151 |
152 | /**
153 | * Constructs a new UnicodeBOMInputStream that wraps the
154 | * specified InputStream.
155 | *
156 | * @param inputStream
157 | * an InputStream.
158 | *
159 | * @throws NullPointerException
160 | * when inputStream is null.
161 | * @throws IOException
162 | * on reading from the specified InputStream when
163 | * trying to detect the Unicode BOM.
164 | */
165 | public UnicodeBOMInputStream(final InputStream inputStream)
166 | throws NullPointerException,
167 | IOException
168 |
169 | {
170 | if (inputStream == null) {
171 | throw new NullPointerException("invalid input stream: null is not allowed");
172 | }
173 |
174 | in = new PushbackInputStream(inputStream, 4);
175 |
176 | final byte bom[] = new byte[4];
177 | final int read = in.read(bom);
178 |
179 | switch (read) {
180 | case 4:
181 | if ((bom[0] == (byte) 0xFF) && (bom[1] == (byte) 0xFE) && (bom[2] == (byte) 0x00)
182 | && (bom[3] == (byte) 0x00)) {
183 | this.bom = BOM.UTF_32_LE;
184 | break;
185 | } else if ((bom[0] == (byte) 0x00) && (bom[1] == (byte) 0x00)
186 | && (bom[2] == (byte) 0xFE) && (bom[3] == (byte) 0xFF)) {
187 | this.bom = BOM.UTF_32_BE;
188 | break;
189 | }
190 |
191 | case 3:
192 | if ((bom[0] == (byte) 0xEF) && (bom[1] == (byte) 0xBB) && (bom[2] == (byte) 0xBF)) {
193 | this.bom = BOM.UTF_8;
194 | break;
195 | }
196 |
197 | case 2:
198 | if ((bom[0] == (byte) 0xFF) && (bom[1] == (byte) 0xFE)) {
199 | this.bom = BOM.UTF_16_LE;
200 | break;
201 | } else if ((bom[0] == (byte) 0xFE) && (bom[1] == (byte) 0xFF)) {
202 | this.bom = BOM.UTF_16_BE;
203 | break;
204 | }
205 |
206 | default:
207 | this.bom = BOM.NONE;
208 | break;
209 | }
210 |
211 | if (read > 0) {
212 | in.unread(bom, 0, read);
213 | }
214 | }
215 |
216 | /**
217 | * Returns the BOM that was detected in the wrapped
218 | * InputStream object.
219 | *
220 | * @return a BOM value.
221 | */
222 | public final BOM getBOM() {
223 | // BOM type is immutable.
224 | return bom;
225 | }
226 |
227 | /**
228 | * Skips the BOM that was found in the wrapped
229 | * InputStream object.
230 | *
231 | * @return this UnicodeBOMInputStream.
232 | *
233 | * @throws IOException
234 | * when trying to skip the BOM from the wrapped
235 | * InputStream object.
236 | */
237 | public final synchronized UnicodeBOMInputStream skipBOM() throws IOException {
238 | if (!skipped) {
239 | in.skip(bom.bytes.length);
240 | skipped = true;
241 | }
242 | return this;
243 | }
244 |
245 | /**
246 | * {@inheritDoc}
247 | */
248 | @Override
249 | public int read() throws IOException {
250 | return in.read();
251 | }
252 |
253 | /**
254 | * {@inheritDoc}
255 | */
256 | @Override
257 | public int read(final byte b[]) throws IOException, NullPointerException {
258 | return in.read(b, 0, b.length);
259 | }
260 |
261 | /**
262 | * {@inheritDoc}
263 | */
264 | @Override
265 | public int read(final byte b[], final int off, final int len) throws IOException,
266 | NullPointerException {
267 | return in.read(b, off, len);
268 | }
269 |
270 | /**
271 | * {@inheritDoc}
272 | */
273 | @Override
274 | public long skip(final long n) throws IOException {
275 | return in.skip(n);
276 | }
277 |
278 | /**
279 | * {@inheritDoc}
280 | */
281 | @Override
282 | public int available() throws IOException {
283 | return in.available();
284 | }
285 |
286 | /**
287 | * {@inheritDoc}
288 | */
289 | @Override
290 | public void close() throws IOException {
291 | in.close();
292 | }
293 |
294 | /**
295 | * {@inheritDoc}
296 | */
297 | @Override
298 | public synchronized void mark(final int readlimit) {
299 | in.mark(readlimit);
300 | }
301 |
302 | /**
303 | * {@inheritDoc}
304 | */
305 | @Override
306 | public synchronized void reset() throws IOException {
307 | in.reset();
308 | }
309 |
310 | /**
311 | * {@inheritDoc}
312 | */
313 | @Override
314 | public boolean markSupported() {
315 | return in.markSupported();
316 | }
317 |
318 | private final PushbackInputStream in;
319 | private final BOM bom;
320 | private boolean skipped = false;
321 |
322 | } // UnicodeBOMInputStream
--------------------------------------------------------------------------------
/android-rest-lib/src/main/java/com/dg/libs/rest/exceptions/HttpException.java:
--------------------------------------------------------------------------------
1 | package com.dg.libs.rest.exceptions;
2 |
3 | /**
4 | * usually represents a general error for the whole api call, if you need to
5 | * know if the parsing failed check the status of the response and the error
6 | * message ( if status is SC_OK means the api call was successful and there was
7 | * a parsing error).
8 | *
9 | * @author DArkO
10 | */
11 | public class HttpException extends Exception {
12 |
13 | private static final long serialVersionUID = -120498658240098246L;
14 | @SuppressWarnings("unused")
15 | private static final String TAG = HttpException.class.getSimpleName();
16 |
17 | public HttpException() {
18 | super();
19 | }
20 |
21 | public HttpException(final String detailMessage, final Throwable throwable) {
22 | super(detailMessage, throwable);
23 | }
24 |
25 | public HttpException(final String detailMessage) {
26 | super(detailMessage);
27 | }
28 |
29 | public HttpException(final Throwable throwable) {
30 | super(throwable);
31 | }
32 |
33 | }
34 |
--------------------------------------------------------------------------------
/android-rest-lib/src/main/java/com/dg/libs/rest/exceptions/ParseException.java:
--------------------------------------------------------------------------------
1 | package com.dg.libs.rest.exceptions;
2 |
3 | public class ParseException extends HttpException {
4 |
5 | private static final long serialVersionUID = -7964127989566422126L;
6 | @SuppressWarnings("unused")
7 | private static final String TAG = ParseException.class.getSimpleName();
8 |
9 | public ParseException(final String s) {
10 | super(s);
11 | }
12 |
13 | public ParseException(final String detailMessage, final Throwable throwable) {
14 | super(detailMessage, throwable);
15 | }
16 |
17 | public ParseException(final Throwable throwable) {
18 | super(throwable);
19 | }
20 |
21 | }
22 |
--------------------------------------------------------------------------------
/android-rest-lib/src/main/java/com/dg/libs/rest/handlers/BackgroundThreadResponseHandler.java:
--------------------------------------------------------------------------------
1 | package com.dg.libs.rest.handlers;
2 |
3 | import com.dg.libs.rest.callbacks.HttpCallback;
4 | import com.dg.libs.rest.domain.ResponseStatus;
5 |
6 | public class BackgroundThreadResponseHandler implements ResponseHandler {
7 |
8 | public static final String TAG = BackgroundThreadResponseHandler.class.getSimpleName();
9 | protected final HttpCallback callback;
10 |
11 | public BackgroundThreadResponseHandler(HttpCallback callback) {
12 | this.callback = callback;
13 | }
14 |
15 | @Override
16 | public HttpCallback getCallback() {
17 | return callback;
18 | }
19 |
20 | @Override
21 | public void handleSuccess(final T responseData, ResponseStatus status) {
22 | if (callback != null) {
23 | callback.onSuccess(responseData, status);
24 | }
25 | }
26 |
27 | @Override
28 | public void handleError(final ResponseStatus status) {
29 | if (callback != null) {
30 | callback.onHttpError(status);
31 | }
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/android-rest-lib/src/main/java/com/dg/libs/rest/handlers/DefaultResponseStatusHandler.java:
--------------------------------------------------------------------------------
1 | package com.dg.libs.rest.handlers;
2 |
3 | import com.dg.libs.rest.domain.ResponseStatus;
4 |
5 | public class DefaultResponseStatusHandler implements ResponseStatusHandler {
6 |
7 | public DefaultResponseStatusHandler() {
8 | super();
9 | }
10 |
11 | @Override
12 | public boolean hasErrorInStatus(ResponseStatus status) {
13 | return (status.getStatusCode() < 200 || status.getStatusCode() >= 300);
14 | }
15 |
16 | }
17 |
--------------------------------------------------------------------------------
/android-rest-lib/src/main/java/com/dg/libs/rest/handlers/ResponseHandler.java:
--------------------------------------------------------------------------------
1 | package com.dg.libs.rest.handlers;
2 |
3 | import com.dg.libs.rest.callbacks.HttpCallback;
4 | import com.dg.libs.rest.domain.ResponseStatus;
5 |
6 | public interface ResponseHandler {
7 |
8 | public HttpCallback getCallback();
9 |
10 | public void handleSuccess(final T responseData, ResponseStatus status);
11 |
12 | public void handleError(final ResponseStatus status);
13 | }
14 |
--------------------------------------------------------------------------------
/android-rest-lib/src/main/java/com/dg/libs/rest/handlers/ResponseStatusHandler.java:
--------------------------------------------------------------------------------
1 | package com.dg.libs.rest.handlers;
2 |
3 | import com.dg.libs.rest.domain.ResponseStatus;
4 |
5 | public interface ResponseStatusHandler {
6 |
7 | public boolean hasErrorInStatus(ResponseStatus status);
8 |
9 | }
--------------------------------------------------------------------------------
/android-rest-lib/src/main/java/com/dg/libs/rest/handlers/UIThreadResponseHandler.java:
--------------------------------------------------------------------------------
1 | package com.dg.libs.rest.handlers;
2 |
3 | import android.os.Handler;
4 | import android.os.Looper;
5 | import com.dg.libs.rest.callbacks.HttpCallback;
6 | import com.dg.libs.rest.domain.ResponseStatus;
7 |
8 | public class UIThreadResponseHandler extends BackgroundThreadResponseHandler
9 | implements ResponseHandler {
10 |
11 | public static final String TAG = UIThreadResponseHandler.class.getSimpleName();
12 | protected static Handler handler;
13 |
14 | public UIThreadResponseHandler(HttpCallback callback) {
15 | super(callback);
16 | if (handler == null) {
17 | handler = new Handler(Looper.getMainLooper());
18 | }
19 | }
20 |
21 | @Override
22 | public void handleSuccess(final T responseData, final ResponseStatus status) {
23 | handler.post(new Runnable() {
24 |
25 | @Override
26 | public void run() {
27 | if (callback != null) {
28 | callback.onSuccess(responseData, status);
29 | }
30 | }
31 | });
32 | }
33 |
34 | @Override
35 | public void handleError(final ResponseStatus status) {
36 | handler.post(new Runnable() {
37 |
38 | @Override
39 | public void run() {
40 | if (callback != null) {
41 | callback.onHttpError(status);
42 | }
43 | }
44 | });
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/android-rest-lib/src/main/java/com/dg/libs/rest/parsers/HttpResponseParser.java:
--------------------------------------------------------------------------------
1 | package com.dg.libs.rest.parsers;
2 |
3 | import java.io.InputStream;
4 |
5 | /**
6 | * The {@link HttpResponseParser} interface has the responsibility to parse
7 | * responses from the server.
8 | *
9 | * @param
10 | * Parameter that indicates which object the parser returns. It can be
11 | * of any type.
12 | */
13 | public interface HttpResponseParser {
14 |
15 | /**
16 | * This method is used for parsing JSON response from server. Given a JSON
17 | * string, returns response data which can be of any type.
18 | *
19 | * @param instream
20 | * The JSON string needed for parsing.
21 | * @return Object of any type returned by the parser.
22 | * @throws Exception
23 | * Thrown when various parsing errors occur.
24 | */
25 | public T parse(final InputStream instream) throws Exception;
26 | }
27 |
--------------------------------------------------------------------------------
/android-rest-lib/src/main/java/com/dg/libs/rest/parsers/NoResponseParser.java:
--------------------------------------------------------------------------------
1 | package com.dg.libs.rest.parsers;
2 |
3 | import java.io.InputStream;
4 |
5 | public class NoResponseParser implements HttpResponseParser {
6 |
7 | public static final String TAG = NoResponseParser.class.getSimpleName();
8 |
9 | @Override
10 | public Void parse(InputStream responseStream) throws Exception {
11 | return null;
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/android-rest-lib/src/main/java/com/dg/libs/rest/requests/RequestBodyUtils.java:
--------------------------------------------------------------------------------
1 | package com.dg.libs.rest.requests;
2 |
3 | import com.squareup.okhttp.MediaType;
4 | import com.squareup.okhttp.RequestBody;
5 | import com.squareup.okhttp.internal.Util;
6 |
7 | import java.io.IOException;
8 | import java.io.InputStream;
9 |
10 | import okio.BufferedSink;
11 | import okio.Okio;
12 | import okio.Source;
13 |
14 | public class RequestBodyUtils {
15 |
16 | public static RequestBody create(final MediaType mediaType, final InputStream inputStream) {
17 | return new RequestBody() {
18 | @Override
19 | public MediaType contentType() {
20 | return mediaType;
21 | }
22 |
23 | @Override
24 | public long contentLength() {
25 | try {
26 | return inputStream.available();
27 | } catch (IOException e) {
28 | return 0;
29 | }
30 | }
31 |
32 | @Override
33 | public void writeTo(BufferedSink sink) throws IOException {
34 | Source source = null;
35 | try {
36 | source = Okio.source(inputStream);
37 | sink.writeAll(source);
38 | } finally {
39 | Util.closeQuietly(source);
40 | }
41 | }
42 | };
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/android-rest-lib/src/main/java/com/dg/libs/rest/requests/RestClientRequest.java:
--------------------------------------------------------------------------------
1 | package com.dg.libs.rest.requests;
2 |
3 | import android.app.Activity;
4 | import android.app.Fragment;
5 | import android.text.TextUtils;
6 | import android.util.Log;
7 |
8 | import com.araneaapps.android.libs.asyncrunners.models.RequestOptions;
9 | import com.araneaapps.android.libs.asyncrunners.models.TaskStore;
10 | import com.dg.libs.rest.HttpRequest;
11 | import com.dg.libs.rest.RestClientConfiguration;
12 | import com.dg.libs.rest.authentication.AuthenticationProvider;
13 | import com.dg.libs.rest.callbacks.ActivityBoundHttpCallback;
14 | import com.dg.libs.rest.callbacks.BoundCallback;
15 | import com.dg.libs.rest.callbacks.FragmentBoundHttpCallback;
16 | import com.dg.libs.rest.callbacks.HttpCallback;
17 | import com.dg.libs.rest.client.RequestMethod;
18 | import com.dg.libs.rest.domain.ResponseStatus;
19 | import com.dg.libs.rest.handlers.DefaultResponseStatusHandler;
20 | import com.dg.libs.rest.handlers.ResponseHandler;
21 | import com.dg.libs.rest.handlers.ResponseStatusHandler;
22 | import com.dg.libs.rest.handlers.UIThreadResponseHandler;
23 | import com.dg.libs.rest.parsers.HttpResponseParser;
24 | import com.squareup.okhttp.OkHttpClient;
25 | import com.squareup.okhttp.Request;
26 | import com.squareup.okhttp.RequestBody;
27 | import com.squareup.okhttp.Response;
28 | import com.squareup.okhttp.ResponseBody;
29 |
30 | import java.io.IOException;
31 | import java.io.InputStream;
32 | import java.io.UnsupportedEncodingException;
33 | import java.lang.reflect.Array;
34 | import java.net.URLEncoder;
35 | import java.util.concurrent.TimeUnit;
36 |
37 | public abstract class RestClientRequest implements HttpRequest {
38 |
39 | private String TAG = RestClientRequest.class.getSimpleName();
40 |
41 | private HttpResponseParser parser;
42 | private ResponseHandler handler;
43 | private ResponseStatusHandler statusHandler;
44 | private BoundCallback callback;
45 | private Request.Builder request = new Request.Builder();
46 | private StringBuilder queryParams;
47 | private String url;
48 |
49 | RequestOptions requestOptions = null;
50 | AuthenticationProvider authenticationProvider;
51 |
52 | protected RestClientRequest() {
53 | authenticationProvider = RestClientConfiguration.get().getAuthenticationProvider();
54 | }
55 |
56 | public RestClientRequest setAuthenticationProvider(AuthenticationProvider authenticationProvider) {
57 | this.authenticationProvider = authenticationProvider;
58 | return this;
59 | }
60 |
61 | protected HttpCallback getCallback() {
62 | return callback;
63 | }
64 |
65 | public RestClientRequest setCallback(HttpCallback callback) {
66 | BoundCallback boundCallback = new BoundCallback<>(callback);
67 | this.callback = boundCallback;
68 | return this;
69 | }
70 |
71 | public RestClientRequest setActivityBoundCallback(Activity activity, HttpCallback callback) {
72 | this.callback = new ActivityBoundHttpCallback<>(activity, callback);
73 | return this;
74 | }
75 |
76 | public RestClientRequest setFragmentBoundCallback(Fragment fragment, HttpCallback callback) {
77 | this.callback = new FragmentBoundHttpCallback<>(fragment, callback);
78 | return this;
79 | }
80 |
81 |
82 | public RestClientRequest setParser(HttpResponseParser parser) {
83 | this.parser = parser;
84 | return this;
85 | }
86 |
87 | public ResponseHandler getHandler() {
88 | return handler;
89 | }
90 |
91 | /**
92 | * Adds a new header value, existing value with same key will not be overwritten
93 | *
94 | * @param key
95 | * @param value
96 | */
97 | public RestClientRequest addHeader(final String key, final String value) {
98 | request.addHeader(key, value);
99 | return this;
100 | }
101 |
102 | /**
103 | * Overrides an existing header value
104 | *
105 | * @param key
106 | * @param value
107 | */
108 | public RestClientRequest header(final String key, final String value) {
109 | request.header(key, value);
110 | return this;
111 | }
112 |
113 | @Override
114 | public void run() {
115 | doBeforeRunRequestInBackgroundThread();
116 | validateRequestArguments();
117 | runRequest();
118 | }
119 |
120 | public void validateRequestArguments() {
121 | if (TextUtils.isEmpty(this.url)) {
122 | Log.e(TAG, "Request url is empty or null", new IllegalArgumentException());
123 | }
124 | }
125 |
126 | @Override
127 | public void cancel() {
128 | if (callback != null) {
129 | callback.unregister();
130 | }
131 | }
132 |
133 | public boolean isCanceled() {
134 | return callback != null && callback.isRegistered();
135 | }
136 |
137 | /**
138 | * Set a custom handler that will be triggered when the response returns
139 | * either Success or Fail. You can choose where this info is sent. **Default**
140 | * is the UIThreadREsponseHandler implementation which runs the appropriate
141 | * callback on the UI thread.
142 | *
143 | * @param handler
144 | */
145 | public RestClientRequest setResponseHandler(ResponseHandler handler) {
146 | this.handler = handler;
147 | return this;
148 | }
149 |
150 | /**
151 | * By default success is a code in the range of 2xx. Everything else triggers
152 | * an Error. You can set a handler which will take into account your own
153 | * custom error codes to determine if the response is a success or fail.
154 | *
155 | * @param statusHandler
156 | */
157 | public RestClientRequest setStatusHandler(ResponseStatusHandler statusHandler) {
158 | this.statusHandler = statusHandler;
159 | return this;
160 | }
161 |
162 | protected HttpResponseParser getParser() {
163 | return parser;
164 | }
165 |
166 | public RestClientRequest setUrl(String url) {
167 | this.url = url;
168 | return this;
169 | }
170 |
171 | /**
172 | * Access URL formatting options with the format ex. /action/:type/otheraction/:other
173 | * Removes any suffixes such as query params (url ends with somepath?one=two becomes somepath)
174 | *
175 | * @param url a string url
176 | * @param params
177 | * @return
178 | */
179 | public RestClientRequest setUrlWithFormat(String url, String... params) {
180 | if (params.length == 0) {
181 | this.url = url;
182 | return this;
183 | }
184 | int questionMark = url.indexOf("?");
185 | StringBuilder sb = new StringBuilder(questionMark > -1 ? url.substring(0, questionMark) : url);
186 | for (String param : params) {
187 | int start = sb.indexOf("/:");
188 | if (start == -1) {
189 | throw new IllegalArgumentException("Need to add the same amount of placeholder params in the string as /:value/ where you want to replace it");
190 | }
191 | int end = sb.indexOf("/", start + 1);
192 | if (end == -1) {
193 | end = sb.length();
194 | }
195 | sb.replace(start + 1, end, param);
196 | }
197 | this.url = sb.toString();
198 | return this;
199 | }
200 |
201 | public RestClientRequest setRequestMethod(RequestMethod requestMethod) {
202 | return setRequestMethod(requestMethod, null);
203 |
204 | }
205 |
206 | public RestClientRequest setRequestMethod(RequestMethod requestMethod, RequestBody requestBody) {
207 | request.method(requestMethod.name(), requestBody);
208 | return this;
209 | }
210 |
211 | protected void runRequest() {
212 | if (handler == null) {
213 | handler = new UIThreadResponseHandler<>(callback);
214 | }
215 | if (statusHandler == null) {
216 | statusHandler = new DefaultResponseStatusHandler();
217 | }
218 |
219 | OkHttpClient client = generateClient();
220 | StringBuilder url = new StringBuilder(this.url);
221 | StringBuilder queryParams = this.queryParams;
222 | if (queryParams != null) {
223 | url.append(queryParams);
224 | }
225 |
226 | request.url(url.toString());
227 |
228 | if (this.authenticationProvider != null) {
229 | authenticationProvider.authenticateRequest(this);
230 | }
231 |
232 | Request preparedRequest = request.build();
233 | Response response;
234 | try {
235 | response = client.newCall(preparedRequest).execute();
236 | } catch (final Exception e) {
237 | ResponseStatus responseStatus = ResponseStatus.getConnectionErrorStatus();
238 | Log.e(TAG, responseStatus.toString(), e);
239 | handler.handleError(responseStatus);
240 | doAfterRunRequestInBackgroundThread();
241 | return;
242 | }
243 |
244 | final ResponseStatus status = new ResponseStatus(response.code(), response.message());
245 | Log.d(TAG, status.toString());
246 | if (handleResponseStatus(status)) {
247 | doAfterRunRequestInBackgroundThread();
248 | return;
249 | }
250 |
251 | try {
252 | if (parser != null) {
253 | InputStream instream = response.body().byteStream();
254 | final T responseData = parser.parse(instream);
255 | close(response.body());
256 | doAfterSuccessfulRequestInBackgroundThread(responseData);
257 | handler.handleSuccess(responseData, status);
258 | } else {
259 | Log.i(TAG, "You haven't added a parser for your request");
260 | handler.handleSuccess(null, status);
261 | doAfterSuccessfulRequestInBackgroundThread(null);
262 | }
263 | } catch (final Exception e) {
264 | ResponseStatus responseStatus = ResponseStatus.getParseErrorStatus();
265 | Log.d(TAG, responseStatus.toString(), e);
266 | handler.handleError(responseStatus);
267 | }
268 | doAfterRunRequestInBackgroundThread();
269 |
270 | }
271 |
272 | /**
273 | * Return true if you have handled the status yourself.
274 | */
275 | protected boolean handleResponseStatus(ResponseStatus status) {
276 | if (statusHandler.hasErrorInStatus(status)) {
277 | handler.handleError(status);
278 | return true;
279 | }
280 | return false;
281 | }
282 |
283 | @Override
284 | public void executeAsync() {
285 | TaskStore.get(RestClientConfiguration.get().getContext()).queue(this, getRequestOptions());
286 | }
287 |
288 | public RequestOptions getRequestOptions() {
289 | return requestOptions;
290 | }
291 |
292 | public RestClientRequest setRequestOptions(RequestOptions requestOptions) {
293 | this.requestOptions = requestOptions;
294 | return this;
295 | }
296 |
297 | /**
298 | * Use this method to add the required data to the request. This will happen
299 | * in the background thread which enables you to pre-process the parameters,
300 | * do queries etc..
301 | */
302 | protected void doBeforeRunRequestInBackgroundThread() {
303 | }
304 |
305 | /**
306 | * This will happen in the background thread which enables you to do some
307 | * cleanup in the background after the request finishes
308 | */
309 | protected void doAfterRunRequestInBackgroundThread() {
310 | }
311 |
312 | /**
313 | * This will happen in the background thread only if the request execution is successful
314 | */
315 | protected void doAfterSuccessfulRequestInBackgroundThread(T data) {
316 | }
317 |
318 | private OkHttpClient generateClient() {
319 | OkHttpClient client = new OkHttpClient();
320 | customizeClient(client);
321 | return client;
322 | }
323 |
324 | protected void customizeClient(OkHttpClient client) {
325 | client.setConnectTimeout(RestClientConfiguration.get().getConnectionTimeout(), TimeUnit.MILLISECONDS);
326 | client.setReadTimeout(RestClientConfiguration.get().getReadTimeout(), TimeUnit.MILLISECONDS);
327 | client.setWriteTimeout(RestClientConfiguration.get().getWriteTimeout(), TimeUnit.MILLISECONDS);
328 | }
329 |
330 | public RestClientRequest addQueryParam(String name, String value) {
331 | addQueryParam(name, value, false, true);
332 | return this;
333 | }
334 |
335 | public RestClientRequest addEncodedQueryParam(String name, String value) {
336 | addQueryParam(name, value, false, false);
337 | return this;
338 | }
339 |
340 | private void addQueryParam(String name, Object value, boolean encodeName, boolean encodeValue) {
341 | if (value instanceof Iterable) {
342 | for (Object iterableValue : (Iterable>) value) {
343 | if (iterableValue != null) { // Skip null values
344 | addQueryParam(name, iterableValue.toString(), encodeName, encodeValue);
345 | }
346 | }
347 | } else if (value.getClass().isArray()) {
348 | for (int x = 0, arrayLength = Array.getLength(value); x < arrayLength; x++) {
349 | Object arrayValue = Array.get(value, x);
350 | if (arrayValue != null) { // Skip null values
351 | addQueryParam(name, arrayValue.toString(), encodeName, encodeValue);
352 | }
353 | }
354 | } else {
355 | addQueryParam(name, value.toString(), encodeName, encodeValue);
356 | }
357 | }
358 |
359 | private void addQueryParam(String name, String value, boolean encodeName, boolean encodeValue) {
360 | if (name == null) {
361 | throw new IllegalArgumentException("Query param name must not be null.");
362 | }
363 | if (value == null) {
364 | throw new IllegalArgumentException("Query param \"" + name + "\" value must not be null.");
365 | }
366 | try {
367 | StringBuilder queryParams = this.queryParams;
368 | if (queryParams == null) {
369 | this.queryParams = queryParams = new StringBuilder();
370 | }
371 |
372 | queryParams.append(queryParams.length() > 0 ? '&' : '?');
373 |
374 | if (encodeName) {
375 | name = URLEncoder.encode(name, "UTF-8");
376 | }
377 | if (encodeValue) {
378 | value = URLEncoder.encode(value, "UTF-8");
379 | }
380 | queryParams.append(name).append('=').append(value);
381 | } catch (UnsupportedEncodingException e) {
382 | throw new RuntimeException(
383 | "Unable to convert query parameter \"" + name + "\" value to UTF-8: " + value, e);
384 | }
385 | }
386 |
387 | private void close(ResponseBody body) {
388 | try {
389 | if (body != null) {
390 | body.close();
391 | }
392 | } catch (IOException e) {
393 | }
394 |
395 | }
396 | }
397 |
--------------------------------------------------------------------------------
/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 |
8 | dependencies {
9 | classpath 'com.android.tools.build:gradle:1.1.0'
10 | }
11 | }
12 |
13 | allprojects {
14 | version "${VERSION_MAJOR}.${VERSION_MINOR}.${VERSION_PATCH}"
15 | group = GROUP
16 |
17 | repositories {
18 | jcenter()
19 | }
20 | }
--------------------------------------------------------------------------------
/gradle-mvn-push.gradle:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2013 Chris Banes
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | apply plugin: 'maven'
18 | apply plugin: 'signing'
19 | def isReleaseBuild() {
20 | return "${VERSION_MAJOR}.${VERSION_MINOR}.${VERSION_PATCH}.${VERSION_BUILD}".contains("SNAPSHOT") == false
21 | }
22 |
23 | def getReleaseRepositoryUrl() {
24 | return hasProperty('RELEASE_REPOSITORY_URL') ? RELEASE_REPOSITORY_URL
25 | : "https://oss.sonatype.org/service/local/staging/deploy/maven2/"
26 | }
27 |
28 | def getSnapshotRepositoryUrl() {
29 | return hasProperty('SNAPSHOT_REPOSITORY_URL') ? SNAPSHOT_REPOSITORY_URL
30 | : "https://oss.sonatype.org/content/repositories/snapshots/"
31 | }
32 |
33 | def getRepositoryUsername() {
34 | return hasProperty('NEXUS_USERNAME') ? NEXUS_USERNAME : ""
35 | }
36 |
37 | def getRepositoryPassword() {
38 | return hasProperty('NEXUS_PASSWORD') ? NEXUS_PASSWORD : ""
39 | }
40 |
41 | afterEvaluate { project ->
42 | uploadArchives {
43 | repositories {
44 | mavenDeployer {
45 | beforeDeployment { MavenDeployment deployment -> signing.signPom(deployment) }
46 |
47 | pom.groupId = GROUP
48 | pom.artifactId = POM_ARTIFACT_ID
49 | pom.version = "${VERSION_MAJOR}.${VERSION_MINOR}.${VERSION_PATCH}"
50 |
51 | repository(url: getReleaseRepositoryUrl()) {
52 | authentication(userName: getRepositoryUsername(), password: getRepositoryPassword())
53 | }
54 | snapshotRepository(url: getSnapshotRepositoryUrl()) {
55 | authentication(userName: getRepositoryUsername(), password: getRepositoryPassword())
56 | }
57 |
58 | pom.project {
59 | name POM_NAME
60 | packaging POM_PACKAGING
61 | description POM_DESCRIPTION
62 | url POM_URL
63 |
64 | scm {
65 | url POM_SCM_URL
66 | connection POM_SCM_CONNECTION
67 | developerConnection POM_SCM_DEV_CONNECTION
68 | }
69 |
70 | licenses {
71 | license {
72 | name POM_LICENCE_NAME
73 | url POM_LICENCE_URL
74 | distribution POM_LICENCE_DIST
75 | }
76 | }
77 |
78 | developers {
79 | developer {
80 | id POM_DEVELOPER_ID
81 | name POM_DEVELOPER_NAME
82 | }
83 | }
84 | }
85 | }
86 | }
87 | }
88 |
89 | signing {
90 | required { isReleaseBuild() && gradle.taskGraph.hasTask("uploadArchives") }
91 | sign configurations.archives
92 | }
93 |
94 | task androidJavadocs(type: Javadoc) {
95 | source = android.sourceSets.main.java.srcDirs
96 | classpath += project.files(android.getBootClasspath().join(File.pathSeparator))
97 | }
98 |
99 | task androidJavadocsJar(type: Jar, dependsOn: androidJavadocs) {
100 | classifier = 'javadoc'
101 | from androidJavadocs.destinationDir
102 | }
103 |
104 | task androidSourcesJar(type: Jar) {
105 | classifier = 'sources'
106 | from android.sourceSets.main.java.sourceFiles
107 | }
108 |
109 | artifacts {
110 | archives androidSourcesJar
111 | archives androidJavadocsJar
112 | }
113 | }
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | VERSION_MAJOR = 2
2 | VERSION_MINOR = 9
3 | VERSION_PATCH = 0
4 | VERSION_BUILD = 0
5 |
6 | GROUP=com.aranea-apps.android.libs
7 | POM_DESCRIPTION=Android library for creating async HTTP reuqests
8 | POM_URL=https://github.com/darko1002001/android-rest-client
9 | POM_SCM_URL=https://github.com/darko1002001/android-rest-client
10 | POM_SCM_CONNECTION=scm:git:git@github.com:darko1002001/android-rest-client.git
11 | POM_SCM_DEV_CONNECTION=scm:git:git@github.com:darko1002001/android-rest-client.git
12 | POM_LICENCE_NAME=The Apache Software License, Version 2.0
13 | POM_LICENCE_URL=http://www.apache.org/licenses/LICENSE-2.0.txt
14 | POM_LICENCE_DIST=repo
15 | POM_DEVELOPER_ID=darko10002001
16 | POM_DEVELOPER_NAME=Darko Grozdanovski
17 |
18 | ANDROID_BUILD_TARGET_SDK_VERSION=22
19 | ANDROID_BUILD_TOOLS_VERSION=22.0.1
20 | ANDROID_BUILD_SDK_VERSION=22
21 | ANDROID_MIN_SDK_VERSION=8
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/darko1002001/android-rest-client/3e58498ac831513de8094f72b320ef7c5861c3b0/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Wed Dec 10 10:42:13 CET 2014
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.2.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 |
--------------------------------------------------------------------------------
/parent.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
--------------------------------------------------------------------------------
/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | 4.0.0
4 |
5 |
6 | org.sonatype.oss
7 | oss-parent
8 | 7
9 |
10 |
11 | com.aranea-apps.android.libs
12 | parent
13 | pom
14 | 1.7.1-SNAPSHOT
15 |
16 | Android Rest Lib (Parent)
17 | Android library for creating async HTTP reuqests
18 | http://darko1002001.github.io/android-rest-client/
19 | 2012
20 |
21 |
22 | android-rest-lib
23 | android-rest-lib-additions
24 | rest-client-demo
25 |
26 |
27 |
28 |
29 | https://github.com/darko1002001/android-rest-client/
30 | scm:git:git@github.com:darko1002001/android-rest-client.git
31 | scm:git:git@github.com:darko1002001/android-rest-client.git
32 | stable
33 |
34 |
35 |
36 |
37 | The Apache Software License, Version 2.0
38 | http://www.apache.org/licenses/LICENSE-2.0.txt
39 | repo
40 |
41 |
42 |
43 |
44 | Darko Grozdanovski
45 | darko@aranea-apps.com
46 | darko1002001
47 |
48 | developer
49 |
50 |
51 |
52 |
53 |
54 | Aranea
55 | http://aranea-apps.com
56 |
57 |
58 |
59 | GitHub Issues
60 | https://github.com/darko1002001/android-rest-client/issues
61 |
62 |
63 |
64 | UTF-8
65 | UTF-8
66 |
67 | 1.6
68 | 4.8.1
69 | 2.2.1
70 | 16
71 |
72 | darko1002001
73 | android-rest-client
74 |
75 |
76 |
77 | junit
78 | junit
79 | ${junit.version}
80 | test
81 |
82 |
83 | com.google.android
84 | android
85 | ${android.version}
86 | provided
87 |
88 |
89 |
90 |
91 |
92 | org.apache.maven.plugins
93 | maven-compiler-plugin
94 | 3.0
95 |
96 | ${java.version}
97 | ${java.version}
98 | true
99 |
100 |
101 |
102 | org.apache.maven.plugins
103 | maven-release-plugin
104 | 2.4
105 |
106 | true
107 |
108 |
109 |
110 |
111 |
112 |
113 | com.jayway.maven.plugins.android.generation2
114 | android-maven-plugin
115 | 3.8.0
116 |
117 |
118 | ${android.sdk.platform}
119 |
120 |
121 |
122 |
123 |
124 | org.apache.maven.plugins
125 | maven-invoker-plugin
126 | 1.7
127 |
128 |
129 |
130 | org.apache.maven.plugins
131 | maven-surefire-plugin
132 | 2.16
133 |
134 | -Xmx1024m
135 |
136 |
137 |
138 |
139 |
140 |
141 |
142 |
143 |
144 |
145 |
--------------------------------------------------------------------------------
/rest-client-demo/.classpath:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
--------------------------------------------------------------------------------
/rest-client-demo/.gitignore:
--------------------------------------------------------------------------------
1 | # built application files
2 | *.apk
3 | *.ap_
4 |
5 | # files for the dex VM
6 | *.dex
7 |
8 | # Java class files
9 | *.class
10 |
11 | # generated files
12 | bin/
13 | gen/
14 |
15 | # Local configuration file (sdk path, etc)
16 | local.properties
17 | .idea
18 | build/
--------------------------------------------------------------------------------
/rest-client-demo/.project:
--------------------------------------------------------------------------------
1 |
2 |
3 | rest-client-demo
4 |
5 |
6 |
7 |
8 |
9 | com.android.ide.eclipse.adt.ResourceManagerBuilder
10 |
11 |
12 |
13 |
14 | com.android.ide.eclipse.adt.PreCompilerBuilder
15 |
16 |
17 |
18 |
19 | org.eclipse.jdt.core.javabuilder
20 |
21 |
22 |
23 |
24 | com.android.ide.eclipse.adt.ApkBuilder
25 |
26 |
27 |
28 |
29 | org.eclipse.m2e.core.maven2Builder
30 |
31 |
32 |
33 |
34 |
35 | org.eclipse.m2e.core.maven2Nature
36 | com.android.ide.eclipse.adt.AndroidNature
37 | org.eclipse.jdt.core.javanature
38 |
39 |
40 |
--------------------------------------------------------------------------------
/rest-client-demo/.settings/org.eclipse.jdt.core.prefs:
--------------------------------------------------------------------------------
1 | eclipse.preferences.version=1
2 | org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
3 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6
4 | org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
5 | org.eclipse.jdt.core.compiler.compliance=1.6
6 | org.eclipse.jdt.core.compiler.debug.lineNumber=generate
7 | org.eclipse.jdt.core.compiler.debug.localVariable=generate
8 | org.eclipse.jdt.core.compiler.debug.sourceFile=generate
9 | org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
10 | org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
11 | org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning
12 | org.eclipse.jdt.core.compiler.source=1.6
13 |
--------------------------------------------------------------------------------
/rest-client-demo/.settings/org.eclipse.m2e.core.prefs:
--------------------------------------------------------------------------------
1 | activeProfiles=
2 | eclipse.preferences.version=1
3 | resolveWorkspaceProjects=true
4 | version=1
5 |
--------------------------------------------------------------------------------
/rest-client-demo/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 |
3 | android {
4 | packagingOptions {
5 | exclude 'META-INF/LICENSE'
6 | exclude 'META-INF/NOTICE'
7 | }
8 | compileSdkVersion Integer.parseInt(project.ANDROID_BUILD_SDK_VERSION)
9 | buildToolsVersion project.ANDROID_BUILD_TOOLS_VERSION
10 |
11 |
12 | defaultConfig {
13 | applicationId project.PACKAGE_NAME
14 | targetSdkVersion Integer.parseInt(project.ANDROID_BUILD_TARGET_SDK_VERSION)
15 | minSdkVersion 8
16 |
17 | buildTypes {
18 | release {
19 | minifyEnabled false
20 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
21 | }
22 | }
23 | }
24 |
25 | }
26 |
27 | dependencies {
28 | compile fileTree(dir: 'libs', include: ['*.jar'])
29 | compile project(":android-rest-lib")
30 | compile project(":android-rest-lib-additions")
31 | }
--------------------------------------------------------------------------------
/rest-client-demo/gradle.properties:
--------------------------------------------------------------------------------
1 | POM_NAME=Rest Client Android - Demo
2 | POM_ARTIFACT_ID=android-rest-additions
3 | PACKAGE_NAME=com.araneaapps.android.libs.androidrestdemo
4 | POM_PACKAGING=aar
--------------------------------------------------------------------------------
/rest-client-demo/lint.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
--------------------------------------------------------------------------------
/rest-client-demo/pom.xml:
--------------------------------------------------------------------------------
1 |
2 | 4.0.0
3 | com.aranea-apps.android.demo
4 | rest-client-demo
5 | 1.7.1-SNAPSHOT
6 |
7 | apk
8 | Rest Client Demo
9 |
10 |
11 | com.aranea-apps.android.libs
12 | parent
13 | 1.7.1-SNAPSHOT
14 |
15 |
16 |
17 |
18 | com.google.android
19 | android
20 | 2.2.1
21 | provided
22 |
23 |
24 | com.aranea-apps.android.libs
25 | android-rest
26 | ${project.version}
27 |
28 |
29 | com.aranea-apps.android.libs
30 | android-rest-additions
31 | ${project.version}
32 |
33 |
34 |
35 | ${project.artifactId}
36 |
37 |
38 | com.jayway.maven.plugins.android.generation2
39 | android-maven-plugin
40 | true
41 |
42 |
43 |
44 |
45 |
--------------------------------------------------------------------------------
/rest-client-demo/proguard-project.txt:
--------------------------------------------------------------------------------
1 | # To enable ProGuard in your project, edit project.properties
2 | # to define the proguard.config property as described in that file.
3 | #
4 | # Add project specific ProGuard rules here.
5 | # By default, the flags in this file are appended to flags specified
6 | # in ${sdk.dir}/tools/proguard/proguard-android.txt
7 | # You can edit the include path and order by changing the ProGuard
8 | # include property in project.properties.
9 | #
10 | # For more details, see
11 | # http://developer.android.com/guide/developing/tools/proguard.html
12 |
13 | # Add any project specific keep options here:
14 |
15 | # If your project uses WebView with JS, uncomment the following
16 | # and specify the fully qualified class name to the JavaScript interface
17 | # class:
18 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
19 | # public *;
20 | #}
21 |
--------------------------------------------------------------------------------
/rest-client-demo/project.properties:
--------------------------------------------------------------------------------
1 | # This file is automatically generated by Android Tools.
2 | # Do not modify this file -- YOUR CHANGES WILL BE ERASED!
3 | #
4 | # This file must be checked in Version Control Systems.
5 | #
6 | # To customize properties used by the Ant build system edit
7 | # "ant.properties", and override values to adapt the script to your
8 | # project structure.
9 | #
10 | # To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home):
11 | #proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt
12 |
13 | # Project target.
14 | target=android-18
15 |
--------------------------------------------------------------------------------
/rest-client-demo/rest-client-demo.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
--------------------------------------------------------------------------------
/rest-client-demo/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
5 |
6 |
7 |
8 |
12 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
--------------------------------------------------------------------------------
/rest-client-demo/src/main/java/com/dg/examples/restclientdemo/MainActivity.java:
--------------------------------------------------------------------------------
1 | package com.dg.examples.restclientdemo;
2 |
3 | import android.app.Activity;
4 | import android.os.Bundle;
5 | import android.widget.TextView;
6 | import android.widget.Toast;
7 |
8 | import com.dg.examples.restclientdemo.communication.requests.BlogsGoogleRequest;
9 | import com.dg.examples.restclientdemo.communication.requests.PatchRequest;
10 | import com.dg.examples.restclientdemo.domain.ResponseModel;
11 | import com.dg.libs.rest.callbacks.HttpCallback;
12 | import com.dg.libs.rest.domain.ResponseStatus;
13 | import com.dg.libs.rest.requests.RestClientRequest;
14 |
15 |
16 | public class MainActivity extends Activity {
17 |
18 |
19 | private TextView textViewResponse;
20 | private RestClientRequest request;
21 |
22 | @Override
23 | public void onCreate(Bundle savedInstanceState) {
24 | super.onCreate(savedInstanceState);
25 | setContentView(R.layout.activity_main);
26 |
27 | textViewResponse = (TextView) findViewById(R.id.textViewResponse);
28 |
29 | request = new BlogsGoogleRequest("Official Google Blogs").setCallback(new GoogleBlogsCallback());
30 | request
31 | .executeAsync();
32 |
33 | new PatchRequest("Hello").setCallback(new HttpCallback() {
34 | @Override
35 | public void onSuccess(Void responseData, ResponseStatus responseStatus) {
36 | Toast.makeText(getApplicationContext(), "Success patch", Toast.LENGTH_LONG).show();
37 | }
38 |
39 | @Override
40 | public void onHttpError(ResponseStatus responseStatus) {
41 | Toast.makeText(getApplicationContext(), "FAIL patch", Toast.LENGTH_LONG).show();
42 | }
43 | }).executeAsync();
44 | }
45 |
46 | @Override
47 | protected void onDestroy() {
48 | super.onDestroy();
49 | request.cancel();
50 | }
51 |
52 | private final class GoogleBlogsCallback implements HttpCallback {
53 |
54 |
55 | @Override
56 | public void onSuccess(ResponseModel responseData, ResponseStatus responseStatus) {
57 | textViewResponse.setText(responseData.toString());
58 | }
59 |
60 | @Override
61 | public void onHttpError(ResponseStatus responseStatus) {
62 |
63 | }
64 |
65 | }
66 | }
67 |
--------------------------------------------------------------------------------
/rest-client-demo/src/main/java/com/dg/examples/restclientdemo/app/App.java:
--------------------------------------------------------------------------------
1 | package com.dg.examples.restclientdemo.app;
2 |
3 | import android.app.Application;
4 |
5 | import com.dg.libs.rest.RestClientConfiguration;
6 | import com.dg.libs.rest.authentication.AuthenticationProvider;
7 | import com.dg.libs.rest.requests.RestClientRequest;
8 |
9 | public class App extends Application {
10 |
11 | public static final String TAG = App.class.getSimpleName();
12 |
13 | @Override
14 | public void onCreate() {
15 | super.onCreate();
16 |
17 | /*
18 | This is a simple token auth provider which stores a single token string in shared preferences. You can access it as a singleton and set/get token
19 | TokenAuthenticationProvider.init(this);
20 | RestClientConfiguration.init(this, new RestClientConfiguration.ConfigurationBuilder().
21 | setAuthenticationProvider(TokenAuthenticationProvider.getInstance())
22 | .create());
23 | */
24 |
25 | RestClientConfiguration builder = new RestClientConfiguration.ConfigurationBuilder()
26 | .setAuthenticationProvider(new AuthenticationProvider() {
27 | @Override
28 | public void authenticateRequest(RestClientRequest client) {
29 | // YOu can add parameters or headers which will be attached to each request
30 | }
31 | })
32 | .create();
33 |
34 | RestClientConfiguration.init(this, builder);
35 |
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/rest-client-demo/src/main/java/com/dg/examples/restclientdemo/app/TokenAuthenticationProvider.java:
--------------------------------------------------------------------------------
1 | package com.dg.examples.restclientdemo.app;
2 |
3 | import android.content.Context;
4 | import android.content.SharedPreferences;
5 | import android.content.SharedPreferences.Editor;
6 | import android.preference.PreferenceManager;
7 | import android.text.TextUtils;
8 |
9 | import com.dg.libs.rest.authentication.AuthenticationProvider;
10 | import com.dg.libs.rest.requests.RestClientRequest;
11 |
12 | public class TokenAuthenticationProvider implements AuthenticationProvider {
13 |
14 | private static final String TOKEN_KEY = "api_key";
15 |
16 | private static TokenAuthenticationProvider account;
17 | private final Context context;
18 | private String token;
19 |
20 | /**
21 | * this object will be using a Reference to the application context via
22 | * getApplicationContext() NOT the Activity context Recomended to be
23 | * initialized at the application startup or by initializing in your own class
24 | * extending application
25 | *
26 | * Dont forget to set the password on first init
27 | *
28 | * @return
29 | */
30 | public static synchronized TokenAuthenticationProvider getInstance() {
31 | if (account == null) {
32 | throw new RuntimeException("Initialize the Provider first");
33 | }
34 | return account;
35 | }
36 |
37 | public static synchronized void init(Context context) {
38 | if (account == null) {
39 | account = new TokenAuthenticationProvider(context);
40 | }
41 | }
42 |
43 | private TokenAuthenticationProvider(final Context context) {
44 | this.context = context.getApplicationContext();
45 | initializeToken();
46 | }
47 |
48 | @Override
49 | public void authenticateRequest(RestClientRequest client) {
50 | if (TextUtils.isEmpty(token)) {
51 | return;
52 | }
53 | client.addHeader("Authorization", "OAuth " + token);
54 | }
55 |
56 | public String getToken() {
57 | return token;
58 | }
59 |
60 | public void setToken(String token) {
61 | this.token = token;
62 | saveApiKey(token);
63 | }
64 |
65 | public boolean isTokenValid() {
66 | return !TextUtils.isEmpty(token);
67 | }
68 |
69 | public boolean clearAuth() {
70 | Editor editor = PreferenceManager.getDefaultSharedPreferences(context).edit();
71 | editor.remove(TOKEN_KEY);
72 | boolean commit = editor.commit();
73 | return commit;
74 | }
75 |
76 | /**
77 | * Use as an alternative for saving the token to accounts (Note that using the
78 | * account manager is a preferred and safer method)
79 | *
80 | * @param apiKey
81 | * the token aqured from chute auth
82 | * @return if the save was successful
83 | */
84 | private boolean saveApiKey(final String apiKey) {
85 | Editor editor = PreferenceManager.getDefaultSharedPreferences(context).edit();
86 | editor.putString(TOKEN_KEY, apiKey);
87 | boolean commit = editor.commit();
88 | return commit;
89 | }
90 |
91 | private String restoreApiKey() {
92 | SharedPreferences savedSession = PreferenceManager
93 | .getDefaultSharedPreferences(context);
94 | return savedSession.getString(TOKEN_KEY, "");
95 | }
96 |
97 | private void initializeToken() {
98 | String apiKey = restoreApiKey();
99 | if (!TextUtils.isEmpty(apiKey)) {
100 | this.setToken(apiKey);
101 | return;
102 | }
103 | // Set a manual token for testing
104 | // this.setPassword("46e580a90085912ed11c565084f1f2465f28630bd58fa80cc98432f3078fc5ac");
105 | }
106 | }
107 |
--------------------------------------------------------------------------------
/rest-client-demo/src/main/java/com/dg/examples/restclientdemo/communication/RestConstants.java:
--------------------------------------------------------------------------------
1 | package com.dg.examples.restclientdemo.communication;
2 |
3 |
4 | public class RestConstants {
5 |
6 | public static final String TAG = RestConstants.class.getSimpleName();
7 |
8 | public static final String BASE_URL = "https://ajax.googleapis.com";
9 | public static final String LOG_SERVICE_URL = "http://log-requests.herokuapp.com/";
10 | public static final String HTTP_BIN_URL = "http://httpbin.org/";
11 |
12 |
13 | public static final String GOOGLE_BLOGS = BASE_URL + "/ajax/services/feed/find";
14 | }
15 |
16 |
--------------------------------------------------------------------------------
/rest-client-demo/src/main/java/com/dg/examples/restclientdemo/communication/parsers/BlogsGoogleParser.java:
--------------------------------------------------------------------------------
1 | package com.dg.examples.restclientdemo.communication.parsers;
2 |
3 | import com.dg.examples.restclientdemo.domain.ResponseModel;
4 | import com.dg.libs.rest.parsers.BaseJacksonMapperResponseParser;
5 |
6 | import java.io.InputStream;
7 |
8 |
9 | public class BlogsGoogleParser extends BaseJacksonMapperResponseParser {
10 |
11 | public static final String TAG = BlogsGoogleParser.class.getSimpleName();
12 |
13 | @Override
14 | public ResponseModel parse(InputStream instream) throws Exception {
15 | return mapper.readValue(instream, ResponseModel.class);
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/rest-client-demo/src/main/java/com/dg/examples/restclientdemo/communication/requests/BlogsGoogleRequest.java:
--------------------------------------------------------------------------------
1 | package com.dg.examples.restclientdemo.communication.requests;
2 |
3 | import android.util.Log;
4 |
5 | import com.dg.examples.restclientdemo.communication.RestConstants;
6 | import com.dg.examples.restclientdemo.communication.parsers.BlogsGoogleParser;
7 | import com.dg.examples.restclientdemo.domain.ResponseModel;
8 | import com.dg.libs.rest.client.RequestMethod;
9 | import com.dg.libs.rest.requests.RestClientRequest;
10 | import com.squareup.okhttp.OkHttpClient;
11 |
12 | public class BlogsGoogleRequest extends RestClientRequest {
13 |
14 | public static final String TAG = BlogsGoogleRequest.class.getSimpleName();
15 |
16 | public BlogsGoogleRequest(String query) {
17 | super();
18 | setRequestMethod(RequestMethod.GET);
19 | setUrl(RestConstants.GOOGLE_BLOGS);
20 |
21 | setParser(new BlogsGoogleParser());
22 |
23 | addQueryParam("q", query);
24 | addQueryParam("v", "1.0");
25 | addQueryParam("include_entities", "" + true);
26 | }
27 |
28 | @Override
29 | protected void doAfterSuccessfulRequestInBackgroundThread(ResponseModel data) {
30 | try {
31 |
32 | Log.d(TAG, "sleeping to be able to see Bound callbacks in action");
33 | Thread.sleep(3000);
34 | } catch (InterruptedException e) {
35 | }
36 | super.doAfterSuccessfulRequestInBackgroundThread(data);
37 | }
38 |
39 | @Override
40 | protected void customizeClient(OkHttpClient client) {
41 | super.customizeClient(client);
42 | client.setRetryOnConnectionFailure(false);
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/rest-client-demo/src/main/java/com/dg/examples/restclientdemo/communication/requests/CustomHandlersRequest.java:
--------------------------------------------------------------------------------
1 | package com.dg.examples.restclientdemo.communication.requests;
2 |
3 | import android.os.Handler;
4 | import android.os.Looper;
5 |
6 | import com.araneaapps.android.libs.asyncrunners.enums.DownloadPriority;
7 | import com.araneaapps.android.libs.asyncrunners.models.RequestOptions;
8 | import com.dg.libs.rest.callbacks.HttpCallback;
9 | import com.dg.libs.rest.client.RequestMethod;
10 | import com.dg.libs.rest.domain.ResponseStatus;
11 | import com.dg.libs.rest.handlers.UIThreadResponseHandler;
12 | import com.dg.libs.rest.requests.RestClientRequest;
13 |
14 | public class CustomHandlersRequest extends RestClientRequest {
15 |
16 | private final CustomHandlersRequest.CustomUIHandler handler;
17 | private VoidHttpCallback callback;
18 |
19 | public CustomHandlersRequest(VoidHttpCallback callback) {
20 | super();
21 | this.callback = callback;
22 | setRequestMethod(RequestMethod.GET);
23 | setUrl("http://some-dummy-url.com");
24 |
25 | handler = new CustomUIHandler(callback);
26 | setResponseHandler(handler);
27 | // You can add custom request options for specific request. there is a queue running the requests so new requests coming in
28 | // will be sorted and executed according to priority if needed.
29 | // ex. you queue 50 downloads but you want the app to still run API get requests without waiting for everything else to finish first.
30 | RequestOptions requestOptions = new RequestOptions.RequestOptionsBuilder()
31 | .setPriority(DownloadPriority.HIGH)
32 | .setRunInSingleThread(true).build();
33 | setRequestOptions(requestOptions);
34 | }
35 |
36 | @Override
37 | protected boolean handleResponseStatus(final ResponseStatus status) {
38 | // This method will also run in the background thread. Returning true means you have handled the request and this will be
39 | // the last piece of code which will be executed.
40 | // False means the execution will continue with the parser and then success if the request is parsed successfully.
41 | if (status.getStatusCode() == 204) {
42 |
43 | callback.onCustomResult(status);// careful this runs in Background thread.
44 |
45 | // Or to run in UI thread:
46 | Handler handler = new Handler(Looper.getMainLooper());
47 | handler.post(new Runnable() {
48 | @Override
49 | public void run() {
50 | callback.onCustomResult(status); // This will run in UI thread.
51 | }
52 | });
53 |
54 | // Alternatively:
55 | CustomHandlersRequest.this.handler.handleCustom(status);
56 | // will also run in UI thread but needs extra logic to implement as opposed to the code above. Cleaner but a bit more complex.
57 |
58 | return true;
59 | } else {
60 | return super.handleResponseStatus(status);
61 | }
62 | }
63 |
64 | private class CustomUIHandler extends UIThreadResponseHandler {
65 |
66 | private VoidHttpCallback callback;
67 |
68 | public CustomUIHandler(VoidHttpCallback callback) {
69 | super(callback);
70 | this.callback = callback;
71 | }
72 |
73 | public void handleCustom(final ResponseStatus status) {
74 | handler.post(new Runnable() {
75 | @Override
76 | public void run() {
77 | callback.onCustomResult(status); // This will run in UI thread.
78 | }
79 | });
80 | }
81 | }
82 |
83 | @Override
84 | protected void doAfterSuccessfulRequestInBackgroundThread(Void data) {
85 | super.doAfterSuccessfulRequestInBackgroundThread(data);
86 | }
87 |
88 | @Override
89 | protected void doBeforeRunRequestInBackgroundThread() {
90 | // this will run before the request runs. here you can query databases, add parameters or headers in the request background thread.
91 | // So there is no need to do async tasks or similar stuff to fetch parameters before executing a request if needed.
92 | super.doBeforeRunRequestInBackgroundThread();
93 | }
94 |
95 | private static class VoidHttpCallback implements HttpCallback {
96 |
97 | @Override
98 | public void onSuccess(Void responseData, ResponseStatus responseStatus) {
99 |
100 | }
101 |
102 | @Override
103 | public void onHttpError(ResponseStatus responseCode) {
104 |
105 | }
106 |
107 | public void onCustomResult(ResponseStatus status) {
108 | }
109 | }
110 | }
111 |
--------------------------------------------------------------------------------
/rest-client-demo/src/main/java/com/dg/examples/restclientdemo/communication/requests/PatchRequest.java:
--------------------------------------------------------------------------------
1 | package com.dg.examples.restclientdemo.communication.requests;
2 |
3 | import android.util.Log;
4 |
5 | import com.dg.examples.restclientdemo.communication.RestConstants;
6 | import com.dg.libs.rest.client.RequestMethod;
7 | import com.dg.libs.rest.parsers.HttpResponseParser;
8 | import com.dg.libs.rest.requests.RestClientRequest;
9 |
10 | import java.io.InputStream;
11 |
12 | public class PatchRequest extends RestClientRequest {
13 |
14 | public static final String TAG = PatchRequest.class.getSimpleName();
15 |
16 | public PatchRequest(String query) {
17 | super();
18 |
19 | setParser(new HttpResponseParser() {
20 | @Override
21 | public Void parse(InputStream instream) throws Exception {
22 | Log.d(TAG, org.apache.commons.io.IOUtils.toString(instream));
23 | return null;
24 | }
25 | });
26 |
27 | setRequestMethod(RequestMethod.PATCH);
28 | addEncodedQueryParam("q", query);
29 | addQueryParam("v", "1.0");
30 | addQueryParam("include_entities", "" + true);
31 | setUrl(RestConstants.HTTP_BIN_URL + "patch");
32 | }
33 |
34 | }
35 |
--------------------------------------------------------------------------------
/rest-client-demo/src/main/java/com/dg/examples/restclientdemo/domain/EntriesModel.java:
--------------------------------------------------------------------------------
1 | package com.dg.examples.restclientdemo.domain;
2 |
3 | import com.fasterxml.jackson.annotation.JsonProperty;
4 |
5 |
6 | public class EntriesModel {
7 |
8 | @JsonProperty
9 | private String url;
10 |
11 | @JsonProperty
12 | private String title;
13 |
14 | @JsonProperty
15 | private String contentSnippet;
16 |
17 | @JsonProperty
18 | private String link;
19 |
20 | public String getUrl() {
21 | return url;
22 | }
23 |
24 | public void setUrl(String url) {
25 | this.url = url;
26 | }
27 |
28 | public String getTitle() {
29 | return title;
30 | }
31 |
32 | public void setTitle(String title) {
33 | this.title = title;
34 | }
35 |
36 | public String getContentSnippet() {
37 | return contentSnippet;
38 | }
39 |
40 | public void setContentSnippet(String contentSnippet) {
41 | this.contentSnippet = contentSnippet;
42 | }
43 |
44 | public String getLink() {
45 | return link;
46 | }
47 |
48 | public void setLink(String link) {
49 | this.link = link;
50 | }
51 |
52 | @Override
53 | public String toString() {
54 | return "EntriesModel [url=" + url + ", title=" + title
55 | + ", contentSnippet=" + contentSnippet + ", link=" + link + "]";
56 | }
57 |
58 |
59 | }
60 |
--------------------------------------------------------------------------------
/rest-client-demo/src/main/java/com/dg/examples/restclientdemo/domain/ResponseDataModel.java:
--------------------------------------------------------------------------------
1 | package com.dg.examples.restclientdemo.domain;
2 |
3 | import com.fasterxml.jackson.annotation.JsonProperty;
4 |
5 | import java.util.ArrayList;
6 |
7 | public class ResponseDataModel {
8 |
9 | @JsonProperty
10 | private String query;
11 |
12 | @JsonProperty
13 | ArrayList entries;
14 |
15 | @Override
16 | public String toString() {
17 | return "ResponseDataModel [query=" + query + ", entries=" + entries
18 | + "]";
19 | }
20 |
21 | }
22 |
--------------------------------------------------------------------------------
/rest-client-demo/src/main/java/com/dg/examples/restclientdemo/domain/ResponseModel.java:
--------------------------------------------------------------------------------
1 | package com.dg.examples.restclientdemo.domain;
2 |
3 | import com.fasterxml.jackson.annotation.JsonProperty;
4 |
5 |
6 | public class ResponseModel {
7 | // To learn how to configure this go here:
8 | // http://wiki.fasterxml.com/JacksonInFiveMinutes
9 | // Url to pull down is set under communication/RestConstants.java
10 | public static final String TAG = ResponseModel.class.getSimpleName();
11 |
12 | @JsonProperty
13 | private String responseStatus;
14 |
15 | @JsonProperty
16 | private String responseDetails;
17 |
18 | @JsonProperty
19 | private ResponseDataModel responseData;
20 |
21 | public String getResponseStatus() {
22 | return responseStatus;
23 | }
24 |
25 | public void setResponseStatus(String responseStatus) {
26 | this.responseStatus = responseStatus;
27 | }
28 |
29 | public String getResponseDetails() {
30 | return responseDetails;
31 | }
32 |
33 | public void setResponseDetails(String responseDetails) {
34 | this.responseDetails = responseDetails;
35 | }
36 |
37 | public ResponseDataModel getResponseData() {
38 | return responseData;
39 | }
40 |
41 | public void setResponseData(ResponseDataModel responseData) {
42 | this.responseData = responseData;
43 | }
44 |
45 | @Override
46 | public String toString() {
47 | return "ResponseModel [responseStatus=" + responseStatus
48 | + ", responseDetails=" + responseDetails + ", responseData="
49 | + responseData + "]";
50 | }
51 |
52 |
53 | }
54 |
--------------------------------------------------------------------------------
/rest-client-demo/src/main/res/drawable-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/darko1002001/android-rest-client/3e58498ac831513de8094f72b320ef7c5861c3b0/rest-client-demo/src/main/res/drawable-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/rest-client-demo/src/main/res/drawable-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/darko1002001/android-rest-client/3e58498ac831513de8094f72b320ef7c5861c3b0/rest-client-demo/src/main/res/drawable-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/rest-client-demo/src/main/res/drawable-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/darko1002001/android-rest-client/3e58498ac831513de8094f72b320ef7c5861c3b0/rest-client-demo/src/main/res/drawable-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/rest-client-demo/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
5 |
6 |
14 |
15 |
16 |
--------------------------------------------------------------------------------
/rest-client-demo/src/main/res/menu/activity_main.xml:
--------------------------------------------------------------------------------
1 |
6 |
--------------------------------------------------------------------------------
/rest-client-demo/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | rest-client-demo
4 | Hello world!
5 | Settings
6 | MainActivity
7 |
8 |
--------------------------------------------------------------------------------
/rest-client-demo/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':android-rest-lib', ':android-rest-lib-additions', ':rest-client-demo'
2 |
--------------------------------------------------------------------------------