Changed the synchronization process to limit the number and type of failures supporte...
authorDavid A. Velasco <dvelasco@solidgear.es>
Wed, 24 Oct 2012 17:39:55 +0000 (19:39 +0200)
committerDavid A. Velasco <dvelasco@solidgear.es>
Wed, 24 Oct 2012 17:39:55 +0000 (19:39 +0200)
src/com/owncloud/android/network/OwnCloudClientUtils.java
src/com/owncloud/android/operations/DownloadFileOperation.java
src/com/owncloud/android/operations/RemoteOperationResult.java
src/com/owncloud/android/operations/UpdateOCVersionOperation.java [new file with mode: 0644]
src/com/owncloud/android/syncadapter/AbstractOwnCloudSyncAdapter.java
src/com/owncloud/android/syncadapter/FileSyncAdapter.java
src/eu/alefzero/webdav/WebdavClient.java

index 9cbc3fd..5cc7a9f 100644 (file)
@@ -38,8 +38,6 @@ import org.apache.http.conn.ssl.BrowserCompatHostnameVerifier;
 import org.apache.http.conn.ssl.X509HostnameVerifier;
 
 import com.owncloud.android.AccountUtils;
-import com.owncloud.android.authenticator.AccountAuthenticator;
-import com.owncloud.android.utils.OwnCloudVersion;
 
 import eu.alefzero.webdav.WebdavClient;
 
