From: David A. Velasco Date: Wed, 25 Mar 2015 09:57:04 +0000 (+0100) Subject: Merge pull request #924 from owncloud/add_user_agent_support X-Git-Tag: oc-android-1.7.1_signed^2~8 X-Git-Url: http://git.linex4red.de/pub/Android/ownCloud.git/commitdiff_plain/6bef4abf744cb03d50dd4ecff121c20a1e267aab?hp=30b72638a6cd1b1ae6e7c1fbc770985db3bd7ae8 Merge pull request #924 from owncloud/add_user_agent_support Updated after adding custom user agent support to library --- diff --git a/owncloud-android-library b/owncloud-android-library index 0dd68c1f..925227b4 160000 --- a/owncloud-android-library +++ b/owncloud-android-library @@ -1 +1 @@ -Subproject commit 0dd68c1f65c31bd716b2de26e644c87c98e9b9c2 +Subproject commit 925227b41be9a40e6c30a1fd833ea0a25bc8c3dc diff --git a/res/values/setup.xml b/res/values/setup.xml index 6c1a67a9..0c341bd8 100644 --- a/res/values/setup.xml +++ b/res/values/setup.xml @@ -9,6 +9,7 @@ owncloud Owncloud_ ownCloud + Mozilla/5.0 (Android) ownCloud diff --git a/src/com/owncloud/android/MainApp.java b/src/com/owncloud/android/MainApp.java index 2d819f49..4d13f8b7 100644 --- a/src/com/owncloud/android/MainApp.java +++ b/src/com/owncloud/android/MainApp.java @@ -22,6 +22,8 @@ package com.owncloud.android; import android.app.Application; import android.content.Context; +import android.content.pm.PackageInfo; +import android.content.pm.PackageManager; import com.owncloud.android.datamodel.ThumbnailsCacheManager; import com.owncloud.android.lib.common.OwnCloudClientManagerFactory; @@ -34,7 +36,9 @@ import com.owncloud.android.lib.common.utils.Log_OC; * classes */ public class MainApp extends Application { - + + private static final String TAG = MainApp.class.getSimpleName(); + private static final String AUTH_ON = "on"; @SuppressWarnings("unused") @@ -49,7 +53,8 @@ public class MainApp extends Application { MainApp.mContext = getApplicationContext(); boolean isSamlAuth = AUTH_ON.equals(getString(R.string.auth_method_saml_web_sso)); - + + OwnCloudClientManagerFactory.setUserAgent(getUserAgent()); if (isSamlAuth) { OwnCloudClientManagerFactory.setDefaultPolicy(Policy.SINGLE_SESSION_PER_ACCOUNT); @@ -117,4 +122,25 @@ public class MainApp extends Application { return getAppContext().getResources().getString(R.string.log_name); } + // user agent + public static String getUserAgent() { + String appString = getAppContext().getResources().getString(R.string.user_agent); + String packageName = getAppContext().getPackageName(); + String version = ""; + + PackageInfo pInfo = null; + try { + pInfo = getAppContext().getPackageManager().getPackageInfo(packageName, 0); + if (pInfo != null) { + version = "/" + pInfo.versionName; + } + } catch (PackageManager.NameNotFoundException e) { + Log_OC.e(TAG, "Trying to get packageName", e.getCause()); + } + + // Mozilla/5.0 (Android) ownCloud /1.7.0 + String userAgent = appString + version; + + return userAgent; + } } diff --git a/src/com/owncloud/android/authentication/AuthenticatorAsyncTask.java b/src/com/owncloud/android/authentication/AuthenticatorAsyncTask.java index be15d1c0..4b2aed50 100644 --- a/src/com/owncloud/android/authentication/AuthenticatorAsyncTask.java +++ b/src/com/owncloud/android/authentication/AuthenticatorAsyncTask.java @@ -24,6 +24,7 @@ import android.content.Context; import android.net.Uri; import android.os.AsyncTask; +import com.owncloud.android.MainApp; import com.owncloud.android.lib.common.OwnCloudClient; import com.owncloud.android.lib.common.OwnCloudClientFactory; import com.owncloud.android.lib.common.OwnCloudCredentials; diff --git a/src/com/owncloud/android/datamodel/ThumbnailsCacheManager.java b/src/com/owncloud/android/datamodel/ThumbnailsCacheManager.java index 87fa43ff..c375f8d7 100644 --- a/src/com/owncloud/android/datamodel/ThumbnailsCacheManager.java +++ b/src/com/owncloud/android/datamodel/ThumbnailsCacheManager.java @@ -145,7 +145,8 @@ public class ThumbnailsCacheManager { private FileDataStorageManager mStorageManager; - public ThumbnailGenerationTask(ImageView imageView, FileDataStorageManager storageManager, Account account) { + public ThumbnailGenerationTask(ImageView imageView, FileDataStorageManager storageManager, + Account account) { // Use a WeakReference to ensure the ImageView can be garbage collected mImageViewReference = new WeakReference(imageView); if (storageManager == null) @@ -168,7 +169,8 @@ public class ThumbnailsCacheManager { AccountManager accountMgr = AccountManager.get(MainApp.getAppContext()); mServerVersion = accountMgr.getUserData(mAccount, Constants.KEY_OC_VERSION); - OwnCloudAccount ocAccount = new OwnCloudAccount(mAccount, MainApp.getAppContext()); + OwnCloudAccount ocAccount = new OwnCloudAccount(mAccount, + MainApp.getAppContext()); mClient = OwnCloudClientManagerFactory.getDefaultSingleton(). getClientFor(ocAccount, MainApp.getAppContext()); } @@ -276,18 +278,21 @@ public class ThumbnailsCacheManager { // Download thumbnail from server if (mClient != null && mServerVersion != null) { OwnCloudVersion serverOCVersion = new OwnCloudVersion(mServerVersion); - if (serverOCVersion.compareTo(new OwnCloudVersion(MINOR_SERVER_VERSION_FOR_THUMBS)) >= 0) { + if (serverOCVersion.compareTo( + new OwnCloudVersion(MINOR_SERVER_VERSION_FOR_THUMBS)) >= 0) { try { int status = -1; - String uri = mClient.getBaseUri() + "/index.php/apps/files/api/v1/thumbnail/" + + String uri = mClient.getBaseUri() + "" + + "/index.php/apps/files/api/v1/thumbnail/" + px + "/" + px + Uri.encode(file.getRemotePath(), "/"); Log_OC.d("Thumbnail", "URI: " + uri); GetMethod get = new GetMethod(uri); status = mClient.executeMethod(get); if (status == HttpStatus.SC_OK) { byte[] bytes = get.getResponseBody(); - Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length); + Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, + bytes.length); thumbnail = ThumbnailUtils.extractThumbnail(bitmap, px, px); // Add thumbnail to cache diff --git a/src/com/owncloud/android/files/services/FileDownloader.java b/src/com/owncloud/android/files/services/FileDownloader.java index f5be6a76..f6d3b50f 100644 --- a/src/com/owncloud/android/files/services/FileDownloader.java +++ b/src/com/owncloud/android/files/services/FileDownloader.java @@ -28,6 +28,7 @@ import java.util.Iterator; import java.util.Map; import java.util.Vector; +import com.owncloud.android.MainApp; import com.owncloud.android.R; import com.owncloud.android.authentication.AccountUtils; import com.owncloud.android.authentication.AuthenticatorActivity; @@ -117,7 +118,8 @@ public class FileDownloader extends Service super.onCreate(); Log_OC.d(TAG, "Creating service"); mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); - HandlerThread thread = new HandlerThread("FileDownloaderThread", Process.THREAD_PRIORITY_BACKGROUND); + HandlerThread thread = new HandlerThread("FileDownloaderThread", + Process.THREAD_PRIORITY_BACKGROUND); thread.start(); mServiceLooper = thread.getLooper(); mServiceHandler = new ServiceHandler(mServiceLooper, this); @@ -190,8 +192,10 @@ public class FileDownloader extends Service // Store file on db with state 'downloading' /* - TODO - check if helps with UI responsiveness, letting only folders use FileDownloaderBinder to check - FileDataStorageManager storageManager = new FileDataStorageManager(account, getContentResolver()); + TODO - check if helps with UI responsiveness, + letting only folders use FileDownloaderBinder to check + FileDataStorageManager storageManager = + new FileDataStorageManager(account, getContentResolver()); file.setDownloading(true); storageManager.saveFile(file); */ @@ -256,7 +260,8 @@ public class FileDownloader extends Service public class FileDownloaderBinder extends Binder implements OnDatatransferProgressListener { /** - * Map of listeners that will be reported about progress of downloads from a {@link FileDownloaderBinder} + * Map of listeners that will be reported about progress of downloads from a + * {@link FileDownloaderBinder} * instance. */ private Map mBoundListeners = @@ -288,7 +293,7 @@ public class FileDownloader extends Service mCurrentDownload.getRemotePath().startsWith(file.getRemotePath()) && account.name.equals(mCurrentAccount.name)) { /*Log_OC.v( "NOW " + TAG + ", thread " + Thread.currentThread().getName(), - "Canceling current sync as descendant: " + mCurrentDownload.getRemotePath());*/ + "Canceling current sync as descendant: " + mCurrentDownload.getRemotePath());*/ mCurrentDownload.cancel(); } } @@ -318,8 +323,8 @@ public class FileDownloader extends Service /** - * Returns True when the file described by 'file' in the ownCloud account 'account' is downloading or - * waiting to download. + * Returns True when the file described by 'file' in the ownCloud account 'account' + * is downloading or waiting to download. *

