Java tutorial
/* * Cos android client for Cozy Cloud * * Copyright (C) 2016 Hamza Abdelkebir * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package eu.codeplumbers.cosi.api.tasks; import android.app.Activity; import android.app.ProgressDialog; import android.os.AsyncTask; import android.util.Base64; import android.widget.Toast; import org.apache.commons.io.IOUtils; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.StringWriter; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.ProtocolException; import java.net.URL; import eu.codeplumbers.cosi.activities.ExpenseDetailsActivity; import eu.codeplumbers.cosi.activities.NoteDetailsActivity; import eu.codeplumbers.cosi.db.models.Call; import eu.codeplumbers.cosi.db.models.Device; import eu.codeplumbers.cosi.db.models.Expense; import eu.codeplumbers.cosi.db.models.Note; import eu.codeplumbers.cosi.db.models.Sms; public class SyncDocumentTask extends AsyncTask<JSONObject, String, String> { private final String url; private final String authHeader; private Activity activity; private String result; private String errorMessage; private ProgressDialog dialog; private long objectId; public SyncDocumentTask(Activity activity) { this.activity = activity; result = ""; Device device = Device.registeredDevice(); // cozy register device url this.url = device.getUrl() + "/ds-api/data/"; // concatenate username and password with colon for authentication final String credentials = device.getLogin() + ":" + device.getPassword(); authHeader = "Basic " + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP); dialog = new ProgressDialog(activity); dialog.setCancelable(false); dialog.setProgress(0); dialog.setMax(100); dialog.setMessage("Please wait"); dialog.setIndeterminate(false); dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); dialog.show(); } @Override protected String doInBackground(JSONObject... jsonObjects) { for (int i = 0; i < jsonObjects.length; i++) { JSONObject jsonObject = jsonObjects[i]; URL urlO = null; try { publishProgress("Syncing " + jsonObject.getString("docType") + ":", i + "", jsonObjects.length + ""); String remoteId = jsonObject.getString("remoteId"); String requestMethod = ""; if (remoteId.isEmpty()) { urlO = new URL(url); requestMethod = "POST"; } else { urlO = new URL(url + remoteId + "/"); requestMethod = "PUT"; } HttpURLConnection conn = (HttpURLConnection) urlO.openConnection(); conn.setConnectTimeout(5000); conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); conn.setRequestProperty("Authorization", authHeader); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestMethod(requestMethod); // set request body jsonObject.remove("remoteId"); objectId = jsonObject.getLong("id"); jsonObject.remove("id"); OutputStream os = conn.getOutputStream(); os.write(jsonObject.toString().getBytes("UTF-8")); os.flush(); // read the response InputStream in = new BufferedInputStream(conn.getInputStream()); StringWriter writer = new StringWriter(); IOUtils.copy(in, writer, "UTF-8"); String result = writer.toString(); JSONObject jsonObjectResult = new JSONObject(result); if (jsonObjectResult != null && jsonObjectResult.has("_id")) { result = jsonObjectResult.getString("_id"); if (jsonObject.get("docType").equals("Sms")) { Sms sms = Sms.load(Sms.class, objectId); sms.setRemoteId(result); sms.save(); } if (jsonObject.get("docType").equals("Note")) { Note note = Note.load(Note.class, objectId); note.setRemoteId(result); note.save(); } if (jsonObject.get("docType").equals("Call")) { Call call = Call.load(Call.class, objectId); call.setRemoteId(result); call.save(); } if (jsonObject.get("docType").equals("Expense")) { Expense expense = Expense.load(Expense.class, objectId); expense.setRemoteId(result); expense.save(); } } in.close(); conn.disconnect(); } catch (MalformedURLException e) { result = "error"; e.printStackTrace(); errorMessage = e.getLocalizedMessage(); } catch (ProtocolException e) { result = "error"; errorMessage = e.getLocalizedMessage(); e.printStackTrace(); } catch (IOException e) { result = "error"; errorMessage = e.getLocalizedMessage(); e.printStackTrace(); } catch (JSONException e) { result = "error"; errorMessage = e.getLocalizedMessage(); e.printStackTrace(); } } return result; } @Override protected void onProgressUpdate(String... values) { super.onProgressUpdate(values); dialog.setProgress(Integer.valueOf(values[1])); dialog.setMax(Integer.valueOf(values[2])); dialog.setMessage(values[0]); } @Override protected void onPostExecute(String result) { super.onPostExecute(result); dialog.cancel(); if (result != "error") { if (activity instanceof NoteDetailsActivity) { ((NoteDetailsActivity) activity).onNoteSynced(result); } if (activity instanceof ExpenseDetailsActivity) { ((ExpenseDetailsActivity) activity).onExpenseSynced(result); } } else { Toast.makeText(activity, errorMessage, Toast.LENGTH_LONG).show(); } } }