Example usage for android.content SyncResult toDebugString

List of usage examples for android.content SyncResult toDebugString

Introduction

In this page you can find the example usage for android.content SyncResult toDebugString.

Prototype

public String toDebugString() 

Source Link

Document

Generates a debugging string indicating the status.

Usage

From source file:com.nononsenseapps.notepad.sync.googleapi.GoogleTaskSync.java

/**
 * Returns true if sync was successful, false otherwise
 */// w  ww. ja  va2  s.  co m
public static boolean fullSync(final Context context, final Account account, final Bundle extras,
        final String authority, final ContentProviderClient provider, final SyncResult syncResult) {

    Log.d(TAG, "fullSync");
    // Is saved at a successful sync
    final long startTime = Calendar.getInstance().getTimeInMillis();

    boolean success = false;
    // Initialize necessary stuff
    final AccountManager accountManager = AccountManager.get(context);
    final GoogleAPITalker apiTalker = new GoogleAPITalker(context);

    try {
        boolean connected = apiTalker.initialize(accountManager, account, AUTH_TOKEN_TYPE, NOTIFY_AUTH_FAILURE);

        if (connected) {

            Log.d(TAG, "AuthToken acquired, we are connected...");

            try {
                // IF full sync, download since start of all time
                // Temporary fix for delete all bug
                //               if (PreferenceManager.getDefaultSharedPreferences(context)
                //                     .getBoolean(SyncPrefs.KEY_FULLSYNC, false)) {
                PreferenceManager.getDefaultSharedPreferences(context).edit()
                        .putBoolean(SyncPrefs.KEY_FULLSYNC, false).putLong(PREFS_GTASK_LAST_SYNC_TIME, 0)
                        .commit();
                //               }

                // Download lists from server
                Log.d(TAG, "download lists");
                final List<GoogleTaskList> remoteLists = downloadLists(apiTalker);

                // merge with local complement
                Log.d(TAG, "merge lists");
                mergeListsWithLocalDB(context, account.name, remoteLists);

                // Synchronize lists locally
                Log.d(TAG, "sync lists locally");
                final List<Pair<TaskList, GoogleTaskList>> listPairs = synchronizeListsLocally(context,
                        remoteLists);

                // Synchronize lists remotely
                Log.d(TAG, "sync lists remotely");
                final List<Pair<TaskList, GoogleTaskList>> syncedPairs = synchronizeListsRemotely(context,
                        listPairs, apiTalker);

                // For each list
                for (Pair<TaskList, GoogleTaskList> syncedPair : syncedPairs) {
                    // Download tasks from server
                    Log.d(TAG, "download tasks");
                    final List<GoogleTask> remoteTasks = downloadChangedTasks(context, apiTalker,
                            syncedPair.second);

                    // merge with local complement
                    Log.d(TAG, "merge tasks");
                    mergeTasksWithLocalDB(context, account.name, remoteTasks, syncedPair.first._id);

                    // Synchronize tasks locally
                    Log.d(TAG, "sync tasks locally");
                    final List<Pair<Task, GoogleTask>> taskPairs = synchronizeTasksLocally(context, remoteTasks,
                            syncedPair);
                    // Synchronize tasks remotely
                    Log.d(TAG, "sync tasks remotely");
                    synchronizeTasksRemotely(context, taskPairs, syncedPair.second, apiTalker);
                }

                Log.d(TAG, "Sync Complete!");
                success = true;
                PreferenceManager.getDefaultSharedPreferences(context).edit()
                        .putLong(PREFS_GTASK_LAST_SYNC_TIME, startTime).commit();

                /*
                 * Tasks Step 1: Download changes from the server Step 2:
                 * Iterate and compare with local content Step 2a: If both
                 * versions changed, choose the latest Step 2b: If remote is
                 * newer, put info in local task, save Step 2c: If local is
                 * newer, upload it (in background) Step 3: For remote items
                 * that do not exist locally, save Step 4: For local items
                 * that do not exist remotely, upload
                 */

            } catch (ClientProtocolException e) {

                Log.e(TAG, "ClientProtocolException: " + e.getLocalizedMessage());
                syncResult.stats.numAuthExceptions++;
            } catch (IOException e) {
                syncResult.stats.numIoExceptions++;

                Log.e(TAG, "IOException: " + e.getLocalizedMessage());
            } catch (ClassCastException e) {
                // GetListofLists will cast this if it returns a string.
                // It should not return a string but it did...
                syncResult.stats.numAuthExceptions++;
                Log.e(TAG, "ClassCastException: " + e.getLocalizedMessage());
            }

        } else {
            // return real failure

            Log.d(TAG, "Could not get authToken. Reporting authException");
            syncResult.stats.numAuthExceptions++;
            // doneIntent.putExtra(SYNC_RESULT, LOGIN_FAIL);
        }

    } catch (Exception e) {
        // Something went wrong, don't punish the user
        syncResult.stats.numAuthExceptions++;
        Log.e(TAG, "bobs your uncle: " + e.getLocalizedMessage());
    } finally {
        // This must always be called or we will leak resources
        if (apiTalker != null) {
            apiTalker.closeClient();
        }

        Log.d(TAG, "SyncResult: " + syncResult.toDebugString());
    }

    return success;
}

