Merge two-way synch changes with synch-service refactoring for SSL warning
authorDavid A. Velasco <dvelasco@solidgear.es>
Thu, 25 Oct 2012 08:41:24 +0000 (10:41 +0200)
committerDavid A. Velasco <dvelasco@solidgear.es>
Thu, 25 Oct 2012 08:41:24 +0000 (10:41 +0200)
12 files changed:
src/com/owncloud/android/datamodel/DataStorageManager.java
src/com/owncloud/android/network/CertificateCombinedException.java
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/SynchronizeFolderOperation.java [new file with mode: 0644]
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/com/owncloud/android/syncadapter/FileSyncService.java
src/com/owncloud/android/ui/activity/FileDisplayActivity.java
src/eu/alefzero/webdav/WebdavClient.java

index e824bde..49a3cd7 100644 (file)
@@ -23,6 +23,8 @@ import java.util.Vector;
 
 public interface DataStorageManager {
 
+    public static final int ROOT_PARENT_ID = 0;
+    
     public OCFile getFileByPath(String path);
 
     public OCFile getFileById(long id);
index fad7a6f..27427dd 100644 (file)
@@ -45,7 +45,7 @@ import javax.net.ssl.SSLPeerUnverifiedException;
  */
 public class CertificateCombinedException extends RuntimeException {
 
-    /** Generated */
+    /** Generated - to refresh every time the class changes */
     private static final long serialVersionUID = -8875782030758554999L;
     
     private X509Certificate mServerCert = null;
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 0618b86..60b2b1a 100644 (file)
@@ -19,6 +19,7 @@
 package com.owncloud.android.operations;
 
 import java.io.IOException;
+import java.io.Serializable;
 import java.net.MalformedURLException;
 import java.net.SocketException;
 import java.net.SocketTimeoutException;
@@ -29,6 +30,7 @@ import javax.net.ssl.SSLException;
 import org.apache.commons.httpclient.ConnectTimeoutException;
 import org.apache.commons.httpclient.HttpException;
 import org.apache.commons.httpclient.HttpStatus;
+import org.apache.jackrabbit.webdav.DavException;
 
 import com.owncloud.android.network.CertificateCombinedException;
 
@@ -40,13 +42,18 @@ import com.owncloud.android.network.CertificateCombinedException;
  * 
  * @author David A. Velasco
  */
-public class RemoteOperationResult {
+public class RemoteOperationResult implements Serializable {
+    
+    /** Generated - to refresh every time the class changes */
+    private static final long serialVersionUID = -7805531062432602444L;
+
     
     public enum ResultCode { 
         OK,
         OK_SSL,
         OK_NO_SSL,
         UNHANDLED_HTTP_CODE,
+        UNAUTHORIZED,        
         FILE_NOT_FOUND, 
         INSTANCE_NOT_CONFIGURED, 
         UNKNOWN_ERROR, 
@@ -81,6 +88,9 @@ public class RemoteOperationResult {
             
         } else if (httpCode > 0) {
             switch (httpCode) {
+                case HttpStatus.SC_UNAUTHORIZED:
+                    mCode = ResultCode.UNAUTHORIZED;
+                    break;
                 case HttpStatus.SC_NOT_FOUND:
                     mCode = ResultCode.FILE_NOT_FOUND;
                     break;
@@ -196,11 +206,17 @@ public class RemoteOperationResult {
             } 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";
 
             } else if (mException instanceof HttpException) {
                 return "HTTP violation";
@@ -227,7 +243,7 @@ public class RemoteOperationResult {
         }
         
         return "Operation finished with HTTP status code " + mHttpCode + " (" + (isSuccess()?"success":"fail") + ")";
-
+        
     }
 
 }
diff --git a/src/com/owncloud/android/operations/SynchronizeFolderOperation.java b/src/com/owncloud/android/operations/SynchronizeFolderOperation.java
new file mode 100644 (file)
index 0000000..91de06e
--- /dev/null
@@ -0,0 +1,234 @@
+/* ownCloud Android client application
+ *   Copyright (C) 2012 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 java.util.List;
+import java.util.Vector;
+
+import org.apache.http.HttpStatus;
+import org.apache.jackrabbit.webdav.MultiStatus;
+import org.apache.jackrabbit.webdav.client.methods.PropFindMethod;
+
+import android.accounts.Account;
+import android.content.Context;
+import android.content.Intent;
+import android.util.Log;
+
+import com.owncloud.android.datamodel.DataStorageManager;
+import com.owncloud.android.datamodel.OCFile;
+import com.owncloud.android.files.services.FileDownloader;
+import com.owncloud.android.files.services.FileObserverService;
+
+import eu.alefzero.webdav.WebdavClient;
+import eu.alefzero.webdav.WebdavEntry;
+import eu.alefzero.webdav.WebdavUtils;
+
+
+/**
+ * Remote operation performing the synchronization a the contents of a remote folder with the local database
+ * 
+ * @author David A. Velasco
+ */
+public class SynchronizeFolderOperation extends RemoteOperation {
+
+    private static final String TAG = SynchronizeFolderOperation.class.getCanonicalName();
+
+    /** Remote folder to synchronize */
+    private String mRemotePath;
+    
+    /** Timestamp for the synchronization in progress */
+    private long mCurrentSyncTime;
+    
+    /** Id of the folder to synchronize in the local database */
+    private long mParentId;
+    
+    /** Access to the local database */
+    private DataStorageManager mStorageManager;
+    
+    /** Account where the file to synchronize belongs */
+    private Account mAccount;
+    
+    /** Android context; necessary to send requests to the download service; maybe something to refactor */
+    private Context mContext;
+    
+    /** Files and folders contained in the synchronized folder */
+    private List<OCFile> mChildren;
+    
+    
+    public SynchronizeFolderOperation(  String remotePath, 
+                                        long currentSyncTime, 
+                                        long parentId, 
+                                        DataStorageManager dataStorageManager, 
+                                        Account account, 
+                                        Context context ) {
+        mRemotePath = remotePath;
+        mCurrentSyncTime = currentSyncTime;
+        mParentId = parentId;
+        mStorageManager = dataStorageManager;
+        mAccount = account;
+        mContext = context;
+    }
+    
+    
+    /**
+     * Returns the list of files and folders contained in the synchronized folder, if called after synchronization is complete.
+     * 
+     * @return      List of files and folders contained in the synchronized folder.
+     */
+    public List<OCFile> getChildren() {
+        return mChildren;
+    }
+    
+    
+    @Override
+    protected RemoteOperationResult run(WebdavClient client) {
+        RemoteOperationResult result = null;
+        
+        // code before in FileSyncAdapter.fetchData
+        PropFindMethod query = null;
+        try {
+            Log.d(TAG, "Synchronizing " + mAccount.name + ", fetching files in " + mRemotePath);
+            
+            // remote request 
+            query = new PropFindMethod(client.getBaseUri() + WebdavUtils.encodePath(mRemotePath));
+            int status = client.executeMethod(query);
+            
+            // check and process response   - /// TODO take into account all the possible status per child-resource
+            if (isMultiStatus(status)) { 
+                MultiStatus resp = query.getResponseBodyAsMultiStatus();
+            
+                // synchronize properties of the parent folder, if necessary
+                if (mParentId == DataStorageManager.ROOT_PARENT_ID) {
+                    WebdavEntry we = new WebdavEntry(resp.getResponses()[0], client.getBaseUri().getPath());
+                    OCFile parent = fillOCFile(we);
+                    parent.setParentId(mParentId);
+                    mStorageManager.saveFile(parent);
+                    mParentId = parent.getFileId();
+                }
+                
+                // read contents in folder
+                List<OCFile> updatedFiles = new Vector<OCFile>(resp.getResponses().length - 1);
+                for (int i = 1; i < resp.getResponses().length; ++i) {
+                    WebdavEntry we = new WebdavEntry(resp.getResponses()[i], client.getBaseUri().getPath());
+                    OCFile file = fillOCFile(we);
+                    file.setParentId(mParentId);
+                    OCFile oldFile = mStorageManager.getFileByPath(file.getRemotePath());
+                    if (oldFile != null) {
+                        if (oldFile.keepInSync() && file.getModificationTimestamp() > oldFile.getModificationTimestamp()) {
+                            disableObservance(file);        // first disable observer so we won't get file upload right after download
+                            requestContentDownload(file);
+                        }
+                        file.setKeepInSync(oldFile.keepInSync());
+                    }
+                
+                    updatedFiles.add(file);
+                }
+                                
+                // save updated contents in local database; all at once, trying to get a best performance in database update (not a big deal, indeed)
+                mStorageManager.saveFiles(updatedFiles);
+
+                
+                // removal of obsolete files
+                mChildren = mStorageManager.getDirectoryContent(mStorageManager.getFileById(mParentId));
+                OCFile file;
+                String currentSavePath = FileDownloader.getSavePath(mAccount.name);
+                for (int i=0; i < mChildren.size(); ) {
+                    file = mChildren.get(i);
+                    if (file.getLastSyncDate() != mCurrentSyncTime) {
+                        Log.d(TAG, "removing file: " + file);
+                        mStorageManager.removeFile(file, (file.isDown() && file.getStoragePath().startsWith(currentSavePath)));
+                        mChildren.remove(i);
+                    } else {
+                        i++;
+                    }
+                }
+                
+            } else {
+                client.exhaustResponse(query.getResponseBodyAsStream());
+            }
+            
+            // prepare result object
+            result = new RemoteOperationResult(isMultiStatus(status), status);
+            Log.i(TAG, "Synchronizing " + mAccount.name + ", folder " + mRemotePath + ": " + result.getLogMessage());
+            
+            
+        } catch (Exception e) {
+            result = new RemoteOperationResult(e);
+            Log.e(TAG, "Synchronizing " + mAccount.name + ", folder " + mRemotePath + ": " + result.getLogMessage(), result.getException());
+
+        } finally {
+            if (query != null)
+                query.releaseConnection();  // let the connection available for other methods
+        }
+        
+        return result;
+    }
+    
+
+    public boolean isMultiStatus(int status) {
+        return (status == HttpStatus.SC_MULTI_STATUS); 
+    }
+
+
+    /**
+     * Creates and populates a new {@link OCFile} object with the data read from the server.
+     * 
+     * @param we        WebDAV entry read from the server for a WebDAV resource (remote file or folder).
+     * @return          New OCFile instance representing the remote resource described by we.
+     */
+    private OCFile fillOCFile(WebdavEntry we) {
+        OCFile file = new OCFile(we.decodedPath());
+        file.setCreationTimestamp(we.createTimestamp());
+        file.setFileLength(we.contentLength());
+        file.setMimetype(we.contentType());
+        file.setModificationTimestamp(we.modifiedTimesamp());
+        file.setLastSyncDate(mCurrentSyncTime);
+        return file;
+    }
+    
+    
+    /**
+     * Request to stop the observance of local updates for a file.  
+     * 
+     * @param file      OCFile representing the remote file to stop to monitor for local updates
+     */
+    private void disableObservance(OCFile file) {
+        Log.d(TAG, "Disabling observation of remote file" + file.getRemotePath());
+        Intent intent = new Intent(mContext, FileObserverService.class);
+        intent.putExtra(FileObserverService.KEY_FILE_CMD, FileObserverService.CMD_ADD_DOWNLOADING_FILE);
+        intent.putExtra(FileObserverService.KEY_CMD_ARG, file.getRemotePath());
+        mContext.startService(intent);
+        
+    }
+
+
+    /** 
+     * Requests a download to the file download service
+     * 
+     * @param   file    OCFile representing the remote file to download
+     */
+    private void requestContentDownload(OCFile file) {
+        Intent intent = new Intent(mContext, FileDownloader.class);
+        intent.putExtra(FileDownloader.EXTRA_ACCOUNT, mAccount);
+        intent.putExtra(FileDownloader.EXTRA_FILE, file);
+        mContext.startService(intent);
+    }
+
+
+}
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 8c9a153..b78b127 100644 (file)
 package com.owncloud.android.syncadapter;\r
 \r
 import java.io.IOException;\r
+import java.net.UnknownHostException;\r
 import java.util.List;\r
-import java.util.Vector;\r
 \r
-import org.apache.http.HttpStatus;\r
 import org.apache.jackrabbit.webdav.DavException;\r
-import org.apache.jackrabbit.webdav.MultiStatus;\r
-import org.apache.jackrabbit.webdav.client.methods.PropFindMethod;\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
+//<<<<<<< HEAD
+import com.owncloud.android.operations.RemoteOperationResult;\r
+import com.owncloud.android.operations.SynchronizeFolderOperation;\r
+import com.owncloud.android.operations.UpdateOCVersionOperation;\r
+/*=======
 import com.owncloud.android.files.services.FileDownloader;\r
 import com.owncloud.android.files.services.FileObserverService;\r
 import com.owncloud.android.utils.OwnCloudVersion;\r
+>>>>>>> origin/master*/
 \r
 import android.accounts.Account;\r
 import android.app.Notification;\r
@@ -48,8 +49,6 @@ import android.content.Intent;
 import android.content.SyncResult;\r
 import android.os.Bundle;\r
 import android.util.Log;\r
-import eu.alefzero.webdav.WebdavEntry;\r
-import eu.alefzero.webdav.WebdavUtils;\r
 \r
 /**\r
  * SyncAdapter implementation for syncing sample SyncAdapter contacts to the\r
@@ -59,25 +58,27 @@ import eu.alefzero.webdav.WebdavUtils;
  */\r
 public class FileSyncAdapter extends AbstractOwnCloudSyncAdapter {\r
 \r
-    private final static String TAG = "FileSyncAdapter"; \r
-    \r
-    /*  Commented code for ugly performance tests\r
-    private final static int MAX_DELAYS = 100;\r
-    private static long[] mResponseDelays = new long[MAX_DELAYS]; \r
-    private static long[] mSaveDelays = new long[MAX_DELAYS];\r
-    private int mDelaysIndex = 0;\r
-    private int mDelaysCount = 0;\r
-    */\r
+    private final static String TAG = "FileSyncAdapter";\r
+\r
+    /** \r
+     * Maximum number of failed folder synchronizations that are supported before finishing the synchronization operation\r
+     */\r
+    private static final int MAX_FAILED_RESULTS = 3; \r
     \r
     private long mCurrentSyncTime;\r
     private boolean mCancellation;\r
     private boolean mIsManualSync;\r
-    private boolean mRightSync;\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
@@ -85,123 +86,122 @@ public class FileSyncAdapter extends AbstractOwnCloudSyncAdapter {
 \r
         mCancellation = false;\r
         mIsManualSync = extras.getBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, false);\r
-        mRightSync = true;\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
-        /*  Commented code for ugly performance tests\r
-        mDelaysIndex = 0;\r
-        mDelaysCount = 0;\r
-        */\r
-\r
-        Log.d(TAG, "syncing owncloud account " + account.name);\r
-\r
-        sendStickyBroadcast(true, null);  // message to signal the start to the UI\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
-        updateOCVersion();\r
-\r
-        String uri = getUri().toString();\r
-        PropFindMethod query = null;\r
         try {\r
+            updateOCVersion();\r
             mCurrentSyncTime = System.currentTimeMillis();\r
-            query = new PropFindMethod(uri + "/");\r
-            int status = getClient().executeMethod(query);\r
-            if (status != HttpStatus.SC_UNAUTHORIZED) {\r
-                MultiStatus resp = query.getResponseBodyAsMultiStatus();\r
-\r
-                if (resp.getResponses().length > 0) {\r
-                    WebdavEntry we = new WebdavEntry(resp.getResponses()[0], getUri().getPath());\r
-                    OCFile file = fillOCFile(we);\r
-                    file.setParentId(0);\r
-                    getStorageManager().saveFile(file);\r
-                    if (!mCancellation) {\r
-                        fetchData(uri, syncResult, file.getFileId());\r
-                    }\r
-                }\r
-\r
+            if (!mCancellation) {\r
+                fetchData(OCFile.PATH_SEPARATOR, DataStorageManager.ROOT_PARENT_ID);\r
+                \r
             } else {\r
-                syncResult.stats.numAuthExceptions++;\r
+                Log.d(TAG, "Leaving synchronization before any remote request due to cancellation was requested");\r
             }\r
-        } catch (IOException e) {\r
-            syncResult.stats.numIoExceptions++;\r
-            logException(e, uri + "/");\r
-            \r
-        } catch (DavException e) {\r
-            syncResult.stats.numParseExceptions++;\r
-            logException(e, uri + "/");\r
             \r
-        } catch (Exception e) {\r
-            // TODO something smart with syncresult\r
-            logException(e, uri + "/");\r
-            mRightSync = false;\r
             \r
         } finally {\r
-            if (query != null)\r
-                query.releaseConnection();  // let the connection available for other methods\r
-            mRightSync &= (syncResult.stats.numIoExceptions == 0 && syncResult.stats.numAuthExceptions == 0 && syncResult.stats.numParseExceptions == 0);\r
-            if (!mRightSync && mIsManualSync) {\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
-                Notification notification = new Notification(R.drawable.icon, getContext().getString(R.string.sync_fail_ticker), System.currentTimeMillis());\r
-                notification.flags |= Notification.FLAG_AUTO_CANCEL;\r
-                // TODO put something smart in the contentIntent below\r
-                notification.contentIntent = PendingIntent.getActivity(getContext().getApplicationContext(), (int)System.currentTimeMillis(), new Intent(), 0);\r
-                notification.setLatestEventInfo(getContext().getApplicationContext(), \r
-                                                getContext().getString(R.string.sync_fail_ticker), \r
-                                                String.format(getContext().getString(R.string.sync_fail_content), account.name), \r
-                                                notification.contentIntent);\r
-                ((NotificationManager) getContext().getSystemService(Context.NOTIFICATION_SERVICE)).notify(R.string.sync_fail_ticker, notification);\r
+                notifyFailedSynchronization();\r
             }\r
-            sendStickyBroadcast(false, null);        // message to signal the end to the UI\r
+            sendStickyBroadcast(false, null, mLastFailedResult);        // message to signal the end to the UI\r
         }\r
         \r
-        /*  Commented code for ugly performance tests\r
-        long sum = 0, mean = 0, max = 0, min = Long.MAX_VALUE;\r
-        for (int i=0; i<MAX_DELAYS && i<mDelaysCount; i++) {\r
-            sum += mResponseDelays[i];\r
-            max = Math.max(max, mResponseDelays[i]);\r
-            min = Math.min(min, mResponseDelays[i]);\r
-        }\r
-        mean = sum / mDelaysCount;\r
-        Log.e(TAG, "SYNC STATS - response: mean time = " + mean + " ; max time = " + max + " ; min time = " + min);\r
-        \r
-        sum = 0; max = 0; min = Long.MAX_VALUE;\r
-        for (int i=0; i<MAX_DELAYS && i<mDelaysCount; i++) {\r
-            sum += mSaveDelays[i];\r
-            max = Math.max(max, mSaveDelays[i]);\r
-            min = Math.min(min, mSaveDelays[i]);\r
+    }\r
+    \r
+    \r
+    \r
+    /**\r
+     * Called by system SyncManager when a synchronization is required to be cancelled.\r
+     * \r
+     * Sets the mCancellation flag to 'true'. THe synchronization will be stopped when before a new folder is fetched. Data of the last folder\r
+     * fetched will be still saved in the database. See onPerformSync implementation.\r
+     */\r
+    @Override\r
+    public void onSyncCanceled() {\r
+        Log.d(TAG, "Synchronization of " + getAccount().name + " has been requested to cancel");\r
+        mCancellation = true;\r
+        super.onSyncCanceled();\r
+    }\r
+    \r
+    \r
+    /**\r
+     * Updates the locally stored version value of the ownCloud server\r
+     */\r
+    private void updateOCVersion() {\r
+        UpdateOCVersionOperation update = new UpdateOCVersionOperation(getAccount(), getContext());\r
+        RemoteOperationResult result = update.execute(getClient());\r
+        if (!result.isSuccess()) {\r
+            mLastFailedResult = result; \r
         }\r
-        mean = sum / mDelaysCount;\r
-        Log.e(TAG, "SYNC STATS - save:     mean time = " + mean + " ; max time = " + max + " ; min time = " + min);\r
-        Log.e(TAG, "SYNC STATS - folders measured: " + mDelaysCount);\r
-        */\r
-        \r
     }\r
 \r
-    private void fetchData(String uri, SyncResult syncResult, long parentId) {\r
-        PropFindMethod query = null;\r
-        Vector<OCFile> children = null;\r
-        try {\r
-            Log.d(TAG, "fetching " + uri);\r
-            \r
-            // remote request \r
-            query = new PropFindMethod(uri);\r
-            /*  Commented code for ugly performance tests\r
-            long responseDelay = System.currentTimeMillis();\r
-            */\r
-            int status = getClient().executeMethod(query);\r
-            /*  Commented code for ugly performance tests\r
-            responseDelay = System.currentTimeMillis() - responseDelay;\r
-            Log.e(TAG, "syncing: RESPONSE TIME for " + uri + " contents, " + responseDelay + "ms");\r
-            */\r
-            if (status != HttpStatus.SC_UNAUTHORIZED) {\r
-                MultiStatus resp = query.getResponseBodyAsMultiStatus();\r
+    \r
+    \r
+    /**\r
+     * Synchronize the properties of files and folders contained in a remote folder given by remotePath.\r
+     * \r
+     * @param remotePath        Remote path to the folder to synchronize.\r
+     * @param parentId          Database Id of the folder to synchronize.\r
+     */\r
+    private void fetchData(String remotePath, long parentId) {\r
+        \r
+        if (mFailedResultsCounter > MAX_FAILED_RESULTS || isFinisher(mLastFailedResult))\r
+            return;\r
+        \r
+        // perform folder synchronization\r
+        SynchronizeFolderOperation synchFolderOp = new SynchronizeFolderOperation(  remotePath, \r
+                                                                                    mCurrentSyncTime, \r
+                                                                                    parentId, \r
+                                                                                    getStorageManager(), \r
+                                                                                    getAccount(), \r
+                                                                                    getContext()\r
+                                                                                  );\r
+        RemoteOperationResult result = synchFolderOp.execute(getClient());\r
+        \r
+        \r
+        // synchronized folder -> notice to UI - ALWAYS, although !result.isSuccess\r
+        sendStickyBroadcast(true, remotePath, null);\r
+        \r
+        if (result.isSuccess()) {\r
+            // synchronize children folders \r
+            List<OCFile> children = synchFolderOp.getChildren();\r
+            fetchChildren(children);    // beware of the 'hidden' recursion here!\r
             \r
+//<<<<<<< HEAD
+        } else {\r
+            if (result.getCode() == RemoteOperationResult.ResultCode.UNAUTHORIZED) {\r
+                mSyncResult.stats.numAuthExceptions++;\r
+                \r
+            } else if (result.getException() instanceof DavException) {\r
+                mSyncResult.stats.numParseExceptions++;\r
+                \r
+            } else if (result.getException() instanceof IOException) { \r
+                mSyncResult.stats.numIoExceptions++;\r
+/*=======
                 // insertion or update of files\r
                 List<OCFile> updatedFiles = new Vector<OCFile>(resp.getResponses().length - 1);\r
                 for (int i = 1; i < resp.getResponses().length; ++i) {\r
@@ -226,170 +226,86 @@ public class FileSyncAdapter extends AbstractOwnCloudSyncAdapter {
                     }\r
                     if (getStorageManager().getFileByPath(file.getRemotePath()) != null)\r
                         file.setKeepInSync(getStorageManager().getFileByPath(file.getRemotePath()).keepInSync());\r
+>>>>>>> origin/master*/
                 \r
-                    // Log.v(TAG, "adding file: " + file);\r
-                    updatedFiles.add(file);\r
-                }\r
-                /*  Commented code for ugly performance tests\r
-                long saveDelay = System.currentTimeMillis();\r
-                 */            \r
-                getStorageManager().saveFiles(updatedFiles);    // all "at once" ; trying to get a best performance in database update\r
-                /*  Commented code for ugly performance tests\r
-                saveDelay = System.currentTimeMillis() - saveDelay;\r
-                Log.e(TAG, "syncing: SAVE TIME for " + uri + " contents, " + mSaveDelays[mDelaysIndex] + "ms");\r
-                 */\r
-            \r
-                // removal of obsolete files\r
-                 children = getStorageManager().getDirectoryContent(\r
-                        getStorageManager().getFileById(parentId));\r
-                OCFile file;\r
-                String currentSavePath = FileDownloader.getSavePath(getAccount().name);\r
-                for (int i=0; i < children.size(); ) {\r
-                    file = children.get(i);\r
-                    if (file.getLastSyncDate() != mCurrentSyncTime) {\r
-                        Log.v(TAG, "removing file: " + file);\r
-                        getStorageManager().removeFile(file, (file.isDown() && file.getStoragePath().startsWith(currentSavePath)));\r
-                        children.remove(i);\r
-                    } else {\r
-                        i++;\r
-                    }\r
-                }\r
-            \r
-            } else {\r
-                syncResult.stats.numAuthExceptions++;\r
             }\r
-        } catch (IOException e) {\r
-            syncResult.stats.numIoExceptions++;\r
-            logException(e, uri);\r
-            \r
-        } catch (DavException e) {\r
-            syncResult.stats.numParseExceptions++;\r
-            logException(e, uri);\r
+            mFailedResultsCounter++;\r
+            mLastFailedResult = result;\r
+        }\r
             \r
-        } catch (Exception e) {\r
-            // TODO something smart with syncresult\r
-            mRightSync = false;\r
-            logException(e, uri);\r
-\r
-        } finally {\r
-            if (query != null)\r
-                query.releaseConnection();  // let the connection available for other methods\r
+    }\r
 \r
-            // synchronized folder -> notice to UI\r
-            sendStickyBroadcast(true, getStorageManager().getFileById(parentId).getRemotePath());\r
+    /**\r
+     * Checks if a failed result should terminate the synchronization process immediately, according to\r
+     * OUR OWN POLICY\r
+     * \r
+     * @param   failedResult        Remote operation result to check.\r
+     * @return                      'True' if the result should immediately finish the synchronization\r
+     */\r
+    private boolean isFinisher(RemoteOperationResult failedResult) {\r
+        if  (failedResult != null) {\r
+            RemoteOperationResult.ResultCode code = failedResult.getCode();\r
+            return (code.equals(RemoteOperationResult.ResultCode.SSL_ERROR) ||\r
+                    code.equals(RemoteOperationResult.ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED) ||\r
+                    code.equals(RemoteOperationResult.ResultCode.BAD_OC_VERSION) ||\r
+                    code.equals(RemoteOperationResult.ResultCode.INSTANCE_NOT_CONFIGURED));\r
         }\r
-        \r
-        \r
-        fetchChildren(children, syncResult);\r
-        if (mCancellation) Log.d(TAG, "Leaving " + uri + " because cancelation request");\r
-        \r
-        \r
-        /*  Commented code for ugly performance tests\r
-        mResponseDelays[mDelaysIndex] = responseDelay;\r
-        mSaveDelays[mDelaysIndex] = saveDelay;\r
-        mDelaysCount++;\r
-        mDelaysIndex++;\r
-        if (mDelaysIndex >= MAX_DELAYS)\r
-            mDelaysIndex = 0;\r
-         */\r
-        \r
+        return false;\r
     }\r
 \r
     /**\r
      * 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(Vector<OCFile> files, SyncResult syncResult) {\r
-        for (int i=0; i < files.size() && !mCancellation; i++) {\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.getMimetype().equals("DIR")) {\r
-                fetchData(getUri().toString() + WebdavUtils.encodePath(newFile.getRemotePath()), syncResult, newFile.getFileId());\r
+            if (newFile.isDirectory()) {\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
     }\r
 \r
     \r
-    private OCFile fillOCFile(WebdavEntry we) {\r
-        OCFile file = new OCFile(we.decodedPath());\r
-        file.setCreationTimestamp(we.createTimestamp());\r
-        file.setFileLength(we.contentLength());\r
-        file.setMimetype(we.contentType());\r
-        file.setModificationTimestamp(we.modifiedTimesamp());\r
-        file.setLastSyncDate(mCurrentSyncTime);\r
-        return file;\r
-    }\r
-    \r
-    \r
-    private void sendStickyBroadcast(boolean inProgress, String dirRemotePath) {\r
+    /**\r
+     * Sends a message to any application component interested in the progress of the synchronization.\r
+     * \r
+     * @param inProgress        'True' when the synchronization progress is not finished.\r
+     * @param dirRemotePath     Remote path of a folder that was just synchronized (with or without success)\r
+     */\r
+    private void sendStickyBroadcast(boolean inProgress, String dirRemotePath, RemoteOperationResult result) {\r
         Intent i = new Intent(FileSyncService.SYNC_MESSAGE);\r
         i.putExtra(FileSyncService.IN_PROGRESS, inProgress);\r
         i.putExtra(FileSyncService.ACCOUNT_NAME, getAccount().name);\r
         if (dirRemotePath != null) {\r
             i.putExtra(FileSyncService.SYNC_FOLDER_REMOTE_PATH, dirRemotePath);\r
         }\r
+        if (result != null) {\r
+            i.putExtra(FileSyncService.SYNC_RESULT, result);\r
+        }\r
         getContext().sendStickyBroadcast(i);\r
     }\r
+\r
+    \r
     \r
     /**\r
-     * Called by system SyncManager when a synchronization is required to be cancelled.\r
-     * \r
-     * Sets the mCancellation flag to 'true'. THe synchronization will be stopped when before a new folder is fetched. Data of the last folder\r
-     * fetched will be still saved in the database. See onPerformSync implementation.\r
+     * Notifies the user about a failed synchronization through the status notification bar \r
      */\r
-    @Override\r
-    public void onSyncCanceled() {\r
-        Log.d(TAG, "Synchronization of " + getAccount().name + " has been requested to cancel");\r
-        mCancellation = true;\r
-        super.onSyncCanceled();\r
+    private void notifyFailedSynchronization() {\r
+        Notification notification = new Notification(R.drawable.icon, getContext().getString(R.string.sync_fail_ticker), System.currentTimeMillis());\r
+        notification.flags |= Notification.FLAG_AUTO_CANCEL;\r
+        // TODO put something smart in the contentIntent below\r
+        notification.contentIntent = PendingIntent.getActivity(getContext().getApplicationContext(), (int)System.currentTimeMillis(), new Intent(), 0);\r
+        notification.setLatestEventInfo(getContext().getApplicationContext(), \r
+                                        getContext().getString(R.string.sync_fail_ticker), \r
+                                        String.format(getContext().getString(R.string.sync_fail_content), getAccount().name), \r
+                                        notification.contentIntent);\r
+        ((NotificationManager) getContext().getSystemService(Context.NOTIFICATION_SERVICE)).notify(R.string.sync_fail_ticker, notification);\r
     }\r
 \r
     \r
-    /**\r
-     * Logs an exception triggered in a synchronization request. \r
-     * \r
-     * @param e       Caught exception.\r
-     * @param uri     Uri to the remote directory that was fetched when the synchronization failed \r
-     */\r
-    private void logException(Exception e, String uri) {\r
-        if (e instanceof IOException) {\r
-            Log.e(TAG, "Unrecovered transport exception while synchronizing " + uri + " at " + getAccount().name, e);\r
 \r
-        } else if (e instanceof DavException) {\r
-            Log.e(TAG, "Unexpected WebDAV exception while synchronizing " + uri + " at " + getAccount().name, e);\r
-\r
-        } else {\r
-            Log.e(TAG, "Unexpected exception while synchronizing " + uri  + " at " + getAccount().name, e);\r
-        }\r
-    }\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
-        }\r
-    }\r
 }\r
index 74c7fa6..cb2f720 100644 (file)
@@ -32,6 +32,7 @@ public class FileSyncService extends Service {
     public static final String SYNC_FOLDER_REMOTE_PATH = "SYNC_FOLDER_REMOTE_PATH";\r
     public static final String IN_PROGRESS = "SYNC_IN_PROGRESS";\r
     public static final String ACCOUNT_NAME = "ACCOUNT_NAME";\r
+    public static final String SYNC_RESULT = "SYNC_RESULT";\r
 \r
     /*\r
      * {@inheritDoc}\r
index 328d396..9b204f3 100644 (file)
@@ -72,7 +72,10 @@ import com.owncloud.android.files.services.FileObserverService;
 import com.owncloud.android.files.services.FileUploader;\r
 import com.owncloud.android.files.services.FileUploader.FileUploaderBinder;\r
 import com.owncloud.android.network.OwnCloudClientUtils;\r
+import com.owncloud.android.operations.RemoteOperationResult;\r
 import com.owncloud.android.syncadapter.FileSyncService;\r
+import com.owncloud.android.ui.dialog.SslValidatorDialog;\r
+import com.owncloud.android.ui.dialog.SslValidatorDialog.OnSslValidatorListener;\r
 import com.owncloud.android.ui.fragment.FileDetailFragment;\r
 import com.owncloud.android.ui.fragment.OCFileListFragment;\r
 \r
@@ -87,7 +90,7 @@ import eu.alefzero.webdav.WebdavClient;
  */\r
 \r
 public class FileDisplayActivity extends SherlockFragmentActivity implements\r
-    OCFileListFragment.ContainerActivity, FileDetailFragment.ContainerActivity, OnNavigationListener {\r
+    OCFileListFragment.ContainerActivity, FileDetailFragment.ContainerActivity, OnNavigationListener, OnSslValidatorListener {\r
     \r
     private ArrayAdapter<String> mDirectories;\r
     private OCFile mCurrentDir = null;\r
@@ -100,6 +103,7 @@ public class FileDisplayActivity extends SherlockFragmentActivity implements
     private FileDownloaderBinder mDownloaderBinder = null;\r
     private FileUploaderBinder mUploaderBinder = null;\r
     private ServiceConnection mDownloadConnection = null, mUploadConnection = null;\r
+    private RemoteOperationResult mLastSslUntrustedServerResult = null;\r
     \r
     private OCFileListFragment mFileList;\r
     \r
@@ -110,6 +114,9 @@ public class FileDisplayActivity extends SherlockFragmentActivity implements
     private static final int DIALOG_ABOUT_APP = 2;\r
     public static final int DIALOG_SHORT_WAIT = 3;\r
     private static final int DIALOG_CHOOSE_UPLOAD_SOURCE = 4;\r
+    private static final int DIALOG_SSL_VALIDATOR = 5;\r
+    private static final int DIALOG_CERT_NOT_SAVED = 6;\r
+\r
     \r
     private static final int ACTION_SELECT_CONTENT_FROM_APPS = 1;\r
     private static final int ACTION_SELECT_MULTIPLE_FILES = 2;\r
@@ -275,12 +282,7 @@ public class FileDisplayActivity extends SherlockFragmentActivity implements
                 break;\r
             }\r
             case R.id.startSync: {\r
-                ContentResolver.cancelSync(null, AccountAuthenticator.AUTH_TOKEN_TYPE);   // cancel the current synchronizations of any ownCloud account\r
-                Bundle bundle = new Bundle();\r
-                bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);\r
-                ContentResolver.requestSync(\r
-                        AccountUtils.getCurrentOwnCloudAccount(this),\r
-                        AccountAuthenticator.AUTH_TOKEN_TYPE, bundle);\r
+                startSynchronization();\r
                 break;\r
             }\r
             case R.id.action_upload: {\r
@@ -308,6 +310,16 @@ public class FileDisplayActivity extends SherlockFragmentActivity implements
         return retval;\r
     }\r
 \r
+    private void startSynchronization() {\r
+        ContentResolver.cancelSync(null, AccountAuthenticator.AUTH_TOKEN_TYPE);   // cancel the current synchronizations of any ownCloud account\r
+        Bundle bundle = new Bundle();\r
+        bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);\r
+        ContentResolver.requestSync(\r
+                AccountUtils.getCurrentOwnCloudAccount(this),\r
+                AccountAuthenticator.AUTH_TOKEN_TYPE, bundle);\r
+    }\r
+\r
+\r
     @Override\r
     public boolean onNavigationItemSelected(int itemPosition, long itemId) {\r
         int i = itemPosition;\r
@@ -521,6 +533,15 @@ public class FileDisplayActivity extends SherlockFragmentActivity implements
         Log.d(getClass().toString(), "onPause() end");\r
     }\r
 \r
+    \r
+    @Override\r
+    protected void onPrepareDialog(int id, Dialog dialog, Bundle args) {\r
+        if (id == DIALOG_SSL_VALIDATOR && mLastSslUntrustedServerResult != null) {\r
+            ((SslValidatorDialog)dialog).updateResult(mLastSslUntrustedServerResult);\r
+        }\r
+    }\r
+\r
+    \r
     @Override\r
     protected Dialog onCreateDialog(int id) {\r
         Dialog dialog = null;\r
@@ -646,6 +667,23 @@ public class FileDisplayActivity extends SherlockFragmentActivity implements
             dialog = builder.create();\r
             break;\r
         }\r
+        case DIALOG_SSL_VALIDATOR: {\r
+            dialog = SslValidatorDialog.newInstance(this, mLastSslUntrustedServerResult, this);\r
+            break;\r
+        }\r
+        case DIALOG_CERT_NOT_SAVED: {\r
+            builder = new AlertDialog.Builder(this);\r
+            builder.setMessage(getResources().getString(R.string.ssl_validator_not_saved));\r
+            builder.setCancelable(false);\r
+            builder.setPositiveButton(R.string.common_ok, new DialogInterface.OnClickListener() {\r
+                    @Override\r
+                    public void onClick(DialogInterface dialog, int which) {\r
+                        dialog.dismiss();\r
+                    };\r
+                });\r
+            dialog = builder.create();\r
+            break;\r
+        }\r
         default:\r
             dialog = null;\r
         }\r
@@ -773,6 +811,7 @@ public class FileDisplayActivity extends SherlockFragmentActivity implements
     }\r
 \r
     private class SyncBroadcastReceiver extends BroadcastReceiver {\r
+\r
         /**\r
          * {@link BroadcastReceiver} to enable syncing feedback in UI\r
          */\r
@@ -810,6 +849,14 @@ public class FileDisplayActivity extends SherlockFragmentActivity implements
                 setSupportProgressBarIndeterminateVisibility(inProgress);\r
                 \r
             }\r
+            \r
+            RemoteOperationResult synchResult = (RemoteOperationResult)intent.getSerializableExtra(FileSyncService.SYNC_RESULT);\r
+            if (synchResult != null) {\r
+                if (synchResult.getCode().equals(RemoteOperationResult.ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED)) {\r
+                    mLastSslUntrustedServerResult = synchResult;\r
+                    showDialog(DIALOG_SSL_VALIDATOR); \r
+                }\r
+            }\r
         }\r
     }\r
     \r
@@ -1010,4 +1057,16 @@ public class FileDisplayActivity extends SherlockFragmentActivity implements
     }\r
 \r
 \r
+    @Override\r
+    public void onSavedCertificate() {\r
+        startSynchronization();                \r
+    }\r
+\r
+\r
+    @Override\r
+    public void onFailedSavingCertificate() {\r
+        showDialog(DIALOG_CERT_NOT_SAVED);\r
+    }\r
+\r
+\r
 }\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