@@ -79,11 +77,8 @@ public class OwnCloudClientUtils {
     public static WebdavClient createOwnCloudClient (Account account, Context context) {
         Log.d(TAG, "Creating WebdavClient associated to " + account.name);
        
-        String baseUrl = AccountManager.get(context).getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL);
-        OwnCloudVersion ownCloudVersion = new OwnCloudVersion(AccountManager.get(context).getUserData(account, AccountAuthenticator.KEY_OC_VERSION));
-        String webDavPath = AccountUtils.getWebdavPath(ownCloudVersion);
-        
-        WebdavClient client = createOwnCloudClient(Uri.parse(baseUrl + webDavPath), context);
+        Uri uri = Uri.parse(AccountUtils.constructFullURLForAccount(context, account));
+        WebdavClient client = createOwnCloudClient(uri, context);
         
         String username = account.name.substring(0, account.name.lastIndexOf('@'));
         String password = AccountManager.get(context).getPassword(account);
index e6120d6..c732c8b 100644 (file)
@@ -119,7 +119,7 @@ public class DownloadFileOperation extends RemoteOperation {
     protected RemoteOperationResult run(WebdavClient client) {
         RemoteOperationResult result = null;
         File newFile = null;
-        boolean moved = false;
+        boolean moved = true;
         
         /// download will be performed to a temporal file, then moved to the final location
         File tmpFile = new File(getTmpPath());
index d1d39f6..60b2b1a 100644 (file)
@@ -206,11 +206,14 @@ public class RemoteOperationResult implements Serializable {
             } else if (mException instanceof UnknownHostException) {
                 return "Unknown host exception";
         
-            } else if (mException instanceof SSLException) {
-                if (mCode == ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED)
+            } else if (mException instanceof CertificateCombinedException) {
+                if (((CertificateCombinedException) mException).isRecoverable())
                     return "SSL recoverable exception";
                 else
                     return "SSL exception";
+                
+            } else if (mException instanceof SSLException) {
+                return "SSL exception";
 
             } else if (mException instanceof DavException) {
                 return "Unexpected WebDAV exception";
diff --git a/src/com/owncloud/android/operations/UpdateOCVersionOperation.java b/src/com/owncloud/android/operations/UpdateOCVersionOperation.java
new file mode 100644 (file)
index 0000000..dbe5df8
--- /dev/null
@@ -0,0 +1,109 @@
+/* ownCloud Android client application
+ *   Copyright (C) 2011  Bartek Przybylski
+ *
+ *   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 com.owncloud.android.operations;
+
+import org.apache.commons.httpclient.HttpStatus;
+import org.apache.commons.httpclient.methods.GetMethod;
+import org.json.JSONException;
+import org.json.JSONObject;
+
+import android.accounts.Account;
+import android.accounts.AccountManager;
+import android.content.Context;
+import android.util.Log;
+
+import com.owncloud.android.AccountUtils;
+import com.owncloud.android.authenticator.AccountAuthenticator;
+import com.owncloud.android.operations.RemoteOperationResult.ResultCode;
+import com.owncloud.android.utils.OwnCloudVersion;
+
+import eu.alefzero.webdav.WebdavClient;
+
+/**
+ * Remote operation that checks the version of an ownCloud server and stores it locally
+ * 
+ * @author David A. Velasco
+ */
+public class UpdateOCVersionOperation extends RemoteOperation {
+
+    private static final String TAG = UploadFileOperation.class.getCanonicalName();
+
+    private Account mAccount;
+    private Context mContext;
+    
+    
+    public UpdateOCVersionOperation(Account account, Context context) {
+        mAccount = account;
+        mContext = context;
+    }
+    
+    
+    @Override
+    protected RemoteOperationResult run(WebdavClient client) {
+        AccountManager accountMngr = AccountManager.get(mContext); 
+        String statUrl = accountMngr.getUserData(mAccount, AccountAuthenticator.KEY_OC_BASE_URL);
+        statUrl += AccountUtils.STATUS_PATH;
+        RemoteOperationResult result = null;
+        GetMethod get = null;
+        try {
+            get = new GetMethod(statUrl);
+            int status = client.executeMethod(get);
+            if (status != HttpStatus.SC_OK) {
+                client.exhaustResponse(get.getResponseBodyAsStream());
+                result = new RemoteOperationResult(false, status);
+                
+            } else {
+                String response = get.getResponseBodyAsString();
+                if (response != null) {
+                    JSONObject json = new JSONObject(response);
+                    if (json != null && json.getString("version") != null) {
+                        OwnCloudVersion ocver = new OwnCloudVersion(json.getString("version"));
+                        if (ocver.isVersionValid()) {
+                            accountMngr.setUserData(mAccount, AccountAuthenticator.KEY_OC_VERSION, ocver.toString());
+                            Log.d(TAG, "Got new OC version " + ocver.toString());
+                            result = new RemoteOperationResult(ResultCode.OK);
+                            
+                        } else {
+                            Log.w(TAG, "Invalid version number received from server: " + json.getString("version"));
+                            result = new RemoteOperationResult(RemoteOperationResult.ResultCode.BAD_OC_VERSION);
+                        }
+                    }
+                }
+                if (result == null) {
+                    result = new RemoteOperationResult(RemoteOperationResult.ResultCode.INSTANCE_NOT_CONFIGURED);
+                }
+            }
+            Log.i(TAG, "Check for update of ownCloud server version at " + client.getBaseUri() + ": " + result.getLogMessage());
+            
+        } catch (JSONException e) {
+            result = new RemoteOperationResult(RemoteOperationResult.ResultCode.INSTANCE_NOT_CONFIGURED);
+            Log.e(TAG, "Check for update of ownCloud server version at " + client.getBaseUri() + ": " + result.getLogMessage(), e);
+                
+        } catch (Exception e) {
+            result = new RemoteOperationResult(e);
+            Log.e(TAG, "Check for update of ownCloud server version at " + client.getBaseUri() + ": " + result.getLogMessage(), e);
+            
+        } finally {
+            if (get != null) 
+                get.releaseConnection();
+        }
+        return result;
+    }
+
+}
index 878c696..92c0b72 100644 (file)
@@ -39,7 +39,6 @@ import android.accounts.OperationCanceledException;
 import android.content.AbstractThreadedSyncAdapter;\r
 import android.content.ContentProviderClient;\r
 import android.content.Context;\r
-import android.net.Uri;\r
 import eu.alefzero.webdav.WebdavClient;\r
 \r
 /**\r
@@ -143,19 +142,14 @@ public abstract class AbstractOwnCloudSyncAdapter extends
         return null;\r
     }\r
 \r
-    protected Uri getUri() {\r
-        return Uri.parse(AccountUtils.constructFullURLForAccount(getContext(), getAccount()));\r
-    }\r
-\r
-    protected WebdavClient getClient() throws /*OperationCanceledException,\r
-            AuthenticatorException,*/ IOException {\r
-        if (mClient == null) {\r
-            if (AccountUtils.constructFullURLForAccount(getContext(), getAccount()) == null) {\r
-                throw new UnknownHostException();\r
-            }\r
-            mClient = OwnCloudClientUtils.createOwnCloudClient(account, getContext());\r
+    protected void initClientForCurrentAccount() throws UnknownHostException {\r
+        if (AccountUtils.constructFullURLForAccount(getContext(), account) == null) {\r
+            throw new UnknownHostException();\r
         }\r
-\r
+        mClient = OwnCloudClientUtils.createOwnCloudClient(account, getContext());\r
+    }\r
+    \r
+    protected WebdavClient getClient() {\r
         return mClient;\r
     }\r
 }
\ No newline at end of file
index 1f0d908..3763908 100644 (file)
 package com.owncloud.android.syncadapter;\r
 \r
 import java.io.IOException;\r
+import java.net.UnknownHostException;\r
 import java.util.List;\r
 \r
 import org.apache.jackrabbit.webdav.DavException;\r
-import org.json.JSONObject;\r
 \r
-import com.owncloud.android.AccountUtils;\r
 import com.owncloud.android.R;\r
-import com.owncloud.android.authenticator.AccountAuthenticator;\r
 import com.owncloud.android.datamodel.DataStorageManager;\r
 import com.owncloud.android.datamodel.FileDataStorageManager;\r
 import com.owncloud.android.datamodel.OCFile;\r
 import com.owncloud.android.operations.RemoteOperationResult;\r
 import com.owncloud.android.operations.SynchronizeFolderOperation;\r
-import com.owncloud.android.utils.OwnCloudVersion;\r
+import com.owncloud.android.operations.UpdateOCVersionOperation;\r
 \r
 import android.accounts.Account;\r
 import android.app.Notification;\r
@@ -45,7 +43,6 @@ import android.content.Intent;
 import android.content.SyncResult;\r
 import android.os.Bundle;\r
 import android.util.Log;\r
-import eu.alefzero.webdav.WebdavClient;\r
 \r
 /**\r
  * SyncAdapter implementation for syncing sample SyncAdapter contacts to the\r
@@ -67,11 +64,15 @@ public class FileSyncAdapter extends AbstractOwnCloudSyncAdapter {
     private boolean mIsManualSync;\r
     private int mFailedResultsCounter;    \r
     private RemoteOperationResult mLastFailedResult;\r
+    private SyncResult mSyncResult;\r
     \r
     public FileSyncAdapter(Context context, boolean autoInitialize) {\r
         super(context, autoInitialize);\r
     }\r
 \r
+    /**\r
+     * {@inheritDoc}\r
+     */\r
     @Override\r
     public synchronized void onPerformSync(Account account, Bundle extras,\r
             String authority, ContentProviderClient provider,\r
@@ -81,32 +82,41 @@ public class FileSyncAdapter extends AbstractOwnCloudSyncAdapter {
         mIsManualSync = extras.getBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, false);\r
         mFailedResultsCounter = 0;\r
         mLastFailedResult = null;\r
+        mSyncResult = syncResult;\r
         \r
         this.setAccount(account);\r
         this.setContentProvider(provider);\r
         this.setStorageManager(new FileDataStorageManager(account, getContentProvider()));\r
+        try {\r
+            this.initClientForCurrentAccount();\r
+        } catch (UnknownHostException e) {\r
+            /// the account is unknown for the Synchronization Manager, or unreachable for this context; don't try this again\r
+            mSyncResult.tooManyRetries = true;\r
+            notifyFailedSynchronization();\r
+            return;\r
+        }\r
         \r
-        Log.d(TAG, "syncing owncloud account " + account.name);\r
-\r
+        Log.d(TAG, "Synchronization of ownCloud account " + account.name + " starting");\r
         sendStickyBroadcast(true, null, null);  // message to signal the start of the synchronization to the UI\r
         \r
         try {\r
             updateOCVersion();\r
             mCurrentSyncTime = System.currentTimeMillis();\r
             if (!mCancellation) {\r
-                fetchData(OCFile.PATH_SEPARATOR, syncResult, DataStorageManager.ROOT_PARENT_ID);\r
+                fetchData(OCFile.PATH_SEPARATOR, DataStorageManager.ROOT_PARENT_ID);\r
                 \r
             } else {\r
                 Log.d(TAG, "Leaving synchronization before any remote request due to cancellation was requested");\r
             }\r
             \r
+            \r
         } finally {\r
             // it's important making this although very unexpected errors occur; that's the reason for the finally\r
             \r
             if (mFailedResultsCounter > 0 && mIsManualSync) {\r
                 /// don't let the system synchronization manager retries MANUAL synchronizations\r
                 //      (be careful: "MANUAL" currently includes the synchronization requested when a new account is created and when the user changes the current account)\r
-                syncResult.tooManyRetries = true;\r
+                mSyncResult.tooManyRetries = true;\r
                 \r
                 /// notify the user about the failure of MANUAL synchronization\r
                 notifyFailedSynchronization();\r
@@ -136,31 +146,10 @@ public class FileSyncAdapter extends AbstractOwnCloudSyncAdapter {
      * Updates the locally stored version value of the ownCloud server\r
      */\r
     private void updateOCVersion() {\r
-        String statUrl = getAccountManager().getUserData(getAccount(), AccountAuthenticator.KEY_OC_BASE_URL);\r
-        statUrl += AccountUtils.STATUS_PATH;\r
-        \r
-        try {\r
-            String result = getClient().getResultAsString(statUrl);\r
-            if (result != null) {\r
-                try {\r
-                    JSONObject json = new JSONObject(result);\r
-                    if (json != null && json.getString("version") != null) {\r
-                        OwnCloudVersion ocver = new OwnCloudVersion(json.getString("version"));\r
-                        if (ocver.isVersionValid()) {\r
-                            getAccountManager().setUserData(getAccount(), AccountAuthenticator.KEY_OC_VERSION, ocver.toString());\r
-                            Log.d(TAG, "Got new OC version " + ocver.toString());\r
-                        } else {\r
-                            Log.w(TAG, "Invalid version number received from server: " + json.getString("version"));\r
-                        }\r
-                    }\r
-                } catch (Throwable e) {\r
-                    Log.w(TAG, "Couldn't parse version response", e);\r
-                }\r
-            } else {\r
-                Log.w(TAG, "Problem while getting ocversion from server");\r
-            }\r
-        } catch (Exception e) {\r
-            Log.e(TAG, "Problem getting response from server", e);\r
+        UpdateOCVersionOperation update = new UpdateOCVersionOperation(getAccount(), getContext());\r
+        RemoteOperationResult result = update.execute(getClient());\r
+        if (!result.isSuccess()) {\r
+            mLastFailedResult = result; \r
         }\r
     }\r
 \r
@@ -171,23 +160,12 @@ public class FileSyncAdapter extends AbstractOwnCloudSyncAdapter {
      * \r
      * @param remotePath        Remote path to the folder to synchronize.\r
      * @param parentId          Database Id of the folder to synchronize.\r
-     * @param syncResult        Object to update for communicate results to the system's synchronization manager.        \r
      */\r
-    private void fetchData(String remotePath, SyncResult syncResult, long parentId) {\r
+    private void fetchData(String remotePath, long parentId) {\r
         \r
-        if (mFailedResultsCounter > MAX_FAILED_RESULTS && isFinisher(mLastFailedResult))\r
+        if (mFailedResultsCounter > MAX_FAILED_RESULTS || isFinisher(mLastFailedResult))\r
             return;\r
         \r
-        // get client object to connect to the remote ownCloud server\r
-        WebdavClient client = null;\r
-        try {\r
-            client = getClient();\r
-        } catch (IOException e) {\r
-            syncResult.stats.numIoExceptions++;\r
-            Log.d(TAG, "Could not get client object while trying to synchronize - impossible to continue");\r
-            return;\r
-        }\r
-        \r
         // perform folder synchronization\r
         SynchronizeFolderOperation synchFolderOp = new SynchronizeFolderOperation(  remotePath, \r
                                                                                     mCurrentSyncTime, \r
@@ -196,7 +174,7 @@ public class FileSyncAdapter extends AbstractOwnCloudSyncAdapter {
                                                                                     getAccount(), \r
                                                                                     getContext()\r
                                                                                   );\r
-        RemoteOperationResult result = synchFolderOp.execute(client);\r
+        RemoteOperationResult result = synchFolderOp.execute(getClient());\r
         \r
         \r
         // synchronized folder -> notice to UI - ALWAYS, although !result.isSuccess\r
@@ -205,17 +183,17 @@ public class FileSyncAdapter extends AbstractOwnCloudSyncAdapter {
         if (result.isSuccess()) {\r
             // synchronize children folders \r
             List<OCFile> children = synchFolderOp.getChildren();\r
-            fetchChildren(children, syncResult);    // beware of the 'hidden' recursion here!\r
+            fetchChildren(children);    // beware of the 'hidden' recursion here!\r
             \r
         } else {\r
             if (result.getCode() == RemoteOperationResult.ResultCode.UNAUTHORIZED) {\r
-                syncResult.stats.numAuthExceptions++;\r
+                mSyncResult.stats.numAuthExceptions++;\r
                 \r
             } else if (result.getException() instanceof DavException) {\r
-                syncResult.stats.numParseExceptions++;\r
+                mSyncResult.stats.numParseExceptions++;\r
                 \r
             } else if (result.getException() instanceof IOException) { \r
-                syncResult.stats.numIoExceptions++;\r
+                mSyncResult.stats.numIoExceptions++;\r
                 \r
             }\r
             mFailedResultsCounter++;\r
@@ -246,14 +224,13 @@ public class FileSyncAdapter extends AbstractOwnCloudSyncAdapter {
      * Synchronize data of folders in the list of received files\r
      * \r
      * @param files         Files to recursively fetch \r
-     * @param syncResult    Updated object to provide results to the Synchronization Manager\r
      */\r
-    private void fetchChildren(List<OCFile> files, SyncResult syncResult) {\r
+    private void fetchChildren(List<OCFile> files) {\r
         int i;\r
         for (i=0; i < files.size() && !mCancellation; i++) {\r
             OCFile newFile = files.get(i);\r
             if (newFile.isDirectory()) {\r
-                fetchData(newFile.getRemotePath(), syncResult, newFile.getFileId());\r
+                fetchData(newFile.getRemotePath(), newFile.getFileId());\r
             }\r
         }\r
         if (mCancellation && i <files.size()) Log.d(TAG, "Leaving synchronization before synchronizing " + files.get(i).getRemotePath() + " because cancelation request");\r
index 6f98f50..61f1660 100644 (file)
@@ -337,19 +337,4 @@ public class WebdavClient extends HttpClient {
         return mUri;\r
     }\r
 \r
-    public String getResultAsString(String targetUrl) {\r
-        String getResult = null;\r
-        try {\r
-            GetMethod get = new GetMethod(targetUrl);\r
-            int status = executeMethod(get);\r
-            if (status == HttpStatus.SC_OK) {\r
-                getResult = get.getResponseBodyAsString();\r
-            }\r
-        } catch (Exception e) {\r
-            Log.e(TAG, "Error while getting requested file: " + targetUrl, e);\r
-            getResult = null;\r
-        }\r
-        return getResult;\r
-    }\r
-    \r
 }\r