Sync.java 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  1. package com.ivalentin.margolariak;
  2. import java.io.BufferedInputStream;
  3. import java.io.BufferedReader;
  4. import java.io.IOException;
  5. import java.io.InputStream;
  6. import java.io.InputStreamReader;
  7. import java.net.HttpURLConnection;
  8. import java.net.MalformedURLException;
  9. import java.net.URL;
  10. import java.net.URLEncoder;
  11. import java.util.ArrayList;
  12. import java.util.List;
  13. import android.app.Activity;
  14. import android.app.Dialog;
  15. import android.content.Context;
  16. import android.content.SharedPreferences;
  17. import android.database.sqlite.SQLiteDatabase;
  18. import android.os.AsyncTask;
  19. import android.util.Log;
  20. import android.view.View;
  21. import android.view.View.OnClickListener;
  22. import android.view.Window;
  23. import android.widget.Button;
  24. import android.widget.ImageView;
  25. import android.widget.ProgressBar;
  26. import android.widget.TextView;
  27. import org.json.*;
  28. /**
  29. * AsyncTask that synchronizes the online database to the device.
  30. * Is run every time the app is started, and periodically in the background.
  31. *
  32. * @author Inigo Valentin
  33. *
  34. */
  35. class Sync extends AsyncTask<Void, Void, Void> {
  36. private final Context myContextRef;
  37. private ProgressBar pbSync;
  38. private ImageView ivSync;
  39. private Dialog dialog;
  40. private MainActivity activity;
  41. private int fg;
  42. private int newVersion;
  43. private String strings[];
  44. private boolean doProgress = false;
  45. private long millis = 0;
  46. private TextView tv;
  47. /**
  48. * Things to do before sync. Namely, displaying a spinning progress bar.
  49. * @see android.os.AsyncTask#onPreExecute()
  50. */
  51. @Override
  52. protected void onPreExecute(){
  53. if (pbSync != null) {
  54. pbSync.setVisibility(View.VISIBLE);
  55. ivSync.setVisibility(View.GONE);
  56. }
  57. if (dialog != null) {
  58. dialog.show();
  59. strings = new String[10];
  60. strings[0] = myContextRef.getString(R.string.dialog_sync_text_0);
  61. strings[1] = myContextRef.getString(R.string.dialog_sync_text_1);
  62. strings[2] = myContextRef.getString(R.string.dialog_sync_text_2);
  63. strings[3] = myContextRef.getString(R.string.dialog_sync_text_3);
  64. strings[4] = myContextRef.getString(R.string.dialog_sync_text_4);
  65. strings[5] = myContextRef.getString(R.string.dialog_sync_text_5);
  66. strings[6] = myContextRef.getString(R.string.dialog_sync_text_6);
  67. strings[7] = myContextRef.getString(R.string.dialog_sync_text_7);
  68. strings[8] = myContextRef.getString(R.string.dialog_sync_text_8);
  69. strings[9] = myContextRef.getString(R.string.dialog_sync_text_8); //In case I get a 9;
  70. tv = (TextView) dialog.findViewById(R.id.tv_dialog_sync_text);
  71. int idx = (int) (Math.random() * 9);
  72. tv.setText(strings[idx]);
  73. doProgress = true;
  74. }
  75. Log.d("Sync", "Starting full sync");
  76. }
  77. /**
  78. * Things to do after sync. Namely, hiddng the spinning progress bar.
  79. * @see android.os.AsyncTask#onPreExecute()
  80. */
  81. @Override
  82. protected void onPostExecute(Void v){
  83. if (pbSync != null) {
  84. pbSync.setVisibility(View.GONE);
  85. ivSync.setVisibility(View.VISIBLE);
  86. }
  87. if (dialog != null){
  88. dialog.dismiss();
  89. //Check db version agan
  90. SharedPreferences preferences = myContextRef.getSharedPreferences(GM.PREF, Context.MODE_PRIVATE);
  91. if (preferences.getInt(GM.PREF_DB_VERSION, GM.DEFAULT_PREF_DB_VERSION) == GM.DEFAULT_PREF_DB_VERSION){
  92. //Create a dialog
  93. final Dialog dial = new Dialog(activity);
  94. dial.setCancelable(false);
  95. //Set up the window
  96. dial.requestWindowFeature(Window.FEATURE_NO_TITLE);
  97. dial.setContentView(R.layout.dialog_sync_failed);
  98. //Set button
  99. Button btClose = (Button) dial.findViewById(R.id.bt_dialog_sync_failed_close);
  100. btClose.setOnClickListener(new OnClickListener(){
  101. @Override
  102. public void onClick(View v) {
  103. dial.dismiss();
  104. activity.finish();
  105. }
  106. });
  107. //Show the dialog
  108. dial.show();
  109. }
  110. else{
  111. activity.loadSection(GM.SECTION_HOME);
  112. }
  113. }
  114. Log.d("Sync", "Full sync finished");
  115. }
  116. /**
  117. * Called when the AsyncTask is created.
  118. *
  119. * @param myContextRef The Context of the calling activity.
  120. */
  121. public Sync(Activity myContextRef){
  122. this.myContextRef = myContextRef;
  123. }
  124. /**
  125. * Called when the AsyncTask is created.
  126. *
  127. * @param myContextRef The Context of the calling activity.
  128. * @param pb The progress bar that will be shown while the sync goes on.
  129. */
  130. public Sync(Activity myContextRef, ProgressBar pb, ImageView iv) {
  131. this.myContextRef = myContextRef;
  132. dialog = null;
  133. pbSync = pb;
  134. ivSync = iv;
  135. fg = 1;
  136. }
  137. /**
  138. * Called when the AsyncTask is created.
  139. * This constructor is intended to use only in the first sync,
  140. * because a dialog will block the UI.
  141. *
  142. * @param myContextRef The Context of the calling activity.
  143. * @param d Dialog of the initial sync
  144. * @param pb The progress bar that will be shown while the sync goes on.
  145. * @param activity The calling MainActvity
  146. */
  147. public Sync(Activity myContextRef, ProgressBar pb, ImageView iv, Dialog d, MainActivity activity) {
  148. this.dialog = d;
  149. this.activity = activity;
  150. this.myContextRef = myContextRef;
  151. pbSync = pb;
  152. ivSync = iv;
  153. fg = 1;
  154. }
  155. /**
  156. * Called when the AsyncTask is created.
  157. *
  158. * @param context The Context of the calling activity.
  159. */
  160. public Sync(Context context) {
  161. this.myContextRef = context;
  162. pbSync = null;
  163. fg = 0;
  164. }
  165. @Override
  166. /**
  167. * Called when the AsyncTask is updated.
  168. * Used to change text in the sync window.
  169. */
  170. protected void onProgressUpdate(Void...progress) {
  171. if (doProgress){
  172. if (millis + 600 < System.currentTimeMillis()) {
  173. millis = System.currentTimeMillis();
  174. int idx = (int) (Math.random() * ((4) + 1));
  175. tv.setText(strings[idx]);
  176. }
  177. }
  178. }
  179. /**
  180. * Creates the URL required to performa a sync. Uses static data and data passed as arguments.
  181. *
  182. * @param user A unique user identifier.
  183. * @param version The db version of the client.
  184. * @param foreground 1 if the sync is done while the app is running, 0 otherwise.
  185. * @param lang Two letter language identifier.
  186. * @return The URL that will be used for syncing.
  187. */
  188. private String buildUrl(String user, int version, int foreground, String lang){
  189. String url = "";
  190. try {
  191. url = GM.SERVER + GM.SERVER_SYNC + "?" +
  192. GM.SERVER_SYNC_KEY_CLIENT + "=" + URLEncoder.encode(GM.CLIENT, "UTF-8") + "&" +
  193. GM.SERVER_SYNC_KEY_USER + "=" + URLEncoder.encode(user, "UTF-8") + "&" +
  194. GM.SERVER_SYNC_KEY_ACTION + "=" + URLEncoder.encode(GM.SERVER_SYNC_VALUE_ACTION, "UTF-8") + "&" +
  195. GM.SERVER_SYNC_KEY_SECTION + "=" + URLEncoder.encode(GM.SERVER_SYNC_VALUE_SECTION, "UTF-8") + "&" +
  196. GM.SERVER_SYNC_KEY_VERSION + "=" + version + "&" +
  197. GM.SERVER_SYNC_KEY_FOREGROUND + "=" + foreground + "&" +
  198. GM.SERVER_SYNC_KEY_FORMAT + "=" + URLEncoder.encode(GM.SERVER_SYNC_VALUE_FORMAT, "UTF-8") + "&" +
  199. GM.SERVER_SYNC_KEY_LANG + "=" + URLEncoder.encode(lang, "UTF-8");
  200. }
  201. catch (java.io.UnsupportedEncodingException ex){
  202. Log.e("UTF-8", "Error encoding url for sync \"" + url + "\" - " + ex.toString());
  203. }
  204. return url;
  205. }
  206. /**
  207. * Stores version data for each section in the database.
  208. * Uses a custom JSON parser.
  209. *
  210. * @param db Database store the data.
  211. * @param versions List of strings with data about the versions.
  212. * @return False if there were errors, true otherwise.
  213. */
  214. protected boolean saveVersions(SQLiteDatabase db, String versions){
  215. String str = versions;
  216. String key;
  217. boolean result = true;
  218. int value;
  219. int totalVersions = 0;
  220. //If I ever have a database with more than 99 public sections (not tables), I'll have to change this. Also, ask for a raise.
  221. int[] values = new int[99];
  222. String[] keys = new String[99];
  223. try {
  224. while (str.indexOf("{") > 0){
  225. key = str.substring(str.indexOf("{\"") + 2, str.indexOf("\":"));
  226. str = str.substring(str.indexOf("\":\"") + 3);
  227. value = Integer.parseInt(str.substring(0, str.indexOf("\"")));
  228. str = str.substring(str.indexOf("}") + 1);
  229. keys[totalVersions] = key;
  230. values[totalVersions] = value;
  231. totalVersions ++;
  232. }
  233. if (totalVersions > 0 && totalVersions < 99){
  234. db.execSQL("CREATE TABLE IF NOT EXISTS version (section VARCHAR, version INT);");
  235. db.execSQL("DELETE FROM version;");
  236. for (int i = 0; i < totalVersions; i ++){
  237. db.execSQL("INSERT INTO version VALUES ('" + keys[i] + "', " + values[i] + ");");
  238. }
  239. }
  240. else{
  241. result = false;
  242. }
  243. }
  244. catch (Exception ex){
  245. result = false;
  246. Log.e("saveVersions", "Error saving the remote db versions: " + ex.toString());
  247. }
  248. return result;
  249. }
  250. /**
  251. * Stores version data for each section in the database.
  252. * Uses a custom JSON parser.
  253. *
  254. * @param db Database store the data.
  255. * @param data List of strings in json format with the tables.
  256. * @return False if there were errors, true otherwise.
  257. */
  258. protected boolean saveData(SQLiteDatabase db, String data){
  259. Log.e("ENTER", "SAVEDATA");
  260. String str;
  261. String key;
  262. String value;
  263. int i = 0;
  264. boolean result = true;
  265. try{
  266. str = data.substring(data.indexOf("[") + 1, data.lastIndexOf("]"));
  267. while (str.indexOf("]") > 0){
  268. key = str.substring(str.indexOf("\"") + 1, str.indexOf("\"", str.indexOf("\"") + 1));
  269. value = str.substring(str.indexOf("["), str.indexOf("]"));
  270. str = str.substring(str.indexOf("]") + 1);
  271. if (!saveTable(db, key, value)){
  272. //TODO: Uncoment to finish the loop as sonn as error
  273. //return false;
  274. }
  275. i ++;
  276. str = str.substring(str.indexOf("]") + 1);
  277. }
  278. }
  279. catch (Exception ex){
  280. Log.e("saveData", "Error saving the remote db data: " + ex.toString());
  281. result = false;
  282. }
  283. return result;
  284. }
  285. /**
  286. * Stores a table data into the database.
  287. * Uses a custom JSON parser.
  288. *
  289. * @param db Database to store the data.
  290. * @param table Name of the table.
  291. * @param data String in JSON format with the data of the table.
  292. * @return False if there were errors, true otherwise.
  293. */
  294. protected boolean saveTable(SQLiteDatabase db, String table, String data){
  295. String str = data;
  296. str = str.replace(":null", ":\"\"");
  297. String key, fields, vals;
  298. boolean result = true;
  299. String value;
  300. int totalFields = 0;
  301. //If I ever have a database with more than 99 public sections (not tables), I'll have to change this. Also, ask for a raise.
  302. String[] values = new String[99];
  303. String[] keys = new String[99];
  304. List<String> queries = new ArrayList<>();
  305. queries.add("DELETE FROM " + table + ";");
  306. int i = 0;
  307. try {
  308. while (str.indexOf("{") > 0){
  309. String row = str.substring(str.indexOf("{"), str.indexOf("}") + 1);
  310. totalFields = 0;
  311. while (row.indexOf("\",") > 0) {
  312. key = row.substring(row.indexOf("\"") + 1, row.indexOf("\":"));
  313. value = row.substring(row.indexOf("\"", row.indexOf(":")), row.indexOf("\"", row.indexOf(":") + 2) + 1);
  314. //Log.e("FIELD", key + ": " + value);
  315. keys[totalFields] = key;
  316. values[totalFields] = value;
  317. totalFields ++;
  318. row = row.substring(row.indexOf(value) + value.length() + 1);
  319. }
  320. //TODO: With all the keys and the values, create an INSERT query and add to queries
  321. fields = "(";
  322. vals = "(";
  323. for (int j = 0; j < totalFields; j ++){
  324. fields = fields + keys[j] + ", ";
  325. vals = vals + values[j] + ", ";
  326. }
  327. fields = fields.substring(0, fields.length()-2) + ")";
  328. vals = vals.substring(0, vals.length()-2) + ")";
  329. queries.add("INSERT INTO " + table + " " + fields + " VALUES " + vals + ";");
  330. i ++;
  331. str = str.substring(str.indexOf("}") + 1);
  332. }
  333. /*if (totalFields > 0 && totalFields < 99){
  334. //db.execSQL("CREATE TABLE IF NOT EXISTS version (section VARCHAR, version INT);");
  335. db.execSQL("DELETE FROM " + table + ";");
  336. Log.e("QUERY", "DELETE FROM " + table + ";");
  337. for (i = 0; i < totalFields; i ++){
  338. //db.execSQL("INSERT INTO " + table + " VALUES ('" + keys[i] + "', " + values[i] + ");");
  339. Log.e("QUERY", "INSERT INTO " + table + " VALUES ('" + keys[i] + "', " + values[i] + ");");
  340. }
  341. }
  342. else{
  343. result = false;
  344. }*/
  345. }
  346. catch (Exception ex){
  347. Log.e("saveVersions", "Error saving the remote db versions: " + ex.toString());
  348. return false;
  349. }
  350. //If I get to this point, there were no errors, and I can safely execute the queries
  351. int totalQueries = queries.size();
  352. for (i = 0; i < totalQueries; i ++){
  353. db.execSQL(queries.get(i));
  354. Log.e("QUERY", queries.get(i));
  355. }
  356. //TODO: Uncomment
  357. //return result;
  358. return false;
  359. }
  360. /**
  361. * The sweet stuff. Actually performs the sync.
  362. */
  363. @Override
  364. protected Void doInBackground(Void... params) {
  365. //Get preferences
  366. SharedPreferences preferences = myContextRef.getSharedPreferences(GM.PREF, Context.MODE_PRIVATE);
  367. SharedPreferences.Editor prefEditor;
  368. prefEditor = preferences.edit();
  369. //Get usefull data for the uri
  370. String userCode = preferences.getString(GM.USER_CODE, "");
  371. int dbVersion = preferences.getInt(GM.PREF_DB_VERSION, GM.DEFAULT_PREF_DB_VERSION);
  372. //Get database. Stop if it's locked
  373. SQLiteDatabase db = myContextRef.openOrCreateDatabase(GM.DB_NAME, Activity.MODE_PRIVATE, null);
  374. if (db.isReadOnly()){
  375. Log.e("Db ro", "Database is locked and in read only mode. Skipping sync.");
  376. return null;
  377. }
  378. URL url;
  379. String uri = buildUrl(userCode, dbVersion, fg, GM.getLang());
  380. try {
  381. url = new URL(uri);
  382. HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
  383. int httpCode = urlConnection.getResponseCode();
  384. switch (httpCode){
  385. case 400: //Client error: Bad request
  386. Log.e("Sync error", "The server returned a 400 code (Client Error: Bad request) for the url \"" + uri + "\"");
  387. break;
  388. case 403: //Client error: Forbidden
  389. Log.e("Sync error", "The server returned a 403 code (Client Error: Forbidden) for the url \"" + uri + "\"");
  390. break;
  391. case 204: //Success: No content
  392. Log.d("Sync success", "The server returned a 204 code (Success: No content) for the url \"" + uri + "\". Stoping sync process...");
  393. break;
  394. case 200: //Success: OK
  395. Log.d("Sync", "The server returned a 200 code (Success: OK) for the url \"" + uri + "\". Now syncing...");
  396. InputStream in = new BufferedInputStream(urlConnection.getInputStream());
  397. BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
  398. StringBuilder sb = new StringBuilder();
  399. String o;
  400. while ((o = br.readLine()) != null)
  401. sb.append(o);
  402. //Get the string with the sync json. (The whole page)
  403. String strSync = sb.toString();
  404. //Get the JSON object from the string.
  405. JSONObject jsonSync = new JSONObject(strSync);
  406. jsonSync = new JSONObject(jsonSync.get("sync").toString().substring(1, jsonSync.get("sync").toString().length() - 1));
  407. //Get the string wit the versions in JSON format.
  408. String strVersion = jsonSync.get("version").toString();
  409. //Handmade parser, because with:
  410. //String strData = jsonSync.get("data").toString();
  411. //I get an error: "No value for data"
  412. String strData = strSync.substring(1, strSync.toString().length() - 1);
  413. strData = strData.substring(strData.indexOf("{\"data\":"));
  414. //If the data is correctly parsed and stored, commit changes to the database.
  415. db.beginTransaction();
  416. if (saveVersions(db, strVersion) && saveData(db, strData)){
  417. db.setTransactionSuccessful();
  418. Log.d("SYNC", "The sync process finished correctly. Changes to the database will be commited");
  419. }
  420. else{
  421. Log.e("SYNC", "The sync process did not finish correctly. Any changes made to the database will be reverted");
  422. }
  423. db.endTransaction();
  424. break;
  425. default:
  426. Log.e("Sync error", "The server returned an unexpected code (" + httpCode + ") for the url \"" + uri + "\"");
  427. }
  428. urlConnection.disconnect();
  429. return null;
  430. }
  431. catch (MalformedURLException e) {
  432. Log.e("Sync error", "Malformed URL (" + uri + "): " + e.toString());
  433. e.printStackTrace();
  434. }
  435. catch (IOException e) {
  436. Log.e("Sync error", "IOException for URL (" + uri + "): " + e.toString());
  437. e.printStackTrace();
  438. }
  439. catch (org.json.JSONException e) {
  440. Log.e("Sync error", "JSONException for URL (" + uri + "): " + e.toString());
  441. e.printStackTrace();
  442. }
  443. return null;
  444. }
  445. }