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.services; import android.app.IntentService; import android.app.NotificationManager; import android.content.Context; import android.content.Intent; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.support.v4.content.WakefulBroadcastReceiver; import android.support.v7.app.NotificationCompat; import android.util.Base64; import android.util.Log; import com.activeandroid.query.Delete; import org.apache.commons.io.IOUtils; import org.greenrobot.eventbus.EventBus; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.io.InputStream; import java.io.StringWriter; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.ProtocolException; import java.net.URL; import eu.codeplumbers.cosi.R; import eu.codeplumbers.cosi.db.models.Device; import eu.codeplumbers.cosi.db.models.Note; import eu.codeplumbers.cosi.services.events.NoteSyncEvent; import eu.codeplumbers.cosi.utils.DateUtils; import static eu.codeplumbers.cosi.utils.Constants.REFRESH; import static eu.codeplumbers.cosi.utils.Constants.SERVICE_ERROR; import static eu.codeplumbers.cosi.utils.Constants.SYNC_MESSAGE; /** * Created by thor on 10/29/16. */ public class CosiNoteService extends IntentService { private String authHeader; private String url; private int notification_id = 1347; private NotificationManager mNotifyManager; private NotificationCompat.Builder mBuilder; private boolean mSyncRunning; private boolean stopSync; public CosiNoteService() { super("CosiNoteService"); mSyncRunning = false; } public CosiNoteService(String name) { super(name); } @Override protected void onHandleIntent(Intent intent) { // Do the task here Log.i(CosiNoteService.class.getName(), "Cosi Service running"); // Release the wake lock provided by the WakefulBroadcastReceiver. WakefulBroadcastReceiver.completeWakefulIntent(intent); Device device = Device.registeredDevice(); // delete all local notes new Delete().from(Note.class).execute(); // cozy register device url this.url = device.getUrl() + "/ds-api/request/note/cosiall/"; // concatenate username and password with colon for authentication final String credentials = device.getLogin() + ":" + device.getPassword(); authHeader = "Basic " + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP); showNotification(); if (isNetworkAvailable()) { try { URL urlO = new URL(url); HttpURLConnection conn = (HttpURLConnection) urlO.openConnection(); conn.setConnectTimeout(5000); conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); conn.setRequestProperty("Authorization", authHeader); conn.setDoInput(true); conn.setRequestMethod("POST"); // read the response int status = conn.getResponseCode(); InputStream in = null; if (status >= HttpURLConnection.HTTP_BAD_REQUEST) { in = conn.getErrorStream(); } else { in = conn.getInputStream(); } StringWriter writer = new StringWriter(); IOUtils.copy(in, writer, "UTF-8"); String result = writer.toString(); JSONArray jsonArray = new JSONArray(result); if (jsonArray != null) { for (int i = 0; i < jsonArray.length(); i++) { String version = "0"; if (jsonArray.getJSONObject(i).has("version")) { version = jsonArray.getJSONObject(i).getString("version"); } JSONObject noteJson = jsonArray.getJSONObject(i).getJSONObject("value"); Note note = Note.getByRemoteId(noteJson.get("_id").toString()); if (note == null) { note = new Note(noteJson); } else { boolean versionIncremented = note.getVersion() < Integer .valueOf(noteJson.getString("version")); int modifiedOnServer = DateUtils.compareDateStrings( Long.valueOf(note.getLastModificationValueOf()), noteJson.getLong("lastModificationValueOf")); if (versionIncremented || modifiedOnServer == -1) { note.setTitle(noteJson.getString("title")); note.setContent(noteJson.getString("content")); note.setCreationDate(noteJson.getString("creationDate")); note.setLastModificationDate(noteJson.getString("lastModificationDate")); note.setLastModificationValueOf(noteJson.getString("lastModificationValueOf")); note.setParentId(noteJson.getString("parent_id")); // TODO: 10/3/16 // handle note paths note.setPath(noteJson.getString("path")); note.setVersion(Integer.valueOf(version)); } } mBuilder.setProgress(jsonArray.length(), i, false); mBuilder.setContentText("Getting note : " + note.getTitle()); mNotifyManager.notify(notification_id, mBuilder.build()); EventBus.getDefault() .post(new NoteSyncEvent(SYNC_MESSAGE, "Getting note : " + note.getTitle())); note.save(); } } else { EventBus.getDefault().post(new NoteSyncEvent(SERVICE_ERROR, "Failed to parse API response")); } in.close(); conn.disconnect(); mNotifyManager.cancel(notification_id); EventBus.getDefault().post(new NoteSyncEvent(REFRESH, "Sync OK")); } catch (MalformedURLException e) { EventBus.getDefault().post(new NoteSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); mNotifyManager.notify(notification_id, mBuilder.build()); stopSelf(); } catch (ProtocolException e) { EventBus.getDefault().post(new NoteSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); mNotifyManager.notify(notification_id, mBuilder.build()); stopSelf(); } catch (IOException e) { EventBus.getDefault().post(new NoteSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); mNotifyManager.notify(notification_id, mBuilder.build()); stopSelf(); } catch (JSONException e) { EventBus.getDefault().post(new NoteSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); mNotifyManager.notify(notification_id, mBuilder.build()); stopSelf(); } } else { mSyncRunning = false; EventBus.getDefault().post(new NoteSyncEvent(SERVICE_ERROR, "No Internet connection")); mBuilder.setContentText("Sync failed because no Internet connection was available"); mNotifyManager.notify(notification_id, mBuilder.build()); } } private boolean isNetworkAvailable() { ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService( Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); return activeNetworkInfo != null && activeNetworkInfo.isConnected(); } public void showNotification() { //PendingIntent pendingIntent = PendingIntent.getActivity(this, notification_id, this,PendingIntent.FLAG_UPDATE_CURRENT); mNotifyManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); mBuilder = new NotificationCompat.Builder(this); mBuilder.setContentTitle(getString(R.string.lbl_files)) .setContentText(getString(R.string.lbl_files_downloading)).setSmallIcon(R.drawable.ic_fa_file) //.addAction(R.drawable.ic_action_cancel, "Dismiss", getPendingIntent()) .setOngoing(true); } }