* If 'file' is a directory, returns 'true' if any of its descendant files is downloading or * waiting to download. @@ -368,12 +373,15 @@ public class FileDownloader extends Service } @Override - public void onTransferProgress(long progressRate, long totalTransferredSoFar, long totalToTransfer, - String fileName) { - //String key = buildKey(mCurrentDownload.getAccount(), mCurrentDownload.getFile().getRemotePath()); - OnDatatransferProgressListener boundListener = mBoundListeners.get(mCurrentDownload.getFile().getFileId()); + public void onTransferProgress(long progressRate, long totalTransferredSoFar, + long totalToTransfer, String fileName) { + //String key = buildKey(mCurrentDownload.getAccount(), + // mCurrentDownload.getFile().getRemotePath()); + OnDatatransferProgressListener boundListener = + mBoundListeners.get(mCurrentDownload.getFile().getFileId()); if (boundListener != null) { - boundListener.onTransferProgress(progressRate, totalTransferredSoFar, totalToTransfer, fileName); + boundListener.onTransferProgress(progressRate, totalTransferredSoFar, + totalToTransfer, fileName); } } @@ -397,7 +405,8 @@ public class FileDownloader extends Service * Created with the Looper of a new thread, started in {@link FileUploader#onCreate()}. */ private static class ServiceHandler extends Handler { - // don't make it a final class, and don't remove the static ; lint will warn about a possible memory leak + // don't make it a final class, and don't remove the static ; lint will warn about a + // possible memory leak FileDownloader mService; public ServiceHandler(Looper looper, FileDownloader service) { @@ -444,7 +453,8 @@ public class FileDownloader extends Service RemoteOperationResult downloadResult = null; try { /// prepare client object to send the request to the ownCloud server - if (mCurrentAccount == null || !mCurrentAccount.equals(mCurrentDownload.getAccount())) { + if (mCurrentAccount == null || + !mCurrentAccount.equals(mCurrentDownload.getAccount())) { mCurrentAccount = mCurrentDownload.getAccount(); mStorageManager = new FileDataStorageManager( mCurrentAccount, @@ -452,7 +462,8 @@ public class FileDownloader extends Service ); } // else, reuse storage manager from previous operation - // always get client from client manager, to get fresh credentials in case of update + // always get client from client manager, to get fresh credentials in case + // of update OwnCloudAccount ocAccount = new OwnCloudAccount(mCurrentAccount, this); mDownloadClient = OwnCloudClientManagerFactory.getDefaultSingleton(). getClientFor(ocAccount, this); @@ -467,10 +478,12 @@ public class FileDownloader extends Service } } catch (AccountsException e) { - Log_OC.e(TAG, "Error while trying to get authorization for " + mCurrentAccount.name, e); + Log_OC.e(TAG, "Error while trying to get authorization for " + + mCurrentAccount.name, e); downloadResult = new RemoteOperationResult(e); } catch (IOException e) { - Log_OC.e(TAG, "Error while trying to get authorization for " + mCurrentAccount.name, e); + Log_OC.e(TAG, "Error while trying to get authorization for " + + mCurrentAccount.name, e); downloadResult = new RemoteOperationResult(e); } finally { @@ -478,16 +491,19 @@ public class FileDownloader extends Service "Removing payload " + mCurrentDownload.getRemotePath());*/ Pair removeResult = - mPendingDownloads.removePayload(mCurrentAccount, mCurrentDownload.getRemotePath()); + mPendingDownloads.removePayload(mCurrentAccount, + mCurrentDownload.getRemotePath()); /// notify result notifyDownloadResult(mCurrentDownload, downloadResult); - sendBroadcastDownloadFinished(mCurrentDownload, downloadResult, removeResult.second); + sendBroadcastDownloadFinished(mCurrentDownload, downloadResult, + removeResult.second); } } else { // Cancel the transfer - Log_OC.d(TAG, "Account " + mCurrentDownload.getAccount().toString() + " doesn't exist"); + Log_OC.d(TAG, "Account " + mCurrentDownload.getAccount().toString() + + " doesn't exist"); cancelDownloadsForAccount(mCurrentDownload.getAccount()); } @@ -569,7 +585,8 @@ public class FileDownloader extends Service * Callback method to update the progress bar in the status notification. */ @Override - public void onTransferProgress(long progressRate, long totalTransferredSoFar, long totalToTransfer, String filePath) { + public void onTransferProgress(long progressRate, long totalTransferredSoFar, + long totalToTransfer, String filePath) { int percent = (int) (100.0 * ((double) totalTransferredSoFar) / ((double) totalToTransfer)); if (percent != mLastPercent) { mNotificationBuilder.setProgress(100, percent, totalToTransfer < 0); @@ -588,7 +605,8 @@ public class FileDownloader extends Service * @param downloadResult Result of the download operation. * @param download Finished download operation */ - private void notifyDownloadResult(DownloadFileOperation download, RemoteOperationResult downloadResult) { + private void notifyDownloadResult(DownloadFileOperation download, + RemoteOperationResult downloadResult) { mNotificationManager.cancel(R.string.downloader_download_in_progress_ticker); if (!downloadResult.isCancelled()) { int tickerId = (downloadResult.isSuccess()) ? R.string.downloader_download_succeeded_ticker : @@ -612,16 +630,19 @@ public class FileDownloader extends Service // let the user update credentials with one click Intent updateAccountCredentials = new Intent(this, AuthenticatorActivity.class); - updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACCOUNT, download.getAccount()); + updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACCOUNT, + download.getAccount()); updateAccountCredentials.putExtra( - AuthenticatorActivity.EXTRA_ACTION, AuthenticatorActivity.ACTION_UPDATE_EXPIRED_TOKEN + AuthenticatorActivity.EXTRA_ACTION, + AuthenticatorActivity.ACTION_UPDATE_EXPIRED_TOKEN ); updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS); updateAccountCredentials.addFlags(Intent.FLAG_FROM_BACKGROUND); mNotificationBuilder .setContentIntent(PendingIntent.getActivity( - this, (int) System.currentTimeMillis(), updateAccountCredentials, PendingIntent.FLAG_ONE_SHOT)); + this, (int) System.currentTimeMillis(), updateAccountCredentials, + PendingIntent.FLAG_ONE_SHOT)); } else { // TODO put something smart in showDetailsIntent @@ -632,7 +653,8 @@ public class FileDownloader extends Service } mNotificationBuilder.setContentText( - ErrorMessageAdapter.getErrorCauseMessage(downloadResult, download, getResources()) + ErrorMessageAdapter.getErrorCauseMessage(downloadResult, download, + getResources()) ); mNotificationManager.notify(tickerId, mNotificationBuilder.build()); @@ -650,7 +672,8 @@ public class FileDownloader extends Service /** - * Sends a broadcast when a download finishes in order to the interested activities can update their view + * Sends a broadcast when a download finishes in order to the interested activities can + * update their view * * @param download Finished download operation * @param downloadResult Result of the download operation @@ -678,7 +701,8 @@ public class FileDownloader extends Service * @param download Added download operation * @param linkedToRemotePath Path in the downloads tree where the download was linked to */ - private void sendBroadcastNewDownload(DownloadFileOperation download, String linkedToRemotePath) { + private void sendBroadcastNewDownload(DownloadFileOperation download, + String linkedToRemotePath) { Intent added = new Intent(getDownloadAddedMessage()); added.putExtra(ACCOUNT_NAME, download.getAccount().name); added.putExtra(EXTRA_REMOTE_PATH, download.getRemotePath()); diff --git a/src/com/owncloud/android/files/services/FileUploader.java b/src/com/owncloud/android/files/services/FileUploader.java index 851e343f..8beff92d 100644 --- a/src/com/owncloud/android/files/services/FileUploader.java +++ b/src/com/owncloud/android/files/services/FileUploader.java @@ -48,6 +48,7 @@ import android.os.Process; import android.support.v4.app.NotificationCompat; import android.webkit.MimeTypeMap; +import com.owncloud.android.MainApp; import com.owncloud.android.R; import com.owncloud.android.authentication.AccountUtils; import com.owncloud.android.authentication.AuthenticatorActivity; @@ -166,7 +167,8 @@ public class FileUploader extends Service super.onCreate(); Log_OC.d(TAG, "Creating service"); mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); - HandlerThread thread = new HandlerThread("FileUploaderThread", Process.THREAD_PRIORITY_BACKGROUND); + HandlerThread thread = new HandlerThread("FileUploaderThread", + Process.THREAD_PRIORITY_BACKGROUND); thread.start(); mServiceLooper = thread.getLooper(); mServiceHandler = new ServiceHandler(mServiceLooper, this); @@ -253,7 +255,8 @@ public class FileUploader extends Service } } - FileDataStorageManager storageManager = new FileDataStorageManager(account, getContentResolver()); + FileDataStorageManager storageManager = new FileDataStorageManager(account, + getContentResolver()); boolean forceOverwrite = intent.getBooleanExtra(KEY_FORCE_OVERWRITE, false); boolean isInstant = intent.getBooleanExtra(KEY_INSTANT_UPLOAD, false); @@ -279,8 +282,8 @@ public class FileUploader extends Service files = new OCFile[localPaths.length]; for (int i = 0; i < localPaths.length; i++) { - files[i] = obtainNewOCFileToUpload(remotePaths[i], localPaths[i], ((mimeTypes != null) ? mimeTypes[i] - : (String) null), storageManager); + files[i] = obtainNewOCFileToUpload(remotePaths[i], localPaths[i], + ((mimeTypes != null) ? mimeTypes[i] : (String) null), storageManager); if (files[i] == null) { // TODO @andomaex add failure Notification return Service.START_NOT_STICKY; @@ -299,12 +302,14 @@ public class FileUploader extends Service try { for (int i = 0; i < files.length; i++) { uploadKey = buildRemoteName(account, files[i].getRemotePath()); - newUpload = new UploadFileOperation(account, files[i], chunked, isInstant, forceOverwrite, localAction, + newUpload = new UploadFileOperation(account, files[i], chunked, isInstant, + forceOverwrite, localAction, getApplicationContext()); if (isInstant) { newUpload.setRemoteFolderToBeCreated(); } - mPendingUploads.putIfAbsent(uploadKey, newUpload); // Grants that the file only upload once time + // Grants that the file only upload once time + mPendingUploads.putIfAbsent(uploadKey, newUpload); newUpload.addDatatransferProgressListener(this); newUpload.addDatatransferProgressListener((FileUploaderBinder)mBinder); @@ -375,7 +380,8 @@ public class FileUploader extends Service public class FileUploaderBinder extends Binder implements OnDatatransferProgressListener { /** - * Map of listeners that will be reported about progress of uploads from a {@link FileUploaderBinder} instance + * Map of listeners that will be reported about progress of uploads from a + * {@link FileUploaderBinder} instance */ private Map mBoundListeners = new HashMap(); @@ -421,7 +427,8 @@ public class FileUploader extends Service * Returns True when the file described by 'file' is being uploaded to * the ownCloud account 'account' or waiting for it * - * If 'file' is a directory, returns 'true' if some of its descendant files is uploading or waiting to upload. + * If 'file' is a directory, returns 'true' if some of its descendant files + * is uploading or waiting to upload. * * @param account ownCloud account where the remote file will be stored. * @param file A file that could be in the queue of pending uploads @@ -453,7 +460,8 @@ public class FileUploader extends Service * @param account ownCloud account holding the file of interest. * @param file {@link OCFile} of interest for listener. */ - public void addDatatransferProgressListener (OnDatatransferProgressListener listener, Account account, OCFile file) { + public void addDatatransferProgressListener (OnDatatransferProgressListener listener, + Account account, OCFile file) { if (account == null || file == null || listener == null) return; String targetKey = buildRemoteName(account, file); mBoundListeners.put(targetKey, listener); @@ -468,7 +476,8 @@ public class FileUploader extends Service * @param account ownCloud account holding the file of interest. * @param file {@link OCFile} of interest for listener. */ - public void removeDatatransferProgressListener (OnDatatransferProgressListener listener, Account account, OCFile file) { + public void removeDatatransferProgressListener (OnDatatransferProgressListener listener, + Account account, OCFile file) { if (account == null || file == null || listener == null) return; String targetKey = buildRemoteName(account, file); if (mBoundListeners.get(targetKey) == listener) { @@ -478,12 +487,13 @@ public class FileUploader extends Service @Override - public void onTransferProgress(long progressRate, long totalTransferredSoFar, long totalToTransfer, - String fileName) { + public void onTransferProgress(long progressRate, long totalTransferredSoFar, + long totalToTransfer, String fileName) { String key = buildRemoteName(mCurrentUpload.getAccount(), mCurrentUpload.getFile()); OnDatatransferProgressListener boundListener = mBoundListeners.get(key); if (boundListener != null) { - boundListener.onTransferProgress(progressRate, totalTransferredSoFar, totalToTransfer, fileName); + boundListener.onTransferProgress(progressRate, totalTransferredSoFar, + totalToTransfer, fileName); } } @@ -557,7 +567,8 @@ public class FileUploader extends Service try { /// prepare client object to send requests to the ownCloud server - if (mUploadClient == null || !mLastAccount.equals(mCurrentUpload.getAccount())) { + if (mUploadClient == null || + !mLastAccount.equals(mCurrentUpload.getAccount())) { mLastAccount = mCurrentUpload.getAccount(); mStorageManager = new FileDataStorageManager(mLastAccount, getContentResolver()); @@ -585,11 +596,13 @@ public class FileUploader extends Service } } catch (AccountsException e) { - Log_OC.e(TAG, "Error while trying to get autorization for " + mLastAccount.name, e); + Log_OC.e(TAG, "Error while trying to get autorization for " + + mLastAccount.name, e); uploadResult = new RemoteOperationResult(e); } catch (IOException e) { - Log_OC.e(TAG, "Error while trying to get autorization for " + mLastAccount.name, e); + Log_OC.e(TAG, "Error while trying to get autorization for " + + mLastAccount.name, e); uploadResult = new RemoteOperationResult(e); } finally { @@ -598,8 +611,9 @@ public class FileUploader extends Service Log_OC.i(TAG, "Remove CurrentUploadItem from pending upload Item Map."); } if (uploadResult.isException()) { - // enforce the creation of a new client object for next uploads; this grant that a new socket will - // be created in the future if the current exception is due to an abrupt lose of network connection + // enforce the creation of a new client object for next uploads; + // this grant that a new socket will be created in the future if + // the current exception is due to an abrupt lose of network connection mUploadClient = null; } } @@ -610,7 +624,8 @@ public class FileUploader extends Service } else { // Cancel the transfer - Log_OC.d(TAG, "Account " + mCurrentUpload.getAccount().toString() + " doesn't exist"); + Log_OC.d(TAG, "Account " + mCurrentUpload.getAccount().toString() + + " doesn't exist"); cancelUploadForAccount(mCurrentUpload.getAccount().name); } @@ -619,14 +634,15 @@ public class FileUploader extends Service } /** - * Checks the existence of the folder where the current file will be uploaded both in the remote server - * and in the local database. + * Checks the existence of the folder where the current file will be uploaded both + * in the remote server and in the local database. * - * If the upload is set to enforce the creation of the folder, the method tries to create it both remote - * and locally. + * If the upload is set to enforce the creation of the folder, the method tries to + * create it both remote and locally. * * @param pathToGrant Full remote path whose existence will be granted. - * @return An {@link OCFile} instance corresponding to the folder where the file will be uploaded. + * @return An {@link OCFile} instance corresponding to the folder where the file + * will be uploaded. */ private RemoteOperationResult grantFolderExistence(String pathToGrant) { RemoteOperation operation = new ExistenceCheckRemoteOperation(pathToGrant, this, false); @@ -689,7 +705,8 @@ public class FileUploader extends Service // new PROPFIND to keep data consistent with server // in theory, should return the same we already have - ReadRemoteFileOperation operation = new ReadRemoteFileOperation(mCurrentUpload.getRemotePath()); + ReadRemoteFileOperation operation = + new ReadRemoteFileOperation(mCurrentUpload.getRemotePath()); RemoteOperationResult result = operation.execute(mUploadClient); if (result.isSuccess()) { updateOCFile(file, (RemoteFile) result.getData().get(0)); @@ -731,7 +748,8 @@ public class FileUploader extends Service mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension( remotePath.substring(remotePath.lastIndexOf('.') + 1)); } catch (IndexOutOfBoundsException e) { - Log_OC.e(TAG, "Trying to find out MIME type of a file without extension: " + remotePath); + Log_OC.e(TAG, "Trying to find out MIME type of a file without extension: " + + remotePath); } } if (mimeType == null) { @@ -796,11 +814,13 @@ public class FileUploader extends Service * Callback method to update the progress bar in the status notification */ @Override - public void onTransferProgress(long progressRate, long totalTransferredSoFar, long totalToTransfer, String filePath) { + public void onTransferProgress(long progressRate, long totalTransferredSoFar, + long totalToTransfer, String filePath) { int percent = (int) (100.0 * ((double) totalTransferredSoFar) / ((double) totalToTransfer)); if (percent != mLastPercent) { mNotificationBuilder.setProgress(100, percent, false); - String fileName = filePath.substring(filePath.lastIndexOf(FileUtils.PATH_SEPARATOR) + 1); + String fileName = filePath.substring( + filePath.lastIndexOf(FileUtils.PATH_SEPARATOR) + 1); String text = String.format(getString(R.string.uploader_upload_in_progress_content), percent, fileName); mNotificationBuilder.setContentText(text); mNotificationManager.notify(R.string.uploader_upload_in_progress_ticker, mNotificationBuilder.build()); @@ -948,7 +968,8 @@ public class FileUploader extends Service * @param mimeType * @return true if is needed to add the pdf file extension to the file */ - private boolean isPdfFileFromContentProviderWithoutExtension(String localPath, String mimeType) { + private boolean isPdfFileFromContentProviderWithoutExtension(String localPath, + String mimeType) { return localPath.startsWith(UriUtils.URI_CONTENT_SCHEME) && mimeType.equals(MIME_TYPE_PDF) && !localPath.endsWith(FILE_EXTENSION_PDF); diff --git a/src/com/owncloud/android/operations/CreateFolderOperation.java b/src/com/owncloud/android/operations/CreateFolderOperation.java index b3c17f1d..b020b92c 100644 --- a/src/com/owncloud/android/operations/CreateFolderOperation.java +++ b/src/com/owncloud/android/operations/CreateFolderOperation.java @@ -21,6 +21,7 @@ package com.owncloud.android.operations; +import com.owncloud.android.MainApp; import com.owncloud.android.datamodel.OCFile; import com.owncloud.android.lib.common.OwnCloudClient; import com.owncloud.android.lib.resources.files.CreateRemoteFolderOperation; @@ -46,7 +47,8 @@ public class CreateFolderOperation extends SyncOperation implements OnRemoteOper /** * Constructor * - * @param createFullPath 'True' means that all the ancestor folders should be created if don't exist yet. + * @param createFullPath 'True' means that all the ancestor folders should be created + * if don't exist yet. */ public CreateFolderOperation(String remotePath, boolean createFullPath) { mRemotePath = remotePath; @@ -57,7 +59,8 @@ public class CreateFolderOperation extends SyncOperation implements OnRemoteOper @Override protected RemoteOperationResult run(OwnCloudClient client) { - CreateRemoteFolderOperation operation = new CreateRemoteFolderOperation(mRemotePath, mCreateFullPath); + CreateRemoteFolderOperation operation = new CreateRemoteFolderOperation(mRemotePath, + mCreateFullPath); RemoteOperationResult result = operation.execute(client); if (result.isSuccess()) { @@ -77,7 +80,8 @@ public class CreateFolderOperation extends SyncOperation implements OnRemoteOper } - private void onCreateRemoteFolderOperationFinish(CreateRemoteFolderOperation operation, RemoteOperationResult result) { + private void onCreateRemoteFolderOperationFinish(CreateRemoteFolderOperation operation, + RemoteOperationResult result) { if (result.isSuccess()) { saveFolderInDB(); } else { diff --git a/src/com/owncloud/android/operations/CreateShareOperation.java b/src/com/owncloud/android/operations/CreateShareOperation.java index 70d6bf7b..63f7493e 100644 --- a/src/com/owncloud/android/operations/CreateShareOperation.java +++ b/src/com/owncloud/android/operations/CreateShareOperation.java @@ -27,6 +27,7 @@ package com.owncloud.android.operations; import android.content.Context; import android.content.Intent; +import com.owncloud.android.MainApp; import com.owncloud.android.R; import com.owncloud.android.datamodel.FileDataStorageManager; import com.owncloud.android.datamodel.OCFile; @@ -61,10 +62,13 @@ public class CreateShareOperation extends SyncOperation { * @param context The context that the share is coming from. * @param path Full path of the file/folder being shared. Mandatory argument * @param shareType 0 = user, 1 = group, 3 = Public link. Mandatory argument - * @param shareWith User/group ID with who the file should be shared. This is mandatory for shareType of 0 or 1 + * @param shareWith User/group ID with who the file should be shared. + * This is mandatory for shareType of 0 or 1 * @param publicUpload If false (default) public cannot upload to a public shared folder. - * If true public can upload to a shared folder. Only available for public link shares - * @param password Password to protect a public link share. Only available for public link shares + * If true public can upload to a shared folder. + * Only available for public link shares + * @param password Password to protect a public link share. + * Only available for public link shares * @param permissions 1 - Read only - Default for public shares * 2 - Update * 4 - Create @@ -95,7 +99,8 @@ public class CreateShareOperation extends SyncOperation { // Check if the share link already exists operation = new GetRemoteSharesForFileOperation(mPath, false, false); - RemoteOperationResult result = ((GetRemoteSharesForFileOperation)operation).execute(client); + RemoteOperationResult result = + ((GetRemoteSharesForFileOperation)operation).execute(client); if (!result.isSuccess() || result.getData().size() <= 0) { operation = new CreateRemoteShareOperation(mPath, mShareType, mShareWith, mPublicUpload, diff --git a/src/com/owncloud/android/operations/DetectAuthenticationMethodOperation.java b/src/com/owncloud/android/operations/DetectAuthenticationMethodOperation.java index 9f2827f4..4aeff99f 100644 --- a/src/com/owncloud/android/operations/DetectAuthenticationMethodOperation.java +++ b/src/com/owncloud/android/operations/DetectAuthenticationMethodOperation.java @@ -22,6 +22,7 @@ package com.owncloud.android.operations; import java.util.ArrayList; +import com.owncloud.android.MainApp; import com.owncloud.android.lib.common.OwnCloudClient; import com.owncloud.android.lib.common.operations.OnRemoteOperationListener; import com.owncloud.android.lib.common.operations.RemoteOperation; @@ -63,7 +64,6 @@ public class DetectAuthenticationMethodOperation extends RemoteOperation { * Constructor * * @param context Android context of the caller. - * @param webdavUrl */ public DetectAuthenticationMethodOperation(Context context) { mContext = context; @@ -124,7 +124,8 @@ public class DetectAuthenticationMethodOperation extends RemoteOperation { ArrayList data = new ArrayList(); data.add(authMethod); result.setData(data); - return result; // same result instance, so that other errors can be handled by the caller transparently + return result; // same result instance, so that other errors + // can be handled by the caller transparently } diff --git a/src/com/owncloud/android/operations/DownloadFileOperation.java b/src/com/owncloud/android/operations/DownloadFileOperation.java index 78811f8b..0cb303ce 100644 --- a/src/com/owncloud/android/operations/DownloadFileOperation.java +++ b/src/com/owncloud/android/operations/DownloadFileOperation.java @@ -27,6 +27,7 @@ import java.util.Iterator; import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; +import com.owncloud.android.MainApp; import com.owncloud.android.datamodel.OCFile; import com.owncloud.android.lib.common.network.OnDatatransferProgressListener; import com.owncloud.android.lib.common.OwnCloudClient; @@ -58,9 +59,11 @@ public class DownloadFileOperation extends RemoteOperation { public DownloadFileOperation(Account account, OCFile file) { if (account == null) - throw new IllegalArgumentException("Illegal null account in DownloadFileOperation creation"); + throw new IllegalArgumentException("Illegal null account in DownloadFileOperation " + + "creation"); if (file == null) - throw new IllegalArgumentException("Illegal null file in DownloadFileOperation creation"); + throw new IllegalArgumentException("Illegal null file in DownloadFileOperation " + + "creation"); mAccount = account; mFile = file; @@ -77,7 +80,7 @@ public class DownloadFileOperation extends RemoteOperation { } public String getSavePath() { - String path = mFile.getStoragePath(); // re-downloads should be done over the original file + String path = mFile.getStoragePath(); // re-downloads should be done over the original file if (path != null && path.length() > 0) { return path; } @@ -102,9 +105,11 @@ public class DownloadFileOperation extends RemoteOperation { try { mimeType = MimeTypeMap.getSingleton() .getMimeTypeFromExtension( - mFile.getRemotePath().substring(mFile.getRemotePath().lastIndexOf('.') + 1)); + mFile.getRemotePath().substring( + mFile.getRemotePath().lastIndexOf('.') + 1)); } catch (IndexOutOfBoundsException e) { - Log_OC.e(TAG, "Trying to find out MIME type of a file without extension: " + mFile.getRemotePath()); + Log_OC.e(TAG, "Trying to find out MIME type of a file without extension: " + + mFile.getRemotePath()); } } if (mimeType == null) { @@ -118,7 +123,8 @@ public class DownloadFileOperation extends RemoteOperation { } public long getModificationTimestamp() { - return (mModificationTimestamp > 0) ? mModificationTimestamp : mFile.getModificationTimestamp(); + return (mModificationTimestamp > 0) ? mModificationTimestamp : + mFile.getModificationTimestamp(); } @Override @@ -152,9 +158,11 @@ public class DownloadFileOperation extends RemoteOperation { newFile.getParentFile().mkdirs(); moved = tmpFile.renameTo(newFile); if (!moved) - result = new RemoteOperationResult(RemoteOperationResult.ResultCode.LOCAL_STORAGE_NOT_MOVED); + result = new RemoteOperationResult( + RemoteOperationResult.ResultCode.LOCAL_STORAGE_NOT_MOVED); } - Log_OC.i(TAG, "Download of " + mFile.getRemotePath() + " to " + getSavePath() + ": " + result.getLogMessage()); + Log_OC.i(TAG, "Download of " + mFile.getRemotePath() + " to " + getSavePath() + ": " + + result.getLogMessage()); return result; } diff --git a/src/com/owncloud/android/operations/GetServerInfoOperation.java b/src/com/owncloud/android/operations/GetServerInfoOperation.java index e081d4eb..8e911000 100644 --- a/src/com/owncloud/android/operations/GetServerInfoOperation.java +++ b/src/com/owncloud/android/operations/GetServerInfoOperation.java @@ -23,6 +23,7 @@ package com.owncloud.android.operations; import java.util.ArrayList; +import com.owncloud.android.MainApp; import com.owncloud.android.authentication.AccountUtils; import com.owncloud.android.lib.common.OwnCloudClient; import com.owncloud.android.lib.common.operations.RemoteOperation; diff --git a/src/com/owncloud/android/operations/GetSharesForFileOperation.java b/src/com/owncloud/android/operations/GetSharesForFileOperation.java index 06e399e8..bf136ad3 100644 --- a/src/com/owncloud/android/operations/GetSharesForFileOperation.java +++ b/src/com/owncloud/android/operations/GetSharesForFileOperation.java @@ -23,6 +23,7 @@ package com.owncloud.android.operations; import java.util.ArrayList; +import com.owncloud.android.MainApp; import com.owncloud.android.lib.common.OwnCloudClient; import com.owncloud.android.lib.resources.shares.OCShare; import com.owncloud.android.lib.common.operations.RemoteOperationResult; @@ -58,7 +59,8 @@ public class GetSharesForFileOperation extends SyncOperation { @Override protected RemoteOperationResult run(OwnCloudClient client) { - GetRemoteSharesForFileOperation operation = new GetRemoteSharesForFileOperation(mPath, mReshares, mSubfiles); + GetRemoteSharesForFileOperation operation = new GetRemoteSharesForFileOperation(mPath, + mReshares, mSubfiles); RemoteOperationResult result = operation.execute(client); if (result.isSuccess()) { diff --git a/src/com/owncloud/android/operations/GetSharesOperation.java b/src/com/owncloud/android/operations/GetSharesOperation.java index fb838b4d..09a8e344 100644 --- a/src/com/owncloud/android/operations/GetSharesOperation.java +++ b/src/com/owncloud/android/operations/GetSharesOperation.java @@ -23,6 +23,7 @@ package com.owncloud.android.operations; import java.util.ArrayList; +import com.owncloud.android.MainApp; import com.owncloud.android.lib.common.OwnCloudClient; import com.owncloud.android.lib.common.operations.RemoteOperationResult; import com.owncloud.android.lib.common.utils.Log_OC; diff --git a/src/com/owncloud/android/operations/MoveFileOperation.java b/src/com/owncloud/android/operations/MoveFileOperation.java index 3a1103b1..be254e7e 100644 --- a/src/com/owncloud/android/operations/MoveFileOperation.java +++ b/src/com/owncloud/android/operations/MoveFileOperation.java @@ -20,6 +20,7 @@ package com.owncloud.android.operations; +import com.owncloud.android.MainApp; import com.owncloud.android.datamodel.OCFile; import com.owncloud.android.lib.common.OwnCloudClient; import com.owncloud.android.lib.common.operations.RemoteOperationResult; @@ -47,8 +48,8 @@ public class MoveFileOperation extends SyncOperation { /** * Constructor * - * @param path Remote path of the {@link OCFile} to move. - * @param newParentPath Path to the folder where the file will be moved into. + * @param srcPath Remote path of the {@link OCFile} to move. + * @param targetParentPath Path to the folder where the file will be moved into. * @param account OwnCloud account containing both the file and the target folder */ public MoveFileOperation(String srcPath, String targetParentPath, Account account) { diff --git a/src/com/owncloud/android/operations/RefreshFolderOperation.java b/src/com/owncloud/android/operations/RefreshFolderOperation.java index 8d6cfbb5..50a35fdb 100644 --- a/src/com/owncloud/android/operations/RefreshFolderOperation.java +++ b/src/com/owncloud/android/operations/RefreshFolderOperation.java @@ -39,6 +39,7 @@ import android.content.Intent; import android.util.Log; //import android.support.v4.content.LocalBroadcastManager; +import com.owncloud.android.MainApp; import com.owncloud.android.datamodel.FileDataStorageManager; import com.owncloud.android.datamodel.OCFile; @@ -128,7 +129,7 @@ public class RefreshFolderOperation extends RemoteOperation { * @param syncFullAccount 'True' means that this operation is part of a full account * synchronization. * @param isShareSupported 'True' means that the server supports the sharing API. - * @param ignoreEtag 'True' means that the content of the remote folder should + * @param ignoreETag 'True' means that the content of the remote folder should * be fetched and updated even though the 'eTag' did not * change. * @param dataStorageManager Interface with the local database. @@ -375,7 +376,8 @@ public class RefreshFolderOperation extends RemoteOperation { remoteFile.setFileLength(localFile.getFileLength()); // TODO move operations about size of folders to FileContentProvider } else if (mRemoteFolderChanged && remoteFile.isImage() && - remoteFile.getModificationTimestamp() != localFile.getModificationTimestamp()) { + remoteFile.getModificationTimestamp() != + localFile.getModificationTimestamp()) { remoteFile.setNeedsUpdateThumbnail(true); Log.d(TAG, "Image " + remoteFile.getFileName() + " updated on the server"); } diff --git a/src/com/owncloud/android/operations/RemoveFileOperation.java b/src/com/owncloud/android/operations/RemoveFileOperation.java index 8f7067df..012ef237 100644 --- a/src/com/owncloud/android/operations/RemoveFileOperation.java +++ b/src/com/owncloud/android/operations/RemoveFileOperation.java @@ -21,6 +21,7 @@ package com.owncloud.android.operations; +import com.owncloud.android.MainApp; import com.owncloud.android.datamodel.OCFile; import com.owncloud.android.lib.common.OwnCloudClient; import com.owncloud.android.lib.common.operations.RemoteOperationResult; diff --git a/src/com/owncloud/android/operations/RenameFileOperation.java b/src/com/owncloud/android/operations/RenameFileOperation.java index 9726395a..a4cfa021 100644 --- a/src/com/owncloud/android/operations/RenameFileOperation.java +++ b/src/com/owncloud/android/operations/RenameFileOperation.java @@ -24,6 +24,7 @@ package com.owncloud.android.operations; import java.io.File; import java.io.IOException; +import com.owncloud.android.MainApp; import com.owncloud.android.datamodel.OCFile; import com.owncloud.android.lib.common.OwnCloudClient; import com.owncloud.android.lib.common.operations.RemoteOperationResult; @@ -51,7 +52,8 @@ public class RenameFileOperation extends SyncOperation { /** * Constructor * - * @param remotePath RemotePath of the OCFile instance describing the remote file or folder to rename + * @param remotePath RemotePath of the OCFile instance describing the remote file or + * folder to rename * @param newName New name to set as the name of file. */ public RenameFileOperation(String remotePath, String newName) { @@ -82,7 +84,8 @@ public class RenameFileOperation extends SyncOperation { return new RemoteOperationResult(ResultCode.INVALID_LOCAL_FILE_NAME); } String parent = (new File(mFile.getRemotePath())).getParent(); - parent = (parent.endsWith(OCFile.PATH_SEPARATOR)) ? parent : parent + OCFile.PATH_SEPARATOR; + parent = (parent.endsWith(OCFile.PATH_SEPARATOR)) ? parent : parent + + OCFile.PATH_SEPARATOR; mNewRemotePath = parent + mNewName; if (mFile.isFolder()) { mNewRemotePath += OCFile.PATH_SEPARATOR; @@ -93,7 +96,8 @@ public class RenameFileOperation extends SyncOperation { return new RemoteOperationResult(ResultCode.INVALID_OVERWRITE); } - RenameRemoteFileOperation operation = new RenameRemoteFileOperation(mFile.getFileName(), mFile.getRemotePath(), + RenameRemoteFileOperation operation = new RenameRemoteFileOperation(mFile.getFileName(), + mFile.getRemotePath(), mNewName, mFile.isFolder()); result = operation.execute(client); @@ -108,7 +112,8 @@ public class RenameFileOperation extends SyncOperation { } } catch (IOException e) { - Log_OC.e(TAG, "Rename " + mFile.getRemotePath() + " to " + ((mNewRemotePath==null) ? mNewName : mNewRemotePath) + ": " + + Log_OC.e(TAG, "Rename " + mFile.getRemotePath() + " to " + ((mNewRemotePath==null) ? + mNewName : mNewRemotePath) + ": " + ((result!= null) ? result.getLogMessage() : ""), e); } @@ -134,7 +139,8 @@ public class RenameFileOperation extends SyncOperation { // notify to scan about new file getStorageManager().triggerMediaScan(newPath); } - // else - NOTHING: the link to the local file is kept although the local name can't be updated + // else - NOTHING: the link to the local file is kept although the local name + // can't be updated // TODO - study conditions when this could be a problem } @@ -144,16 +150,17 @@ public class RenameFileOperation extends SyncOperation { /** * Checks if the new name to set is valid in the file system * - * The only way to be sure is trying to create a file with that name. It's made in the temporal directory - * for downloads, out of any account, and then removed. + * The only way to be sure is trying to create a file with that name. It's made in the + * temporal directory for downloads, out of any account, and then removed. * - * IMPORTANT: The test must be made in the same file system where files are download. The internal storage - * could be formatted with a different file system. + * IMPORTANT: The test must be made in the same file system where files are download. + * The internal storage could be formatted with a different file system. * - * TODO move this method, and maybe FileDownload.get***Path(), to a class with utilities specific for the interactions with the file system + * TODO move this method, and maybe FileDownload.get***Path(), to a class with utilities + * specific for the interactions with the file system * - * @return 'True' if a temporal file named with the name to set could be created in the file system where - * local files are stored. + * @return 'True' if a temporal file named with the name to set could be + * created in the file system where local files are stored. * @throws IOException When the temporal folder can not be created. */ private boolean isValidNewName() throws IOException { @@ -170,14 +177,16 @@ public class RenameFileOperation extends SyncOperation { throw new IOException("Unexpected error: temporal directory could not be created"); } try { - testFile.createNewFile(); // return value is ignored; it could be 'false' because the file already existed, that doesn't invalidate the name + testFile.createNewFile(); // return value is ignored; it could be 'false' because + // the file already existed, that doesn't invalidate the name } catch (IOException e) { Log_OC.i(TAG, "Test for validity of name " + mNewName + " in the file system failed"); return false; } boolean result = (testFile.exists() && testFile.isFile()); - // cleaning ; result is ignored, since there is not much we could do in case of failure, but repeat and repeat... + // cleaning ; result is ignored, since there is not much we could do in case of failure, + // but repeat and repeat... testFile.delete(); return result; diff --git a/src/com/owncloud/android/operations/SynchronizeFileOperation.java b/src/com/owncloud/android/operations/SynchronizeFileOperation.java index 6f1730e8..27b0b5ad 100644 --- a/src/com/owncloud/android/operations/SynchronizeFileOperation.java +++ b/src/com/owncloud/android/operations/SynchronizeFileOperation.java @@ -22,6 +22,7 @@ package com.owncloud.android.operations; +import com.owncloud.android.MainApp; import com.owncloud.android.datamodel.OCFile; import com.owncloud.android.files.services.FileDownloader; import com.owncloud.android.files.services.FileUploader; @@ -66,8 +67,8 @@ public class SynchronizeFileOperation extends SyncOperation { /** * Constructor for "full synchronization mode". * - * Uses remotePath to retrieve all the data both in local cache and in the remote OC server when the operation - * is executed, instead of reusing {@link OCFile} instances. + * Uses remotePath to retrieve all the data both in local cache and in the remote OC server + * when the operation is executed, instead of reusing {@link OCFile} instances. * * Useful for direct synchronization of a single file. * @@ -94,17 +95,19 @@ public class SynchronizeFileOperation extends SyncOperation { /** - * Constructor allowing to reuse {@link OCFile} instances just queried from local cache or from remote OC server. + * Constructor allowing to reuse {@link OCFile} instances just queried from local cache or + * from remote OC server. * - * Useful to include this operation as part of the synchronization of a folder (or a full account), avoiding the - * repetition of fetch operations (both in local database or remote server). + * Useful to include this operation as part of the synchronization of a folder + * (or a full account), avoiding the repetition of fetch operations (both in local database + * or remote server). * - * At least one of localFile or serverFile MUST NOT BE NULL. If you don't have none of them, use the other - * constructor. + * At least one of localFile or serverFile MUST NOT BE NULL. If you don't have none of them, + * use the other constructor. * * @param localFile Data of file (just) retrieved from local cache/database. - * @param serverFile Data of file (just) retrieved from a remote server. If null, will be - * retrieved from network by the operation when executed. + * @param serverFile Data of file (just) retrieved from a remote server. If null, + * will be retrieved from network by the operation when executed. * @param account ownCloud account holding the file. * @param syncFileContents When 'true', transference of data will be started by the * operation if needed and no conflict is detected. @@ -122,7 +125,8 @@ public class SynchronizeFileOperation extends SyncOperation { if (mLocalFile != null) { mRemotePath = mLocalFile.getRemotePath(); if (mServerFile != null && !mServerFile.getRemotePath().equals(mRemotePath)) { - throw new IllegalArgumentException("serverFile and localFile do not correspond to the same OC file"); + throw new IllegalArgumentException("serverFile and localFile do not correspond" + + " to the same OC file"); } } else if (mServerFile != null) { mRemotePath = mServerFile.getRemotePath(); @@ -139,21 +143,24 @@ public class SynchronizeFileOperation extends SyncOperation { /** * Temporal constructor. * - * Extends the previous one to allow constrained synchronizations where uploads are never performed - only - * downloads or conflict detection. + * Extends the previous one to allow constrained synchronizations where uploads are never + * performed - only downloads or conflict detection. * - * Do not use unless you are involved in 'folder synchronization' or 'folder download' work in progress. + * Do not use unless you are involved in 'folder synchronization' or 'folder download' work + * in progress. * * TODO Remove when 'folder synchronization' replaces 'folder download'. * - * @param localFile Data of file (just) retrieved from local cache/database. MUSTN't be null. - * @param serverFile Data of file (just) retrieved from a remote server. If null, will be - * retrieved from network by the operation when executed. + * @param localFile Data of file (just) retrieved from local cache/database. + * MUSTN't be null. + * @param serverFile Data of file (just) retrieved from a remote server. + * If null, will be retrieved from network by the operation + * when executed. * @param account ownCloud account holding the file. * @param syncFileContents When 'true', transference of data will be started by the * operation if needed and no conflict is detected. - * @param allowUploads When 'false', uploads to the server are not done; only downloads or conflict - * detection. + * @param allowUploads When 'false', uploads to the server are not done; + * only downloads or conflict detection. * @param context Android context; needed to start transfers. */ public SynchronizeFileOperation( @@ -206,7 +213,8 @@ public class SynchronizeFileOperation extends SyncOperation { serverChanged = (!mServerFile.getEtag().equals(mLocalFile.getEtag())); } else { */ serverChanged = ( - mServerFile.getModificationTimestamp() != mLocalFile.getModificationTimestampAtLastSyncForData() + mServerFile.getModificationTimestamp() != + mLocalFile.getModificationTimestampAtLastSyncForData() ); //} boolean localChanged = ( @@ -221,10 +229,13 @@ public class SynchronizeFileOperation extends SyncOperation { } else if (localChanged) { if (mSyncFileContents && mAllowUploads) { requestForUpload(mLocalFile); - // the local update of file properties will be done by the FileUploader service when the upload finishes + // the local update of file properties will be done by the FileUploader + // service when the upload finishes } else { - // NOTHING TO DO HERE: updating the properties of the file in the server without uploading the contents would be stupid; - // So, an instance of SynchronizeFileOperation created with syncFileContents == false is completely useless when we suspect + // NOTHING TO DO HERE: updating the properties of the file in the server + // without uploading the contents would be stupid; + // So, an instance of SynchronizeFileOperation created with + // syncFileContents == false is completely useless when we suspect // that an upload is necessary (for instance, in FileObserverService). } result = new RemoteOperationResult(ResultCode.OK); @@ -233,8 +244,10 @@ public class SynchronizeFileOperation extends SyncOperation { mLocalFile.setRemoteId(mServerFile.getRemoteId()); if (mSyncFileContents) { - requestForDownload(mLocalFile); // local, not server; we won't to keep the value of keepInSync! - // the update of local data will be done later by the FileUploader service when the upload finishes + requestForDownload(mLocalFile); // local, not server; we won't to keep + // the value of keepInSync! + // the update of local data will be done later by the FileUploader + // service when the upload finishes } else { // TODO CHECK: is this really useful in some point in the code? mServerFile.setKeepInSync(mLocalFile.keepInSync()); @@ -255,8 +268,8 @@ public class SynchronizeFileOperation extends SyncOperation { } - Log_OC.i(TAG, "Synchronizing " + mAccount.name + ", file " + mLocalFile.getRemotePath() + ": " - + result.getLogMessage()); + Log_OC.i(TAG, "Synchronizing " + mAccount.name + ", file " + mLocalFile.getRemotePath() + + ": " + result.getLogMessage()); return result; } @@ -271,7 +284,9 @@ public class SynchronizeFileOperation extends SyncOperation { Intent i = new Intent(mContext, FileUploader.class); i.putExtra(FileUploader.KEY_ACCOUNT, mAccount); i.putExtra(FileUploader.KEY_FILE, file); - /*i.putExtra(FileUploader.KEY_REMOTE_FILE, mRemotePath); // doing this we would lose the value of keepInSync in the road, and maybe it's not updated in the database when the FileUploader service gets it! + /*i.putExtra(FileUploader.KEY_REMOTE_FILE, mRemotePath); + // doing this we would lose the value of keepInSync in the road, and maybe + // it's not updated in the database when the FileUploader service gets it! i.putExtra(FileUploader.KEY_LOCAL_FILE, localFile.getStoragePath());*/ i.putExtra(FileUploader.KEY_UPLOAD_TYPE, FileUploader.UPLOAD_SINGLE_FILE); i.putExtra(FileUploader.KEY_FORCE_OVERWRITE, true); diff --git a/src/com/owncloud/android/operations/SynchronizeFolderOperation.java b/src/com/owncloud/android/operations/SynchronizeFolderOperation.java index e80b42fa..286b5ea9 100644 --- a/src/com/owncloud/android/operations/SynchronizeFolderOperation.java +++ b/src/com/owncloud/android/operations/SynchronizeFolderOperation.java @@ -25,6 +25,7 @@ import android.content.Context; import android.content.Intent; import android.util.Log; +import com.owncloud.android.MainApp; import com.owncloud.android.datamodel.FileDataStorageManager; import com.owncloud.android.datamodel.OCFile; import com.owncloud.android.files.services.FileDownloader; @@ -110,7 +111,8 @@ public class SynchronizeFolderOperation extends SyncOperation { * @param account ownCloud account where the folder is located. * @param currentSyncTime Time stamp for the synchronization process in progress. */ - public SynchronizeFolderOperation(Context context, String remotePath, Account account, long currentSyncTime){ + public SynchronizeFolderOperation(Context context, String remotePath, Account account, + long currentSyncTime){ mRemotePath = remotePath; mCurrentSyncTime = currentSyncTime; mAccount = account; @@ -174,7 +176,8 @@ public class SynchronizeFolderOperation extends SyncOperation { } - private RemoteOperationResult checkForChanges(OwnCloudClient client) throws OperationCancelledException { + private RemoteOperationResult checkForChanges(OwnCloudClient client) + throws OperationCancelledException { Log_OC.d(TAG, "Checking changes in " + mAccount.name + mRemotePath); mRemoteFolderChanged = true; @@ -218,7 +221,8 @@ public class SynchronizeFolderOperation extends SyncOperation { } - private RemoteOperationResult fetchAndSyncRemoteFolder(OwnCloudClient client) throws OperationCancelledException { + private RemoteOperationResult fetchAndSyncRemoteFolder(OwnCloudClient client) + throws OperationCancelledException { if (mCancellationRequested.get()) { throw new OperationCancelledException(); } @@ -250,7 +254,8 @@ public class SynchronizeFolderOperation extends SyncOperation { storageManager.removeFolder( mLocalFolder, true, - ( mLocalFolder.isDown() && // TODO: debug, I think this is always false for folders + ( mLocalFolder.isDown() && // TODO: debug, I think this is + // always false for folders mLocalFolder.getStoragePath().startsWith(currentSavePath) ) ); @@ -327,7 +332,8 @@ public class SynchronizeFolderOperation extends SyncOperation { remoteFile.setFileLength(localFile.getFileLength()); // TODO move operations about size of folders to FileContentProvider } else if (mRemoteFolderChanged && remoteFile.isImage() && - remoteFile.getModificationTimestamp() != localFile.getModificationTimestamp()) { + remoteFile.getModificationTimestamp() != + localFile.getModificationTimestamp()) { remoteFile.setNeedsUpdateThumbnail(true); Log.d(TAG, "Image " + remoteFile.getFileName() + " updated on the server"); } @@ -439,7 +445,8 @@ public class SynchronizeFolderOperation extends SyncOperation { * @param filesToSyncContents Synchronization operations to execute. * @param client Interface to the remote ownCloud server. */ - private void startContentSynchronizations(List filesToSyncContents, OwnCloudClient client) + private void startContentSynchronizations(List filesToSyncContents, + OwnCloudClient client) throws OperationCancelledException { Log_OC.v(TAG, "Starting content synchronization... "); @@ -469,7 +476,8 @@ public class SynchronizeFolderOperation extends SyncOperation { /** - * Creates and populates a new {@link com.owncloud.android.datamodel.OCFile} object with the data read from the server. + * Creates and populates a new {@link com.owncloud.android.datamodel.OCFile} + * object with the data read from the server. * * @param remote remote file read from the server (remote file or folder). * @return New OCFile instance representing the remote resource described by we. @@ -489,8 +497,8 @@ public class SynchronizeFolderOperation extends SyncOperation { /** * Scans the default location for saving local copies of files searching for - * a 'lost' file with the same full name as the {@link com.owncloud.android.datamodel.OCFile} received as - * parameter. + * a 'lost' file with the same full name as the {@link com.owncloud.android.datamodel.OCFile} + * received as parameter. * * @param file File to associate a possible 'lost' local file. */ diff --git a/src/com/owncloud/android/operations/UnshareLinkOperation.java b/src/com/owncloud/android/operations/UnshareLinkOperation.java index 79370b74..1b662261 100644 --- a/src/com/owncloud/android/operations/UnshareLinkOperation.java +++ b/src/com/owncloud/android/operations/UnshareLinkOperation.java @@ -22,6 +22,7 @@ package com.owncloud.android.operations; import android.content.Context; +import com.owncloud.android.MainApp; import com.owncloud.android.datamodel.OCFile; import com.owncloud.android.lib.common.OwnCloudClient; @@ -57,10 +58,12 @@ public class UnshareLinkOperation extends SyncOperation { RemoteOperationResult result = null; // Get Share for a file - OCShare share = getStorageManager().getFirstShareByPathAndType(mRemotePath, ShareType.PUBLIC_LINK); + OCShare share = getStorageManager().getFirstShareByPathAndType(mRemotePath, + ShareType.PUBLIC_LINK); if (share != null) { - RemoveRemoteShareOperation operation = new RemoveRemoteShareOperation((int) share.getIdRemoteShared()); + RemoveRemoteShareOperation operation = + new RemoveRemoteShareOperation((int) share.getIdRemoteShared()); result = operation.execute(client); if (result.isSuccess() || result.getCode() == ResultCode.SHARE_NOT_FOUND) { @@ -89,7 +92,8 @@ public class UnshareLinkOperation extends SyncOperation { } private boolean existsFile(OwnCloudClient client, String remotePath){ - ExistenceCheckRemoteOperation existsOperation = new ExistenceCheckRemoteOperation(remotePath, mContext, false); + ExistenceCheckRemoteOperation existsOperation = + new ExistenceCheckRemoteOperation(remotePath, mContext, false); RemoteOperationResult result = existsOperation.execute(client); return result.isSuccess(); } diff --git a/src/com/owncloud/android/operations/UploadFileOperation.java b/src/com/owncloud/android/operations/UploadFileOperation.java index cd5f8a13..b114195b 100644 --- a/src/com/owncloud/android/operations/UploadFileOperation.java +++ b/src/com/owncloud/android/operations/UploadFileOperation.java @@ -29,7 +29,6 @@ import java.io.OutputStream; import java.util.HashSet; import java.util.Iterator; import java.util.Set; -import java.util.concurrent.CancellationException; import java.util.concurrent.atomic.AtomicBoolean; import org.apache.commons.httpclient.methods.PutMethod; @@ -94,7 +93,8 @@ public class UploadFileOperation extends RemoteOperation { int localBehaviour, Context context) { if (account == null) - throw new IllegalArgumentException("Illegal NULL account in UploadFileOperation creation"); + throw new IllegalArgumentException("Illegal NULL account in UploadFileOperation " + + "creation"); if (file == null) throw new IllegalArgumentException("Illegal NULL file in UploadFileOperation creation"); if (file.getStoragePath() == null || file.getStoragePath().length() <= 0) { diff --git a/src/com/owncloud/android/operations/common/SyncOperation.java b/src/com/owncloud/android/operations/common/SyncOperation.java index 512be4e0..5fb5c8cf 100644 --- a/src/com/owncloud/android/operations/common/SyncOperation.java +++ b/src/com/owncloud/android/operations/common/SyncOperation.java @@ -20,6 +20,7 @@ package com.owncloud.android.operations.common; +import com.owncloud.android.MainApp; import com.owncloud.android.datamodel.FileDataStorageManager; import com.owncloud.android.lib.common.OwnCloudClient; import com.owncloud.android.lib.common.operations.OnRemoteOperationListener; @@ -52,18 +53,21 @@ public abstract class SyncOperation extends RemoteOperation { * * Do not call this method from the main thread. * - * This method should be used whenever an ownCloud account is available, instead of {@link #execute(OwnCloudClient)}. + * This method should be used whenever an ownCloud account is available, instead of + * {@link #execute(OwnCloudClient, com.owncloud.android.datamodel.FileDataStorageManager)}. * - * @param account ownCloud account in remote ownCloud server to reach during the execution of the operation. + * @param storageManager * @param context Android context for the component calling the method. * @return Result of the operation. */ public RemoteOperationResult execute(FileDataStorageManager storageManager, Context context) { if (storageManager == null) { - throw new IllegalArgumentException("Trying to execute a sync operation with a NULL storage manager"); + throw new IllegalArgumentException("Trying to execute a sync operation with a " + + "NULL storage manager"); } if (storageManager.getAccount() == null) { - throw new IllegalArgumentException("Trying to execute a sync operation with a storage manager for a NULL account"); + throw new IllegalArgumentException("Trying to execute a sync operation with a " + + "storage manager for a NULL account"); } mStorageManager = storageManager; return super.execute(mStorageManager.getAccount(), context); @@ -75,12 +79,16 @@ public abstract class SyncOperation extends RemoteOperation { * * Do not call this method from the main thread. * - * @param client Client object to reach an ownCloud server during the execution of the operation. + * @param client Client object to reach an ownCloud server during the execution of the o + * peration. + * @param storageManager * @return Result of the operation. */ - public RemoteOperationResult execute(OwnCloudClient client, FileDataStorageManager storageManager) { + public RemoteOperationResult execute(OwnCloudClient client, + FileDataStorageManager storageManager) { if (storageManager == null) - throw new IllegalArgumentException("Trying to execute a sync operation with a NULL storage manager"); + throw new IllegalArgumentException("Trying to execute a sync operation with a " + + "NULL storage manager"); mStorageManager = storageManager; return super.execute(client); } @@ -89,24 +97,31 @@ public abstract class SyncOperation extends RemoteOperation { /** * Asynchronously executes the remote operation * - * This method should be used whenever an ownCloud account is available, instead of {@link #execute(OwnCloudClient)}. + * This method should be used whenever an ownCloud account is available, instead of + * {@link #execute(OwnCloudClient)}. * - * @param account ownCloud account in remote ownCloud server to reach during the execution of the operation. + * @param account ownCloud account in remote ownCloud server to reach during the + * execution of the operation. * @param context Android context for the component calling the method. * @param listener Listener to be notified about the execution of the operation. - * @param listenerHandler Handler associated to the thread where the methods of the listener objects must be called. + * @param listenerHandler Handler associated to the thread where the methods of the listener + * objects must be called. * @return Thread were the remote operation is executed. */ /* - public Thread execute(FileDataStorageManager storageManager, Context context, OnRemoteOperationListener listener, Handler listenerHandler, Activity callerActivity) { + public Thread execute(FileDataStorageManager storageManager, + Context context, OnRemoteOperationListener listener, Handler listenerHandler, Activity callerActivity) { if (storageManager == null) { - throw new IllegalArgumentException("Trying to execute a sync operation with a NULL storage manager"); + throw new IllegalArgumentException("Trying to execute a sync operation + with a NULL storage manager"); } if (storageManager.getAccount() == null) { - throw new IllegalArgumentException("Trying to execute a sync operation with a storage manager for a NULL account"); + throw new IllegalArgumentException("Trying to execute a sync operation with a + storage manager for a NULL account"); } mStorageManager = storageManager; - return super.execute(storageManager.getAccount(), context, listener, listenerHandler, callerActivity); + return super.execute(storageManager.getAccount(), context, listener, listenerHandler, + callerActivity); } */ @@ -114,14 +129,18 @@ public abstract class SyncOperation extends RemoteOperation { /** * Asynchronously executes the remote operation * - * @param client Client object to reach an ownCloud server during the execution of the operation. + * @param client Client object to reach an ownCloud server during the + * execution of the operation. * @param listener Listener to be notified about the execution of the operation. - * @param listenerHandler Handler associated to the thread where the methods of the listener objects must be called. + * @param listenerHandler Handler associated to the thread where the methods of + * the listener objects must be called. * @return Thread were the remote operation is executed. */ - public Thread execute(OwnCloudClient client, FileDataStorageManager storageManager, OnRemoteOperationListener listener, Handler listenerHandler) { + public Thread execute(OwnCloudClient client, FileDataStorageManager storageManager, + OnRemoteOperationListener listener, Handler listenerHandler) { if (storageManager == null) { - throw new IllegalArgumentException("Trying to execute a sync operation with a NULL storage manager"); + throw new IllegalArgumentException("Trying to execute a sync operation " + + "with a NULL storage manager"); } mStorageManager = storageManager; return super.execute(client, listener, listenerHandler); diff --git a/src/com/owncloud/android/services/OperationsService.java b/src/com/owncloud/android/services/OperationsService.java index 6a32af06..fcaf0c79 100644 --- a/src/com/owncloud/android/services/OperationsService.java +++ b/src/com/owncloud/android/services/OperationsService.java @@ -98,11 +98,13 @@ public class OperationsService extends Service { public static final String ACTION_REMOVE = "REMOVE"; public static final String ACTION_CREATE_FOLDER = "CREATE_FOLDER"; public static final String ACTION_SYNC_FILE = "SYNC_FILE"; - public static final String ACTION_SYNC_FOLDER = "SYNC_FOLDER"; // for the moment, just to download + public static final String ACTION_SYNC_FOLDER = "SYNC_FOLDER";//for the moment, just to download public static final String ACTION_MOVE_FILE = "MOVE_FILE"; - public static final String ACTION_OPERATION_ADDED = OperationsService.class.getName() + ".OPERATION_ADDED"; - public static final String ACTION_OPERATION_FINISHED = OperationsService.class.getName() + ".OPERATION_FINISHED"; + public static final String ACTION_OPERATION_ADDED = OperationsService.class.getName() + + ".OPERATION_ADDED"; + public static final String ACTION_OPERATION_FINISHED = OperationsService.class.getName() + + ".OPERATION_FINISHED"; private ConcurrentMap> @@ -135,7 +137,8 @@ public class OperationsService extends Service { Log_OC.d(TAG, "Creating service"); /// First worker thread for most of operations - HandlerThread thread = new HandlerThread("Operations thread", Process.THREAD_PRIORITY_BACKGROUND); + HandlerThread thread = new HandlerThread("Operations thread", + Process.THREAD_PRIORITY_BACKGROUND); thread.start(); mOperationsHandler = new ServiceHandler(thread.getLooper(), this); mOperationsBinder = new OperationsServiceBinder(mOperationsHandler); @@ -172,7 +175,8 @@ public class OperationsService extends Service { Pair itemToQueue = newOperation(intent); if (itemToQueue != null) { - mSyncFolderHandler.add(account, remotePath, (SynchronizeFolderOperation)itemToQueue.second); + mSyncFolderHandler.add(account, remotePath, + (SynchronizeFolderOperation)itemToQueue.second); Message msg = mSyncFolderHandler.obtainMessage(); msg.arg1 = startId; msg.obj = itemSyncKey; @@ -249,7 +253,8 @@ public class OperationsService extends Service { public class OperationsServiceBinder extends Binder /* implements OnRemoteOperationListener */ { /** - * Map of listeners that will be reported about the end of operations from a {@link OperationsServiceBinder} instance + * Map of listeners that will be reported about the end of operations from a + * {@link OperationsServiceBinder} instance */ private ConcurrentMap mBoundListeners = new ConcurrentHashMap(); @@ -282,9 +287,11 @@ public class OperationsService extends Service { * Adds a listener interested in being reported about the end of operations. * * @param listener Object to notify about the end of operations. - * @param callbackHandler {@link Handler} to access the listener without breaking Android threading protection. + * @param callbackHandler {@link Handler} to access the listener without + * breaking Android threading protection. */ - public void addOperationListener (OnRemoteOperationListener listener, Handler callbackHandler) { + public void addOperationListener (OnRemoteOperationListener listener, + Handler callbackHandler) { synchronized (mBoundListeners) { mBoundListeners.put(listener, callbackHandler); } @@ -292,7 +299,8 @@ public class OperationsService extends Service { /** - * Removes a listener from the list of objects interested in the being reported about the end of operations. + * Removes a listener from the list of objects interested in the being reported about + * the end of operations. * * @param listener Object to notify about progress of transfer. */ @@ -306,7 +314,8 @@ public class OperationsService extends Service { /** * TODO - IMPORTANT: update implementation when more operations are moved into the service * - * @return 'True' when an operation that enforces the user to wait for completion is in process. + * @return 'True' when an operation that enforces the user to wait for completion is + * in process. */ public boolean isPerformingBlockingOperation() { return (!mServiceHandler.mPendingOperations.isEmpty()); @@ -334,7 +343,8 @@ public class OperationsService extends Service { } - public boolean dispatchResultIfFinished(int operationId, OnRemoteOperationListener listener) { + public boolean dispatchResultIfFinished(int operationId, + OnRemoteOperationListener listener) { Pair undispatched = mUndispatchedFinishedOperations.remove(operationId); if (undispatched != null) { @@ -353,15 +363,15 @@ public class OperationsService extends Service { /** - * Returns True when the file described by 'file' in the ownCloud account 'account' is downloading or waiting - * to download. + * Returns True when the file described by 'file' in the ownCloud account 'account' is + * downloading or waiting to download. * - * If 'file' is a directory, returns 'true' if some of its descendant files is downloading or waiting - * to download. + * If 'file' is a directory, returns 'true' if some of its descendant files is downloading + * or waiting to download. * * @param account ownCloud account where the remote file is stored. - * @param remotePath Path of the folder to check if something is synchronizing / downloading / uploading - * inside. + * @param remotePath Path of the folder to check if something is synchronizing + * / downloading / uploading inside. */ public boolean isSynchronizing(Account account, String remotePath) { return mSyncFolderHandler.isSynchronizing(account, remotePath); @@ -376,7 +386,8 @@ public class OperationsService extends Service { * Created with the Looper of a new thread, started in {@link OperationsService#onCreate()}. */ private static class ServiceHandler extends Handler { - // don't make it a final class, and don't remove the static ; lint will warn about a possible memory leak + // don't make it a final class, and don't remove the static ; lint will warn about a p + // ossible memory leak OperationsService mService; @@ -427,7 +438,8 @@ public class OperationsService extends Service { if (mLastTarget == null || !mLastTarget.equals(next.first)) { mLastTarget = next.first; if (mLastTarget.mAccount != null) { - OwnCloudAccount ocAccount = new OwnCloudAccount(mLastTarget.mAccount, mService); + OwnCloudAccount ocAccount = new OwnCloudAccount(mLastTarget.mAccount, + mService); mOwnCloudClient = OwnCloudClientManagerFactory.getDefaultSingleton(). getClientFor(ocAccount, mService); mStorageManager = new FileDataStorageManager( @@ -439,7 +451,8 @@ public class OperationsService extends Service { if (mLastTarget.mCookie != null && mLastTarget.mCookie.length() > 0) { // just used for GetUserName - // TODO refactor to run GetUserName as AsyncTask in the context of AuthenticatorActivity + // TODO refactor to run GetUserName as AsyncTask in the context of + // AuthenticatorActivity credentials = OwnCloudCredentialsFactory.newSamlSsoCredentials( mLastTarget.mCookie); // SAML SSO } @@ -453,24 +466,29 @@ public class OperationsService extends Service { /// perform the operation if (mCurrentOperation instanceof SyncOperation) { - result = ((SyncOperation)mCurrentOperation).execute(mOwnCloudClient, mStorageManager); + result = ((SyncOperation)mCurrentOperation).execute(mOwnCloudClient, + mStorageManager); } else { result = mCurrentOperation.execute(mOwnCloudClient); } } catch (AccountsException e) { if (mLastTarget.mAccount == null) { - Log_OC.e(TAG, "Error while trying to get authorization for a NULL account", e); + Log_OC.e(TAG, "Error while trying to get authorization for a NULL account", + e); } else { - Log_OC.e(TAG, "Error while trying to get authorization for " + mLastTarget.mAccount.name, e); + Log_OC.e(TAG, "Error while trying to get authorization for " + + mLastTarget.mAccount.name, e); } result = new RemoteOperationResult(e); } catch (IOException e) { if (mLastTarget.mAccount == null) { - Log_OC.e(TAG, "Error while trying to get authorization for a NULL account", e); + Log_OC.e(TAG, "Error while trying to get authorization for a NULL account", + e); } else { - Log_OC.e(TAG, "Error while trying to get authorization for " + mLastTarget.mAccount.name, e); + Log_OC.e(TAG, "Error while trying to get authorization for " + + mLastTarget.mAccount.name, e); } result = new RemoteOperationResult(e); } catch (Exception e) { @@ -503,7 +521,8 @@ public class OperationsService extends Service { * TODO - move to ServiceHandler (probably) * * @param operationIntent Intent describing a new operation to queue and execute. - * @return Pair with the new operation object and the information about its target server. + * @return Pair with the new operation object and the information about its + * target server. */ private Pair newOperation(Intent operationIntent) { RemoteOperation operation = null; @@ -569,19 +588,22 @@ public class OperationsService extends Service { } else if (action.equals(ACTION_REMOVE)) { // Remove file or folder String remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH); - boolean onlyLocalCopy = operationIntent.getBooleanExtra(EXTRA_REMOVE_ONLY_LOCAL, false); + boolean onlyLocalCopy = operationIntent.getBooleanExtra(EXTRA_REMOVE_ONLY_LOCAL, + false); operation = new RemoveFileOperation(remotePath, onlyLocalCopy); } else if (action.equals(ACTION_CREATE_FOLDER)) { // Create Folder String remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH); - boolean createFullPath = operationIntent.getBooleanExtra(EXTRA_CREATE_FULL_PATH, true); + boolean createFullPath = operationIntent.getBooleanExtra(EXTRA_CREATE_FULL_PATH, + true); operation = new CreateFolderOperation(remotePath, createFullPath); } else if (action.equals(ACTION_SYNC_FILE)) { // Sync file String remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH); - boolean syncFileContents = operationIntent.getBooleanExtra(EXTRA_SYNC_FILE_CONTENTS, true); + boolean syncFileContents = + operationIntent.getBooleanExtra(EXTRA_SYNC_FILE_CONTENTS, true); operation = new SynchronizeFileOperation( remotePath, account, syncFileContents, getApplicationContext() ); @@ -590,7 +612,7 @@ public class OperationsService extends Service { // Sync file String remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH); operation = new SynchronizeFolderOperation( - this, // TODO remove this dependency from construction time + this, // TODO remove this dependency from construction time remotePath, account, System.currentTimeMillis() // TODO remove this dependency from construction time @@ -621,7 +643,8 @@ public class OperationsService extends Service { /** * Sends a broadcast when a new operation is added to the queue. * - * Local broadcasts are only delivered to activities in the same process, but can't be done sticky :\ + * Local broadcasts are only delivered to activities in the same process, but can't be + * done sticky :\ * * @param target Account or URL pointing to an OC server. * @param operation Added operation. @@ -642,7 +665,8 @@ public class OperationsService extends Service { // TODO - maybe add a notification for real start of operations /** - * Sends a LOCAL broadcast when an operations finishes in order to the interested activities can update their view + * Sends a LOCAL broadcast when an operations finishes in order to the interested activities c + * an update their view * * Local broadcasts are only delivered to activities in the same process. * @@ -650,7 +674,8 @@ public class OperationsService extends Service { * @param operation Finished operation. * @param result Result of the operation. */ - private void sendBroadcastOperationFinished(Target target, RemoteOperation operation, RemoteOperationResult result) { + private void sendBroadcastOperationFinished(Target target, RemoteOperation operation, + RemoteOperationResult result) { Intent intent = new Intent(ACTION_OPERATION_FINISHED); intent.putExtra(EXTRA_RESULT, result); if (target.mAccount != null) { @@ -674,7 +699,8 @@ public class OperationsService extends Service { final RemoteOperation operation, final RemoteOperationResult result ) { int count = 0; - Iterator listeners = mOperationsBinder.mBoundListeners.keySet().iterator(); + Iterator listeners = + mOperationsBinder.mBoundListeners.keySet().iterator(); while (listeners.hasNext()) { final OnRemoteOperationListener listener = listeners.next(); final Handler handler = mOperationsBinder.mBoundListeners.get(listener); diff --git a/src/com/owncloud/android/services/SyncFolderHandler.java b/src/com/owncloud/android/services/SyncFolderHandler.java index 57271eb5..33318f57 100644 --- a/src/com/owncloud/android/services/SyncFolderHandler.java +++ b/src/com/owncloud/android/services/SyncFolderHandler.java @@ -27,6 +27,7 @@ import android.os.Looper; import android.os.Message; import android.util.Pair; +import com.owncloud.android.MainApp; import com.owncloud.android.datamodel.FileDataStorageManager; import com.owncloud.android.datamodel.OCFile; import com.owncloud.android.files.services.FileDownloader; @@ -135,7 +136,8 @@ class SyncFolderHandler extends Handler { } } - public void add(Account account, String remotePath, SynchronizeFolderOperation syncFolderOperation){ + public void add(Account account, String remotePath, + SynchronizeFolderOperation syncFolderOperation){ mPendingOperations.putIfAbsent(account, remotePath, syncFolderOperation); sendBroadcastNewSyncFolder(account, remotePath); // TODO upgrade! } @@ -170,26 +172,29 @@ class SyncFolderHandler extends Handler { } /** - * TODO review this method when "folder synchronization" replaces "folder download"; this is a fast and ugly - * patch. + * TODO review this method when "folder synchronization" replaces "folder download"; + * this is a fast and ugly patch. */ private void sendBroadcastNewSyncFolder(Account account, String remotePath) { Intent added = new Intent(FileDownloader.getDownloadAddedMessage()); added.putExtra(FileDownloader.ACCOUNT_NAME, account.name); added.putExtra(FileDownloader.EXTRA_REMOTE_PATH, remotePath); - added.putExtra(FileDownloader.EXTRA_FILE_PATH, FileStorageUtils.getSavePath(account.name) + remotePath); + added.putExtra(FileDownloader.EXTRA_FILE_PATH, FileStorageUtils.getSavePath(account.name) + + remotePath); mService.sendStickyBroadcast(added); } /** - * TODO review this method when "folder synchronization" replaces "folder download"; this is a fast and ugly - * patch. + * TODO review this method when "folder synchronization" replaces "folder download"; + * this is a fast and ugly patch. */ - private void sendBroadcastFinishedSyncFolder(Account account, String remotePath, boolean success) { + private void sendBroadcastFinishedSyncFolder(Account account, String remotePath, + boolean success) { Intent finished = new Intent(FileDownloader.getDownloadFinishMessage()); finished.putExtra(FileDownloader.ACCOUNT_NAME, account.name); finished.putExtra(FileDownloader.EXTRA_REMOTE_PATH, remotePath); - finished.putExtra(FileDownloader.EXTRA_FILE_PATH, FileStorageUtils.getSavePath(account.name) + remotePath); + finished.putExtra(FileDownloader.EXTRA_FILE_PATH, + FileStorageUtils.getSavePath(account.name) + remotePath); finished.putExtra(FileDownloader.EXTRA_DOWNLOAD_RESULT, success); mService.sendStickyBroadcast(finished); } diff --git a/src/com/owncloud/android/syncadapter/AbstractOwnCloudSyncAdapter.java b/src/com/owncloud/android/syncadapter/AbstractOwnCloudSyncAdapter.java index 7ccbc118..47403100 100644 --- a/src/com/owncloud/android/syncadapter/AbstractOwnCloudSyncAdapter.java +++ b/src/com/owncloud/android/syncadapter/AbstractOwnCloudSyncAdapter.java @@ -28,6 +28,7 @@ import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; +import com.owncloud.android.MainApp; import com.owncloud.android.datamodel.FileDataStorageManager; import com.owncloud.android.lib.common.accounts.AccountUtils; import com.owncloud.android.lib.common.accounts.AccountUtils.AccountNotFoundException; @@ -64,7 +65,8 @@ public abstract class AbstractOwnCloudSyncAdapter extends this.setAccountManager(AccountManager.get(context)); } - public AbstractOwnCloudSyncAdapter(Context context, boolean autoInitialize, boolean allowParallelSyncs) { + public AbstractOwnCloudSyncAdapter(Context context, boolean autoInitialize, + boolean allowParallelSyncs) { super(context, autoInitialize, allowParallelSyncs); this.setAccountManager(AccountManager.get(context)); } @@ -101,7 +103,8 @@ public abstract class AbstractOwnCloudSyncAdapter extends return mStoreManager; } - protected void initClientForCurrentAccount() throws OperationCanceledException, AuthenticatorException, IOException, AccountNotFoundException { + protected void initClientForCurrentAccount() throws OperationCanceledException, + AuthenticatorException, IOException, AccountNotFoundException { AccountUtils.constructFullURLForAccount(getContext(), account); OwnCloudAccount ocAccount = new OwnCloudAccount(account, getContext()); mClient = OwnCloudClientManagerFactory.getDefaultSingleton(). diff --git a/src/com/owncloud/android/syncadapter/FileSyncAdapter.java b/src/com/owncloud/android/syncadapter/FileSyncAdapter.java index 07e68c6a..43ddae33 100644 --- a/src/com/owncloud/android/syncadapter/FileSyncAdapter.java +++ b/src/com/owncloud/android/syncadapter/FileSyncAdapter.java @@ -30,6 +30,7 @@ import java.util.Map; import org.apache.jackrabbit.webdav.DavException; +import com.owncloud.android.MainApp; import com.owncloud.android.R; import com.owncloud.android.authentication.AuthenticatorActivity; import com.owncloud.android.datamodel.FileDataStorageManager; @@ -58,23 +59,31 @@ import android.support.v4.app.NotificationCompat; * Implementation of {@link AbstractThreadedSyncAdapter} responsible for synchronizing * ownCloud files. * - * Performs a full synchronization of the account recieved in {@link #onPerformSync(Account, Bundle, String, ContentProviderClient, SyncResult)}. + * Performs a full synchronization of the account recieved in {@link #onPerformSync(Account, Bundle, + * String, ContentProviderClient, SyncResult)}. */ public class FileSyncAdapter extends AbstractOwnCloudSyncAdapter { private final static String TAG = FileSyncAdapter.class.getSimpleName(); - /** Maximum number of failed folder synchronizations that are supported before finishing the synchronization operation */ + /** Maximum number of failed folder synchronizations that are supported before finishing + * the synchronization operation */ private static final int MAX_FAILED_RESULTS = 3; - public static final String EVENT_FULL_SYNC_START = FileSyncAdapter.class.getName() + ".EVENT_FULL_SYNC_START"; - public static final String EVENT_FULL_SYNC_END = FileSyncAdapter.class.getName() + ".EVENT_FULL_SYNC_END"; - public static final String EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED = FileSyncAdapter.class.getName() + ".EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED"; - //public static final String EVENT_FULL_SYNC_FOLDER_SIZE_SYNCED = FileSyncAdapter.class.getName() + ".EVENT_FULL_SYNC_FOLDER_SIZE_SYNCED"; + public static final String EVENT_FULL_SYNC_START = FileSyncAdapter.class.getName() + + ".EVENT_FULL_SYNC_START"; + public static final String EVENT_FULL_SYNC_END = FileSyncAdapter.class.getName() + + ".EVENT_FULL_SYNC_END"; + public static final String EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED = + FileSyncAdapter.class.getName() + ".EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED"; + //public static final String EVENT_FULL_SYNC_FOLDER_SIZE_SYNCED = + // FileSyncAdapter.class.getName() + ".EVENT_FULL_SYNC_FOLDER_SIZE_SYNCED"; - public static final String EXTRA_ACCOUNT_NAME = FileSyncAdapter.class.getName() + ".EXTRA_ACCOUNT_NAME"; - public static final String EXTRA_FOLDER_PATH = FileSyncAdapter.class.getName() + ".EXTRA_FOLDER_PATH"; + public static final String EXTRA_ACCOUNT_NAME = FileSyncAdapter.class.getName() + + ".EXTRA_ACCOUNT_NAME"; + public static final String EXTRA_FOLDER_PATH = FileSyncAdapter.class.getName() + + ".EXTRA_FOLDER_PATH"; public static final String EXTRA_RESULT = FileSyncAdapter.class.getName() + ".EXTRA_RESULT"; @@ -84,7 +93,8 @@ public class FileSyncAdapter extends AbstractOwnCloudSyncAdapter { /** Flag made 'true' when a request to cancel the synchronization is received */ private boolean mCancellation; - /** When 'true' the process was requested by the user through the user interface; when 'false', it was requested automatically by the system */ + /** When 'true' the process was requested by the user through the user interface; + * when 'false', it was requested automatically by the system */ private boolean mIsManualSync; /** Counter for failed operations in the synchronization process */ @@ -99,7 +109,8 @@ public class FileSyncAdapter extends AbstractOwnCloudSyncAdapter { /** Counter of failed operations in synchronization of kept-in-sync files */ private int mFailsInFavouritesFound; - /** Map of remote and local paths to files that where locally stored in a location out of the ownCloud folder and couldn't be copied automatically into it */ + /** Map of remote and local paths to files that where locally stored in a location out + * of the ownCloud folder and couldn't be copied automatically into it */ private Map mForgottenLocalFiles; /** {@link SyncResult} instance to return to the system when the synchronization finish */ @@ -155,19 +166,22 @@ public class FileSyncAdapter extends AbstractOwnCloudSyncAdapter { try { this.initClientForCurrentAccount(); } catch (IOException e) { - /// the account is unknown for the Synchronization Manager, unreachable this context, or can not be authenticated; don't try this again + /// the account is unknown for the Synchronization Manager, unreachable this context, + // or can not be authenticated; don't try this again mSyncResult.tooManyRetries = true; notifyFailedSynchronization(); return; } catch (AccountsException e) { - /// the account is unknown for the Synchronization Manager, unreachable this context, or can not be authenticated; don't try this again + /// the account is unknown for the Synchronization Manager, unreachable this context, + // or can not be authenticated; don't try this again mSyncResult.tooManyRetries = true; notifyFailedSynchronization(); return; } Log_OC.d(TAG, "Synchronization of ownCloud account " + account.name + " starting"); - sendLocalBroadcast(EVENT_FULL_SYNC_START, null, null); // message to signal the start of the synchronization to the UI + sendLocalBroadcast(EVENT_FULL_SYNC_START, null, null); // message to signal the start + // of the synchronization to the UI try { updateOCVersion(); @@ -176,16 +190,19 @@ public class FileSyncAdapter extends AbstractOwnCloudSyncAdapter { synchronizeFolder(getStorageManager().getFileByPath(OCFile.ROOT_PATH)); } else { - Log_OC.d(TAG, "Leaving synchronization before synchronizing the root folder because cancelation request"); + Log_OC.d(TAG, "Leaving synchronization before synchronizing the root folder " + + "because cancelation request"); } } finally { - // it's important making this although very unexpected errors occur; that's the reason for the finally + // it's important making this although very unexpected errors occur; + // that's the reason for the finally if (mFailedResultsCounter > 0 && mIsManualSync) { /// don't let the system synchronization manager retries MANUAL synchronizations - // (be careful: "MANUAL" currently includes the synchronization requested when a new account is created and when the user changes the current account) + // (be careful: "MANUAL" currently includes the synchronization requested when + // a new account is created and when the user changes the current account) mSyncResult.tooManyRetries = true; /// notify the user about the failure of MANUAL synchronization @@ -197,7 +214,8 @@ public class FileSyncAdapter extends AbstractOwnCloudSyncAdapter { if (mForgottenLocalFiles.size() > 0) { notifyForgottenLocalFiles(); } - sendLocalBroadcast(EVENT_FULL_SYNC_END, null, mLastFailedResult); // message to signal the end to the UI + sendLocalBroadcast(EVENT_FULL_SYNC_END, null, mLastFailedResult); // message to signal + // the end to the UI } } @@ -210,7 +228,7 @@ public class FileSyncAdapter extends AbstractOwnCloudSyncAdapter { * locally saved. * * See {@link #onPerformSync(Account, Bundle, String, ContentProviderClient, SyncResult)} - * and {@link #synchronizeFolder(String, long)}. + * and {@link #synchronizeFolder(OCFile)}. */ @Override public void onSyncCanceled() { @@ -261,14 +279,14 @@ public class FileSyncAdapter extends AbstractOwnCloudSyncAdapter { } */ // folder synchronization - RefreshFolderOperation synchFolderOp = new RefreshFolderOperation( folder, - mCurrentSyncTime, - true, - mIsShareSupported, - false, - getStorageManager(), - getAccount(), - getContext() + RefreshFolderOperation synchFolderOp = new RefreshFolderOperation( folder, + mCurrentSyncTime, + true, + mIsShareSupported, + false, + getStorageManager(), + getAccount(), + getContext() ); RemoteOperationResult result = synchFolderOp.execute(getClient()); @@ -289,7 +307,8 @@ public class FileSyncAdapter extends AbstractOwnCloudSyncAdapter { if (result.isSuccess()) { // synchronize children folders List children = synchFolderOp.getChildren(); - fetchChildren(folder, children, synchFolderOp.getRemoteFolderChanged()); // beware of the 'hidden' recursion here! + // beware of the 'hidden' recursion here! + fetchChildren(folder, children, synchFolderOp.getRemoteFolderChanged()); } } else { @@ -312,11 +331,12 @@ public class FileSyncAdapter extends AbstractOwnCloudSyncAdapter { } /** - * Checks if a failed result should terminate the synchronization process immediately, according to - * OUR OWN POLICY + * Checks if a failed result should terminate the synchronization process immediately, + * according to OUR OWN POLICY * * @param failedResult Remote operation result to check. - * @return 'True' if the result should immediately finish the synchronization + * @return 'True' if the result should immediately finish the + * synchronization */ private boolean isFinisher(RemoteOperationResult failedResult) { if (failedResult != null) { @@ -347,23 +367,29 @@ public class FileSyncAdapter extends AbstractOwnCloudSyncAdapter { syncDown = (parentEtagChanged || etag == null || etag.length() == 0); if(syncDown) { */ synchronizeFolder(newFile); - //sendLocalBroadcast(EVENT_FULL_SYNC_FOLDER_SIZE_SYNCED, parent.getRemotePath(), null); + //sendLocalBroadcast(EVENT_FULL_SYNC_FOLDER_SIZE_SYNCED, parent.getRemotePath(), + // null); //} } } - if (mCancellation && i