From source file:com.nononsenseapps.notepad.sync.SyncAdapter.java

@SuppressWarnings("unchecked")
@Override//from  www  .  j a v a2s  .  c  om
public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider,
        SyncResult syncResult) {
    final SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(mContext);

    // Only sync if it has been enabled by the user, and account is selected
    // Issue on reinstall where account approval is remembered by system
    if (settings.getBoolean(SyncPrefs.KEY_SYNC_ENABLE, false)
            && !settings.getString(SyncPrefs.KEY_ACCOUNT, "").isEmpty()
            && account.name.equals(settings.getString(SyncPrefs.KEY_ACCOUNT, ""))) {

        if (SYNC_DEBUG_PRINTS)
            Log.d(TAG, "onPerformSync");
        Intent i = new Intent(SYNC_STARTED);
        mContext.sendBroadcast(i);
        // For later
        Intent doneIntent = new Intent(SYNC_FINISHED);
        doneIntent.putExtra(SYNC_RESULT, ERROR);

        // Initialize necessary stuff
        GoogleDBTalker dbTalker = new GoogleDBTalker(account.name, provider);
        GoogleAPITalker apiTalker = new GoogleAPITalker();

        try {
            boolean connected = apiTalker.initialize(accountManager, account, AUTH_TOKEN_TYPE,
                    NOTIFY_AUTH_FAILURE);

            if (connected) {
                if (SYNC_DEBUG_PRINTS)
                    Log.d(TAG, "We got an authToken atleast");

                try {
                    // FIrst of all, we need the latest updated time later.
                    // So
                    // save
                    // that for now.
                    // This is the latest time we synced
                    String lastUpdate = dbTalker.getLastUpdated(account.name);
                    //String lastUpdate = settings.getString(PREFS_LAST_SYNC_DATE, null);
                    // Get the latest hash value we saw on the server
                    String localEtag = settings.getString(PREFS_LAST_SYNC_ETAG, "");

                    // Prepare lists for items
                    ArrayList<GoogleTaskList> listsToSaveToDB = new ArrayList<GoogleTaskList>();
                    HashMap<GoogleTaskList, ArrayList<GoogleTask>> tasksInListToSaveToDB = new HashMap<GoogleTaskList, ArrayList<GoogleTask>>();

                    HashMap<Long, ArrayList<GoogleTask>> tasksInListToUpload = new HashMap<Long, ArrayList<GoogleTask>>();
                    HashMap<Long, ArrayList<GoogleTask>> allTasksInList = new HashMap<Long, ArrayList<GoogleTask>>();

                    // gets all tasks in one query
                    ArrayList<GoogleTask> allTasks = dbTalker.getAllTasks(allTasksInList, tasksInListToUpload);

                    ArrayList<GoogleTaskList> listsToUpload = new ArrayList<GoogleTaskList>();
                    ArrayList<GoogleTaskList> allLocalLists = new ArrayList<GoogleTaskList>();

                    // gets all lists in one query
                    dbTalker.getAllLists(allLocalLists, listsToUpload);

                    // Get the current hash value on the server and all
                    // remote
                    // lists if upload is not true

                    String serverEtag = apiTalker.getModifiedLists(localEtag, allLocalLists, listsToSaveToDB);

                    // IF the tags match, then nothing has changed on
                    // server.
                    if (localEtag.equals(serverEtag)) {
                        if (SYNC_DEBUG_PRINTS)
                            Log.d(TAG, "Etags match, nothing to download");
                    } else {
                        if (SYNC_DEBUG_PRINTS)
                            Log.d(TAG, "Etags dont match, downloading new tasks");
                        // Download tasks which have been updated since last
                        // time
                        for (GoogleTaskList list : listsToSaveToDB) {
                            if (list.id != null && !list.id.isEmpty()) {
                                if (SYNC_DEBUG_PRINTS)
                                    Log.d(TAG, "Saving remote modified tasks for: " + list.id);
                                tasksInListToSaveToDB.put(list,
                                        list.downloadModifiedTasks(apiTalker, allTasks, lastUpdate));
                            }
                        }
                    }

                    if (SYNC_DEBUG_PRINTS)
                        Log.d(TAG, "Getting stuff we want to upload");
                    // Get stuff we would like to upload to server
                    // In case of lists, locally modified versions always
                    // wins
                    // in
                    // conflict, so nothing more to do

                    for (GoogleTaskList list : allLocalLists) {
                        ArrayList<GoogleTask> moddedTasks = tasksInListToUpload.get(list.dbId);
                        if (moddedTasks != null && !moddedTasks.isEmpty()) {
                            // There are some tasks here which we want to
                            // upload
                            if (SYNC_DEBUG_PRINTS)
                                Log.d(TAG, "List id " + list.dbId + ", Locally modified tasks found: "
                                        + moddedTasks.size());

                            // Now we need to handle possible conflicts in
                            // the
                            // tasks. But this has already been sorted when
                            // we
                            // downloaded them
                            // For any task which exists in stuffToSaveToDB,
                            // we
                            // should not upload it
                            // Iterate over a clone to avoid concurrency
                            // problems since we will be modifying
                            // the list during iteration
                            for (GoogleTask moddedTask : (ArrayList<GoogleTask>) moddedTasks.clone()) {
                                ArrayList<GoogleTask> tasksToBeSaved = tasksInListToSaveToDB.get(list);
                                if (tasksToBeSaved != null && tasksToBeSaved.contains(moddedTask)) {
                                    if (SYNC_DEBUG_PRINTS)
                                        Log.d(TAG,
                                                "This modified task was newer on server, removing from upload list: "
                                                        + moddedTask.title);
                                    moddedTasks.remove(moddedTask);
                                }
                                // In the case that a task has been deleted
                                // before it was synced the first time
                                // We should definitely not sync it. Only
                                // delete
                                // it later
                                if (moddedTask.deleted == 1
                                        && (moddedTask.id == null || moddedTask.id.isEmpty())) {
                                    moddedTasks.remove(moddedTask);
                                }
                            }
                        }
                    }

                    if (SYNC_DEBUG_PRINTS)
                        Log.d(TAG, "Uploading lists");
                    // First thing we want to do is upload stuff, because
                    // some
                    // values are updated then
                    boolean uploadedStuff = false;
                    // Start with lists
                    for (GoogleTaskList list : listsToUpload) {
                        GoogleTaskList result = apiTalker.uploadList(list);
                        uploadedStuff = true;
                        if (result != null) {
                            // Make sure that local version is the same as
                            // server's
                            for (GoogleTaskList localList : allLocalLists) {
                                if (result.equals(localList)) {
                                    localList.title = result.title;
                                    localList.id = result.id;
                                    result.dbId = localList.dbId;
                                    break;
                                }
                            }
                            listsToSaveToDB.add(result);
                        }
                    }

                    if (SYNC_DEBUG_PRINTS)
                        Log.d(TAG, "Uploading tasks");
                    // Right, now upload tasks
                    for (GoogleTaskList list : allLocalLists) {
                        ArrayList<GoogleTask> tasksToUpload = tasksInListToUpload.get(list.dbId);
                        if (tasksToUpload != null) {
                            for (GoogleTask task : tasksToUpload) {
                                GoogleTask result = apiTalker.uploadTask(task, list);
                                uploadedStuff = true;
                                // Task now has relevant fields set. Add to
                                // DB-list
                                if (tasksInListToSaveToDB.get(list) == null)
                                    tasksInListToSaveToDB.put(list, new ArrayList<GoogleTask>());
                                tasksInListToSaveToDB.get(list).add(result);
                            }
                        }
                    }

                    // Finally, get the updated etag from the server and
                    // save.
                    // Only worth doing if we actually uploaded anything
                    // Also, only do this if we are doing a full sync
                    String currentEtag = serverEtag;
                    if (uploadedStuff) {
                        currentEtag = apiTalker.getEtag();
                        //lastUpdate = dbTalker.getLastUpdated(account.name);
                    }

                    settings.edit().putString(PREFS_LAST_SYNC_ETAG, currentEtag)
                            //.putString(PREFS_LAST_SYNC_DATE, lastUpdate)
                            .commit();

                    // Now, set sorting values.
                    for (GoogleTaskList list : tasksInListToSaveToDB.keySet()) {
                        if (SYNC_DEBUG_PRINTS)
                            Log.d(TAG, "Setting position values in: " + list.id);
                        ArrayList<GoogleTask> tasks = tasksInListToSaveToDB.get(list);
                        if (tasks != null) {
                            if (SYNC_DEBUG_PRINTS)
                                Log.d(TAG, "Setting position values for #tasks: " + tasks.size());
                            ArrayList<GoogleTask> allListTasks = allTasksInList.get(list.dbId);
                            list.setSortingValues(tasks, allListTasks);
                        }
                    }

                    // Save to database in a single transaction
                    if (SYNC_DEBUG_PRINTS)
                        Log.d(TAG, "Save stuff to DB");
                    dbTalker.SaveToDatabase(listsToSaveToDB, tasksInListToSaveToDB);
                    // Commit it
                    ContentProviderResult[] result = dbTalker.apply();

                    if (SYNC_DEBUG_PRINTS)
                        Log.d(TAG, "Sync Complete!");
                    doneIntent.putExtra(SYNC_RESULT, SUCCESS);

                } catch (ClientProtocolException e) {
                    if (SYNC_DEBUG_PRINTS)
                        Log.d(TAG, "ClientProtocolException: " + e.getLocalizedMessage());
                } catch (JSONException e) {
                    if (SYNC_DEBUG_PRINTS)
                        Log.d(TAG, "JSONException: " + e.getLocalizedMessage());
                } catch (IOException e) {
                    syncResult.stats.numIoExceptions++;
                    if (SYNC_DEBUG_PRINTS)
                        Log.d(TAG, "IOException: " + e.getLocalizedMessage());
                } catch (RemoteException e) {
                    if (SYNC_DEBUG_PRINTS)
                        Log.d(TAG, "RemoteException: " + e.getLocalizedMessage());
                } catch (OperationApplicationException e) {
                    Log.d(TAG, "Joined operation failed: " + e.getLocalizedMessage());
                } catch (ClassCastException e) {
                    // GetListofLists will cast this if it returns a string. It should not return a string
                    // but it did...
                    Log.d(TAG, "ClassCastException: " + e.getLocalizedMessage());
                }

            } else {
                // return real failure
                if (SYNC_DEBUG_PRINTS)
                    Log.d(TAG, "Could not get authToken. Reporting authException");
                syncResult.stats.numAuthExceptions++;
                doneIntent.putExtra(SYNC_RESULT, LOGIN_FAIL);
            }

        } finally {
            // This must always be called or we will leak resources
            if (apiTalker != null) {
                apiTalker.closeClient();
            }

            mContext.sendBroadcast(doneIntent);

            if (SYNC_DEBUG_PRINTS)
                Log.d(TAG, "SyncResult: " + syncResult.toDebugString());
        }
    }
}