This class is - * designed to be passed to get, post, put and delete requests with the {@link #onSuccess(int, - * cz.msebera.android.httpclient.Header[], org.json.JSONArray)} or {@link #onSuccess(int, - * cz.msebera.android.httpclient.Header[], org.json.JSONObject)} methods anonymously overridden.
- * Additionally, you can override the other event methods from the parent class. - */ -public class JsonHttpResponseHandler extends TextHttpResponseHandler { - - private static final String LOG_TAG = "JsonHttpResponseHandler"; - - /** - * Creates new JsonHttpResponseHandler, with JSON String encoding UTF-8 - */ - public JsonHttpResponseHandler() { - super(DEFAULT_CHARSET); - } - - /** - * Creates new JsonHttpRespnseHandler with given JSON String encoding - * - * @param encoding String encoding to be used when parsing JSON - */ - public JsonHttpResponseHandler(String encoding) { - super(encoding); - } - - /** - * Returns when request succeeds - * - * @param statusCode http response status line - * @param headers response headers if any - * @param response parsed response if any - */ - public void onSuccess(int statusCode, Header[] headers, JSONObject response) { - Log.w(LOG_TAG, "onSuccess(int, Header[], JSONObject) was not overriden, but callback was received"); - } - - /** - * Returns when request succeeds - * - * @param statusCode http response status line - * @param headers response headers if any - * @param response parsed response if any - */ - public void onSuccess(int statusCode, Header[] headers, JSONArray response) { - Log.w(LOG_TAG, "onSuccess(int, Header[], JSONArray) was not overriden, but callback was received"); - } - - /** - * Returns when request failed - * - * @param statusCode http response status line - * @param headers response headers if any - * @param throwable throwable describing the way request failed - * @param errorResponse parsed response if any - */ - public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) { - Log.w(LOG_TAG, "onFailure(int, Header[], Throwable, JSONObject) was not overriden, but callback was received", throwable); - } - - /** - * Returns when request failed - * - * @param statusCode http response status line - * @param headers response headers if any - * @param throwable throwable describing the way request failed - * @param errorResponse parsed response if any - */ - public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONArray errorResponse) { - Log.w(LOG_TAG, "onFailure(int, Header[], Throwable, JSONArray) was not overriden, but callback was received", throwable); - } - - @Override - public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) { - Log.w(LOG_TAG, "onFailure(int, Header[], String, Throwable) was not overriden, but callback was received", throwable); - } - - @Override - public void onSuccess(int statusCode, Header[] headers, String responseString) { - Log.w(LOG_TAG, "onSuccess(int, Header[], String) was not overriden, but callback was received"); - } - - @Override - public final void onSuccess(final int statusCode, final Header[] headers, final byte[] responseBytes) { - if (statusCode != HttpStatus.SC_NO_CONTENT) { - Runnable parser = new Runnable() { - @Override - public void run() { - try { - final Object jsonResponse = parseResponse(responseBytes); - postRunnable(new Runnable() { - @Override - public void run() { - if (jsonResponse instanceof JSONObject) { - onSuccess(statusCode, headers, (JSONObject) jsonResponse); - } else if (jsonResponse instanceof JSONArray) { - onSuccess(statusCode, headers, (JSONArray) jsonResponse); - } else if (jsonResponse instanceof String) { - onFailure(statusCode, headers, (String) jsonResponse, new JSONException("Response cannot be parsed as JSON data")); - } else { - onFailure(statusCode, headers, new JSONException("Unexpected response type " + jsonResponse.getClass().getName()), (JSONObject) null); - } - - } - }); - } catch (final JSONException ex) { - postRunnable(new Runnable() { - @Override - public void run() { - onFailure(statusCode, headers, ex, (JSONObject) null); - } - }); - } - } - }; - if (!getUseSynchronousMode()) { - new Thread(parser).start(); - } else { - // In synchronous mode everything should be run on one thread - parser.run(); - } - } else { - onSuccess(statusCode, headers, new JSONObject()); - } - } - - @Override - public final void onFailure(final int statusCode, final Header[] headers, final byte[] responseBytes, final Throwable throwable) { - if (responseBytes != null) { - Runnable parser = new Runnable() { - @Override - public void run() { - try { - final Object jsonResponse = parseResponse(responseBytes); - postRunnable(new Runnable() { - @Override - public void run() { - if (jsonResponse instanceof JSONObject) { - onFailure(statusCode, headers, throwable, (JSONObject) jsonResponse); - } else if (jsonResponse instanceof JSONArray) { - onFailure(statusCode, headers, throwable, (JSONArray) jsonResponse); - } else if (jsonResponse instanceof String) { - onFailure(statusCode, headers, (String) jsonResponse, throwable); - } else { - onFailure(statusCode, headers, new JSONException("Unexpected response type " + jsonResponse.getClass().getName()), (JSONObject) null); - } - } - }); - - } catch (final JSONException ex) { - postRunnable(new Runnable() { - @Override - public void run() { - onFailure(statusCode, headers, ex, (JSONObject) null); - } - }); - - } - } - }; - if (!getUseSynchronousMode()) { - new Thread(parser).start(); - } else { - // In synchronous mode everything should be run on one thread - parser.run(); - } - } else { - Log.v(LOG_TAG, "response body is null, calling onFailure(Throwable, JSONObject)"); - onFailure(statusCode, headers, throwable, (JSONObject) null); - } - - // In all cases, call the default failure listener - onAllFailure(statusCode, headers, responseBytes, throwable); - } - - public void onAllFailure(int statusCode, Header[] headers, byte[] responseBytes, Throwable throwable) { - // All failures go there - } - - /** - * Returns Object of type {@link JSONObject}, {@link JSONArray}, String, Boolean, Integer, Long, - * Double or {@link JSONObject#NULL}, see {@link org.json.JSONTokener#nextValue()} - * - * @param responseBody response bytes to be assembled in String and parsed as JSON - * @return Object parsedResponse - * @throws org.json.JSONException exception if thrown while parsing JSON - */ - protected Object parseResponse(byte[] responseBody) throws JSONException { - if (null == responseBody) - return null; - Object result = null; - //trim the string to prevent start with blank, and test if the string is valid JSON, because the parser don't do this :(. If JSON is not valid this will return null - String jsonString = getResponseString(responseBody, getCharset()); - if (jsonString != null) { - jsonString = jsonString.trim(); - if (jsonString.startsWith(UTF8_BOM)) { - jsonString = jsonString.substring(1); - } - if (jsonString.startsWith("{") || jsonString.startsWith("[")) { - result = new JSONTokener(jsonString).nextValue(); - } - } - if (result == null) { - result = jsonString; - } - return result; - } -} diff --git a/docs-android/app/src/main/java/com/sismics/docs/model/application/ApplicationContext.java b/docs-android/app/src/main/java/com/sismics/docs/model/application/ApplicationContext.java index 3fe032a8..b911ddc3 100644 --- a/docs-android/app/src/main/java/com/sismics/docs/model/application/ApplicationContext.java +++ b/docs-android/app/src/main/java/com/sismics/docs/model/application/ApplicationContext.java @@ -4,14 +4,12 @@ import android.app.Activity; import android.content.Context; import com.sismics.docs.listener.CallbackListener; -import com.sismics.docs.listener.JsonHttpResponseHandler; +import com.sismics.docs.listener.HttpCallback; import com.sismics.docs.resource.UserResource; import com.sismics.docs.util.PreferenceUtil; import org.json.JSONObject; -import cz.msebera.android.httpclient.Header; - /** * Global context of the application. * @@ -81,9 +79,9 @@ public class ApplicationContext { * @param callbackListener CallbackListener */ public void fetchUserInfo(final Activity activity, final CallbackListener callbackListener) { - UserResource.info(activity.getApplicationContext(), new JsonHttpResponseHandler() { + UserResource.info(activity.getApplicationContext(), new HttpCallback() { @Override - public void onSuccess(int statusCode, Header[] headers, final JSONObject json) { + public void onSuccess(JSONObject json) { // Save data in application context if (!json.optBoolean("anonymous", true)) { setUserInfo(activity.getApplicationContext(), json); diff --git a/docs-android/app/src/main/java/com/sismics/docs/resource/BaseResource.java b/docs-android/app/src/main/java/com/sismics/docs/resource/BaseResource.java index c0f421cb..e78bd2a2 100644 --- a/docs-android/app/src/main/java/com/sismics/docs/resource/BaseResource.java +++ b/docs-android/app/src/main/java/com/sismics/docs/resource/BaseResource.java @@ -1,124 +1,15 @@ package com.sismics.docs.resource; import android.content.Context; -import android.os.Build; -import com.loopj.android.http.AsyncHttpClient; -import com.loopj.android.http.PersistentCookieStore; -import com.sismics.docs.util.ApplicationUtil; import com.sismics.docs.util.PreferenceUtil; -import java.io.IOException; -import java.net.Socket; -import java.security.KeyManagementException; -import java.security.KeyStore; -import java.security.KeyStoreException; -import java.security.NoSuchAlgorithmException; -import java.security.UnrecoverableKeyException; -import java.security.cert.CertificateException; -import java.security.cert.X509Certificate; -import java.util.Locale; - -import javax.net.ssl.SSLContext; -import javax.net.ssl.TrustManager; -import javax.net.ssl.X509TrustManager; - -import cz.msebera.android.httpclient.conn.ssl.SSLSocketFactory; - /** * Base class for API access. * * @author bgamard */ public class BaseResource { - /** - * User-Agent to use. - */ - protected static String USER_AGENT = null; - - /** - * Accept-Language header. - */ - protected static String ACCEPT_LANGUAGE = null; - - /** - * Async HTTP client. - */ - protected static AsyncHttpClient client = new AsyncHttpClient(); - - static { - // 20sec default timeout - client.setTimeout(60000); - try { - KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); - trustStore.load(null, null); - - // Async HTTP Client uses another HTTP libary - MySSLSocketFactory sf = new MySSLSocketFactory(trustStore); - sf.setHostnameVerifier(MySSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); - client.setSSLSocketFactory(sf); - } catch (Exception e) { - // NOP - } - } - - /** - * Resource initialization. - * - * @param context Context - */ - protected static void init(Context context) { - client.setCookieStore(new PersistentCookieStore(context)); - - if (USER_AGENT == null) { - USER_AGENT = "Sismics Docs Android " + ApplicationUtil.getVersionName(context) + "/Android " + Build.VERSION.RELEASE + "/" + Build.MODEL; - client.setUserAgent(USER_AGENT); - } - - if (ACCEPT_LANGUAGE == null) { - Locale locale = Locale.getDefault(); - ACCEPT_LANGUAGE = locale.getLanguage() + "_" + locale.getCountry(); - client.addHeader("Accept-Language", ACCEPT_LANGUAGE); - } - } - - /** - * Socket factory to allow self-signed certificates for Async HTTP Client. - * - * @author bgamard - */ - public static class MySSLSocketFactory extends cz.msebera.android.httpclient.conn.ssl.SSLSocketFactory { - SSLContext sslContext = SSLContext.getInstance(SSLSocketFactory.TLS); - - public MySSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException { - super(truststore); - - TrustManager tm = new X509TrustManager() { - public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { - } - - public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { - } - - public X509Certificate[] getAcceptedIssuers() { - return null; - } - }; - - sslContext.init(null, new TrustManager[]{tm}, null); - } - - @Override - public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException { - return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose); - } - - @Override - public Socket createSocket() throws IOException { - return sslContext.getSocketFactory().createSocket(); - } - } - /** * Returns cleaned API URL. * diff --git a/docs-android/app/src/main/java/com/sismics/docs/resource/CommentResource.java b/docs-android/app/src/main/java/com/sismics/docs/resource/CommentResource.java index 6e545956..d93ee657 100644 --- a/docs-android/app/src/main/java/com/sismics/docs/resource/CommentResource.java +++ b/docs-android/app/src/main/java/com/sismics/docs/resource/CommentResource.java @@ -2,8 +2,12 @@ package com.sismics.docs.resource; import android.content.Context; -import com.loopj.android.http.RequestParams; -import com.sismics.docs.listener.JsonHttpResponseHandler; +import com.sismics.docs.listener.HttpCallback; +import com.sismics.docs.util.OkHttpUtil; + +import okhttp3.FormBody; +import okhttp3.HttpUrl; +import okhttp3.Request; /** @@ -17,12 +21,16 @@ public class CommentResource extends BaseResource { * * @param context Context * @param documentId Document ID - * @param responseHandler Callback + * @param callback Callback */ - public static void list(Context context, String documentId, JsonHttpResponseHandler responseHandler) { - init(context); - - client.get(getApiUrl(context) + "/comment/" + documentId, responseHandler); + public static void list(Context context, String documentId, HttpCallback callback) { + Request request = new Request.Builder() + .url(HttpUrl.parse(getApiUrl(context) + "/comment/" + documentId)) + .get() + .build(); + OkHttpUtil.buildClient(context) + .newCall(request) + .enqueue(HttpCallback.buildOkHttpCallback(callback)); } /** @@ -31,15 +39,19 @@ public class CommentResource extends BaseResource { * @param context Context * @param documentId Document ID * @param content Comment content - * @param responseHandler Callback + * @param callback Callback */ - public static void add(Context context, String documentId, String content, JsonHttpResponseHandler responseHandler) { - init(context); - - RequestParams params = new RequestParams(); - params.put("id", documentId); - params.put("content", content); - client.put(getApiUrl(context) + "/comment", params, responseHandler); + public static void add(Context context, String documentId, String content, HttpCallback callback) { + Request request = new Request.Builder() + .url(HttpUrl.parse(getApiUrl(context) + "/comment")) + .put(new FormBody.Builder() + .add("id", documentId) + .add("content", content) + .build()) + .build(); + OkHttpUtil.buildClient(context) + .newCall(request) + .enqueue(HttpCallback.buildOkHttpCallback(callback)); } /** @@ -47,20 +59,15 @@ public class CommentResource extends BaseResource { * * @param context Context * @param commentId Comment ID - * @param responseHandler Callback + * @param callback Callback */ - public static void remove(Context context, String commentId, JsonHttpResponseHandler responseHandler) { - init(context); - - client.delete(getApiUrl(context) + "/comment/" + commentId, responseHandler); - } - - /** - * Cancel pending requests. - * - * @param context Context - */ - public static void cancel(Context context) { - client.cancelRequests(context, true); + public static void remove(Context context, String commentId, HttpCallback callback) { + Request request = new Request.Builder() + .url(HttpUrl.parse(getApiUrl(context) + "/comment/" + commentId)) + .delete() + .build(); + OkHttpUtil.buildClient(context) + .newCall(request) + .enqueue(HttpCallback.buildOkHttpCallback(callback)); } } diff --git a/docs-android/app/src/main/java/com/sismics/docs/resource/DocumentResource.java b/docs-android/app/src/main/java/com/sismics/docs/resource/DocumentResource.java index 474590bf..b3bc5a71 100644 --- a/docs-android/app/src/main/java/com/sismics/docs/resource/DocumentResource.java +++ b/docs-android/app/src/main/java/com/sismics/docs/resource/DocumentResource.java @@ -94,9 +94,8 @@ public class DocumentResource extends BaseResource { .add("description", description) .add("language", language) .add("create_date", Long.toString(createDate)); - String[] tagIdArray = tagIdList.toArray(new String[tagIdList.size()]); - for (int i = 0; i < tagIdArray.length; i++) { - formBuilder.add("tags", tagIdArray[i]); + for( String tagId : tagIdList) { + formBuilder.add("tags", tagId); } Request request = new Request.Builder() @@ -127,9 +126,8 @@ public class DocumentResource extends BaseResource { .add("description", description) .add("language", language) .add("create_date", Long.toString(createDate)); - String[] tagIdArray = tagIdList.toArray(new String[tagIdList.size()]); - for (int i = 0; i < tagIdArray.length; i++) { - formBuilder.add("tags", tagIdArray[i]); + for( String tagId : tagIdList) { + formBuilder.add("tags", tagId); } Request request = new Request.Builder() @@ -140,13 +138,4 @@ public class DocumentResource extends BaseResource { .newCall(request) .enqueue(HttpCallback.buildOkHttpCallback(callback)); } - - /** - * Cancel pending requests. - * - * @param context Context - */ - public static void cancel(Context context) { - client.cancelRequests(context, true); - } } diff --git a/docs-android/app/src/main/java/com/sismics/docs/resource/FileResource.java b/docs-android/app/src/main/java/com/sismics/docs/resource/FileResource.java index 2e594817..87922f8d 100644 --- a/docs-android/app/src/main/java/com/sismics/docs/resource/FileResource.java +++ b/docs-android/app/src/main/java/com/sismics/docs/resource/FileResource.java @@ -2,13 +2,24 @@ package com.sismics.docs.resource; import android.content.Context; -import com.loopj.android.http.PersistentCookieStore; -import com.loopj.android.http.RequestParams; -import com.loopj.android.http.SyncHttpClient; -import com.sismics.docs.listener.JsonHttpResponseHandler; +import com.sismics.docs.listener.HttpCallback; +import com.sismics.docs.util.OkHttpUtil; +import org.json.JSONObject; + +import java.io.IOException; import java.io.InputStream; -import java.security.KeyStore; + +import okhttp3.HttpUrl; +import okhttp3.MediaType; +import okhttp3.MultipartBody; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.internal.Util; +import okio.BufferedSink; +import okio.Okio; +import okio.Source; /** @@ -22,12 +33,19 @@ public class FileResource extends BaseResource { * * @param context Context * @param documentId Document ID - * @param responseHandler Callback + * @param callback Callback */ - public static void list(Context context, String documentId, JsonHttpResponseHandler responseHandler) { - init(context); - - client.get(getApiUrl(context) + "/file/list?id=" + documentId, responseHandler); + public static void list(Context context, String documentId, HttpCallback callback) { + Request request = new Request.Builder() + .url(HttpUrl.parse(getApiUrl(context) + "/file/list") + .newBuilder() + .addQueryParameter("id", documentId) + .build()) + .get() + .build(); + OkHttpUtil.buildClient(context) + .newCall(request) + .enqueue(HttpCallback.buildOkHttpCallback(callback)); } /** @@ -35,12 +53,16 @@ public class FileResource extends BaseResource { * * @param context Context * @param id ID - * @param responseHandler Callback + * @param callback Callback */ - public static void delete(Context context, String id, JsonHttpResponseHandler responseHandler) { - init(context); - - client.delete(getApiUrl(context) + "/file/" + id, responseHandler); + public static void delete(Context context, String id, HttpCallback callback) { + Request request = new Request.Builder() + .url(HttpUrl.parse(getApiUrl(context) + "/file/" + id)) + .delete() + .build(); + OkHttpUtil.buildClient(context) + .newCall(request) + .enqueue(HttpCallback.buildOkHttpCallback(callback)); } /** @@ -49,34 +71,53 @@ public class FileResource extends BaseResource { * @param context Context * @param documentId Document ID * @param is Input stream - * @param responseHandler Callback + * @param callback Callback * @throws Exception */ - public static void addSync(Context context, String documentId, InputStream is, JsonHttpResponseHandler responseHandler) throws Exception { - init(context); + public static void addSync(Context context, String documentId, final InputStream is, HttpCallback callback) throws Exception { + Request request = new Request.Builder() + .url(HttpUrl.parse(getApiUrl(context) + "/file")) + .put(new MultipartBody.Builder() + .setType(MultipartBody.FORM) + .addFormDataPart("id", documentId) + .addFormDataPart("file", "file", new RequestBody() { + @Override + public MediaType contentType() { + return MediaType.parse("application/octet-stream"); + } - SyncHttpClient client = new SyncHttpClient(); - KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); - trustStore.load(null, null); - MySSLSocketFactory sf = new MySSLSocketFactory(trustStore); - sf.setHostnameVerifier(MySSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); - client.setSSLSocketFactory(sf); - client.setCookieStore(new PersistentCookieStore(context)); - client.setUserAgent(USER_AGENT); - client.addHeader("Accept-Language", ACCEPT_LANGUAGE); + @Override + public void writeTo(BufferedSink sink) throws IOException { + Source source = Okio.source(is); + try { + sink.writeAll(source); + } finally { + Util.closeQuietly(source); + } + } + }) + .build()) + .build(); + Response response = OkHttpUtil.buildClient(context) + .newCall(request) + .execute(); - RequestParams params = new RequestParams(); - params.put("id", documentId); - params.put("file", is, "file", "application/octet-stream", true); - client.put(getApiUrl(context) + "/file", params, responseHandler); - } + // Call the right callback + final String body = response.body().string(); + if (response.isSuccessful()) { + try { + callback.onSuccess(new JSONObject(body)); + } catch (Exception e) { + callback.onFailure(null, e); + } + } else { + try { + callback.onFailure(new JSONObject(body), null); + } catch (Exception e) { + callback.onFailure(null, e); + } + } - /** - * Cancel pending requests. - * - * @param context Context - */ - public static void cancel(Context context) { - client.cancelRequests(context, true); + callback.onFinish(); } } diff --git a/docs-android/app/src/main/java/com/sismics/docs/resource/ShareResource.java b/docs-android/app/src/main/java/com/sismics/docs/resource/ShareResource.java index 833d993e..fbbfba81 100644 --- a/docs-android/app/src/main/java/com/sismics/docs/resource/ShareResource.java +++ b/docs-android/app/src/main/java/com/sismics/docs/resource/ShareResource.java @@ -2,8 +2,12 @@ package com.sismics.docs.resource; import android.content.Context; -import com.loopj.android.http.RequestParams; -import com.sismics.docs.listener.JsonHttpResponseHandler; +import com.sismics.docs.listener.HttpCallback; +import com.sismics.docs.util.OkHttpUtil; + +import okhttp3.FormBody; +import okhttp3.HttpUrl; +import okhttp3.Request; /** @@ -18,15 +22,19 @@ public class ShareResource extends BaseResource { * @param context Context * @param documentId Document ID * @param name Name - * @param responseHandler Callback + * @param callback Callback */ - public static void add(Context context, String documentId, String name, JsonHttpResponseHandler responseHandler) { - init(context); - - RequestParams params = new RequestParams(); - params.put("id", documentId); - params.put("name", name); - client.put(getApiUrl(context) + "/share", params, responseHandler); + public static void add(Context context, String documentId, String name, HttpCallback callback) { + Request request = new Request.Builder() + .url(HttpUrl.parse(getApiUrl(context) + "/share")) + .put(new FormBody.Builder() + .add("id", documentId) + .add("name", name) + .build()) + .build(); + OkHttpUtil.buildClient(context) + .newCall(request) + .enqueue(HttpCallback.buildOkHttpCallback(callback)); } /** @@ -34,11 +42,15 @@ public class ShareResource extends BaseResource { * * @param context Context * @param id ID - * @param responseHandler Callback + * @param callback Callback */ - public static void delete(Context context, String id, JsonHttpResponseHandler responseHandler) { - init(context); - - client.delete(getApiUrl(context) + "/share/" + id, responseHandler); + public static void delete(Context context, String id, HttpCallback callback) { + Request request = new Request.Builder() + .url(HttpUrl.parse(getApiUrl(context) + "/share/" + id)) + .delete() + .build(); + OkHttpUtil.buildClient(context) + .newCall(request) + .enqueue(HttpCallback.buildOkHttpCallback(callback)); } } diff --git a/docs-android/app/src/main/java/com/sismics/docs/resource/TagResource.java b/docs-android/app/src/main/java/com/sismics/docs/resource/TagResource.java index db03bb16..34539d14 100644 --- a/docs-android/app/src/main/java/com/sismics/docs/resource/TagResource.java +++ b/docs-android/app/src/main/java/com/sismics/docs/resource/TagResource.java @@ -2,7 +2,11 @@ package com.sismics.docs.resource; import android.content.Context; -import com.sismics.docs.listener.JsonHttpResponseHandler; +import com.sismics.docs.listener.HttpCallback; +import com.sismics.docs.util.OkHttpUtil; + +import okhttp3.HttpUrl; +import okhttp3.Request; /** @@ -15,11 +19,15 @@ public class TagResource extends BaseResource { * GET /tag/stats. * * @param context Context - * @param responseHandler Callback + * @param callback Callback */ - public static void stats(Context context, JsonHttpResponseHandler responseHandler) { - init(context); - - client.get(getApiUrl(context) + "/tag/stats", responseHandler); + public static void stats(Context context, HttpCallback callback) { + Request request = new Request.Builder() + .url(HttpUrl.parse(getApiUrl(context) + "/tag/stats")) + .get() + .build(); + OkHttpUtil.buildClient(context) + .newCall(request) + .enqueue(HttpCallback.buildOkHttpCallback(callback)); } } diff --git a/docs-android/app/src/main/java/com/sismics/docs/resource/UserResource.java b/docs-android/app/src/main/java/com/sismics/docs/resource/UserResource.java index 36cb11db..3d35564a 100644 --- a/docs-android/app/src/main/java/com/sismics/docs/resource/UserResource.java +++ b/docs-android/app/src/main/java/com/sismics/docs/resource/UserResource.java @@ -2,8 +2,12 @@ package com.sismics.docs.resource; import android.content.Context; -import com.loopj.android.http.RequestParams; -import com.sismics.docs.listener.JsonHttpResponseHandler; +import com.sismics.docs.listener.HttpCallback; +import com.sismics.docs.util.OkHttpUtil; + +import okhttp3.FormBody; +import okhttp3.HttpUrl; +import okhttp3.Request; /** * Access to /user API. @@ -18,41 +22,51 @@ public class UserResource extends BaseResource { * @param context Context * @param username Username * @param password Password - * @param responseHandler Callback + * @param callback Callback */ - public static void login(Context context, String username, String password, JsonHttpResponseHandler responseHandler) { - init(context); - - RequestParams params = new RequestParams(); - params.put("username", username); - params.put("password", password); - params.put("remember", "true"); - client.post(getApiUrl(context) + "/user/login", params, responseHandler); + public static void login(Context context, String username, String password, HttpCallback callback) { + Request request = new Request.Builder() + .url(HttpUrl.parse(getApiUrl(context) + "/user/login")) + .post(new FormBody.Builder() + .add("username", username) + .add("password", password) + .add("remember", "true") + .build()) + .build(); + OkHttpUtil.buildClient(context) + .newCall(request) + .enqueue(HttpCallback.buildOkHttpCallback(callback)); } /** * GET /user. * * @param context Context - * @param responseHandler Callback + * @param callback Callback */ - public static void info(Context context, JsonHttpResponseHandler responseHandler) { - init(context); - - RequestParams params = new RequestParams(); - client.get(getApiUrl(context) + "/user", params, responseHandler); + public static void info(Context context, HttpCallback callback) { + Request request = new Request.Builder() + .url(HttpUrl.parse(getApiUrl(context) + "/user")) + .get() + .build(); + OkHttpUtil.buildClient(context) + .newCall(request) + .enqueue(HttpCallback.buildOkHttpCallback(callback)); } /** * POST /user/logout. * * @param context Context - * @param responseHandler Callback + * @param callback Callback */ - public static void logout(Context context, JsonHttpResponseHandler responseHandler) { - init(context); - - RequestParams params = new RequestParams(); - client.post(getApiUrl(context) + "/user/logout", params, responseHandler); + public static void logout(Context context, HttpCallback callback) { + Request request = new Request.Builder() + .url(HttpUrl.parse(getApiUrl(context) + "/user/logout")) + .post(new FormBody.Builder().build()) + .build(); + OkHttpUtil.buildClient(context) + .newCall(request) + .enqueue(HttpCallback.buildOkHttpCallback(callback)); } } diff --git a/docs-android/app/src/main/java/com/sismics/docs/service/FileUploadService.java b/docs-android/app/src/main/java/com/sismics/docs/service/FileUploadService.java index 79903b77..794b9036 100644 --- a/docs-android/app/src/main/java/com/sismics/docs/service/FileUploadService.java +++ b/docs-android/app/src/main/java/com/sismics/docs/service/FileUploadService.java @@ -12,7 +12,7 @@ import android.util.Log; import com.sismics.docs.R; import com.sismics.docs.event.FileAddEvent; -import com.sismics.docs.listener.JsonHttpResponseHandler; +import com.sismics.docs.listener.HttpCallback; import com.sismics.docs.resource.FileResource; import org.json.JSONObject; @@ -20,8 +20,8 @@ import org.json.JSONObject; import java.io.IOException; import java.io.InputStream; -import cz.msebera.android.httpclient.Header; import de.greenrobot.event.EventBus; +import okhttp3.internal.Util; /** * Service to upload a file to a document in the background. @@ -81,17 +81,22 @@ public class FileUploadService extends IntentService { */ private void handleFileUpload(final String documentId, final Uri uri) throws Exception { final InputStream is = getContentResolver().openInputStream(uri); - FileResource.addSync(this, documentId, is, new JsonHttpResponseHandler() { + FileResource.addSync(this, documentId, is, new HttpCallback() { @Override - public void onSuccess(int statusCode, Header[] headers, JSONObject response) { + public void onSuccess(JSONObject response) { EventBus.getDefault().post(new FileAddEvent(documentId, response.optString("id"))); FileUploadService.this.onComplete(); } @Override - public void onAllFailure(int statusCode, Header[] headers, byte[] responseBytes, Throwable throwable) { + public void onFailure(JSONObject json, Exception e) { FileUploadService.this.onError(); } + + @Override + public void onFinish() { + Util.closeQuietly(is); + } }); } diff --git a/docs-android/app/src/main/java/com/sismics/docs/util/OkHttpUtil.java b/docs-android/app/src/main/java/com/sismics/docs/util/OkHttpUtil.java index e6756cdf..8ab91793 100644 --- a/docs-android/app/src/main/java/com/sismics/docs/util/OkHttpUtil.java +++ b/docs-android/app/src/main/java/com/sismics/docs/util/OkHttpUtil.java @@ -11,8 +11,6 @@ import com.squareup.picasso.Picasso; import java.io.IOException; import java.net.CookieManager; import java.net.CookiePolicy; -import java.net.HttpCookie; -import java.net.URI; import java.security.cert.CertificateException; import java.util.Locale; import java.util.concurrent.TimeUnit; @@ -105,10 +103,10 @@ public class OkHttpUtil { @Override public Response intercept(Interceptor.Chain chain) throws IOException { // Override cache configuration final Request original = chain.request(); - final Request.Builder requestBuilder = original.newBuilder() + return chain.proceed(original.newBuilder() .header("Cache-Control", "max-age=" + (3600 * 24 * 365)) - .method(original.method(), original.body()); - return chain.proceed(requestBuilder.build()); + .method(original.method(), original.body()) + .build()); } }) .cache(getCache(context)) @@ -169,8 +167,6 @@ public class OkHttpUtil { // Cookie handling PersistentCookieStore cookieStore = new PersistentCookieStore(context); CookieManager cookieManager = new CookieManager(cookieStore, CookiePolicy.ACCEPT_ALL); - cookieStore.add(URI.create(PreferenceUtil.getServerUrl(context)), - new HttpCookie("auth_token", PreferenceUtil.getAuthToken(context))); // TODO Remove me when async http is ditched // Runtime configuration return okHttpClient.newBuilder() @@ -178,11 +174,11 @@ public class OkHttpUtil { .addNetworkInterceptor(new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { - Request originalRequest = chain.request(); - return chain.proceed(originalRequest.newBuilder() + Request original = chain.request(); + return chain.proceed(original.newBuilder() .header("User-Agent", userAgent) .header("Accept-Language", acceptLanguage) - // TODO necessary?? .method(originalRequest.method(), originalRequest.body()) + .method(original.method(), original.body()) .build()); } }) diff --git a/docs-android/app/src/main/java/com/sismics/docs/util/PreferenceUtil.java b/docs-android/app/src/main/java/com/sismics/docs/util/PreferenceUtil.java index 581bc139..da8537ea 100644 --- a/docs-android/app/src/main/java/com/sismics/docs/util/PreferenceUtil.java +++ b/docs-android/app/src/main/java/com/sismics/docs/util/PreferenceUtil.java @@ -5,14 +5,13 @@ import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.preference.PreferenceManager; -import com.loopj.android.http.PersistentCookieStore; +import com.sismics.docs.resource.cookie.PersistentCookieStore; import org.json.JSONObject; +import java.net.HttpCookie; import java.util.List; -import cz.msebera.android.httpclient.cookie.Cookie; - /** * Utility class on preferences. * @@ -27,6 +26,7 @@ public class PreferenceUtil { /** * Returns a preference of boolean type. + * * @param context Context * @param key Shared preference key * @return Shared preference value @@ -38,6 +38,7 @@ public class PreferenceUtil { /** * Returns a preference of string type. + * * @param context Context * @param key Shared preference key * @return Shared preference value @@ -49,6 +50,7 @@ public class PreferenceUtil { /** * Returns a preference of integer type. + * * @param context Context * @param key Shared preference key * @return Shared preference value @@ -70,6 +72,7 @@ public class PreferenceUtil { /** * Update JSON cache. + * * @param context Context * @param key Shared preference key * @param json JSON data @@ -81,6 +84,7 @@ public class PreferenceUtil { /** * Returns a JSON cache. + * * @param context Context * @param key Shared preference key * @return JSON data @@ -97,6 +101,7 @@ public class PreferenceUtil { /** * Update server URL. + * * @param context Context */ public static void setServerUrl(Context context, String serverUrl) { @@ -106,6 +111,7 @@ public class PreferenceUtil { /** * Empty user caches. + * * @param context Context */ public static void resetUserCache(Context context) { @@ -119,12 +125,13 @@ public class PreferenceUtil { /** * Returns auth token cookie from shared preferences. + * * @return Auth token */ public static String getAuthToken(Context context) { PersistentCookieStore cookieStore = new PersistentCookieStore(context); - List