mirror of
https://github.com/sismics/docs.git
synced 2024-11-22 05:57:57 +01:00
#57: Android: Remove android-async-http for OkHttp
This commit is contained in:
parent
3172a5f216
commit
cfa5888be9
@ -61,13 +61,6 @@
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/main/java" isTestSource="false" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/main/jni" isTestSource="false" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/main/rs" isTestSource="false" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/androidTest/res" type="java-test-resource" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/androidTest/resources" type="java-test-resource" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/androidTest/assets" type="java-test-resource" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/androidTest/aidl" isTestSource="true" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/androidTest/java" isTestSource="true" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/androidTest/jni" isTestSource="true" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/androidTest/rs" isTestSource="true" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/test/res" type="java-test-resource" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/test/resources" type="java-test-resource" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/test/assets" type="java-test-resource" />
|
||||
@ -75,6 +68,13 @@
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/test/java" isTestSource="true" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/test/jni" isTestSource="true" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/test/rs" isTestSource="true" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/androidTest/res" type="java-test-resource" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/androidTest/resources" type="java-test-resource" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/androidTest/assets" type="java-test-resource" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/androidTest/aidl" isTestSource="true" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/androidTest/java" isTestSource="true" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/androidTest/jni" isTestSource="true" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/androidTest/rs" isTestSource="true" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/assets" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/blame" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/builds" />
|
||||
@ -89,7 +89,6 @@
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/incremental" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/incremental-classes" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/incremental-runtime-classes" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/incremental-runtimfe-classes" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/incremental-verifier" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/instant-run-support" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/jniLibs" />
|
||||
@ -108,15 +107,13 @@
|
||||
<orderEntry type="library" exported="" name="support-annotations-23.1.1" level="project" />
|
||||
<orderEntry type="library" exported="" name="android-easing-1.0.3" level="project" />
|
||||
<orderEntry type="library" exported="" name="imagezoom-1.0.5" level="project" />
|
||||
<orderEntry type="library" exported="" name="android-async-http-1.4.9" level="project" />
|
||||
<orderEntry type="library" exported="" name="picasso-2.5.2" level="project" />
|
||||
<orderEntry type="library" exported="" name="eventbus-2.4.1" level="project" />
|
||||
<orderEntry type="library" exported="" name="recyclerview-v7-23.1.1" level="project" />
|
||||
<orderEntry type="library" exported="" name="okhttp-urlconnection-3.0.1" level="project" />
|
||||
<orderEntry type="library" exported="" name="recyclerview-v7-23.1.1" level="project" />
|
||||
<orderEntry type="library" exported="" name="support-v4-23.1.1" level="project" />
|
||||
<orderEntry type="library" exported="" name="fab-0.0.6" level="project" />
|
||||
<orderEntry type="library" exported="" name="appcompat-v7-23.1.1" level="project" />
|
||||
<orderEntry type="library" exported="" name="httpclient-4.3.6" level="project" />
|
||||
<orderEntry type="library" exported="" name="okio-1.6.0" level="project" />
|
||||
<orderEntry type="library" exported="" name="picasso2-okhttp3-downloader-1.0.2" level="project" />
|
||||
<orderEntry type="library" exported="" name="tokenautocomplete-1.2.1" level="project" />
|
||||
|
@ -52,7 +52,6 @@ dependencies {
|
||||
compile fileTree(dir: 'libs', include: '*.jar')
|
||||
compile 'com.android.support:appcompat-v7:23.1.1'
|
||||
compile 'com.android.support:recyclerview-v7:23.1.1'
|
||||
compile 'com.loopj.android:android-async-http:1.4.9'
|
||||
compile 'it.sephiroth.android.library.imagezoom:imagezoom:1.0.5'
|
||||
compile 'de.greenrobot:eventbus:2.4.1'
|
||||
compile 'com.shamanland:fab:0.0.6'
|
||||
|
@ -1,7 +1,6 @@
|
||||
package com.sismics.docs.activity;
|
||||
|
||||
import android.app.ProgressDialog;
|
||||
import android.content.DialogInterface;
|
||||
import android.os.Bundle;
|
||||
import android.support.v7.app.AppCompatActivity;
|
||||
import android.util.Log;
|
||||
@ -164,13 +163,7 @@ public class DocumentEditActivity extends AppCompatActivity {
|
||||
// Cancellable progress dialog
|
||||
final ProgressDialog progressDialog = ProgressDialog.show(this,
|
||||
getString(R.string.please_wait),
|
||||
getString(R.string.document_editing_message), true, true,
|
||||
new DialogInterface.OnCancelListener() {
|
||||
@Override
|
||||
public void onCancel(DialogInterface dialog) {
|
||||
DocumentResource.cancel(DocumentEditActivity.this);
|
||||
}
|
||||
});
|
||||
getString(R.string.document_editing_message), true, true);
|
||||
|
||||
// Server callback
|
||||
HttpCallback callback = new HttpCallback() {
|
||||
|
@ -47,7 +47,6 @@ import com.sismics.docs.event.FileDeleteEvent;
|
||||
import com.sismics.docs.fragment.DocExportPdfFragment;
|
||||
import com.sismics.docs.fragment.DocShareFragment;
|
||||
import com.sismics.docs.listener.HttpCallback;
|
||||
import com.sismics.docs.listener.JsonHttpResponseHandler;
|
||||
import com.sismics.docs.model.application.ApplicationContext;
|
||||
import com.sismics.docs.resource.CommentResource;
|
||||
import com.sismics.docs.resource.DocumentResource;
|
||||
@ -64,7 +63,6 @@ import java.util.ArrayList;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
|
||||
import cz.msebera.android.httpclient.Header;
|
||||
import de.greenrobot.event.EventBus;
|
||||
|
||||
/**
|
||||
@ -282,14 +280,14 @@ public class DocumentViewActivity extends AppCompatActivity {
|
||||
CommentResource.add(DocumentViewActivity.this,
|
||||
DocumentViewActivity.this.document.optString("id"),
|
||||
commentEditText.getText().toString(),
|
||||
new JsonHttpResponseHandler() {
|
||||
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
|
||||
new HttpCallback() {
|
||||
public void onSuccess(JSONObject response) {
|
||||
EventBus.getDefault().post(new CommentAddEvent(response));
|
||||
commentEditText.setText("");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onAllFailure(int statusCode, Header[] headers, byte[] responseBytes, Throwable throwable) {
|
||||
public void onFailure(JSONObject json, Exception e) {
|
||||
Toast.makeText(DocumentViewActivity.this, R.string.comment_add_failure, Toast.LENGTH_LONG).show();
|
||||
}
|
||||
});
|
||||
@ -393,24 +391,18 @@ public class DocumentViewActivity extends AppCompatActivity {
|
||||
// Show a progress dialog while deleting
|
||||
final ProgressDialog progressDialog = ProgressDialog.show(DocumentViewActivity.this,
|
||||
getString(R.string.please_wait),
|
||||
getString(R.string.file_deleting_message), true, true,
|
||||
new DialogInterface.OnCancelListener() {
|
||||
@Override
|
||||
public void onCancel(DialogInterface dialog) {
|
||||
FileResource.cancel(DocumentViewActivity.this);
|
||||
}
|
||||
});
|
||||
getString(R.string.file_deleting_message), true, true);
|
||||
|
||||
// Actual delete server call
|
||||
final String fileId = file.optString("id");
|
||||
FileResource.delete(DocumentViewActivity.this, fileId, new JsonHttpResponseHandler() {
|
||||
FileResource.delete(DocumentViewActivity.this, fileId, new HttpCallback() {
|
||||
@Override
|
||||
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
|
||||
public void onSuccess(JSONObject response) {
|
||||
EventBus.getDefault().post(new FileDeleteEvent(fileId));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onAllFailure(int statusCode, Header[] headers, byte[] responseBytes, Throwable throwable) {
|
||||
public void onFailure(JSONObject json, Exception e) {
|
||||
Toast.makeText(DocumentViewActivity.this, R.string.file_delete_failure, Toast.LENGTH_LONG).show();
|
||||
}
|
||||
|
||||
@ -478,13 +470,7 @@ public class DocumentViewActivity extends AppCompatActivity {
|
||||
// Show a progress dialog while deleting
|
||||
final ProgressDialog progressDialog = ProgressDialog.show(DocumentViewActivity.this,
|
||||
getString(R.string.please_wait),
|
||||
getString(R.string.document_deleting_message), true, true,
|
||||
new DialogInterface.OnCancelListener() {
|
||||
@Override
|
||||
public void onCancel(DialogInterface dialog) {
|
||||
DocumentResource.cancel(DocumentViewActivity.this);
|
||||
}
|
||||
});
|
||||
getString(R.string.document_deleting_message), true, true);
|
||||
|
||||
// Actual delete server call
|
||||
final String documentId = document.optString("id");
|
||||
@ -696,14 +682,14 @@ public class DocumentViewActivity extends AppCompatActivity {
|
||||
final String commentId = comment.optString("id");
|
||||
Toast.makeText(DocumentViewActivity.this, R.string.deleting_comment, Toast.LENGTH_LONG).show();
|
||||
|
||||
CommentResource.remove(DocumentViewActivity.this, commentId, new JsonHttpResponseHandler() {
|
||||
CommentResource.remove(DocumentViewActivity.this, commentId, new HttpCallback() {
|
||||
@Override
|
||||
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
|
||||
public void onSuccess(JSONObject response) {
|
||||
EventBus.getDefault().post(new CommentDeleteEvent(commentId));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onAllFailure(int statusCode, Header[] headers, byte[] responseBytes, Throwable throwable) {
|
||||
public void onFailure(JSONObject json, Exception e) {
|
||||
Toast.makeText(DocumentViewActivity.this, R.string.error_deleting_comment, Toast.LENGTH_LONG).show();
|
||||
}
|
||||
});
|
||||
@ -728,9 +714,9 @@ public class DocumentViewActivity extends AppCompatActivity {
|
||||
listView.setVisibility(View.GONE);
|
||||
registerForContextMenu(listView);
|
||||
|
||||
CommentResource.list(this, document.optString("id"), new JsonHttpResponseHandler() {
|
||||
CommentResource.list(this, document.optString("id"), new HttpCallback() {
|
||||
@Override
|
||||
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
|
||||
public void onSuccess(JSONObject response) {
|
||||
JSONArray comments = response.optJSONArray("comments");
|
||||
commentListAdapter = new CommentListAdapter(DocumentViewActivity.this, comments);
|
||||
listView.setAdapter(commentListAdapter);
|
||||
@ -743,7 +729,7 @@ public class DocumentViewActivity extends AppCompatActivity {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onAllFailure(int statusCode, Header[] headers, byte[] responseBytes, Throwable throwable) {
|
||||
public void onFailure(JSONObject json, Exception e) {
|
||||
emptyView.setText(R.string.error_loading_comments);
|
||||
progressBar.setVisibility(View.GONE);
|
||||
listView.setVisibility(View.GONE);
|
||||
@ -766,9 +752,9 @@ public class DocumentViewActivity extends AppCompatActivity {
|
||||
progressBar.setVisibility(View.VISIBLE);
|
||||
filesEmptyView.setVisibility(View.GONE);
|
||||
|
||||
FileResource.list(this, document.optString("id"), new JsonHttpResponseHandler() {
|
||||
FileResource.list(this, document.optString("id"), new HttpCallback() {
|
||||
@Override
|
||||
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
|
||||
public void onSuccess(JSONObject response) {
|
||||
JSONArray files = response.optJSONArray("files");
|
||||
filePagerAdapter = new FilePagerAdapter(DocumentViewActivity.this, files);
|
||||
fileViewPager.setAdapter(filePagerAdapter);
|
||||
@ -778,7 +764,7 @@ public class DocumentViewActivity extends AppCompatActivity {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onAllFailure(int statusCode, Header[] headers, byte[] responseBytes, Throwable throwable) {
|
||||
public void onFailure(JSONObject json, Exception e) {
|
||||
filesEmptyView.setText(R.string.error_loading_files);
|
||||
progressBar.setVisibility(View.GONE);
|
||||
filesEmptyView.setVisibility(View.VISIBLE);
|
||||
|
@ -14,7 +14,7 @@ import android.widget.TextView;
|
||||
|
||||
import com.sismics.docs.R;
|
||||
import com.sismics.docs.listener.CallbackListener;
|
||||
import com.sismics.docs.listener.JsonHttpResponseHandler;
|
||||
import com.sismics.docs.listener.HttpCallback;
|
||||
import com.sismics.docs.model.application.ApplicationContext;
|
||||
import com.sismics.docs.resource.UserResource;
|
||||
import com.sismics.docs.ui.form.Validator;
|
||||
@ -24,8 +24,6 @@ import com.sismics.docs.util.PreferenceUtil;
|
||||
|
||||
import org.json.JSONObject;
|
||||
|
||||
import cz.msebera.android.httpclient.Header;
|
||||
|
||||
/**
|
||||
* Login activity.
|
||||
*
|
||||
@ -90,9 +88,9 @@ public class LoginActivity extends AppCompatActivity {
|
||||
PreferenceUtil.setServerUrl(LoginActivity.this, txtServer.getText().toString());
|
||||
|
||||
try {
|
||||
UserResource.login(getApplicationContext(), txtUsername.getText().toString(), txtPassword.getText().toString(), new JsonHttpResponseHandler() {
|
||||
UserResource.login(getApplicationContext(), txtUsername.getText().toString(), txtPassword.getText().toString(), new HttpCallback() {
|
||||
@Override
|
||||
public void onSuccess(int statusCode, Header[] headers, JSONObject json) {
|
||||
public void onSuccess(JSONObject json) {
|
||||
// Empty previous user caches
|
||||
PreferenceUtil.resetUserCache(getApplicationContext());
|
||||
|
||||
@ -108,11 +106,11 @@ public class LoginActivity extends AppCompatActivity {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onAllFailure(int statusCode, Header[] headers, byte[] responseBytes, Throwable throwable) {
|
||||
public void onFailure(JSONObject json, Exception e) {
|
||||
loginForm.setVisibility(View.VISIBLE);
|
||||
progressBar.setVisibility(View.GONE);
|
||||
|
||||
if (responseBytes != null && new String(responseBytes).contains("\"ForbiddenError\"")) {
|
||||
if (json != null && json.optString("type").equals("ForbiddenError")) {
|
||||
DialogUtil.showOkDialog(LoginActivity.this, R.string.login_fail_title, R.string.login_fail);
|
||||
} else {
|
||||
DialogUtil.showOkDialog(LoginActivity.this, R.string.network_error_title, R.string.network_error);
|
||||
@ -150,9 +148,9 @@ public class LoginActivity extends AppCompatActivity {
|
||||
finish();
|
||||
} else {
|
||||
// Trying to get user data
|
||||
UserResource.info(getApplicationContext(), new JsonHttpResponseHandler() {
|
||||
UserResource.info(getApplicationContext(), new HttpCallback() {
|
||||
@Override
|
||||
public void onSuccess(int statusCode, Header[] headers, final JSONObject json) {
|
||||
public void onSuccess(final JSONObject json) {
|
||||
if (json.optBoolean("anonymous", true)) {
|
||||
loginForm.setVisibility(View.VISIBLE);
|
||||
return;
|
||||
@ -168,7 +166,7 @@ public class LoginActivity extends AppCompatActivity {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onAllFailure(int statusCode, Header[] headers, byte[] responseBytes, Throwable throwable) {
|
||||
public void onFailure(JSONObject json, Exception e) {
|
||||
DialogUtil.showOkDialog(LoginActivity.this, R.string.network_error_title, R.string.network_error);
|
||||
loginForm.setVisibility(View.VISIBLE);
|
||||
}
|
||||
|
@ -23,7 +23,7 @@ import com.sismics.docs.adapter.TagListAdapter;
|
||||
import com.sismics.docs.event.AdvancedSearchEvent;
|
||||
import com.sismics.docs.event.SearchEvent;
|
||||
import com.sismics.docs.fragment.SearchFragment;
|
||||
import com.sismics.docs.listener.JsonHttpResponseHandler;
|
||||
import com.sismics.docs.listener.HttpCallback;
|
||||
import com.sismics.docs.model.application.ApplicationContext;
|
||||
import com.sismics.docs.provider.RecentSuggestionsProvider;
|
||||
import com.sismics.docs.resource.TagResource;
|
||||
@ -32,7 +32,6 @@ import com.sismics.docs.util.PreferenceUtil;
|
||||
|
||||
import org.json.JSONObject;
|
||||
|
||||
import cz.msebera.android.httpclient.Header;
|
||||
import de.greenrobot.event.EventBus;
|
||||
|
||||
/**
|
||||
@ -90,9 +89,9 @@ public class MainActivity extends AppCompatActivity {
|
||||
if (cacheTags != null) {
|
||||
tagListView.setAdapter(new TagListAdapter(cacheTags.optJSONArray("stats")));
|
||||
}
|
||||
TagResource.stats(this, new JsonHttpResponseHandler() {
|
||||
TagResource.stats(this, new HttpCallback() {
|
||||
@Override
|
||||
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
|
||||
public void onSuccess(JSONObject response) {
|
||||
PreferenceUtil.setCachedJson(MainActivity.this, PreferenceUtil.PREF_CACHED_TAGS_JSON, response);
|
||||
tagListView.setAdapter(new TagListAdapter(response.optJSONArray("stats")));
|
||||
tagProgressView.setVisibility(View.GONE);
|
||||
@ -100,7 +99,7 @@ public class MainActivity extends AppCompatActivity {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onAllFailure(int statusCode, Header[] headers, byte[] responseBytes, Throwable throwable) {
|
||||
public void onFailure(JSONObject json, Exception e) {
|
||||
tagEmptyView.setText(R.string.error_loading_tags);
|
||||
tagProgressView.setVisibility(View.GONE);
|
||||
tagListView.setEmptyView(tagEmptyView);
|
||||
@ -146,7 +145,7 @@ public class MainActivity extends AppCompatActivity {
|
||||
public boolean onOptionsItemSelected(MenuItem item) {
|
||||
switch (item.getItemId()) {
|
||||
case R.id.logout:
|
||||
UserResource.logout(getApplicationContext(), new JsonHttpResponseHandler() {
|
||||
UserResource.logout(getApplicationContext(), new HttpCallback() {
|
||||
@Override
|
||||
public void onFinish() {
|
||||
// Force logout in all cases, so the user is not stuck in case of network error
|
||||
|
@ -22,7 +22,6 @@ import com.sismics.docs.adapter.ShareListAdapter;
|
||||
import com.sismics.docs.event.ShareDeleteEvent;
|
||||
import com.sismics.docs.event.ShareSendEvent;
|
||||
import com.sismics.docs.listener.HttpCallback;
|
||||
import com.sismics.docs.listener.JsonHttpResponseHandler;
|
||||
import com.sismics.docs.resource.DocumentResource;
|
||||
import com.sismics.docs.resource.ShareResource;
|
||||
import com.sismics.docs.util.PreferenceUtil;
|
||||
@ -30,7 +29,6 @@ import com.sismics.docs.util.PreferenceUtil;
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONObject;
|
||||
|
||||
import cz.msebera.android.httpclient.Header;
|
||||
import de.greenrobot.event.EventBus;
|
||||
|
||||
/**
|
||||
@ -76,15 +74,15 @@ public class DocShareFragment extends DialogFragment {
|
||||
shareAddButton.setEnabled(false);
|
||||
|
||||
ShareResource.add(getActivity(), getArguments().getString("id"), shareNameEditText.getText().toString(),
|
||||
new JsonHttpResponseHandler() {
|
||||
new HttpCallback() {
|
||||
@Override
|
||||
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
|
||||
public void onSuccess(JSONObject response) {
|
||||
shareNameEditText.setText("");
|
||||
loadShares(getDialog().getWindow().getDecorView());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onAllFailure(int statusCode, Header[] headers, byte[] responseBytes, Throwable throwable) {
|
||||
public void onFailure(JSONObject json, Exception e) {
|
||||
Toast.makeText(getActivity(), R.string.error_adding_share, Toast.LENGTH_SHORT).show();
|
||||
}
|
||||
|
||||
@ -142,14 +140,14 @@ public class DocShareFragment extends DialogFragment {
|
||||
}
|
||||
|
||||
public void onEventMainThread(ShareDeleteEvent event) {
|
||||
ShareResource.delete(getActivity(), event.getId(), new JsonHttpResponseHandler() {
|
||||
ShareResource.delete(getActivity(), event.getId(), new HttpCallback() {
|
||||
@Override
|
||||
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
|
||||
public void onSuccess(JSONObject response) {
|
||||
loadShares(getDialog().getWindow().getDecorView());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onAllFailure(int statusCode, Header[] headers, byte[] responseBytes, Throwable throwable) {
|
||||
public void onFailure(JSONObject json, Exception e) {
|
||||
Toast.makeText(getActivity(), R.string.error_deleting_share, Toast.LENGTH_SHORT).show();
|
||||
}
|
||||
});
|
||||
|
@ -1,242 +0,0 @@
|
||||
/*
|
||||
Android Asynchronous Http Client
|
||||
Copyright (c) 2011 James Smith <james@loopj.com>
|
||||
http://loopj.com
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
package com.sismics.docs.listener;
|
||||
|
||||
import android.util.Log;
|
||||
|
||||
import com.loopj.android.http.TextHttpResponseHandler;
|
||||
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONException;
|
||||
import org.json.JSONObject;
|
||||
import org.json.JSONTokener;
|
||||
|
||||
import cz.msebera.android.httpclient.Header;
|
||||
import cz.msebera.android.httpclient.HttpStatus;
|
||||
|
||||
/**
|
||||
* Used to intercept and handle the responses from requests made using {@link com.loopj.android.http.AsyncHttpClient}, with
|
||||
* automatic parsing into a {@link JSONObject} or {@link JSONArray}. <p> </p> 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. <p> </p>
|
||||
* 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;
|
||||
}
|
||||
}
|
@ -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);
|
||||
|
@ -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.
|
||||
*
|
||||
|
@ -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));
|
||||
}
|
||||
}
|
||||
|
@ -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);
|
||||
}
|
||||
}
|
||||
|
@ -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();
|
||||
}
|
||||
}
|
||||
|
@ -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));
|
||||
}
|
||||
}
|
||||
|
@ -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));
|
||||
}
|
||||
}
|
||||
|
@ -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));
|
||||
}
|
||||
}
|
||||
|
@ -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);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
|
@ -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());
|
||||
}
|
||||
})
|
||||
|
@ -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<Cookie> cookieList = cookieStore.getCookies();
|
||||
for (Cookie cookie : cookieList) {
|
||||
List<HttpCookie> cookieList = cookieStore.getCookies();
|
||||
for (HttpCookie cookie : cookieList) {
|
||||
if (cookie.getName().equals("auth_token")) {
|
||||
return cookie.getValue();
|
||||
}
|
||||
@ -135,6 +142,7 @@ public class PreferenceUtil {
|
||||
|
||||
/**
|
||||
* Returns cleaned server URL.
|
||||
*
|
||||
* @param context Context
|
||||
* @return Server URL
|
||||
*/
|
||||
|
Loading…
Reference in New Issue
Block a user