From 0a13a5b818acc2ec13e51ad46d244cec56875d87 Mon Sep 17 00:00:00 2001 From: Iskra Delta Date: Fri, 14 Oct 2016 10:09:13 +0000 Subject: [PATCH] PMD appeased Some warnings have been supressed. --- pmd-ruleset.xml | 1 + src/com/owncloud/android/MainApp.java | 2 +- .../authentication/AccountAuthenticator.java | 9 +- .../android/authentication/AccountUtils.java | 15 +- .../authentication/AuthenticatorActivity.java | 54 ++-- .../AuthenticatorAsyncTask.java | 4 +- .../authentication/PassCodeManager.java | 2 +- .../datamodel/FileDataStorageManager.java | 165 +++++----- .../owncloud/android/datamodel/OCFile.java | 10 +- .../datamodel/ThumbnailsCacheManager.java | 69 ++-- .../datamodel/UploadsStorageManager.java | 11 +- src/com/owncloud/android/db/ProviderMeta.java | 13 +- .../files/BootupBroadcastReceiver.java | 2 +- .../files/InstantUploadBroadcastReceiver.java | 8 +- .../services/ConnectivityActionReceiver.java | 28 +- .../files/services/FileDownloader.java | 15 +- .../android/files/services/FileUploader.java | 22 +- .../android/files/services/IndexedForest.java | 2 +- .../services/OnUploadCompletedListener.java | 28 -- .../android/media/MediaControlView.java | 31 +- .../owncloud/android/media/MediaService.java | 6 +- .../CreateShareWithShareeOperation.java | 8 +- .../operations/DownloadFileOperation.java | 10 +- .../operations/GetCapabilitiesOperarion.java | 11 +- .../operations/OAuth2GetAccessToken.java | 21 +- .../operations/RefreshFolderOperation.java | 4 +- .../operations/RenameFileOperation.java | 6 +- .../operations/SynchronizeFileOperation.java | 4 +- .../SynchronizeFolderOperation.java | 3 +- .../operations/UpdateOCVersionOperation.java | 3 +- .../operations/UploadFileOperation.java | 25 +- .../operations/common/SyncOperation.java | 3 +- .../providers/FileContentProvider.java | 296 +++++++++--------- .../android/services/OperationsService.java | 10 +- .../android/services/SyncFolderHandler.java | 6 +- .../observer/FileObserverService.java | 2 +- .../services/observer/FolderObserver.java | 28 +- .../android/syncadapter/FileSyncAdapter.java | 31 +- .../ui/activity/ConflictsResolveActivity.java | 2 +- .../ui/activity/FileDisplayActivity.java | 91 +++--- .../ui/activity/FolderPickerActivity.java | 7 +- .../activity/GenericExplanationActivity.java | 12 +- .../android/ui/activity/PassCodeActivity.java | 13 +- .../ReceiveExternalFilesActivity.java | 21 +- .../ui/activity/UploadFilesActivity.java | 3 +- .../android/ui/adapter/DiskLruImageCache.java | 23 +- .../ui/adapter/FileListListAdapter.java | 8 +- .../ui/adapter/LocalFileListAdapter.java | 14 +- .../android/ui/adapter/UploaderAdapter.java | 3 +- .../adapter/X509CertificateViewAdapter.java | 2 +- .../CopyAndUploadContentUrisTask.java | 8 +- .../ui/dialog/ConfirmationDialogFragment.java | 17 +- .../ui/dialog/ConflictsResolveDialog.java | 9 +- .../ui/dialog/CredentialsDialogFragment.java | 5 +- .../android/ui/dialog/LoadingDialog.java | 3 +- .../ui/dialog/RemoveFileDialogFragment.java | 3 +- .../ui/dialog/RenameFileDialogFragment.java | 2 +- .../android/ui/dialog/SamlWebViewDialog.java | 6 +- .../ui/dialog/SslUntrustedCertDialog.java | 3 +- .../android/ui/dialog/SslValidatorDialog.java | 23 +- .../ui/errorhandling/ExceptionHandler.java | 59 ++-- .../ui/fragment/EditShareFragment.java | 6 +- .../ui/fragment/ExtendedListFragment.java | 4 +- .../ui/fragment/LocalFileListFragment.java | 4 +- .../ui/fragment/OCFileListFragment.java | 16 +- .../ui/fragment/UploadListFragment.java | 2 +- .../ui/preview/FileDownloadFragment.java | 26 +- .../ui/preview/PreviewImageActivity.java | 13 +- .../ui/preview/PreviewImageFragment.java | 12 +- .../ui/preview/PreviewMediaFragment.java | 25 +- .../ui/preview/PreviewTextFragment.java | 10 +- .../owncloud/android/utils/BitmapUtils.java | 29 +- .../owncloud/android/utils/DisplayUtils.java | 14 +- .../android/utils/ErrorMessageAdapter.java | 3 +- .../android/utils/FileStorageUtils.java | 8 +- .../owncloud/android/utils/MimeTypeUtil.java | 3 +- .../android/utils/RecursiveFileObserver.java | 48 +-- src/com/owncloud/android/utils/UriUtils.java | 8 +- .../android/widgets/ActionEditText.java | 54 ++-- .../providers/DocumentsStorageProvider.java | 9 +- .../providers/cursors/FileCursor.java | 4 +- .../daveKoeller/AlphanumComparator.java | 9 +- .../cube/GridViewWithHeaderAndFooter.java | 31 +- .../michaelOrtiz/TouchImageViewCustom.java | 13 +- 84 files changed, 845 insertions(+), 811 deletions(-) delete mode 100644 src/com/owncloud/android/files/services/OnUploadCompletedListener.java diff --git a/pmd-ruleset.xml b/pmd-ruleset.xml index ce61196628..374f90400e 100644 --- a/pmd-ruleset.xml +++ b/pmd-ruleset.xml @@ -9,6 +9,7 @@ .*/R.java .*/gen/.* + .*/third_parties/.* diff --git a/src/com/owncloud/android/MainApp.java b/src/com/owncloud/android/MainApp.java index de0d17026b..526f5a9c0b 100644 --- a/src/com/owncloud/android/MainApp.java +++ b/src/com/owncloud/android/MainApp.java @@ -198,7 +198,7 @@ public class MainApp extends Application { mOnlyOnDevice = state; } - public static boolean getOnlyOnDevice(){ + public static boolean isOnlyOnDevice(){ return mOnlyOnDevice; } diff --git a/src/com/owncloud/android/authentication/AccountAuthenticator.java b/src/com/owncloud/android/authentication/AccountAuthenticator.java index a40b7dd2e6..6734a33251 100644 --- a/src/com/owncloud/android/authentication/AccountAuthenticator.java +++ b/src/com/owncloud/android/authentication/AccountAuthenticator.java @@ -87,8 +87,7 @@ public class AccountAuthenticator extends AbstractAccountAuthenticator { validateAccountType(accountType); } catch (AuthenticatorException e) { Log_OC.e(TAG, "Failed to validate account type " + accountType + ": " - + e.getMessage()); - e.printStackTrace(); + + e.getMessage(), e); return e.getFailureBundle(); } @@ -133,8 +132,7 @@ public class AccountAuthenticator extends AbstractAccountAuthenticator { validateAccountType(account.type); } catch (AuthenticatorException e) { Log_OC.e(TAG, "Failed to validate account type " + account.type + ": " - + e.getMessage()); - e.printStackTrace(); + + e.getMessage(), e); return e.getFailureBundle(); } Intent intent = new Intent(mContext, AuthenticatorActivity.class); @@ -169,8 +167,7 @@ public class AccountAuthenticator extends AbstractAccountAuthenticator { validateAuthTokenType(authTokenType); } catch (AuthenticatorException e) { Log_OC.e(TAG, "Failed to validate account type " + account.type + ": " - + e.getMessage()); - e.printStackTrace(); + + e.getMessage(), e); return e.getFailureBundle(); } diff --git a/src/com/owncloud/android/authentication/AccountUtils.java b/src/com/owncloud/android/authentication/AccountUtils.java index 05324a9b79..93f9628cb4 100644 --- a/src/com/owncloud/android/authentication/AccountUtils.java +++ b/src/com/owncloud/android/authentication/AccountUtils.java @@ -119,7 +119,7 @@ public class AccountUtils { */ public static String getAccountUsername(String accountName) { if (accountName != null) { - return accountName.substring(0, accountName.lastIndexOf("@")); + return accountName.substring(0, accountName.lastIndexOf('@')); } else { return null; } @@ -135,8 +135,9 @@ public class AccountUtils { Account[] ocAccounts = AccountManager.get(context).getAccountsByType( MainApp.getAccountType()); for (Account account : ocAccounts) { - if(account.name.equals(accountName)) + if(account.name.equals(accountName)) { return account; + } } return null; } @@ -241,15 +242,13 @@ public class AccountUtils { ); // copy type of authentication - String isSamlStr = accountMgr.getUserData(account, Constants.KEY_SUPPORTS_SAML_WEB_SSO); - boolean isSaml = "TRUE".equals(isSamlStr); - if (isSaml) { + final String isSamlStr = accountMgr.getUserData(account, Constants.KEY_SUPPORTS_SAML_WEB_SSO); + if (Boolean.parseBoolean(isSamlStr)) { accountMgr.setUserData(newAccount, Constants.KEY_SUPPORTS_SAML_WEB_SSO, "TRUE"); } - String isOauthStr = accountMgr.getUserData(account, Constants.KEY_SUPPORTS_OAUTH2); - boolean isOAuth = "TRUE".equals(isOauthStr); - if (isOAuth) { + final String isOauthStr = accountMgr.getUserData(account, Constants.KEY_SUPPORTS_OAUTH2); + if (Boolean.parseBoolean(isOauthStr)) { accountMgr.setUserData(newAccount, Constants.KEY_SUPPORTS_OAUTH2, "TRUE"); } /* TODO - study if it's possible to run this method in a background thread to copy the authToken diff --git a/src/com/owncloud/android/authentication/AuthenticatorActivity.java b/src/com/owncloud/android/authentication/AuthenticatorActivity.java index 99f0b5b2a0..8f290541ee 100644 --- a/src/com/owncloud/android/authentication/AuthenticatorActivity.java +++ b/src/com/owncloud/android/authentication/AuthenticatorActivity.java @@ -142,6 +142,8 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity private static final String KEY_ASYNC_TASK_IN_PROGRESS = "AUTH_IN_PROGRESS"; public static final String PROTOCOL_SUFFIX = "://"; public static final String LOGIN_URL_DATA_KEY_VALUE_SEPARATOR = ":"; + private static final String HTTPS_PROTOCOL = "https://"; + private static final String HTTP_PROTOCOL = "http://"; /// parameters from EXTRAs in starter Intent private byte mAction; @@ -167,7 +169,6 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity private boolean mServerIsChecked = false; private boolean mServerIsValid = false; - private boolean mPendingAutoCheck = false; private GetServerInfoOperation.ServerInfo mServerInfo = new GetServerInfoOperation.ServerInfo(); @@ -408,11 +409,11 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity if (mAccount != null) { mServerInfo.mBaseUrl = mAccountMgr.getUserData(mAccount, Constants.KEY_OC_BASE_URL); // TODO do next in a setter for mBaseUrl - mServerInfo.mIsSslConn = mServerInfo.mBaseUrl.startsWith("https://"); + mServerInfo.mIsSslConn = mServerInfo.mBaseUrl.startsWith(HTTPS_PROTOCOL); mServerInfo.mVersion = AccountUtils.getServerVersion(mAccount); } else { mServerInfo.mBaseUrl = getString(R.string.server_url).trim(); - mServerInfo.mIsSslConn = mServerInfo.mBaseUrl.startsWith("https://"); + mServerInfo.mIsSslConn = mServerInfo.mBaseUrl.startsWith(HTTPS_PROTOCOL); } } else { mServerStatusText = savedInstanceState.getInt(KEY_SERVER_STATUS_TEXT); @@ -492,24 +493,16 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity findViewById(R.id.scroll).setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View view, MotionEvent event) { - if (event.getAction() == MotionEvent.ACTION_DOWN) { - if ( - AccountTypeUtils.getAuthTokenTypeSamlSessionCookie( - MainApp.getAccountType() - ).equals(mAuthTokenType) && - mHostUrlInput.hasFocus() - ) { - checkOcServer(); - } + if (event.getAction() == MotionEvent.ACTION_DOWN && + AccountTypeUtils + .getAuthTokenTypeSamlSessionCookie(MainApp + .getAccountType()).equals(mAuthTokenType) && + mHostUrlInput.hasFocus()) { + checkOcServer(); } return false; } }); - - - /// step 4 - mark automatic check to be started when OperationsService is ready - mPendingAutoCheck = (savedInstanceState == null && - (mAction != ACTION_CREATE || checkHostUrl)); } @@ -1127,8 +1120,9 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity } } - if (success) + if (success) { finish(); + } } else { updateStatusIconFailUserName(); showAuthStatus(); @@ -1197,14 +1191,15 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity // TODO remove, if possible private String normalizeUrl(String url, boolean sslWhenUnprefixed) { + if (url != null && url.length() > 0) { url = url.trim(); - if (!url.toLowerCase().startsWith("http://") && - !url.toLowerCase().startsWith("https://")) { + if (!url.toLowerCase().startsWith(HTTP_PROTOCOL) && + !url.toLowerCase().startsWith(HTTP_PROTOCOL)) { if (sslWhenUnprefixed) { - url = "https://" + url; + url = HTTPS_PROTOCOL + url; } else { - url = "http://" + url; + url = HTTP_PROTOCOL + url; } } @@ -1259,7 +1254,7 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity case OK_NO_SSL: case OK: - if (mHostUrlInput.getText().toString().trim().toLowerCase().startsWith("http://")) { + if (mHostUrlInput.getText().toString().trim().toLowerCase().startsWith(HTTP_PROTOCOL)) { mServerStatusText = R.string.auth_connection_established; mServerStatusIcon = R.drawable.ic_ok; } else { @@ -1340,7 +1335,7 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity case OK_NO_SSL: case OK: - if (mHostUrlInput.getText().toString().trim().toLowerCase().startsWith("http://")) { + if (mHostUrlInput.getText().toString().trim().toLowerCase().startsWith(HTTP_PROTOCOL)) { mAuthStatusText = R.string.auth_connection_established; mAuthStatusIcon = R.drawable.ic_ok; } else { @@ -1783,11 +1778,10 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity } } else if (actionId == EditorInfo.IME_ACTION_NEXT && inputField != null && - inputField.equals(mHostUrlInput)) { - if (AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType()). - equals(mAuthTokenType)) { + inputField.equals(mHostUrlInput) && + AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType()). + equals(mAuthTokenType)) { checkOcServer(); - } } return false; // always return false to grant that the software keyboard is hidden anyway } @@ -1848,7 +1842,7 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity mAuthToken = sessionCookie; getRemoteUserNameOperation(sessionCookie); Fragment fd = getSupportFragmentManager().findFragmentByTag(SAML_DIALOG_TAG); - if (fd != null && fd instanceof DialogFragment) { + if (fd instanceof DialogFragment) { Dialog d = ((DialogFragment) fd).getDialog(); if (d != null && d.isShowing()) { d.dismiss(); @@ -1951,7 +1945,7 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity private void dismissDialog(String dialogTag) { Fragment frag = getSupportFragmentManager().findFragmentByTag(dialogTag); - if (frag != null && frag instanceof DialogFragment) { + if (frag instanceof DialogFragment) { DialogFragment dialog = (DialogFragment) frag; dialog.dismiss(); } diff --git a/src/com/owncloud/android/authentication/AuthenticatorAsyncTask.java b/src/com/owncloud/android/authentication/AuthenticatorAsyncTask.java index 09997c7255..23c327cf76 100644 --- a/src/com/owncloud/android/authentication/AuthenticatorAsyncTask.java +++ b/src/com/owncloud/android/authentication/AuthenticatorAsyncTask.java @@ -40,8 +40,8 @@ import java.lang.ref.WeakReference; */ public class AuthenticatorAsyncTask extends AsyncTask { - private static String REMOTE_PATH = "/"; - private static boolean SUCCESS_IF_ABSENT = false; + private static final String REMOTE_PATH = "/"; + private static final boolean SUCCESS_IF_ABSENT = false; private Context mContext; private final WeakReference mListener; diff --git a/src/com/owncloud/android/authentication/PassCodeManager.java b/src/com/owncloud/android/authentication/PassCodeManager.java index baab23aa37..cc4dd383d8 100644 --- a/src/com/owncloud/android/authentication/PassCodeManager.java +++ b/src/com/owncloud/android/authentication/PassCodeManager.java @@ -43,7 +43,7 @@ public class PassCodeManager { // other activities may be exempted, if needed } - private static int PASS_CODE_TIMEOUT = 1000; + private static final int PASS_CODE_TIMEOUT = 1000; // keeping a "low" positive value is the easiest way to prevent the pass code is requested on rotations public static PassCodeManager mPassCodeManagerInstance = null; diff --git a/src/com/owncloud/android/datamodel/FileDataStorageManager.java b/src/com/owncloud/android/datamodel/FileDataStorageManager.java index 3eb3407fb8..8d9f5a3a41 100644 --- a/src/com/owncloud/android/datamodel/FileDataStorageManager.java +++ b/src/com/owncloud/android/datamodel/FileDataStorageManager.java @@ -52,6 +52,7 @@ import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.List; +import java.util.Locale; import java.util.Set; import java.util.Vector; @@ -62,8 +63,12 @@ public class FileDataStorageManager { private ContentResolver mContentResolver; private ContentProviderClient mContentProviderClient; private Account mAccount; + private static final String AND = "=? AND "; + private static final String FAILED_TO_INSERT_MSG = "Fail to insert insert file to database "; + private static final String SENDING_TO_FILECONTENTPROVIDER_MSG = "Sending %d operations to FileContentProvider"; + private static final String EXCEPTION_MSG = "Exception in batch of operations "; - private static String TAG = FileDataStorageManager.class.getSimpleName(); + private static final String TAG = FileDataStorageManager.class.getSimpleName(); public FileDataStorageManager(Account account, ContentResolver cr) { @@ -179,8 +184,9 @@ public class FileDataStorageManager { cv.put(ProviderTableMeta.FILE_NAME, file.getFileName()); cv.put(ProviderTableMeta.FILE_PARENT, file.getParentId()); cv.put(ProviderTableMeta.FILE_PATH, file.getRemotePath()); - if (!file.isFolder()) + if (!file.isFolder()) { cv.put(ProviderTableMeta.FILE_STORAGE_PATH, file.getStoragePath()); + } cv.put(ProviderTableMeta.FILE_ACCOUNT_OWNER, mAccount.name); cv.put(ProviderTableMeta.FILE_LAST_SYNC_DATE, file.getLastSyncDateForProperties()); cv.put(ProviderTableMeta.FILE_LAST_SYNC_DATE_FOR_DATA, file.getLastSyncDateForData()); @@ -219,8 +225,7 @@ public class FileDataStorageManager { new String[]{String.valueOf(file.getFileId())}); } catch (RemoteException e) { Log_OC.e(TAG, - "Fail to insert insert file to database " - + e.getMessage()); + FAILED_TO_INSERT_MSG + e.getMessage()); } } } else { @@ -234,8 +239,7 @@ public class FileDataStorageManager { ProviderTableMeta.CONTENT_URI_FILE, cv); } catch (RemoteException e) { Log_OC.e(TAG, - "Fail to insert insert file to database " - + e.getMessage()); + FAILED_TO_INSERT_MSG + e.getMessage()); } } if (result_uri != null) { @@ -332,7 +336,7 @@ public class FileDataStorageManager { } // prepare operations to remove files in the given folder - String where = ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?" + " AND " + + String where = ProviderTableMeta.FILE_ACCOUNT_OWNER + AND + ProviderTableMeta.FILE_PATH + "=?"; String [] whereArgs = null; for (OCFile file : filesToRemove) { @@ -398,7 +402,7 @@ public class FileDataStorageManager { // apply operations in batch ContentProviderResult[] results = null; - Log_OC.d(TAG, "Sending " + operations.size() + " operations to FileContentProvider"); + Log_OC.d(TAG, String.format(Locale.ENGLISH, SENDING_TO_FILECONTENTPROVIDER_MSG, operations.size())); try { if (getContentResolver() != null) { results = getContentResolver().applyBatch(MainApp.getAuthority(), operations); @@ -407,11 +411,9 @@ public class FileDataStorageManager { results = getContentProviderClient().applyBatch(operations); } - } catch (OperationApplicationException e) { - Log_OC.e(TAG, "Exception in batch of operations " + e.getMessage()); + } catch (OperationApplicationException | RemoteException e) { + Log_OC.e(TAG, EXCEPTION_MSG + e.getMessage()); - } catch (RemoteException e) { - Log_OC.e(TAG, "Exception in batch of operations " + e.getMessage()); } // update new id in file objects for insertions @@ -419,14 +421,14 @@ public class FileDataStorageManager { long newId; Iterator filesIt = updatedFiles.iterator(); OCFile file = null; - for (int i = 0; i < results.length; i++) { + for (ContentProviderResult result : results) { if (filesIt.hasNext()) { file = filesIt.next(); } else { file = null; } - if (results[i].uri != null) { - newId = Long.parseLong(results[i].uri.getPathSegments().get(1)); + if (result.uri != null) { + newId = Long.parseLong(result.uri.getPathSegments().get(1)); //updatedFiles.get(i).setFileId(newId); if (file != null) { file.setFileId(newId); @@ -450,7 +452,7 @@ public class FileDataStorageManager { // ""+file.getFileId()); Uri file_uri = ContentUris.withAppendedId(ProviderTableMeta.CONTENT_URI_FILE, file.getFileId()); - String where = ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?" + " AND " + + String where = ProviderTableMeta.FILE_ACCOUNT_OWNER + AND + ProviderTableMeta.FILE_PATH + "=?"; String[] whereArgs = new String[]{mAccount.name, file.getRemotePath()}; int deleted = 0; @@ -458,7 +460,7 @@ public class FileDataStorageManager { try { deleted = getContentProviderClient().delete(file_uri, where, whereArgs); } catch (RemoteException e) { - e.printStackTrace(); + Log_OC.d(TAG, e.getMessage(), e); } } else { deleted = getContentResolver().delete(file_uri, where, whereArgs); @@ -502,7 +504,7 @@ public class FileDataStorageManager { private boolean removeFolderInDb(OCFile folder) { Uri folder_uri = Uri.withAppendedPath(ProviderTableMeta.CONTENT_URI_DIR, "" + folder.getFileId()); // URI for recursive deletion - String where = ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?" + " AND " + + String where = ProviderTableMeta.FILE_ACCOUNT_OWNER + AND + ProviderTableMeta.FILE_PATH + "=?"; String [] whereArgs = new String[]{mAccount.name, folder.getRemotePath()}; int deleted = 0; @@ -510,7 +512,7 @@ public class FileDataStorageManager { try { deleted = getContentProviderClient().delete(folder_uri, where, whereArgs); } catch (RemoteException e) { - e.printStackTrace(); + Log_OC.d(TAG, e.getMessage(), e); } } else { deleted = getContentResolver().delete(folder_uri, where, whereArgs); @@ -592,7 +594,7 @@ public class FileDataStorageManager { c = getContentProviderClient().query( ProviderTableMeta.CONTENT_URI, null, - ProviderTableMeta.FILE_ACCOUNT_OWNER + "=? AND " + + ProviderTableMeta.FILE_ACCOUNT_OWNER + AND + ProviderTableMeta.FILE_PATH + " LIKE ? ", new String[]{ mAccount.name, @@ -608,7 +610,7 @@ public class FileDataStorageManager { c = getContentResolver().query( ProviderTableMeta.CONTENT_URI, null, - ProviderTableMeta.FILE_ACCOUNT_OWNER + "=? AND " + + ProviderTableMeta.FILE_ACCOUNT_OWNER + AND + ProviderTableMeta.FILE_PATH + " LIKE ? ", new String[]{ mAccount.name, @@ -748,6 +750,23 @@ public class FileDataStorageManager { Log_OC.e(TAG, e.getMessage()); throw e; } + } catch (IOException ex) { + ret = false; + } finally { + if (in != null) { + try { + in.close(); + } catch (IOException e) { + Log_OC.d(TAG, e.getMessage(), e); + } + } + if (out != null) { + try { + out.close(); + } catch (IOException e) { + Log_OC.d(TAG, e.getMessage(), e); + } + } } ArrayList operations = @@ -810,17 +829,16 @@ public class FileDataStorageManager { new String[]{String.valueOf(parentId)}, null); } - if (c.moveToFirst()) { + if (c != null && c.moveToFirst()) { do { OCFile child = createFileInstance(c); - if (child.isFolder() || !onlyOnDevice || onlyOnDevice && child.isDown()){ - ret.add(child); + if (child.isFolder() || !onlyOnDevice || child.isDown()){ + ret.add(child); } } while (c.moveToNext()); + c.close(); } - c.close(); - Collections.sort(ret); return ret; @@ -841,7 +859,7 @@ public class FileDataStorageManager { c = getContentResolver() .query(ProviderTableMeta.CONTENT_URI, null, - cmp_key + "=? AND " + cmp_key + AND + ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?", new String[]{value, mAccount.name}, null); @@ -850,7 +868,7 @@ public class FileDataStorageManager { c = getContentProviderClient().query( ProviderTableMeta.CONTENT_URI, null, - cmp_key + "=? AND " + cmp_key + AND + ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?", new String[]{value, mAccount.name}, null); } catch (RemoteException e) { @@ -871,7 +889,7 @@ public class FileDataStorageManager { c = getContentResolver() .query(ProviderTableMeta.CONTENT_URI, null, - key + "=? AND " + key + AND + ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?", new String[]{value, mAccount.name}, null); @@ -880,7 +898,7 @@ public class FileDataStorageManager { c = getContentProviderClient().query( ProviderTableMeta.CONTENT_URI, null, - key + "=? AND " + ProviderTableMeta.FILE_ACCOUNT_OWNER + key + AND + ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?", new String[]{value, mAccount.name}, null); } catch (RemoteException e) { @@ -983,8 +1001,7 @@ public class FileDataStorageManager { new String[]{String.valueOf(share.getRemoteId())}); } catch (RemoteException e) { Log_OC.e(TAG, - "Fail to insert insert file to database " - + e.getMessage()); + FAILED_TO_INSERT_MSG + e.getMessage()); } } } else { @@ -998,8 +1015,7 @@ public class FileDataStorageManager { ProviderTableMeta.CONTENT_URI_SHARE, cv); } catch (RemoteException e) { Log_OC.e(TAG, - "Fail to insert insert file to database " - + e.getMessage()); + FAILED_TO_INSERT_MSG + e.getMessage()); } } if (result_uri != null) { @@ -1076,7 +1092,7 @@ public class FileDataStorageManager { c = getContentResolver() .query(ProviderTableMeta.CONTENT_URI_SHARE, null, - key + "=? AND " + key + AND + ProviderTableMeta.OCSHARES_ACCOUNT_OWNER + "=?", new String[]{value, mAccount.name}, null @@ -1086,7 +1102,7 @@ public class FileDataStorageManager { c = getContentProviderClient().query( ProviderTableMeta.CONTENT_URI_SHARE, null, - key + "=? AND " + key + AND + ProviderTableMeta.OCSHARES_ACCOUNT_OWNER + "=?", new String[]{value, mAccount.name}, null @@ -1116,8 +1132,8 @@ public class FileDataStorageManager { shareWith = ""; } - String selection = ProviderTableMeta.OCSHARES_PATH + "=? AND " - + ProviderTableMeta.OCSHARES_SHARE_TYPE + "=? AND " + String selection = ProviderTableMeta.OCSHARES_PATH + AND + + ProviderTableMeta.OCSHARES_SHARE_TYPE + AND + ProviderTableMeta.OCSHARES_ACCOUNT_OWNER + "=?" ; if (!ShareType.PUBLIC_LINK.equals(type)) { selection += " AND " + ProviderTableMeta.OCSHARES_SHARE_WITH + "=?"; @@ -1223,7 +1239,7 @@ public class FileDataStorageManager { cv.put(ProviderTableMeta.FILE_SHARED_VIA_LINK, false); cv.put(ProviderTableMeta.FILE_SHARED_WITH_SHAREE, false); cv.put(ProviderTableMeta.FILE_PUBLIC_LINK, ""); - String where = ProviderTableMeta.FILE_ACCOUNT_OWNER + "=? AND " + + String where = ProviderTableMeta.FILE_ACCOUNT_OWNER + AND + ProviderTableMeta.FILE_PARENT + "=?"; String [] whereArgs = new String[] { mAccount.name , String.valueOf(folder.getFileId()) }; @@ -1245,7 +1261,7 @@ public class FileDataStorageManager { cv.put(ProviderTableMeta.FILE_SHARED_VIA_LINK, false); cv.put(ProviderTableMeta.FILE_SHARED_WITH_SHAREE, false); cv.put(ProviderTableMeta.FILE_PUBLIC_LINK, ""); - String where = ProviderTableMeta.FILE_ACCOUNT_OWNER + "=? AND " + + String where = ProviderTableMeta.FILE_ACCOUNT_OWNER + AND + ProviderTableMeta.FILE_PATH+ "=?"; String [] whereArgs = new String[] { mAccount.name , filePath }; @@ -1328,8 +1344,7 @@ public class FileDataStorageManager { if (operations.size() > 0) { @SuppressWarnings("unused") ContentProviderResult[] results = null; - Log_OC.d(TAG, "Sending " + operations.size() + - " operations to FileContentProvider"); + Log_OC.d(TAG, String.format(Locale.ENGLISH, SENDING_TO_FILECONTENTPROVIDER_MSG, operations.size())); try { if (getContentResolver() != null) { results = getContentResolver().applyBatch(MainApp.getAuthority(), @@ -1339,10 +1354,10 @@ public class FileDataStorageManager { } } catch (OperationApplicationException e) { - Log_OC.e(TAG, "Exception in batch of operations " + e.getMessage()); + Log_OC.e(TAG, EXCEPTION_MSG + e.getMessage()); } catch (RemoteException e) { - Log_OC.e(TAG, "Exception in batch of operations " + e.getMessage()); + Log_OC.e(TAG, EXCEPTION_MSG + e.getMessage()); } } } @@ -1420,8 +1435,7 @@ public class FileDataStorageManager { if (operations.size() > 0) { @SuppressWarnings("unused") ContentProviderResult[] results = null; - Log_OC.d(TAG, "Sending " + operations.size() + - " operations to FileContentProvider"); + Log_OC.d(TAG, String.format(Locale.ENGLISH, SENDING_TO_FILECONTENTPROVIDER_MSG, operations.size())); try { if (getContentResolver() != null) { results = getContentResolver().applyBatch(MainApp.getAuthority(), operations); @@ -1429,11 +1443,9 @@ public class FileDataStorageManager { results = getContentProviderClient().applyBatch(operations); } - } catch (OperationApplicationException e) { - Log_OC.e(TAG, "Exception in batch of operations " + e.getMessage()); + } catch (OperationApplicationException | RemoteException e) { + Log_OC.e(TAG, EXCEPTION_MSG + e.getMessage()); - } catch (RemoteException e) { - Log_OC.e(TAG, "Exception in batch of operations " + e.getMessage()); } } } @@ -1442,14 +1454,14 @@ public class FileDataStorageManager { public void removeShare(OCShare share) { Uri share_uri = ProviderTableMeta.CONTENT_URI_SHARE; - String where = ProviderTableMeta.OCSHARES_ACCOUNT_OWNER + "=?" + " AND " + + String where = ProviderTableMeta.OCSHARES_ACCOUNT_OWNER + AND + ProviderTableMeta._ID + "=?"; String [] whereArgs = new String[]{mAccount.name, Long.toString(share.getId())}; if (getContentProviderClient() != null) { try { getContentProviderClient().delete(share_uri, where, whereArgs); } catch (RemoteException e) { - e.printStackTrace(); + Log_OC.d(TAG, e.getMessage(), e); } } else { getContentResolver().delete(share_uri, where, whereArgs); @@ -1474,7 +1486,7 @@ public class FileDataStorageManager { // apply operations in batch if (operations.size() > 0) { - Log_OC.d(TAG, "Sending " + operations.size() + " operations to FileContentProvider"); + Log_OC.d(TAG, String.format(Locale.ENGLISH, SENDING_TO_FILECONTENTPROVIDER_MSG, operations.size())); try { if (getContentResolver() != null) { getContentResolver().applyBatch(MainApp.getAuthority(), operations); @@ -1483,11 +1495,9 @@ public class FileDataStorageManager { getContentProviderClient().applyBatch(operations); } - } catch (OperationApplicationException e) { - Log_OC.e(TAG, "Exception in batch of operations " + e.getMessage()); + } catch (OperationApplicationException | RemoteException e) { + Log_OC.e(TAG, EXCEPTION_MSG + e.getMessage()); - } catch (RemoteException e) { - Log_OC.e(TAG, "Exception in batch of operations " + e.getMessage()); } } @@ -1522,7 +1532,7 @@ public class FileDataStorageManager { operations = prepareRemoveSharesInFile(remotePath, operations); // apply operations in batch if (operations.size() > 0) { - Log_OC.d(TAG, "Sending " + operations.size() + " operations to FileContentProvider"); + Log_OC.d(TAG, String.format(Locale.ENGLISH, SENDING_TO_FILECONTENTPROVIDER_MSG, operations.size())); try { if (getContentResolver() != null) { getContentResolver().applyBatch(MainApp.getAuthority(), operations); @@ -1531,11 +1541,9 @@ public class FileDataStorageManager { getContentProviderClient().applyBatch(operations); } - } catch (OperationApplicationException e) { - Log_OC.e(TAG, "Exception in batch of operations " + e.getMessage()); + } catch (OperationApplicationException | RemoteException e) { + Log_OC.e(TAG, EXCEPTION_MSG + e.getMessage()); - } catch (RemoteException e) { - Log_OC.e(TAG, "Exception in batch of operations " + e.getMessage()); } } } @@ -1553,7 +1561,7 @@ public class FileDataStorageManager { // apply operations in batch if (operations.size() > 0) { - Log_OC.d(TAG, "Sending " + operations.size() + " operations to FileContentProvider"); + Log_OC.d(TAG, String.format(Locale.ENGLISH, SENDING_TO_FILECONTENTPROVIDER_MSG, operations.size())); try { if (getContentResolver() != null) { getContentResolver().applyBatch(MainApp.getAuthority(), operations); @@ -1563,10 +1571,8 @@ public class FileDataStorageManager { getContentProviderClient().applyBatch(operations); } - } catch (OperationApplicationException e) { - Log_OC.e(TAG, "Exception in batch of operations " + e.getMessage()); - - } catch (RemoteException e) { + } catch (OperationApplicationException | RemoteException e) { + Log_OC.e(TAG, EXCEPTION_MSG + e.getMessage()); } } @@ -1618,7 +1624,7 @@ public class FileDataStorageManager { private ArrayList prepareRemoveSharesInFolder( OCFile folder, ArrayList preparedOperations) { if (folder != null) { - String where = ProviderTableMeta.OCSHARES_PATH + "=?" + " AND " + String where = ProviderTableMeta.OCSHARES_PATH + AND + ProviderTableMeta.OCSHARES_ACCOUNT_OWNER + "=?"; String [] whereArgs = new String[]{ "", mAccount.name }; @@ -1640,7 +1646,7 @@ public class FileDataStorageManager { private ArrayList prepareRemoveSharesInFile( String filePath, ArrayList preparedOperations) { - String where = ProviderTableMeta.OCSHARES_PATH + "=?" + " AND " + String where = ProviderTableMeta.OCSHARES_PATH + AND + ProviderTableMeta.OCSHARES_ACCOUNT_OWNER + "=?"; String[] whereArgs = new String[]{filePath, mAccount.name}; @@ -1656,8 +1662,8 @@ public class FileDataStorageManager { public ArrayList getSharesWithForAFile(String filePath, String accountName){ // Condition - String where = ProviderTableMeta.OCSHARES_PATH + "=?" + " AND " - + ProviderTableMeta.OCSHARES_ACCOUNT_OWNER + "=?"+ "AND" + String where = ProviderTableMeta.OCSHARES_PATH + AND + + ProviderTableMeta.OCSHARES_ACCOUNT_OWNER + AND + " (" + ProviderTableMeta.OCSHARES_SHARE_TYPE + "=? OR " + ProviderTableMeta.OCSHARES_SHARE_TYPE + "=? OR " + ProviderTableMeta.OCSHARES_SHARE_TYPE + "=? ) "; @@ -1785,13 +1791,12 @@ public class FileDataStorageManager { } if (ancestorIds.size() > 0) { - StringBuffer whereBuffer = new StringBuffer(); + final StringBuffer whereBuffer = new StringBuffer(); whereBuffer.append(ProviderTableMeta._ID).append(" IN ("); for (int i = 0; i < ancestorIds.size() - 1; i++) { whereBuffer.append("?,"); } - whereBuffer.append("?"); - whereBuffer.append(")"); + whereBuffer.append("?)"); if (getContentResolver() != null) { updated = getContentResolver().update( @@ -1829,7 +1834,7 @@ public class FileDataStorageManager { String whereForDescencentsInConflict = ProviderTableMeta.FILE_ETAG_IN_CONFLICT + " IS NOT NULL AND " + ProviderTableMeta.FILE_CONTENT_TYPE + " != 'DIR' AND " + - ProviderTableMeta.FILE_ACCOUNT_OWNER + " = ? AND " + + ProviderTableMeta.FILE_ACCOUNT_OWNER + AND + ProviderTableMeta.FILE_PATH + " LIKE ?"; Cursor descendentsInConflict = null; if (getContentResolver() != null) { @@ -1859,7 +1864,7 @@ public class FileDataStorageManager { updated = getContentResolver().update( ProviderTableMeta.CONTENT_URI_FILE, cv, - ProviderTableMeta.FILE_ACCOUNT_OWNER + "=? AND " + + ProviderTableMeta.FILE_ACCOUNT_OWNER + AND + ProviderTableMeta.FILE_PATH + "=?", new String[]{mAccount.name, parentPath} ); @@ -1868,7 +1873,7 @@ public class FileDataStorageManager { updated = getContentProviderClient().update( ProviderTableMeta.CONTENT_URI_FILE, cv, - ProviderTableMeta.FILE_ACCOUNT_OWNER + "=? AND " + + ProviderTableMeta.FILE_ACCOUNT_OWNER + AND + ProviderTableMeta.FILE_PATH + "=?" , new String[]{mAccount.name, parentPath} ); @@ -1944,8 +1949,7 @@ public class FileDataStorageManager { new String[]{mAccount.name}); } catch (RemoteException e) { Log_OC.e(TAG, - "Fail to insert insert file to database " - + e.getMessage()); + FAILED_TO_INSERT_MSG + e.getMessage()); } } } else { @@ -1959,8 +1963,7 @@ public class FileDataStorageManager { ProviderTableMeta.CONTENT_URI_CAPABILITIES, cv); } catch (RemoteException e) { Log_OC.e(TAG, - "Fail to insert insert capability to database " - + e.getMessage()); + FAILED_TO_INSERT_MSG + e.getMessage()); } } if (result_uri != null) { diff --git a/src/com/owncloud/android/datamodel/OCFile.java b/src/com/owncloud/android/datamodel/OCFile.java index 34761b98f3..bfc5031dcd 100644 --- a/src/com/owncloud/android/datamodel/OCFile.java +++ b/src/com/owncloud/android/datamodel/OCFile.java @@ -549,8 +549,12 @@ public class OCFile implements Parcelable, Comparable { @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } OCFile ocFile = (OCFile) o; @@ -643,7 +647,7 @@ public class OCFile implements Parcelable, Comparable { } public boolean isInConflict() { - return mEtagInConflict != null && mEtagInConflict != ""; + return mEtagInConflict != null && !mEtagInConflict.equals(""); } public void setEtagInConflict(String etagInConflict) { diff --git a/src/com/owncloud/android/datamodel/ThumbnailsCacheManager.java b/src/com/owncloud/android/datamodel/ThumbnailsCacheManager.java index 619c58645e..60fa0aa2c6 100644 --- a/src/com/owncloud/android/datamodel/ThumbnailsCacheManager.java +++ b/src/com/owncloud/android/datamodel/ThumbnailsCacheManager.java @@ -163,15 +163,17 @@ public class ThumbnailsCacheManager { Account account) { // Use a WeakReference to ensure the ImageView can be garbage collected mImageViewReference = new WeakReference(imageView); - if (storageManager == null) + if (storageManager == null) { throw new IllegalArgumentException("storageManager must not be NULL"); + } mStorageManager = storageManager; mAccount = account; } public ThumbnailGenerationTask(FileDataStorageManager storageManager, Account account){ - if (storageManager == null) + if (storageManager == null) { throw new IllegalArgumentException("storageManager must not be NULL"); + } mStorageManager = storageManager; mAccount = account; mImageViewReference = null; @@ -198,17 +200,17 @@ public class ThumbnailsCacheManager { } mFile = params[0]; - if (params.length == 2){ + if (params.length == 2) { mImageKey = (String) params[1]; } - + if (mFile instanceof OCFile) { thumbnail = doOCFileInBackground(); if (MimeTypeUtil.isVideo((OCFile) mFile) && thumbnail != null) { thumbnail = addVideoOverlay(thumbnail); } - } else if (mFile instanceof File) { + } else if (mFile instanceof File) { thumbnail = doFileInBackground(); String url = ((File) mFile).getAbsolutePath(); @@ -217,16 +219,15 @@ public class ThumbnailsCacheManager { if (MimeTypeUtil.isVideo(mMimeType) && thumbnail != null) { thumbnail = addVideoOverlay(thumbnail); } - //} else { do nothing + //} else { do nothing } - }catch(Throwable t){ - // the app should never break due to a problem with thumbnails - Log_OC.e(TAG, "Generation of thumbnail for " + mFile + " failed", t); - if (t instanceof OutOfMemoryError) { - System.gc(); - } - } + } catch(OutOfMemoryError oome) { + System.gc(); + } catch (Throwable t) { + // the app should never break due to a problem with thumbnails + Log_OC.e(TAG, "Generation of thumbnail for " + mFile + " failed", t); + } return thumbnail; } @@ -343,7 +344,7 @@ public class ThumbnailsCacheManager { mClient.exhaustResponse(get.getResponseBodyAsStream()); } } catch (Exception e) { - e.printStackTrace(); + Log_OC.d(TAG, e.getMessage(), e); } finally { if (get != null) { get.releaseConnection(); @@ -401,8 +402,9 @@ public class ThumbnailsCacheManager { FileDataStorageManager storageManager, Account account) { mAvatarGenerationListener = new WeakReference<>(avatarGenerationListener); mCallContext = callContext; - if (storageManager == null) + if (storageManager == null) { throw new IllegalArgumentException("storageManager must not be NULL"); + } mAccount = account; } @@ -422,12 +424,11 @@ public class ThumbnailsCacheManager { mUsername = params[0]; thumbnail = doAvatarInBackground(); + } catch(OutOfMemoryError oome) { + System.gc(); // todo, does this really make sense? } catch(Throwable t){ // the app should never break due to a problem with avatars Log_OC.e(TAG, "Generation of avatar for " + mUsername + " failed", t); - if (t instanceof OutOfMemoryError) { - System.gc(); - } } return thumbnail; @@ -435,15 +436,12 @@ public class ThumbnailsCacheManager { protected void onPostExecute(Bitmap bitmap) { if (bitmap != null) { - if (mAvatarGenerationListener != null) { - AvatarGenerationListener listener = mAvatarGenerationListener.get(); - AvatarGenerationTask avatarWorkerTask = getAvatarWorkerTask(mCallContext); - if (this == avatarWorkerTask) { - if (listener.shouldCallGeneratedCallback(mUsername, mCallContext)) { - listener.avatarGenerated(new BitmapDrawable(bitmap), mCallContext); - } + AvatarGenerationListener listener = mAvatarGenerationListener.get(); + AvatarGenerationTask avatarWorkerTask = getAvatarWorkerTask(mCallContext); + if (this == avatarWorkerTask + && listener.shouldCallGeneratedCallback(mUsername, mCallContext)) { + listener.avatarGenerated(new BitmapDrawable(bitmap), mCallContext); } - } } } @@ -537,7 +535,7 @@ public class ThumbnailsCacheManager { if (bitmapWorkerTask != null) { final Object bitmapData = bitmapWorkerTask.mFile; // If bitmapData is not yet set or it differs from the new data - if (bitmapData == null || bitmapData != file) { + if (bitmapData == null || !bitmapData.equals(file)) { // Cancel previous task bitmapWorkerTask.cancel(true); Log_OC.v(TAG, "Cancelled generation of thumbnail for a reused imageView"); @@ -551,10 +549,11 @@ public class ThumbnailsCacheManager { } public static boolean cancelPotentialAvatarWork(Object file, Object callContext) { - if (callContext instanceof ImageView) - return cancelPotentialAvatarWork(file, (ImageView)callContext); - else if (callContext instanceof MenuItem) + if (callContext instanceof ImageView) { + return cancelPotentialAvatarWork(file, (ImageView) callContext); + } else if (callContext instanceof MenuItem) { return cancelPotentialAvatarWork(file, (MenuItem)callContext); + } return false; } @@ -565,7 +564,7 @@ public class ThumbnailsCacheManager { if (avatarWorkerTask != null) { final Object usernameData = avatarWorkerTask.mUsername; // If usernameData is not yet set or it differs from the new data - if (usernameData == null || usernameData != file) { + if (usernameData == null || !usernameData.equals(file)) { // Cancel previous task avatarWorkerTask.cancel(true); Log_OC.v(TAG, "Cancelled generation of avatar for a reused imageView"); @@ -584,7 +583,7 @@ public class ThumbnailsCacheManager { if (avatarWorkerTask != null) { final Object usernameData = avatarWorkerTask.mUsername; // If usernameData is not yet set or it differs from the new data - if (usernameData == null || usernameData != file) { + if (usernameData == null || !usernameData.equals(file)) { // Cancel previous task avatarWorkerTask.cancel(true); Log_OC.v(TAG, "Cancelled generation of avatar for a reused imageView"); @@ -639,7 +638,6 @@ public class ThumbnailsCacheManager { // offset to top left double ox = - xm; - double oy = thumbnail.getHeight() - ym; c.drawBitmap(thumbnail, 0, 0, null); @@ -654,10 +652,11 @@ public class ThumbnailsCacheManager { } public static AvatarGenerationTask getAvatarWorkerTask(Object callContext) { - if (callContext instanceof ImageView) + if (callContext instanceof ImageView) { return getAvatarWorkerTask(((ImageView)callContext).getDrawable()); - else if (callContext instanceof MenuItem) + } else if (callContext instanceof MenuItem) { return getAvatarWorkerTask(((MenuItem)callContext).getIcon()); + } return null; } diff --git a/src/com/owncloud/android/datamodel/UploadsStorageManager.java b/src/com/owncloud/android/datamodel/UploadsStorageManager.java index 30cf568f18..a6d87e5858 100644 --- a/src/com/owncloud/android/datamodel/UploadsStorageManager.java +++ b/src/com/owncloud/android/datamodel/UploadsStorageManager.java @@ -43,6 +43,7 @@ import java.util.Observable; public class UploadsStorageManager extends Observable { private ContentResolver mContentResolver; + private static final String AND = " AND "; static private final String TAG = UploadsStorageManager.class.getSimpleName(); @@ -391,8 +392,8 @@ public class UploadsStorageManager extends Observable { */ public OCUpload[] getFailedButNotDelayedUploads() { return getUploads( - ProviderTableMeta.UPLOADS_STATUS + "==" + UploadStatus.UPLOAD_FAILED.value + " AND " + - ProviderTableMeta.UPLOADS_LAST_RESULT + "<>" + UploadResult.DELAYED_FOR_WIFI.getValue() + " AND " + + ProviderTableMeta.UPLOADS_STATUS + "==" + UploadStatus.UPLOAD_FAILED.value + AND + + ProviderTableMeta.UPLOADS_LAST_RESULT + "<>" + UploadResult.DELAYED_FOR_WIFI.getValue() + AND + ProviderTableMeta.UPLOADS_LAST_RESULT + "<>" + UploadResult.DELAYED_FOR_CHARGING.getValue(), null ); @@ -405,8 +406,8 @@ public class UploadsStorageManager extends Observable { public long clearFailedButNotDelayedUploads() { long result = getDB().delete( ProviderTableMeta.CONTENT_URI_UPLOADS, - ProviderTableMeta.UPLOADS_STATUS + "==" + UploadStatus.UPLOAD_FAILED.value + " AND " + - ProviderTableMeta.UPLOADS_LAST_RESULT + "<>" + UploadResult.DELAYED_FOR_WIFI.getValue() + " AND " + + ProviderTableMeta.UPLOADS_STATUS + "==" + UploadStatus.UPLOAD_FAILED.value + AND + + ProviderTableMeta.UPLOADS_LAST_RESULT + "<>" + UploadResult.DELAYED_FOR_WIFI.getValue() + AND + ProviderTableMeta.UPLOADS_LAST_RESULT + "<>" + UploadResult.DELAYED_FOR_CHARGING.getValue(), null ); @@ -436,7 +437,7 @@ public class UploadsStorageManager extends Observable { long result = getDB().delete( ProviderTableMeta.CONTENT_URI_UPLOADS, ProviderTableMeta.UPLOADS_STATUS + "=? OR " + ProviderTableMeta.UPLOADS_STATUS + "=? AND " + - ProviderTableMeta.UPLOADS_LAST_RESULT + "<>" + UploadResult.DELAYED_FOR_WIFI.getValue() + " AND " + + ProviderTableMeta.UPLOADS_LAST_RESULT + "<>" + UploadResult.DELAYED_FOR_WIFI.getValue() + AND + ProviderTableMeta.UPLOADS_LAST_RESULT + "<>" + UploadResult.DELAYED_FOR_CHARGING.getValue(), whereArgs ); diff --git a/src/com/owncloud/android/db/ProviderMeta.java b/src/com/owncloud/android/db/ProviderMeta.java index 6d7adbe4be..f9b54baa4c 100644 --- a/src/com/owncloud/android/db/ProviderMeta.java +++ b/src/com/owncloud/android/db/ProviderMeta.java @@ -43,17 +43,18 @@ public class ProviderMeta { public static final String OCSHARES_TABLE_NAME = "ocshares"; public static final String CAPABILITIES_TABLE_NAME = "capabilities"; public static final String UPLOADS_TABLE_NAME = "list_of_uploads"; - public static final Uri CONTENT_URI = Uri.parse("content://" + private static final String CONTENT_PREFIX = "content://"; + public static final Uri CONTENT_URI = Uri.parse(CONTENT_PREFIX + MainApp.getAuthority() + "/"); - public static final Uri CONTENT_URI_FILE = Uri.parse("content://" + public static final Uri CONTENT_URI_FILE = Uri.parse(CONTENT_PREFIX + MainApp.getAuthority() + "/file"); - public static final Uri CONTENT_URI_DIR = Uri.parse("content://" + public static final Uri CONTENT_URI_DIR = Uri.parse(CONTENT_PREFIX + MainApp.getAuthority() + "/dir"); - public static final Uri CONTENT_URI_SHARE = Uri.parse("content://" + public static final Uri CONTENT_URI_SHARE = Uri.parse(CONTENT_PREFIX + MainApp.getAuthority() + "/shares"); - public static final Uri CONTENT_URI_CAPABILITIES = Uri.parse("content://" + public static final Uri CONTENT_URI_CAPABILITIES = Uri.parse(CONTENT_PREFIX + MainApp.getAuthority() + "/capabilities"); - public static final Uri CONTENT_URI_UPLOADS = Uri.parse("content://" + public static final Uri CONTENT_URI_UPLOADS = Uri.parse(CONTENT_PREFIX + MainApp.getAuthority() + "/uploads"); public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.owncloud.file"; diff --git a/src/com/owncloud/android/files/BootupBroadcastReceiver.java b/src/com/owncloud/android/files/BootupBroadcastReceiver.java index 84436a0298..d4921f337d 100644 --- a/src/com/owncloud/android/files/BootupBroadcastReceiver.java +++ b/src/com/owncloud/android/files/BootupBroadcastReceiver.java @@ -35,7 +35,7 @@ import android.content.Intent; */ public class BootupBroadcastReceiver extends BroadcastReceiver { - private static String TAG = BootupBroadcastReceiver.class.getSimpleName(); + private static final String TAG = BootupBroadcastReceiver.class.getSimpleName(); /** * Receives broadcast intent reporting that the system was just boot up. diff --git a/src/com/owncloud/android/files/InstantUploadBroadcastReceiver.java b/src/com/owncloud/android/files/InstantUploadBroadcastReceiver.java index c1bf93f3be..d3cef17860 100644 --- a/src/com/owncloud/android/files/InstantUploadBroadcastReceiver.java +++ b/src/com/owncloud/android/files/InstantUploadBroadcastReceiver.java @@ -42,17 +42,17 @@ import com.owncloud.android.utils.FileStorageUtils; public class InstantUploadBroadcastReceiver extends BroadcastReceiver { - private static String TAG = InstantUploadBroadcastReceiver.class.getName(); + private static final String TAG = InstantUploadBroadcastReceiver.class.getName(); // Image action // Unofficial action, works for most devices but not HTC. See: https://github.com/owncloud/android/issues/6 - private static String NEW_PHOTO_ACTION_UNOFFICIAL = "com.android.camera.NEW_PICTURE"; + private static final String NEW_PHOTO_ACTION_UNOFFICIAL = "com.android.camera.NEW_PICTURE"; // Officially supported action since SDK 14: // http://developer.android.com/reference/android/hardware/Camera.html#ACTION_NEW_PICTURE - private static String NEW_PHOTO_ACTION = "android.hardware.action.NEW_PICTURE"; + private static final String NEW_PHOTO_ACTION = "android.hardware.action.NEW_PICTURE"; // Video action // Officially supported action since SDK 14: // http://developer.android.com/reference/android/hardware/Camera.html#ACTION_NEW_VIDEO - private static String NEW_VIDEO_ACTION = "android.hardware.action.NEW_VIDEO"; + private static final String NEW_VIDEO_ACTION = "android.hardware.action.NEW_VIDEO"; @Override public void onReceive(Context context, Intent intent) { diff --git a/src/com/owncloud/android/files/services/ConnectivityActionReceiver.java b/src/com/owncloud/android/files/services/ConnectivityActionReceiver.java index 83f46e8486..ce698d10a6 100755 --- a/src/com/owncloud/android/files/services/ConnectivityActionReceiver.java +++ b/src/com/owncloud/android/files/services/ConnectivityActionReceiver.java @@ -70,22 +70,20 @@ public class ConnectivityActionReceiver extends BroadcastReceiver { Log_OC.v(TAG, "no extras"); } - if (intent.getAction().equals(Intent.ACTION_POWER_CONNECTED)) { + if (intent.getAction().equals(Intent.ACTION_POWER_CONNECTED) && + (PreferenceManager.instantPictureUploadEnabled(context) && + PreferenceManager.instantPictureUploadWhenChargingOnly(context)) || + (PreferenceManager.instantVideoUploadEnabled(context) && + PreferenceManager.instantVideoUploadWhenChargingOnly(context)) + ) { // for the moment, only recovery of instant uploads, similar to behaviour in release 1.9.1 - if ( - (PreferenceManager.instantPictureUploadEnabled(context) && - PreferenceManager.instantPictureUploadWhenChargingOnly(context)) || - (PreferenceManager.instantVideoUploadEnabled(context) && - PreferenceManager.instantVideoUploadWhenChargingOnly(context)) - ) { - Log_OC.d(TAG, "Requesting retry of instant uploads (& friends) due to charging"); - FileUploader.UploadRequester requester = new FileUploader.UploadRequester(); - requester.retryFailedUploads( - context, - null, - UploadResult.DELAYED_FOR_CHARGING // for the rest of enqueued when Wifi fell - ); - } + Log_OC.d(TAG, "Requesting retry of instant uploads (& friends) due to charging"); + FileUploader.UploadRequester requester = new FileUploader.UploadRequester(); + requester.retryFailedUploads( + context, + null, + UploadResult.DELAYED_FOR_CHARGING // for the rest of enqueued when Wifi fell + ); } /** diff --git a/src/com/owncloud/android/files/services/FileDownloader.java b/src/com/owncloud/android/files/services/FileDownloader.java index f3ac5a0048..40abc46b6e 100644 --- a/src/com/owncloud/android/files/services/FileDownloader.java +++ b/src/com/owncloud/android/files/services/FileDownloader.java @@ -297,7 +297,9 @@ public class FileDownloader extends Service * @param file A file that could be in the queue of downloads. */ public boolean isDownloading(Account account, OCFile file) { - if (account == null || file == null) return false; + if (account == null || file == null) { + return false; + } return (mPendingDownloads.contains(account.name, file.getRemotePath())); } @@ -312,7 +314,9 @@ public class FileDownloader extends Service public void addDatatransferProgressListener( OnDatatransferProgressListener listener, Account account, OCFile file ) { - if (account == null || file == null || listener == null) return; + if (account == null || file == null || listener == null) { + return; + } mBoundListeners.put(file.getFileId(), listener); } @@ -327,7 +331,9 @@ public class FileDownloader extends Service public void removeDatatransferProgressListener( OnDatatransferProgressListener listener, Account account, OCFile file ) { - if (account == null || file == null || listener == null) return; + if (account == null || file == null || listener == null) { + return; + } Long fileId = file.getFileId(); if (mBoundListeners.get(fileId) == listener) { mBoundListeners.remove(fileId); @@ -359,8 +365,9 @@ public class FileDownloader extends Service public ServiceHandler(Looper looper, FileDownloader service) { super(looper); - if (service == null) + if (service == null) { throw new IllegalArgumentException("Received invalid NULL in parameter 'service'"); + } mService = service; } diff --git a/src/com/owncloud/android/files/services/FileUploader.java b/src/com/owncloud/android/files/services/FileUploader.java index a166ed9eed..d63e7a9e81 100644 --- a/src/com/owncloud/android/files/services/FileUploader.java +++ b/src/com/owncloud/android/files/services/FileUploader.java @@ -721,8 +721,9 @@ public class FileUploader extends Service * @param file A file that could be in the queue of pending uploads */ public boolean isUploading(Account account, OCFile file) { - if (account == null || file == null) + if (account == null || file == null) { return false; + } return (mPendingUploads.contains(account.name, file.getRemotePath())); } @@ -750,7 +751,9 @@ public class FileUploader extends Service Account account, OCFile file ) { - if (account == null || file == null || listener == null) return; + if (account == null || file == null || listener == null) { + return; + } String targetKey = buildRemoteName(account.name, file.getRemotePath()); mBoundListeners.put(targetKey, listener); } @@ -766,7 +769,9 @@ public class FileUploader extends Service OnDatatransferProgressListener listener, OCUpload ocUpload ) { - if (ocUpload == null || listener == null) return; + if (ocUpload == null || listener == null) { + return; + } String targetKey = buildRemoteName(ocUpload.getAccountName(), ocUpload.getRemotePath()); mBoundListeners.put(targetKey, listener); } @@ -784,7 +789,9 @@ public class FileUploader extends Service Account account, OCFile file ) { - if (account == null || file == null || listener == null) return; + if (account == null || file == null || listener == null) { + return; + } String targetKey = buildRemoteName(account.name, file.getRemotePath()); if (mBoundListeners.get(targetKey) == listener) { mBoundListeners.remove(targetKey); @@ -802,7 +809,9 @@ public class FileUploader extends Service OnDatatransferProgressListener listener, OCUpload ocUpload ) { - if (ocUpload == null || listener == null) return; + if (ocUpload == null || listener == null) { + return; + } String targetKey = buildRemoteName(ocUpload.getAccountName(), ocUpload.getRemotePath()); if (mBoundListeners.get(targetKey) == listener) { mBoundListeners.remove(targetKey); @@ -851,8 +860,9 @@ public class FileUploader extends Service public ServiceHandler(Looper looper, FileUploader service) { super(looper); - if (service == null) + if (service == null) { throw new IllegalArgumentException("Received invalid NULL in parameter 'service'"); + } mService = service; } diff --git a/src/com/owncloud/android/files/services/IndexedForest.java b/src/com/owncloud/android/files/services/IndexedForest.java index bff8220423..b6e7c843e8 100644 --- a/src/com/owncloud/android/files/services/IndexedForest.java +++ b/src/com/owncloud/android/files/services/IndexedForest.java @@ -43,6 +43,7 @@ public class IndexedForest { private ConcurrentMap> mMap = new ConcurrentHashMap>(); + @SuppressWarnings("PMD.ShortClassName") private class Node { String mKey = null; Node mParent = null; @@ -168,7 +169,6 @@ public class IndexedForest { /// remove ancestors if only here due to firstRemoved Node removed = firstRemoved; Node parent = removed.getParent(); - boolean unlinked = false; while (parent != null) { parent.removeChild(removed); if (!parent.hasChildren()) { diff --git a/src/com/owncloud/android/files/services/OnUploadCompletedListener.java b/src/com/owncloud/android/files/services/OnUploadCompletedListener.java deleted file mode 100644 index f2ed3bbe87..0000000000 --- a/src/com/owncloud/android/files/services/OnUploadCompletedListener.java +++ /dev/null @@ -1,28 +0,0 @@ -/** - * ownCloud Android client application - * - * Copyright (C) 2012 Bartek Przybylski - * Copyright (C) 2015 ownCloud Inc. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License version 2, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - * - */ - -package com.owncloud.android.files.services; - -public interface OnUploadCompletedListener extends Runnable { - - public boolean getUploadResult(); - - public void setUploadResult(boolean result); -} diff --git a/src/com/owncloud/android/media/MediaControlView.java b/src/com/owncloud/android/media/MediaControlView.java index 0978f3436d..0163f9e0ee 100644 --- a/src/com/owncloud/android/media/MediaControlView.java +++ b/src/com/owncloud/android/media/MediaControlView.java @@ -65,8 +65,6 @@ public class MediaControlView extends FrameLayout /* implements OnLayoutChangeLi private TextView mEndTime, mCurrentTime; private boolean mDragging; private static final int SHOW_PROGRESS = 1; - StringBuilder mFormatBuilder; - Formatter mFormatter; private ImageButton mPauseButton; private ImageButton mFfwdButton; private ImageButton mRewButton; @@ -231,9 +229,6 @@ public class MediaControlView extends FrameLayout /* implements OnLayoutChangeLi mEndTime = (TextView) v.findViewById(R.id.totalTimeText); mCurrentTime = (TextView) v.findViewById(R.id.currentTimeText); - mFormatBuilder = new StringBuilder(); - mFormatter = new Formatter(mFormatBuilder, Locale.getDefault()); - } @@ -282,7 +277,8 @@ public class MediaControlView extends FrameLayout /* implements OnLayoutChangeLi int minutes = (totalSeconds / 60) % 60; int hours = totalSeconds / 3600; - mFormatBuilder.setLength(0); + final StringBuilder mFormatBuilder = new StringBuilder(); + final Formatter mFormatter = new Formatter(mFormatBuilder, Locale.getDefault()); if (hours > 0) { return mFormatter.format("%d:%02d:%02d", hours, minutes, seconds).toString(); } else { @@ -306,11 +302,12 @@ public class MediaControlView extends FrameLayout /* implements OnLayoutChangeLi mProgress.setSecondaryProgress(percent * 10); } - if (mEndTime != null) + if (mEndTime != null) { mEndTime.setText(stringForTime(duration)); - if (mCurrentTime != null) + } + if (mCurrentTime != null) { mCurrentTime.setText(stringForTime(position)); - + } return position; } @@ -353,8 +350,9 @@ public class MediaControlView extends FrameLayout /* implements OnLayoutChangeLi } public void updatePausePlay() { - if (mRoot == null || mPauseButton == null) + if (mRoot == null || mPauseButton == null) { return; + } if (mPlayer.isPlaying()) { mPauseButton.setImageResource(android.R.drawable.ic_media_pause); @@ -404,7 +402,9 @@ public class MediaControlView extends FrameLayout /* implements OnLayoutChangeLi pos = mPlayer.getCurrentPosition(); pos -= 5000; mPlayer.seekTo(pos); - if (!playing) mPlayer.pause(); // necessary in some 2.3.x devices + if (!playing) { + mPlayer.pause(); // necessary in some 2.3.x devices + } setProgress(); break; @@ -412,7 +412,9 @@ public class MediaControlView extends FrameLayout /* implements OnLayoutChangeLi pos = mPlayer.getCurrentPosition(); pos += 15000; mPlayer.seekTo(pos); - if (!playing) mPlayer.pause(); // necessary in some 2.3.x devices + if (!playing) { + mPlayer.pause(); // necessary in some 2.3.x devices + } setProgress(); break; } @@ -430,8 +432,9 @@ public class MediaControlView extends FrameLayout /* implements OnLayoutChangeLi long duration = mPlayer.getDuration(); long newposition = (duration * progress) / 1000L; mPlayer.seekTo( (int) newposition); - if (mCurrentTime != null) - mCurrentTime.setText(stringForTime( (int) newposition)); + if (mCurrentTime != null) { + mCurrentTime.setText(stringForTime((int) newposition)); + } } /** diff --git a/src/com/owncloud/android/media/MediaService.java b/src/com/owncloud/android/media/MediaService.java index f7ca1689f5..a3ba705cc4 100644 --- a/src/com/owncloud/android/media/MediaService.java +++ b/src/com/owncloud/android/media/MediaService.java @@ -621,16 +621,18 @@ public class MediaService extends Service implements OnCompletionListener, OnPre // focus gain; check AudioManager.AUDIOFOCUS_* values mAudioFocus = AudioFocus.FOCUS; // restart media player with new focus settings - if (mState == State.PLAYING) + if (mState == State.PLAYING) { configAndStartMediaPlayer(); + } } else if (focusChange < 0) { // focus loss; check AudioManager.AUDIOFOCUS_* values boolean canDuck = AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK == focusChange; mAudioFocus = canDuck ? AudioFocus.NO_FOCUS_CAN_DUCK : AudioFocus.NO_FOCUS; // start/restart/pause media player with new focus settings - if (mPlayer != null && mPlayer.isPlaying()) + if (mPlayer != null && mPlayer.isPlaying()) { configAndStartMediaPlayer(); + } } } diff --git a/src/com/owncloud/android/operations/CreateShareWithShareeOperation.java b/src/com/owncloud/android/operations/CreateShareWithShareeOperation.java index 4aab4b40b7..7c4405a3c3 100644 --- a/src/com/owncloud/android/operations/CreateShareWithShareeOperation.java +++ b/src/com/owncloud/android/operations/CreateShareWithShareeOperation.java @@ -85,11 +85,9 @@ public class CreateShareWithShareeOperation extends SyncOperation { RemoteOperationResult result = operation.execute(client); - if (result.isSuccess()) { - if (result.getData().size() > 0) { - OCShare share = (OCShare) result.getData().get(0); - updateData(share); - } + if (result.isSuccess() && result.getData().size() > 0) { + OCShare share = (OCShare) result.getData().get(0); + updateData(share); } return result; diff --git a/src/com/owncloud/android/operations/DownloadFileOperation.java b/src/com/owncloud/android/operations/DownloadFileOperation.java index dff8aef18f..e2d56b29ed 100644 --- a/src/com/owncloud/android/operations/DownloadFileOperation.java +++ b/src/com/owncloud/android/operations/DownloadFileOperation.java @@ -58,16 +58,17 @@ public class DownloadFileOperation extends RemoteOperation { public DownloadFileOperation(Account account, OCFile file) { - if (account == null) + if (account == null) { throw new IllegalArgumentException("Illegal null account in DownloadFileOperation " + "creation"); - if (file == null) + } + if (file == null) { throw new IllegalArgumentException("Illegal null file in DownloadFileOperation " + "creation"); + } mAccount = account; mFile = file; - } @@ -162,9 +163,10 @@ public class DownloadFileOperation extends RemoteOperation { newFile = new File(getSavePath()); newFile.getParentFile().mkdirs(); moved = tmpFile.renameTo(newFile); - if (!moved) + if (!moved) { result = new RemoteOperationResult( RemoteOperationResult.ResultCode.LOCAL_STORAGE_NOT_MOVED); + } } Log_OC.i(TAG, "Download of " + mFile.getRemotePath() + " to " + getSavePath() + ": " + result.getLogMessage()); diff --git a/src/com/owncloud/android/operations/GetCapabilitiesOperarion.java b/src/com/owncloud/android/operations/GetCapabilitiesOperarion.java index 0a63449d96..a192683b2f 100644 --- a/src/com/owncloud/android/operations/GetCapabilitiesOperarion.java +++ b/src/com/owncloud/android/operations/GetCapabilitiesOperarion.java @@ -35,14 +35,13 @@ public class GetCapabilitiesOperarion extends SyncOperation { GetRemoteCapabilitiesOperation getCapabilities = new GetRemoteCapabilitiesOperation(); RemoteOperationResult result = getCapabilities.execute(client); - if (result.isSuccess()){ + if (result.isSuccess() + && result.getData() != null && result.getData().size() > 0) { // Read data from the result - if( result.getData()!= null && result.getData().size() > 0) { - OCCapability capability = (OCCapability) result.getData().get(0); + OCCapability capability = (OCCapability) result.getData().get(0); - // Save the capabilities into database - getStorageManager().saveCapabilities(capability); - } + // Save the capabilities into database + getStorageManager().saveCapabilities(capability); } return result; diff --git a/src/com/owncloud/android/operations/OAuth2GetAccessToken.java b/src/com/owncloud/android/operations/OAuth2GetAccessToken.java index 590f018b2a..91f039d9f0 100644 --- a/src/com/owncloud/android/operations/OAuth2GetAccessToken.java +++ b/src/com/owncloud/android/operations/OAuth2GetAccessToken.java @@ -65,6 +65,7 @@ public class OAuth2GetAccessToken extends RemoteOperation { */ @Override + @SuppressWarnings("PMD.AvoidDuplicateLiterals") protected RemoteOperationResult run(OwnCloudClient client) { RemoteOperationResult result = null; PostMethod postMethod = null; @@ -115,20 +116,20 @@ public class OAuth2GetAccessToken extends RemoteOperation { result = new RemoteOperationResult(e); } finally { - if (postMethod != null) + if (postMethod != null) { postMethod.releaseConnection(); // let the connection available for other methods - - if (result.isSuccess()) { - Log_OC.i(TAG, "OAuth2 TOKEN REQUEST with auth code " + mOAuth2ParsedAuthorizationResponse.get("code") + " to " + client.getWebdavUri() + ": " + result.getLogMessage()); - + } + + final String code = "code"; + final String oauth_token_request = "OAuth2 TOKEN REQUEST with auth code "; + if (result != null && result.isSuccess()) { + Log_OC.i(TAG, oauth_token_request + mOAuth2ParsedAuthorizationResponse.get(code) + " to " + client.getWebdavUri() + ": " + result.getLogMessage()); } else if (result.getException() != null) { - Log_OC.e(TAG, "OAuth2 TOKEN REQUEST with auth code " + mOAuth2ParsedAuthorizationResponse.get("code") + " to " + client.getWebdavUri() + ": " + result.getLogMessage(), result.getException()); - + Log_OC.e(TAG, oauth_token_request + mOAuth2ParsedAuthorizationResponse.get(code) + " to " + client.getWebdavUri() + ": " + result.getLogMessage(), result.getException()); } else if (result.getCode() == ResultCode.OAUTH2_ERROR) { - Log_OC.e(TAG, "OAuth2 TOKEN REQUEST with auth code " + mOAuth2ParsedAuthorizationResponse.get("code") + " to " + client.getWebdavUri() + ": " + ((mResultTokenMap != null) ? mResultTokenMap.get(OAuth2Constants.KEY_ERROR) : "NULL")); - + Log_OC.e(TAG, oauth_token_request + mOAuth2ParsedAuthorizationResponse.get(code) + " to " + client.getWebdavUri() + ": " + ((mResultTokenMap != null) ? mResultTokenMap.get(OAuth2Constants.KEY_ERROR) : "NULL")); } else { - Log_OC.e(TAG, "OAuth2 TOKEN REQUEST with auth code " + mOAuth2ParsedAuthorizationResponse.get("code") + " to " + client.getWebdavUri() + ": " + result.getLogMessage()); + Log_OC.e(TAG, oauth_token_request + mOAuth2ParsedAuthorizationResponse.get(code) + " to " + client.getWebdavUri() + ": " + result.getLogMessage()); } } diff --git a/src/com/owncloud/android/operations/RefreshFolderOperation.java b/src/com/owncloud/android/operations/RefreshFolderOperation.java index 87ee85298d..b44a4f3a15 100644 --- a/src/com/owncloud/android/operations/RefreshFolderOperation.java +++ b/src/com/owncloud/android/operations/RefreshFolderOperation.java @@ -58,6 +58,7 @@ import java.util.Vector; * * Does NOT enter in the child folders to synchronize their contents also. */ +@SuppressWarnings("PMD.AvoidDuplicateLiterals") public class RefreshFolderOperation extends RemoteOperation { private static final String TAG = RefreshFolderOperation.class.getSimpleName(); @@ -319,8 +320,9 @@ public class RefreshFolderOperation extends RemoteOperation { // should be a different result code, but will do the job } } else { - if (result.getCode() == ResultCode.FILE_NOT_FOUND) + if (result.getCode() == ResultCode.FILE_NOT_FOUND) { removeLocalFolder(); + } } return result; diff --git a/src/com/owncloud/android/operations/RenameFileOperation.java b/src/com/owncloud/android/operations/RenameFileOperation.java index a4cfa0211c..9e27b00c50 100644 --- a/src/com/owncloud/android/operations/RenameFileOperation.java +++ b/src/com/owncloud/android/operations/RenameFileOperation.java @@ -25,6 +25,7 @@ import java.io.File; import java.io.IOException; import com.owncloud.android.MainApp; +import com.owncloud.android.datamodel.FileDataStorageManager; import com.owncloud.android.datamodel.OCFile; import com.owncloud.android.lib.common.OwnCloudClient; import com.owncloud.android.lib.common.operations.RemoteOperationResult; @@ -128,8 +129,9 @@ public class RenameFileOperation extends SyncOperation { String oldPath = mFile.getStoragePath(); File f = new File(oldPath); String parentStoragePath = f.getParent(); - if (!parentStoragePath.endsWith(File.separator)) + if (!parentStoragePath.endsWith(File.separator)) { parentStoragePath += File.separator; + } if (f.renameTo(new File(parentStoragePath + mNewName))) { String newPath = parentStoragePath + mNewName; mFile.setStoragePath(newPath); @@ -137,7 +139,7 @@ public class RenameFileOperation extends SyncOperation { // notify MediaScanner about removed file getStorageManager().deleteFileInMediaScan(oldPath); // notify to scan about new file - getStorageManager().triggerMediaScan(newPath); + FileDataStorageManager.triggerMediaScan(newPath); } // else - NOTHING: the link to the local file is kept although the local name // can't be updated diff --git a/src/com/owncloud/android/operations/SynchronizeFileOperation.java b/src/com/owncloud/android/operations/SynchronizeFileOperation.java index 7d89a43fd7..fb311d657a 100644 --- a/src/com/owncloud/android/operations/SynchronizeFileOperation.java +++ b/src/com/owncloud/android/operations/SynchronizeFileOperation.java @@ -24,6 +24,7 @@ package com.owncloud.android.operations; import android.accounts.Account; import android.content.Context; import android.content.Intent; +import android.util.Log; import com.owncloud.android.datamodel.OCFile; import com.owncloud.android.files.services.FileDownloader; @@ -43,7 +44,7 @@ import com.owncloud.android.utils.FileStorageUtils; public class SynchronizeFileOperation extends SyncOperation { - private String TAG = SynchronizeFileOperation.class.getSimpleName(); + private static final String TAG = SynchronizeFileOperation.class.getSimpleName(); private OCFile mLocalFile; private String mRemotePath; @@ -234,6 +235,7 @@ public class SynchronizeFileOperation extends SyncOperation { // So, an instance of SynchronizeFileOperation created with // syncFileContents == false is completely useless when we suspect // that an upload is necessary (for instance, in FileObserverService). + Log_OC.d(TAG, "Nothing to do here"); } result = new RemoteOperationResult(ResultCode.OK); diff --git a/src/com/owncloud/android/operations/SynchronizeFolderOperation.java b/src/com/owncloud/android/operations/SynchronizeFolderOperation.java index 2582023bbd..2f19253dac 100644 --- a/src/com/owncloud/android/operations/SynchronizeFolderOperation.java +++ b/src/com/owncloud/android/operations/SynchronizeFolderOperation.java @@ -233,8 +233,9 @@ public class SynchronizeFolderOperation extends SyncOperation { // should be a different result code, but will do the job } } else { - if (result.getCode() == ResultCode.FILE_NOT_FOUND) + if (result.getCode() == ResultCode.FILE_NOT_FOUND) { removeLocalFolder(); + } } diff --git a/src/com/owncloud/android/operations/UpdateOCVersionOperation.java b/src/com/owncloud/android/operations/UpdateOCVersionOperation.java index d2bf5f3311..6db21f0def 100644 --- a/src/com/owncloud/android/operations/UpdateOCVersionOperation.java +++ b/src/com/owncloud/android/operations/UpdateOCVersionOperation.java @@ -107,8 +107,9 @@ public class UpdateOCVersionOperation extends RemoteOperation { Log_OC.e(TAG, "Check for update of ownCloud server version at " + client.getWebdavUri() + ": " + result.getLogMessage(), e); } finally { - if (get != null) + if (get != null) { get.releaseConnection(); + } } return result; } diff --git a/src/com/owncloud/android/operations/UploadFileOperation.java b/src/com/owncloud/android/operations/UploadFileOperation.java index 0b2e9d99a9..33e6f42f43 100644 --- a/src/com/owncloud/android/operations/UploadFileOperation.java +++ b/src/com/owncloud/android/operations/UploadFileOperation.java @@ -147,11 +147,13 @@ public class UploadFileOperation extends SyncOperation { int localBehaviour, Context context ) { - if (account == null) + if (account == null) { throw new IllegalArgumentException("Illegal NULL account in UploadFileOperation " + "creation"); - if (upload == null) + } + if (upload == null) { throw new IllegalArgumentException("Illegal NULL file in UploadFileOperation creation"); + } if (upload.getLocalPath() == null || upload.getLocalPath().length() <= 0) { throw new IllegalArgumentException( "Illegal file in UploadFileOperation; storage path invalid: " @@ -286,6 +288,7 @@ public class UploadFileOperation extends SyncOperation { } @Override + @SuppressWarnings("PMD.AvoidDuplicateLiterals") protected RemoteOperationResult run(OwnCloudClient client) { mCancellationRequested.set(false); mUploadStarted.set(true); @@ -308,7 +311,7 @@ public class UploadFileOperation extends SyncOperation { /// check if the file continues existing before schedule the operation if (!originalFile.exists()) { - Log_OC.d(TAG, mOriginalStoragePath.toString() + " not exists anymore"); + Log_OC.d(TAG, mOriginalStoragePath + " not exists anymore"); return new RemoteOperationResult(ResultCode.LOCAL_FILE_NOT_FOUND); } @@ -581,7 +584,7 @@ public class UploadFileOperation extends SyncOperation { return remotePath; } - int pos = remotePath.lastIndexOf("."); + int pos = remotePath.lastIndexOf('.'); String suffix = ""; String extension = ""; if (pos >= 0) { @@ -709,15 +712,17 @@ public class UploadFileOperation extends SyncOperation { } finally { try { - if (in != null) + if (in != null) { in.close(); + } } catch (Exception e) { Log_OC.d(TAG, "Weird exception while closing input stream for " + mOriginalStoragePath + " (ignoring)", e); } try { - if (out != null) + if (out != null) { out.close(); + } } catch (Exception e) { Log_OC.d(TAG, "Weird exception while closing output stream for " + targetFile.getAbsolutePath() + " (ignoring)", e); @@ -760,8 +765,12 @@ public class UploadFileOperation extends SyncOperation { // the best option could be show a warning message } finally { - if (inChannel != null) inChannel.close(); - if (outChannel != null) outChannel.close(); + if (inChannel != null) { + inChannel.close(); + } + if (outChannel != null) { + outChannel.close(); + } } } diff --git a/src/com/owncloud/android/operations/common/SyncOperation.java b/src/com/owncloud/android/operations/common/SyncOperation.java index 3d917d2ab1..a09f17eaf9 100644 --- a/src/com/owncloud/android/operations/common/SyncOperation.java +++ b/src/com/owncloud/android/operations/common/SyncOperation.java @@ -85,9 +85,10 @@ public abstract class SyncOperation extends RemoteOperation { */ public RemoteOperationResult execute(OwnCloudClient client, FileDataStorageManager storageManager) { - if (storageManager == null) + if (storageManager == null) { throw new IllegalArgumentException("Trying to execute a sync operation with a " + "NULL storage manager"); + } mStorageManager = storageManager; return super.execute(client); } diff --git a/src/com/owncloud/android/providers/FileContentProvider.java b/src/com/owncloud/android/providers/FileContentProvider.java index 11796fa6ee..e765abdd12 100644 --- a/src/com/owncloud/android/providers/FileContentProvider.java +++ b/src/com/owncloud/android/providers/FileContentProvider.java @@ -55,10 +55,12 @@ import com.owncloud.android.utils.MimeType; import java.io.File; import java.util.ArrayList; +import java.util.Locale; /** * The ContentProvider for the ownCloud App. */ +@SuppressWarnings("PMD.AvoidDuplicateLiterals") public class FileContentProvider extends ContentProvider { private DataBaseHelper mDbHelper; @@ -72,9 +74,15 @@ public class FileContentProvider extends ContentProvider { private static final String TAG = FileContentProvider.class.getSimpleName(); - private final String MAX_SUCCESSFUL_UPLOADS = "30"; - private UriMatcher mUriMatcher; + // todo avoid string concatenation and use string formatting instead later. + private static final String ERROR = "ERROR "; + private static final String SQL = "SQL"; + private static final String INTEGER = " INTEGER, "; + private static final String TEXT = " TEXT, "; + private static final String ALTER_TABLE = "ALTER TABLE "; + private static final String ADD_COLUMN = " ADD COLUMN "; + private static final String UPGRADE_VERSION_MSG = "OUT of the ADD in onUpgrade; oldVersion == %d, newVersion == %d"; @Override public int delete(Uri uri, String where, String[] whereArgs) { @@ -245,7 +253,7 @@ public class FileContentProvider extends ContentProvider { if (rowId > 0) { return ContentUris.withAppendedId(ProviderTableMeta.CONTENT_URI_FILE, rowId); } else { - throw new SQLException("ERROR " + uri); + throw new SQLException(ERROR + uri); } } else { // file is already inserted; race condition, let's avoid a duplicated entry @@ -265,7 +273,7 @@ public class FileContentProvider extends ContentProvider { insertedShareUri = ContentUris.withAppendedId(ProviderTableMeta.CONTENT_URI_SHARE, rowId); } else { - throw new SQLException("ERROR " + uri); + throw new SQLException(ERROR + uri); } updateFilesTableAccordingToShareInsertion(db, values); @@ -278,7 +286,7 @@ public class FileContentProvider extends ContentProvider { insertedCapUri = ContentUris.withAppendedId(ProviderTableMeta.CONTENT_URI_CAPABILITIES, id); } else { - throw new SQLException("ERROR " + uri); + throw new SQLException(ERROR + uri); } return insertedCapUri; @@ -291,7 +299,7 @@ public class FileContentProvider extends ContentProvider { ContentUris.withAppendedId(ProviderTableMeta.CONTENT_URI_UPLOADS, uploadId); trimSuccessfulUploads(db); } else { - throw new SQLException("ERROR " + uri); + throw new SQLException(ERROR + uri); } return insertedUploadUri; @@ -530,7 +538,7 @@ public class FileContentProvider extends ContentProvider { @Override public void onCreate(SQLiteDatabase db) { // files table - Log_OC.i("SQL", "Entering in onCreate"); + Log_OC.i(SQL, "Entering in onCreate"); createFilesTable(db); // Create ocshares table @@ -546,21 +554,21 @@ public class FileContentProvider extends ContentProvider { @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { - Log_OC.i("SQL", "Entering in onUpgrade"); + Log_OC.i(SQL, "Entering in onUpgrade"); boolean upgraded = false; if (oldVersion == 1 && newVersion >= 2) { - Log_OC.i("SQL", "Entering in the #1 ADD in onUpgrade"); - db.execSQL("ALTER TABLE " + ProviderTableMeta.FILE_TABLE_NAME + - " ADD COLUMN " + ProviderTableMeta.FILE_KEEP_IN_SYNC + " INTEGER " + + Log_OC.i(SQL, "Entering in the #1 ADD in onUpgrade"); + db.execSQL(ALTER_TABLE + ProviderTableMeta.FILE_TABLE_NAME + + ADD_COLUMN + ProviderTableMeta.FILE_KEEP_IN_SYNC + " INTEGER " + " DEFAULT 0"); upgraded = true; } if (oldVersion < 3 && newVersion >= 3) { - Log_OC.i("SQL", "Entering in the #2 ADD in onUpgrade"); + Log_OC.i(SQL, "Entering in the #2 ADD in onUpgrade"); db.beginTransaction(); try { - db.execSQL("ALTER TABLE " + ProviderTableMeta.FILE_TABLE_NAME + - " ADD COLUMN " + ProviderTableMeta.FILE_LAST_SYNC_DATE_FOR_DATA + + db.execSQL(ALTER_TABLE + ProviderTableMeta.FILE_TABLE_NAME + + ADD_COLUMN + ProviderTableMeta.FILE_LAST_SYNC_DATE_FOR_DATA + " INTEGER " + " DEFAULT 0"); // assume there are not local changes pending to upload @@ -576,11 +584,11 @@ public class FileContentProvider extends ContentProvider { } } if (oldVersion < 4 && newVersion >= 4) { - Log_OC.i("SQL", "Entering in the #3 ADD in onUpgrade"); + Log_OC.i(SQL, "Entering in the #3 ADD in onUpgrade"); db.beginTransaction(); try { - db.execSQL("ALTER TABLE " + ProviderTableMeta.FILE_TABLE_NAME + - " ADD COLUMN " + ProviderTableMeta.FILE_MODIFIED_AT_LAST_SYNC_FOR_DATA + + db.execSQL(ALTER_TABLE + ProviderTableMeta.FILE_TABLE_NAME + + ADD_COLUMN + ProviderTableMeta.FILE_MODIFIED_AT_LAST_SYNC_FOR_DATA + " INTEGER " + " DEFAULT 0"); db.execSQL("UPDATE " + ProviderTableMeta.FILE_TABLE_NAME + @@ -594,16 +602,16 @@ public class FileContentProvider extends ContentProvider { db.endTransaction(); } } - if (!upgraded) - Log_OC.i("SQL", "OUT of the ADD in onUpgrade; oldVersion == " + oldVersion + - ", newVersion == " + newVersion); + if (!upgraded) { + Log_OC.i(SQL, String.format(Locale.ENGLISH, UPGRADE_VERSION_MSG, oldVersion, newVersion)); + } if (oldVersion < 5 && newVersion >= 5) { - Log_OC.i("SQL", "Entering in the #4 ADD in onUpgrade"); + Log_OC.i(SQL, "Entering in the #4 ADD in onUpgrade"); db.beginTransaction(); try { - db.execSQL("ALTER TABLE " + ProviderTableMeta.FILE_TABLE_NAME + - " ADD COLUMN " + ProviderTableMeta.FILE_ETAG + " TEXT " + + db.execSQL(ALTER_TABLE + ProviderTableMeta.FILE_TABLE_NAME + + ADD_COLUMN + ProviderTableMeta.FILE_ETAG + " TEXT " + " DEFAULT NULL"); upgraded = true; @@ -612,20 +620,20 @@ public class FileContentProvider extends ContentProvider { db.endTransaction(); } } - if (!upgraded) - Log_OC.i("SQL", "OUT of the ADD in onUpgrade; oldVersion == " + oldVersion + - ", newVersion == " + newVersion); + if (!upgraded) { + Log_OC.i(SQL, String.format(Locale.ENGLISH, UPGRADE_VERSION_MSG, oldVersion, newVersion)); + } if (oldVersion < 6 && newVersion >= 6) { - Log_OC.i("SQL", "Entering in the #5 ADD in onUpgrade"); + Log_OC.i(SQL, "Entering in the #5 ADD in onUpgrade"); db.beginTransaction(); try { - db .execSQL("ALTER TABLE " + ProviderTableMeta.FILE_TABLE_NAME + - " ADD COLUMN " + ProviderTableMeta.FILE_SHARED_VIA_LINK + " INTEGER " + + db .execSQL(ALTER_TABLE + ProviderTableMeta.FILE_TABLE_NAME + + ADD_COLUMN + ProviderTableMeta.FILE_SHARED_VIA_LINK + " INTEGER " + " DEFAULT 0"); - db .execSQL("ALTER TABLE " + ProviderTableMeta.FILE_TABLE_NAME + - " ADD COLUMN " + ProviderTableMeta.FILE_PUBLIC_LINK + " TEXT " + + db .execSQL(ALTER_TABLE + ProviderTableMeta.FILE_TABLE_NAME + + ADD_COLUMN + ProviderTableMeta.FILE_PUBLIC_LINK + " TEXT " + " DEFAULT NULL"); // Create table ocshares @@ -637,20 +645,20 @@ public class FileContentProvider extends ContentProvider { db.endTransaction(); } } - if (!upgraded) - Log_OC.i("SQL", "OUT of the ADD in onUpgrade; oldVersion == " + oldVersion + - ", newVersion == " + newVersion); + if (!upgraded) { + Log_OC.i(SQL, String.format(Locale.ENGLISH, UPGRADE_VERSION_MSG, oldVersion, newVersion)); + } if (oldVersion < 7 && newVersion >= 7) { - Log_OC.i("SQL", "Entering in the #7 ADD in onUpgrade"); + Log_OC.i(SQL, "Entering in the #7 ADD in onUpgrade"); db.beginTransaction(); try { - db.execSQL("ALTER TABLE " + ProviderTableMeta.FILE_TABLE_NAME + - " ADD COLUMN " + ProviderTableMeta.FILE_PERMISSIONS + " TEXT " + + db.execSQL(ALTER_TABLE + ProviderTableMeta.FILE_TABLE_NAME + + ADD_COLUMN + ProviderTableMeta.FILE_PERMISSIONS + " TEXT " + " DEFAULT NULL"); - db.execSQL("ALTER TABLE " + ProviderTableMeta.FILE_TABLE_NAME + - " ADD COLUMN " + ProviderTableMeta.FILE_REMOTE_ID + " TEXT " + + db.execSQL(ALTER_TABLE + ProviderTableMeta.FILE_TABLE_NAME + + ADD_COLUMN + ProviderTableMeta.FILE_REMOTE_ID + " TEXT " + " DEFAULT NULL"); upgraded = true; @@ -659,16 +667,16 @@ public class FileContentProvider extends ContentProvider { db.endTransaction(); } } - if (!upgraded) - Log_OC.i("SQL", "OUT of the ADD in onUpgrade; oldVersion == " + oldVersion + - ", newVersion == " + newVersion); + if (!upgraded) { + Log_OC.i(SQL, String.format(Locale.ENGLISH, UPGRADE_VERSION_MSG, oldVersion, newVersion)); + } if (oldVersion < 8 && newVersion >= 8) { - Log_OC.i("SQL", "Entering in the #8 ADD in onUpgrade"); + Log_OC.i(SQL, "Entering in the #8 ADD in onUpgrade"); db.beginTransaction(); try { - db.execSQL("ALTER TABLE " + ProviderTableMeta.FILE_TABLE_NAME + - " ADD COLUMN " + ProviderTableMeta.FILE_UPDATE_THUMBNAIL + " INTEGER " + + db.execSQL(ALTER_TABLE + ProviderTableMeta.FILE_TABLE_NAME + + ADD_COLUMN + ProviderTableMeta.FILE_UPDATE_THUMBNAIL + " INTEGER " + " DEFAULT 0"); upgraded = true; @@ -677,16 +685,16 @@ public class FileContentProvider extends ContentProvider { db.endTransaction(); } } - if (!upgraded) - Log_OC.i("SQL", "OUT of the ADD in onUpgrade; oldVersion == " + oldVersion + - ", newVersion == " + newVersion); + if (!upgraded) { + Log_OC.i(SQL, String.format(Locale.ENGLISH, UPGRADE_VERSION_MSG, oldVersion, newVersion)); + } if (oldVersion < 9 && newVersion >= 9) { - Log_OC.i("SQL", "Entering in the #9 ADD in onUpgrade"); + Log_OC.i(SQL, "Entering in the #9 ADD in onUpgrade"); db.beginTransaction(); try { - db .execSQL("ALTER TABLE " + ProviderTableMeta.FILE_TABLE_NAME + - " ADD COLUMN " + ProviderTableMeta.FILE_IS_DOWNLOADING + " INTEGER " + + db .execSQL(ALTER_TABLE + ProviderTableMeta.FILE_TABLE_NAME + + ADD_COLUMN + ProviderTableMeta.FILE_IS_DOWNLOADING + " INTEGER " + " DEFAULT 0"); upgraded = true; @@ -695,25 +703,25 @@ public class FileContentProvider extends ContentProvider { db.endTransaction(); } } - if (!upgraded) - Log_OC.i("SQL", "OUT of the ADD in onUpgrade; oldVersion == " + oldVersion + - ", newVersion == " + newVersion); + if (!upgraded) { + Log_OC.i(SQL, String.format(Locale.ENGLISH, UPGRADE_VERSION_MSG, oldVersion, newVersion)); + } if (oldVersion < 10 && newVersion >= 10) { - Log_OC.i("SQL", "Entering in the #10 ADD in onUpgrade"); + Log_OC.i(SQL, "Entering in the #10 ADD in onUpgrade"); updateAccountName(db); upgraded = true; } - if (!upgraded) - Log_OC.i("SQL", "OUT of the ADD in onUpgrade; oldVersion == " + oldVersion + - ", newVersion == " + newVersion); + if (!upgraded) { + Log_OC.i(SQL, String.format(Locale.ENGLISH, UPGRADE_VERSION_MSG, oldVersion, newVersion)); + } if (oldVersion < 11 && newVersion >= 11) { - Log_OC.i("SQL", "Entering in the #11 ADD in onUpgrade"); + Log_OC.i(SQL, "Entering in the #11 ADD in onUpgrade"); db.beginTransaction(); try { - db .execSQL("ALTER TABLE " + ProviderTableMeta.FILE_TABLE_NAME + - " ADD COLUMN " + ProviderTableMeta.FILE_ETAG_IN_CONFLICT + " TEXT " + + db .execSQL(ALTER_TABLE + ProviderTableMeta.FILE_TABLE_NAME + + ADD_COLUMN + ProviderTableMeta.FILE_ETAG_IN_CONFLICT + " TEXT " + " DEFAULT NULL"); upgraded = true; @@ -722,16 +730,16 @@ public class FileContentProvider extends ContentProvider { db.endTransaction(); } } - if (!upgraded) - Log_OC.i("SQL", "OUT of the ADD in onUpgrade; oldVersion == " + oldVersion + - ", newVersion == " + newVersion); + if (!upgraded) { + Log_OC.i(SQL, String.format(Locale.ENGLISH, UPGRADE_VERSION_MSG, oldVersion, newVersion)); + } if (oldVersion < 12 && newVersion >= 12) { - Log_OC.i("SQL", "Entering in the #12 ADD in onUpgrade"); + Log_OC.i(SQL, "Entering in the #12 ADD in onUpgrade"); db.beginTransaction(); try { - db .execSQL("ALTER TABLE " + ProviderTableMeta.FILE_TABLE_NAME + - " ADD COLUMN " + ProviderTableMeta.FILE_SHARED_WITH_SHAREE + " INTEGER " + + db .execSQL(ALTER_TABLE + ProviderTableMeta.FILE_TABLE_NAME + + ADD_COLUMN + ProviderTableMeta.FILE_SHARED_WITH_SHAREE + " INTEGER " + " DEFAULT 0"); upgraded = true; db.setTransactionSuccessful(); @@ -739,12 +747,12 @@ public class FileContentProvider extends ContentProvider { db.endTransaction(); } } - if (!upgraded) - Log_OC.i("SQL", "OUT of the ADD in onUpgrade; oldVersion == " + oldVersion + - ", newVersion == " + newVersion); + if (!upgraded) { + Log_OC.i(SQL, String.format(Locale.ENGLISH, UPGRADE_VERSION_MSG, oldVersion, newVersion)); + } if (oldVersion < 13 && newVersion >= 13) { - Log_OC.i("SQL", "Entering in the #13 ADD in onUpgrade"); + Log_OC.i(SQL, "Entering in the #13 ADD in onUpgrade"); db.beginTransaction(); try { // Create capabilities table @@ -757,7 +765,7 @@ public class FileContentProvider extends ContentProvider { } if (oldVersion < 14 && newVersion >= 14) { - Log_OC.i("SQL", "Entering in the #14 ADD in onUpgrade"); + Log_OC.i(SQL, "Entering in the #14 ADD in onUpgrade"); db.beginTransaction(); try { // drop old instant_upload table @@ -772,7 +780,7 @@ public class FileContentProvider extends ContentProvider { } if (oldVersion < 15 && newVersion >= 15) { - Log_OC.i("SQL", "Entering in the #15 ADD in onUpgrade"); + Log_OC.i(SQL, "Entering in the #15 ADD in onUpgrade"); db.beginTransaction(); try { // drop old capabilities table @@ -786,37 +794,38 @@ public class FileContentProvider extends ContentProvider { } } - if (!upgraded) - Log_OC.i("SQL", "OUT of the ADD in onUpgrade; oldVersion == " + oldVersion + - ", newVersion == " + newVersion); + if (!upgraded) { + Log_OC.i(SQL, String.format(Locale.ENGLISH, UPGRADE_VERSION_MSG, oldVersion, newVersion)); + } } } private void createFilesTable(SQLiteDatabase db){ + db.execSQL("CREATE TABLE " + ProviderTableMeta.FILE_TABLE_NAME + "(" + ProviderTableMeta._ID + " INTEGER PRIMARY KEY, " - + ProviderTableMeta.FILE_NAME + " TEXT, " - + ProviderTableMeta.FILE_PATH + " TEXT, " - + ProviderTableMeta.FILE_PARENT + " INTEGER, " - + ProviderTableMeta.FILE_CREATION + " INTEGER, " - + ProviderTableMeta.FILE_MODIFIED + " INTEGER, " - + ProviderTableMeta.FILE_CONTENT_TYPE + " TEXT, " - + ProviderTableMeta.FILE_CONTENT_LENGTH + " INTEGER, " - + ProviderTableMeta.FILE_STORAGE_PATH + " TEXT, " - + ProviderTableMeta.FILE_ACCOUNT_OWNER + " TEXT, " - + ProviderTableMeta.FILE_LAST_SYNC_DATE + " INTEGER, " - + ProviderTableMeta.FILE_KEEP_IN_SYNC + " INTEGER, " - + ProviderTableMeta.FILE_LAST_SYNC_DATE_FOR_DATA + " INTEGER, " - + ProviderTableMeta.FILE_MODIFIED_AT_LAST_SYNC_FOR_DATA + " INTEGER, " - + ProviderTableMeta.FILE_ETAG + " TEXT, " - + ProviderTableMeta.FILE_SHARED_VIA_LINK + " INTEGER, " - + ProviderTableMeta.FILE_PUBLIC_LINK + " TEXT, " + + ProviderTableMeta.FILE_NAME + TEXT + + ProviderTableMeta.FILE_PATH + TEXT + + ProviderTableMeta.FILE_PARENT + INTEGER + + ProviderTableMeta.FILE_CREATION + INTEGER + + ProviderTableMeta.FILE_MODIFIED + INTEGER + + ProviderTableMeta.FILE_CONTENT_TYPE + TEXT + + ProviderTableMeta.FILE_CONTENT_LENGTH + INTEGER + + ProviderTableMeta.FILE_STORAGE_PATH + TEXT + + ProviderTableMeta.FILE_ACCOUNT_OWNER + TEXT + + ProviderTableMeta.FILE_LAST_SYNC_DATE + INTEGER + + ProviderTableMeta.FILE_KEEP_IN_SYNC + INTEGER + + ProviderTableMeta.FILE_LAST_SYNC_DATE_FOR_DATA + INTEGER + + ProviderTableMeta.FILE_MODIFIED_AT_LAST_SYNC_FOR_DATA + INTEGER + + ProviderTableMeta.FILE_ETAG + TEXT + + ProviderTableMeta.FILE_SHARED_VIA_LINK + INTEGER + + ProviderTableMeta.FILE_PUBLIC_LINK + TEXT + ProviderTableMeta.FILE_PERMISSIONS + " TEXT null," + ProviderTableMeta.FILE_REMOTE_ID + " TEXT null," - + ProviderTableMeta.FILE_UPDATE_THUMBNAIL + " INTEGER," //boolean - + ProviderTableMeta.FILE_IS_DOWNLOADING + " INTEGER," //boolean - + ProviderTableMeta.FILE_ETAG_IN_CONFLICT + " TEXT," + + ProviderTableMeta.FILE_UPDATE_THUMBNAIL + INTEGER //boolean + + ProviderTableMeta.FILE_IS_DOWNLOADING + INTEGER //boolean + + ProviderTableMeta.FILE_ETAG_IN_CONFLICT + TEXT + ProviderTableMeta.FILE_SHARED_WITH_SHAREE + " INTEGER);" ); } @@ -825,19 +834,19 @@ public class FileContentProvider extends ContentProvider { // Create ocshares table db.execSQL("CREATE TABLE " + ProviderTableMeta.OCSHARES_TABLE_NAME + "(" + ProviderTableMeta._ID + " INTEGER PRIMARY KEY, " - + ProviderTableMeta.OCSHARES_FILE_SOURCE + " INTEGER, " - + ProviderTableMeta.OCSHARES_ITEM_SOURCE + " INTEGER, " - + ProviderTableMeta.OCSHARES_SHARE_TYPE + " INTEGER, " - + ProviderTableMeta.OCSHARES_SHARE_WITH + " TEXT, " - + ProviderTableMeta.OCSHARES_PATH + " TEXT, " - + ProviderTableMeta.OCSHARES_PERMISSIONS+ " INTEGER, " - + ProviderTableMeta.OCSHARES_SHARED_DATE + " INTEGER, " - + ProviderTableMeta.OCSHARES_EXPIRATION_DATE + " INTEGER, " - + ProviderTableMeta.OCSHARES_TOKEN + " TEXT, " - + ProviderTableMeta.OCSHARES_SHARE_WITH_DISPLAY_NAME + " TEXT, " - + ProviderTableMeta.OCSHARES_IS_DIRECTORY + " INTEGER, " // boolean - + ProviderTableMeta.OCSHARES_USER_ID + " INTEGER, " - + ProviderTableMeta.OCSHARES_ID_REMOTE_SHARED + " INTEGER," + + ProviderTableMeta.OCSHARES_FILE_SOURCE + INTEGER + + ProviderTableMeta.OCSHARES_ITEM_SOURCE + INTEGER + + ProviderTableMeta.OCSHARES_SHARE_TYPE + INTEGER + + ProviderTableMeta.OCSHARES_SHARE_WITH + TEXT + + ProviderTableMeta.OCSHARES_PATH + TEXT + + ProviderTableMeta.OCSHARES_PERMISSIONS+ INTEGER + + ProviderTableMeta.OCSHARES_SHARED_DATE + INTEGER + + ProviderTableMeta.OCSHARES_EXPIRATION_DATE + INTEGER + + ProviderTableMeta.OCSHARES_TOKEN + TEXT + + ProviderTableMeta.OCSHARES_SHARE_WITH_DISPLAY_NAME + TEXT + + ProviderTableMeta.OCSHARES_IS_DIRECTORY + INTEGER // boolean + + ProviderTableMeta.OCSHARES_USER_ID + INTEGER + + ProviderTableMeta.OCSHARES_ID_REMOTE_SHARED + INTEGER + ProviderTableMeta.OCSHARES_ACCOUNT_OWNER + " TEXT );" ); } @@ -845,28 +854,28 @@ public class FileContentProvider extends ContentProvider { // Create capabilities table db.execSQL("CREATE TABLE " + ProviderTableMeta.CAPABILITIES_TABLE_NAME + "(" + ProviderTableMeta._ID + " INTEGER PRIMARY KEY, " - + ProviderTableMeta.CAPABILITIES_ACCOUNT_NAME + " TEXT, " - + ProviderTableMeta.CAPABILITIES_VERSION_MAYOR + " INTEGER, " - + ProviderTableMeta.CAPABILITIES_VERSION_MINOR + " INTEGER, " - + ProviderTableMeta.CAPABILITIES_VERSION_MICRO + " INTEGER, " - + ProviderTableMeta.CAPABILITIES_VERSION_STRING + " TEXT, " - + ProviderTableMeta.CAPABILITIES_VERSION_EDITION + " TEXT, " - + ProviderTableMeta.CAPABILITIES_CORE_POLLINTERVAL + " INTEGER, " - + ProviderTableMeta.CAPABILITIES_SHARING_API_ENABLED + " INTEGER, " // boolean - + ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_ENABLED + " INTEGER, " // boolean - + ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_PASSWORD_ENFORCED + " INTEGER, " // boolean - + ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_EXPIRE_DATE_ENABLED + " INTEGER, " // boolean - + ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_EXPIRE_DATE_DAYS + " INTEGER, " - + ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_EXPIRE_DATE_ENFORCED + " INTEGER, " // boolean - + ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_SEND_MAIL + " INTEGER, " // boolean - + ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_UPLOAD + " INTEGER, " // boolean - + ProviderTableMeta.CAPABILITIES_SHARING_USER_SEND_MAIL + " INTEGER, " // boolean - + ProviderTableMeta.CAPABILITIES_SHARING_RESHARING + " INTEGER, " // boolean - + ProviderTableMeta.CAPABILITIES_SHARING_FEDERATION_OUTGOING + " INTEGER, " // boolean - + ProviderTableMeta.CAPABILITIES_SHARING_FEDERATION_INCOMING + " INTEGER, " // boolean - + ProviderTableMeta.CAPABILITIES_FILES_BIGFILECHUNKING + " INTEGER, " // boolean - + ProviderTableMeta.CAPABILITIES_FILES_UNDELETE + " INTEGER, " // boolean - + ProviderTableMeta.CAPABILITIES_FILES_VERSIONING + " INTEGER, " // boolean + + ProviderTableMeta.CAPABILITIES_ACCOUNT_NAME + TEXT + + ProviderTableMeta.CAPABILITIES_VERSION_MAYOR + INTEGER + + ProviderTableMeta.CAPABILITIES_VERSION_MINOR + INTEGER + + ProviderTableMeta.CAPABILITIES_VERSION_MICRO + INTEGER + + ProviderTableMeta.CAPABILITIES_VERSION_STRING + TEXT + + ProviderTableMeta.CAPABILITIES_VERSION_EDITION + TEXT + + ProviderTableMeta.CAPABILITIES_CORE_POLLINTERVAL + INTEGER + + ProviderTableMeta.CAPABILITIES_SHARING_API_ENABLED + INTEGER // boolean + + ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_ENABLED + INTEGER // boolean + + ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_PASSWORD_ENFORCED + INTEGER // boolean + + ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_EXPIRE_DATE_ENABLED + INTEGER // boolean + + ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_EXPIRE_DATE_DAYS + INTEGER + + ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_EXPIRE_DATE_ENFORCED + INTEGER // boolean + + ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_SEND_MAIL + INTEGER // boolean + + ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_UPLOAD + INTEGER // boolean + + ProviderTableMeta.CAPABILITIES_SHARING_USER_SEND_MAIL + INTEGER // boolean + + ProviderTableMeta.CAPABILITIES_SHARING_RESHARING + INTEGER // boolean + + ProviderTableMeta.CAPABILITIES_SHARING_FEDERATION_OUTGOING + INTEGER // boolean + + ProviderTableMeta.CAPABILITIES_SHARING_FEDERATION_INCOMING + INTEGER // boolean + + ProviderTableMeta.CAPABILITIES_FILES_BIGFILECHUNKING + INTEGER // boolean + + ProviderTableMeta.CAPABILITIES_FILES_UNDELETE + INTEGER // boolean + + ProviderTableMeta.CAPABILITIES_FILES_VERSIONING + INTEGER // boolean + ProviderTableMeta.CAPABILITIES_FILES_DROP + " INTEGER );" ); // boolean } @@ -874,17 +883,17 @@ public class FileContentProvider extends ContentProvider { // Create uploads table db.execSQL("CREATE TABLE " + ProviderTableMeta.UPLOADS_TABLE_NAME + "(" + ProviderTableMeta._ID + " INTEGER PRIMARY KEY, " - + ProviderTableMeta.UPLOADS_LOCAL_PATH + " TEXT, " - + ProviderTableMeta.UPLOADS_REMOTE_PATH + " TEXT, " - + ProviderTableMeta.UPLOADS_ACCOUNT_NAME + " TEXT, " + + ProviderTableMeta.UPLOADS_LOCAL_PATH + TEXT + + ProviderTableMeta.UPLOADS_REMOTE_PATH + TEXT + + ProviderTableMeta.UPLOADS_ACCOUNT_NAME + TEXT + ProviderTableMeta.UPLOADS_FILE_SIZE + " LONG, " - + ProviderTableMeta.UPLOADS_STATUS + " INTEGER, " // UploadStatus - + ProviderTableMeta.UPLOADS_LOCAL_BEHAVIOUR + " INTEGER, " // Upload LocalBehaviour - + ProviderTableMeta.UPLOADS_UPLOAD_TIME + " INTEGER, " - + ProviderTableMeta.UPLOADS_FORCE_OVERWRITE + " INTEGER, " // boolean - + ProviderTableMeta.UPLOADS_IS_CREATE_REMOTE_FOLDER + " INTEGER, " // boolean - + ProviderTableMeta.UPLOADS_UPLOAD_END_TIMESTAMP + " INTEGER, " - + ProviderTableMeta.UPLOADS_LAST_RESULT + " INTEGER, " // Upload LastResult + + ProviderTableMeta.UPLOADS_STATUS + INTEGER // UploadStatus + + ProviderTableMeta.UPLOADS_LOCAL_BEHAVIOUR + INTEGER // Upload LocalBehaviour + + ProviderTableMeta.UPLOADS_UPLOAD_TIME + INTEGER + + ProviderTableMeta.UPLOADS_FORCE_OVERWRITE + INTEGER // boolean + + ProviderTableMeta.UPLOADS_IS_CREATE_REMOTE_FOLDER + INTEGER // boolean + + ProviderTableMeta.UPLOADS_UPLOAD_END_TIMESTAMP + INTEGER + + ProviderTableMeta.UPLOADS_LAST_RESULT + INTEGER // Upload LastResult + ProviderTableMeta.UPLOADS_CREATED_BY + " INTEGER );" // Upload createdBy ); @@ -909,7 +918,7 @@ public class FileContentProvider extends ContentProvider { * @param db Database where table of files is included. */ private void updateAccountName(SQLiteDatabase db){ - Log_OC.d("SQL", "THREAD: " + Thread.currentThread().getName()); + Log_OC.d(SQL, "THREAD: " + Thread.currentThread().getName()); AccountManager ama = AccountManager.get(getContext()); try { // get accounts from AccountManager ; we can't be sure if accounts in it are updated or not although @@ -935,7 +944,7 @@ public class FileContentProvider extends ContentProvider { ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?", new String[]{oldAccountName}); - Log_OC.d("SQL", "Updated account in database: old name == " + oldAccountName + + Log_OC.d(SQL, "Updated account in database: old name == " + oldAccountName + ", new name == " + newAccountName + " (" + num + " rows updated )"); // update path for downloaded files @@ -1002,7 +1011,7 @@ public class FileContentProvider extends ContentProvider { ProviderTableMeta.FILE_STORAGE_PATH + "=?", new String[]{oldPath}); - Log_OC.v("SQL", "Updated path of downloaded file: old file name == " + oldPath + + Log_OC.v(SQL, "Updated path of downloaded file: old file name == " + oldPath + ", new file name == " + newPath); } while (c.moveToNext()); @@ -1021,6 +1030,7 @@ public class FileContentProvider extends ContentProvider { private void trimSuccessfulUploads(SQLiteDatabase db) { Cursor c = null; try { + String MAX_SUCCESSFUL_UPLOADS = "30"; c = db.rawQuery( "delete from " + ProviderTableMeta.UPLOADS_TABLE_NAME + " where " + ProviderTableMeta.UPLOADS_STATUS + " == " diff --git a/src/com/owncloud/android/services/OperationsService.java b/src/com/owncloud/android/services/OperationsService.java index 2280e6d738..9d1374d158 100644 --- a/src/com/owncloud/android/services/OperationsService.java +++ b/src/com/owncloud/android/services/OperationsService.java @@ -218,14 +218,8 @@ public class OperationsService extends Service { saveAllClients(this, MainApp.getAccountType()); // TODO - get rid of these exceptions - } catch (AccountNotFoundException e) { - e.printStackTrace(); - } catch (AuthenticatorException e) { - e.printStackTrace(); - } catch (OperationCanceledException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); + } catch (AccountNotFoundException | IOException | OperationCanceledException | AuthenticatorException e) { + Log_OC.d(TAG, e.getMessage(), e); } mUndispatchedFinishedOperations.clear(); diff --git a/src/com/owncloud/android/services/SyncFolderHandler.java b/src/com/owncloud/android/services/SyncFolderHandler.java index 3d23b6eead..258570e2a6 100644 --- a/src/com/owncloud/android/services/SyncFolderHandler.java +++ b/src/com/owncloud/android/services/SyncFolderHandler.java @@ -79,8 +79,10 @@ class SyncFolderHandler extends Handler { * @param account ownCloud account where the remote folder is stored. * @param remotePath The path to a folder that could be in the queue of synchronizations. */ - public boolean isSynchronizing(Account account, String remotePath) { - if (account == null || remotePath == null) return false; + boolean isSynchronizing(Account account, String remotePath) { + if (account == null || remotePath == null) { + return false; + } return (mPendingOperations.contains(account.name, remotePath)); } diff --git a/src/com/owncloud/android/services/observer/FileObserverService.java b/src/com/owncloud/android/services/observer/FileObserverService.java index 81e6681848..0fba9dc9b9 100644 --- a/src/com/owncloud/android/services/observer/FileObserverService.java +++ b/src/com/owncloud/android/services/observer/FileObserverService.java @@ -68,7 +68,7 @@ public class FileObserverService extends Service { private final static String ARG_FILE = "ARG_FILE"; private final static String ARG_ACCOUNT = "ARG_ACCOUNT"; - private static String TAG = FileObserverService.class.getSimpleName(); + private static final String TAG = FileObserverService.class.getSimpleName(); private Map mFolderObserversMap; private DownloadCompletedReceiver mDownloadReceiver; diff --git a/src/com/owncloud/android/services/observer/FolderObserver.java b/src/com/owncloud/android/services/observer/FolderObserver.java index 4e6c398cee..eb7995b40e 100644 --- a/src/com/owncloud/android/services/observer/FolderObserver.java +++ b/src/com/owncloud/android/services/observer/FolderObserver.java @@ -52,14 +52,14 @@ import com.owncloud.android.ui.activity.ConflictsResolveActivity; */ public class FolderObserver extends FileObserver { - private static String TAG = FolderObserver.class.getSimpleName(); + private static final String TAG = FolderObserver.class.getSimpleName(); - private static int UPDATE_MASK = ( + private static final int UPDATE_MASK = ( FileObserver.ATTRIB | FileObserver.MODIFY | FileObserver.MOVED_TO | FileObserver.CLOSE_WRITE ); - private static int IN_IGNORE = 32768; + private static final int IN_IGNORE = 32768; /* private static int ALL_EVENTS_EVEN_THOSE_NOT_DOCUMENTED = 0x7fffffff; // NEVER use 0xffffffff */ @@ -67,7 +67,7 @@ public class FolderObserver extends FileObserver { private String mPath; private Account mAccount; private Context mContext; - private Map mObservedChildren; + private final Map mObservedChildren; /** * Constructor. @@ -82,12 +82,15 @@ public class FolderObserver extends FileObserver { public FolderObserver(String path, Account account, Context context) { super(path, UPDATE_MASK); - if (path == null) + if (path == null) { throw new IllegalArgumentException("NULL path argument received"); - if (account == null) + } + if (account == null) { throw new IllegalArgumentException("NULL account argument received"); - if (context == null) + } + if (context == null) { throw new IllegalArgumentException("NULL context argument received"); + } mPath = path; mAccount = account; @@ -113,15 +116,14 @@ public class FolderObserver extends FileObserver { if ( ((event & FileObserver.MODIFY) != 0) || ((event & FileObserver.ATTRIB) != 0) || - ((event & FileObserver.MOVED_TO) != 0) ) { + ((event & FileObserver.MOVED_TO) != 0) + && !mObservedChildren.get(path)) { - if (mObservedChildren.get(path) != true) { - mObservedChildren.put(path, Boolean.valueOf(true)); - } + mObservedChildren.put(path, true); } if ((event & FileObserver.CLOSE_WRITE) != 0 && mObservedChildren.get(path)) { - mObservedChildren.put(path, Boolean.valueOf(false)); + mObservedChildren.put(path, false); shouldSynchronize = true; } } @@ -146,7 +148,7 @@ public class FolderObserver extends FileObserver { public void startWatching(String fileName) { synchronized (mObservedChildren) { if (!mObservedChildren.containsKey(fileName)) { - mObservedChildren.put(fileName, Boolean.valueOf(false)); + mObservedChildren.put(fileName, false); } } diff --git a/src/com/owncloud/android/syncadapter/FileSyncAdapter.java b/src/com/owncloud/android/syncadapter/FileSyncAdapter.java index 285748b7e1..8689d25701 100644 --- a/src/com/owncloud/android/syncadapter/FileSyncAdapter.java +++ b/src/com/owncloud/android/syncadapter/FileSyncAdapter.java @@ -89,11 +89,7 @@ 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 */ - private boolean mIsManualSync; - + /** Counter for failed operations in the synchronization process */ private int mFailedResultsCounter; @@ -146,7 +142,9 @@ public class FileSyncAdapter extends AbstractOwnCloudSyncAdapter { SyncResult syncResult) { mCancellation = false; - mIsManualSync = extras.getBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, false); + /* When 'true' the process was requested by the user through the user interface; + when 'false', it was requested automatically by the system */ + boolean mIsManualSync = extras.getBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, false); mFailedResultsCounter = 0; mLastFailedResult = null; mConflictsFound = 0; @@ -162,20 +160,14 @@ 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 - mSyncResult.tooManyRetries = true; - notifyFailedSynchronization(); - return; - } catch (AccountsException e) { + } catch (IOException | AccountsException e) { /// 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 @@ -262,8 +254,9 @@ public class FileSyncAdapter extends AbstractOwnCloudSyncAdapter { */ private void synchronizeFolder(OCFile folder) { - if (mFailedResultsCounter > MAX_FAILED_RESULTS || isFinisher(mLastFailedResult)) + if (mFailedResultsCounter > MAX_FAILED_RESULTS || isFinisher(mLastFailedResult)) { return; + } // folder synchronization RefreshFolderOperation synchFolderOp = new RefreshFolderOperation( folder, @@ -355,9 +348,11 @@ public class FileSyncAdapter extends AbstractOwnCloudSyncAdapter { } } - if (mCancellation && i do nothing + return; } return; } @@ -296,8 +297,9 @@ public class FileDisplayActivity extends HookActivity // cache until the upload is successful get parent from path parentPath = file.getRemotePath().substring(0, file.getRemotePath().lastIndexOf(file.getFileName())); - if (getStorageManager().getFileByPath(parentPath) == null) + if (getStorageManager().getFileByPath(parentPath) == null) { file = null; // not able to know the directory where the file is uploading + } } else { file = getStorageManager().getFileByPath(file.getRemotePath()); // currentDir = null if not in the current Account @@ -342,7 +344,7 @@ public class FileDisplayActivity extends HookActivity /// First fragment OCFileListFragment listOfFiles = getListOfFilesFragment(); if (listOfFiles != null) { - listOfFiles.listDirectory(getCurrentDir(), MainApp.getOnlyOnDevice()); + listOfFiles.listDirectory(getCurrentDir(), MainApp.isOnlyOnDevice()); } else { Log_OC.e(TAG, "Still have a chance to lose the initializacion of list fragment >("); } @@ -356,8 +358,9 @@ public class FileDisplayActivity extends HookActivity updateActionBarTitleAndHomeButton(file); } else { cleanSecondFragment(); - if (file.isDown() && PreviewTextFragment.canBePreviewed(file)) + if (file.isDown() && PreviewTextFragment.canBePreviewed(file)) { startTextPreview(file); + } } } else { @@ -470,7 +473,7 @@ public class FileDisplayActivity extends HookActivity protected void refreshListOfFilesFragment() { OCFileListFragment fileListFragment = getListOfFilesFragment(); if (fileListFragment != null) { - fileListFragment.listDirectory(MainApp.getOnlyOnDevice()); + fileListFragment.listDirectory(MainApp.isOnlyOnDevice()); } } @@ -479,7 +482,7 @@ public class FileDisplayActivity extends HookActivity FileFragment secondFragment = getSecondFragment(); boolean waitedPreview = (mWaitingToPreview != null && mWaitingToPreview.getRemotePath().equals(downloadedRemotePath)); - if (secondFragment != null && secondFragment instanceof FileDetailFragment) { + if (secondFragment instanceof FileDetailFragment) { FileDetailFragment detailsFragment = (FileDetailFragment) secondFragment; OCFile fileInFragment = detailsFragment.getFile(); if (fileInFragment != null && @@ -682,7 +685,6 @@ public class FileDisplayActivity extends HookActivity } else if (requestCode == REQUEST_CODE__COPY_FILES && resultCode == RESULT_OK) { final Intent fData = data; - final int fResultCode = resultCode; getHandler().postDelayed( new Runnable() { @Override @@ -981,12 +983,11 @@ public class FileDisplayActivity extends HookActivity currentFile = currentDir; } - if (synchFolderRemotePath != null && - currentDir.getRemotePath().equals(synchFolderRemotePath)) { + if (currentDir.getRemotePath().equals(synchFolderRemotePath)) { OCFileListFragment fileListFragment = getListOfFilesFragment(); if (fileListFragment != null) { fileListFragment.listDirectory(currentDir, - MainApp.getOnlyOnDevice()); + MainApp.isOnlyOnDevice()); } } setFile(currentFile); @@ -997,23 +998,22 @@ public class FileDisplayActivity extends HookActivity .equals(event)); if (RefreshFolderOperation.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED. - equals(event)) { + equals(event) && + synchResult != null && !synchResult.isSuccess()) { - if (synchResult != null && !synchResult.isSuccess()) { - /// TODO refactor and make common + /// TODO refactor and make common - if (checkForRemoteOperationError(synchResult)) { + if (checkForRemoteOperationError(synchResult)) { - requestCredentialsUpdate(context); + requestCredentialsUpdate(context); - } else if (RemoteOperationResult.ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED.equals( + } else if (RemoteOperationResult.ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED.equals( synchResult.getCode())) { - showUntrustedCertDialog(synchResult); - } - + showUntrustedCertDialog(synchResult); } + } removeStickyBroadcast(intent); Log_OC.d(TAG, "Setting progress visibility to " + mSyncInProgress); @@ -1023,11 +1023,9 @@ public class FileDisplayActivity extends HookActivity } } - if (synchResult != null) { - if (synchResult.getCode().equals( - RemoteOperationResult.ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED)) { - mLastSslUntrustedServerResult = synchResult; - } + if (synchResult != null && synchResult.getCode().equals( + RemoteOperationResult.ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED)) { + mLastSslUntrustedServerResult = synchResult; } } catch (RuntimeException e) { // avoid app crashes after changing the serial id of RemoteOperationResult @@ -1098,14 +1096,14 @@ public class FileDisplayActivity extends HookActivity boolean sameFile = getFile().getRemotePath().equals(uploadedRemotePath) || renamedInUpload; FileFragment details = getSecondFragment(); - boolean detailFragmentIsShown = (details != null && - details instanceof FileDetailFragment); + boolean detailFragmentIsShown = (details instanceof FileDetailFragment); if (sameAccount && sameFile && detailFragmentIsShown) { if (uploadWasFine) { setFile(getStorageManager().getFileByPath(uploadedRemotePath)); } else { //TODO remove upload progress bar after upload failed. + Log_OC.d(TAG, "Remove upload progress bar after upload failed"); } if (renamedInUpload) { String newName = (new File(uploadedRemotePath)).getName(); @@ -1126,10 +1124,12 @@ public class FileDisplayActivity extends HookActivity // Force the preview if the file is an image or text file if (uploadWasFine) { OCFile ocFile = getFile(); - if (PreviewImageFragment.canBePreviewed(ocFile)) + if (PreviewImageFragment.canBePreviewed(ocFile)) { startImagePreview(getFile()); - else if (PreviewTextFragment.canBePreviewed(ocFile)) + } + else if (PreviewTextFragment.canBePreviewed(ocFile)) { startTextPreview(ocFile); + } // TODO what about other kind of previews? } } @@ -1229,7 +1229,7 @@ public class FileDisplayActivity extends HookActivity OCFileListFragment listOfFiles = getListOfFilesFragment(); if (listOfFiles != null) { // should never be null, indeed OCFile root = getStorageManager().getFileByPath(OCFile.ROOT_PATH); - listOfFiles.listDirectory(root, MainApp.getOnlyOnDevice()); + listOfFiles.listDirectory(root, MainApp.isOnlyOnDevice()); setFile(listOfFiles.getCurrentFile()); startSyncFolderOperation(root, false); } @@ -1295,15 +1295,14 @@ public class FileDisplayActivity extends HookActivity FileDisplayActivity.this, FileDownloader.class))) { Log_OC.d(TAG, "Download service connected"); mDownloaderBinder = (FileDownloaderBinder) service; - if (mWaitingToPreview != null) - if (getStorageManager() != null) { - // update the file - mWaitingToPreview = - getStorageManager().getFileById(mWaitingToPreview.getFileId()); - if (!mWaitingToPreview.isDown()) { - requestForDownload(); - } + if (mWaitingToPreview != null && getStorageManager() != null) { + // update the file + mWaitingToPreview = + getStorageManager().getFileById(mWaitingToPreview.getFileId()); + if (!mWaitingToPreview.isDown()) { + requestForDownload(); } + } } else if (component.equals(new ComponentName(FileDisplayActivity.this, FileUploader.class))) { @@ -1316,10 +1315,10 @@ public class FileDisplayActivity extends HookActivity // getFileDownloadBinder() - THIS IS A MESS OCFileListFragment listOfFiles = getListOfFilesFragment(); if (listOfFiles != null) { - listOfFiles.listDirectory(MainApp.getOnlyOnDevice()); + listOfFiles.listDirectory(MainApp.isOnlyOnDevice()); } FileFragment secondFragment = getSecondFragment(); - if (secondFragment != null && secondFragment instanceof FileDetailFragment) { + if (secondFragment instanceof FileDetailFragment) { FileDetailFragment detailFragment = (FileDetailFragment) secondFragment; detailFragment.listenForTransferProgress(); detailFragment.updateFileDetails(false, false); @@ -1534,13 +1533,11 @@ public class FileDisplayActivity extends HookActivity private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation, RemoteOperationResult result) { - if (result.isSuccess()) { - if (operation.transferWasRequested()) { - OCFile syncedFile = operation.getLocalFile(); - onTransferStateChanged(syncedFile, true, true); - invalidateOptionsMenu(); - refreshShowDetails(); - } + if (result.isSuccess() && operation.transferWasRequested()) { + OCFile syncedFile = operation.getLocalFile(); + onTransferStateChanged(syncedFile, true, true); + invalidateOptionsMenu(); + refreshShowDetails(); } } @@ -1576,7 +1573,7 @@ public class FileDisplayActivity extends HookActivity public void onTransferStateChanged(OCFile file, boolean downloading, boolean uploading) { refreshListOfFilesFragment(); FileFragment details = getSecondFragment(); - if (details != null && details instanceof FileDetailFragment && + if (details instanceof FileDetailFragment && file.equals(details.getFile())) { if (downloading || uploading) { ((FileDetailFragment) details).updateFileDetails(file, getAccount()); diff --git a/src/com/owncloud/android/ui/activity/FolderPickerActivity.java b/src/com/owncloud/android/ui/activity/FolderPickerActivity.java index c15f37457f..e63481369a 100644 --- a/src/com/owncloud/android/ui/activity/FolderPickerActivity.java +++ b/src/com/owncloud/android/ui/activity/FolderPickerActivity.java @@ -363,9 +363,9 @@ public class FolderPickerActivity extends FileActivity implements FileFragment.C @Override public void onClick(View v) { - if (v == mCancelBtn) { + if (v.equals(mCancelBtn)) { finish(); - } else if (v == mChooseBtn) { + } else if (v.equals(mChooseBtn)) { Intent i = getIntent(); ArrayList targetFiles = i.getParcelableArrayListExtra(FolderPickerActivity.EXTRA_FILES); @@ -462,8 +462,7 @@ public class FolderPickerActivity extends FileActivity implements FileFragment.C currentFile = currentDir; } - if (synchFolderRemotePath != null && currentDir.getRemotePath(). - equals(synchFolderRemotePath)) { + if (currentDir.getRemotePath().equals(synchFolderRemotePath)) { OCFileListFragment fileListFragment = getListOfFilesFragment(); if (fileListFragment != null) { fileListFragment.listDirectory(currentDir, false); diff --git a/src/com/owncloud/android/ui/activity/GenericExplanationActivity.java b/src/com/owncloud/android/ui/activity/GenericExplanationActivity.java index a0c9d5e08a..8bef98183a 100644 --- a/src/com/owncloud/android/ui/activity/GenericExplanationActivity.java +++ b/src/com/owncloud/android/ui/activity/GenericExplanationActivity.java @@ -105,13 +105,11 @@ public class GenericExplanationActivity extends AppCompatActivity { @Override public View getView (int position, View convertView, ViewGroup parent) { View view = super.getView(position, convertView, parent); - if (view != null) { - if (mList2 != null && mList2.size() > 0 && position >= 0 && - position < mList2.size()) { - TextView text2 = (TextView) view.findViewById(android.R.id.text2); - if (text2 != null) { - text2.setText(mList2.get(position)); - } + if (mList2 != null && mList2.size() > 0 && position >= 0 && + position < mList2.size()) { + TextView text2 = (TextView) view.findViewById(android.R.id.text2); + if (text2 != null) { + text2.setText(mList2.get(position)); } } return view; diff --git a/src/com/owncloud/android/ui/activity/PassCodeActivity.java b/src/com/owncloud/android/ui/activity/PassCodeActivity.java index 8d86611e15..27f6abf180 100644 --- a/src/com/owncloud/android/ui/activity/PassCodeActivity.java +++ b/src/com/owncloud/android/ui/activity/PassCodeActivity.java @@ -70,9 +70,9 @@ public class PassCodeActivity extends AppCompatActivity { private EditText[] mPassCodeEditTexts = new EditText[4]; private String [] mPassCodeDigits = {"","","",""}; - private static String KEY_PASSCODE_DIGITS = "PASSCODE_DIGITS"; + private static final String KEY_PASSCODE_DIGITS = "PASSCODE_DIGITS"; private boolean mConfirmingPassCode = false; - private static String KEY_CONFIRMING_PASSCODE = "CONFIRMING_PASSCODE"; + private static final String KEY_CONFIRMING_PASSCODE = "CONFIRMING_PASSCODE"; private boolean mBChange = true; // to control that only one blocks jump @@ -185,8 +185,9 @@ public class PassCodeActivity extends AppCompatActivity { // used to control what's exactly happening with DEL, not any custom field... mPassCodeEditTexts[0].setText(""); mPassCodeEditTexts[0].requestFocus(); - if (!mConfirmingPassCode) + if (!mConfirmingPassCode) { mPassCodeDigits[0] = ""; + } mBChange = false; } else if (!mBChange) { @@ -221,8 +222,9 @@ public class PassCodeActivity extends AppCompatActivity { public boolean onKey(View v, int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_DEL && mBChange) { mPassCodeEditTexts[1].requestFocus(); - if (!mConfirmingPassCode) + if (!mConfirmingPassCode) { mPassCodeDigits[1] = ""; + } mPassCodeEditTexts[1].setText(""); mBChange = false; @@ -258,8 +260,9 @@ public class PassCodeActivity extends AppCompatActivity { public boolean onKey(View v, int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_DEL && mBChange) { mPassCodeEditTexts[2].requestFocus(); - if (!mConfirmingPassCode) + if (!mConfirmingPassCode) { mPassCodeDigits[2] = ""; + } mPassCodeEditTexts[2].setText(""); mBChange = false; diff --git a/src/com/owncloud/android/ui/activity/ReceiveExternalFilesActivity.java b/src/com/owncloud/android/ui/activity/ReceiveExternalFilesActivity.java index 58214dec89..7449b90722 100644 --- a/src/com/owncloud/android/ui/activity/ReceiveExternalFilesActivity.java +++ b/src/com/owncloud/android/ui/activity/ReceiveExternalFilesActivity.java @@ -266,7 +266,6 @@ public class ReceiveExternalFilesActivity extends FileActivity case DIALOG_MULTIPLE_ACCOUNT: Account accounts[] = mAccountManager.getAccountsByType(MainApp.getAccountType()); CharSequence dialogItems[] = new CharSequence[accounts.length]; - OwnCloudAccount oca; for (int i = 0; i < dialogItems.length; ++i) { dialogItems[i] = DisplayUtils.getAccountNameDisplayText( this, accounts[i], accounts[i].name, DisplayUtils.convertIdn(accounts[i].name, false)); @@ -316,11 +315,14 @@ public class ReceiveExternalFilesActivity extends FileActivity Vector tmpfiles = getStorageManager().getFolderContent(mFile , false); sortFileList(tmpfiles); - if (tmpfiles.size() <= 0) return; + if (tmpfiles.size() <= 0) { + return; + } // filter on dirtype Vector files = new Vector<>(); - for (OCFile f : tmpfiles) - files.add(f); + for (OCFile f : tmpfiles) { + files.add(f); + } if (files.size() < position) { throw new IndexOutOfBoundsException("Incorrect item selected"); } @@ -526,8 +528,9 @@ public class ReceiveExternalFilesActivity extends FileActivity private String generatePath(Stack dirs) { String full_path = ""; - for (String a : dirs) + for (String a : dirs) { full_path += a + "/"; + } return full_path; } @@ -612,7 +615,7 @@ public class ReceiveExternalFilesActivity extends FileActivity RemoteOperationResult result) { if (result.isSuccess()) { String remotePath = operation.getRemotePath().substring(0, operation.getRemotePath().length() - 1); - String newFolder = remotePath.substring(remotePath.lastIndexOf("/") + 1); + String newFolder = remotePath.substring(remotePath.lastIndexOf('/') + 1); mParents.push(newFolder); populateDirectoryList(); } else { @@ -647,8 +650,9 @@ public class ReceiveExternalFilesActivity extends FileActivity } else { String[] dir_names = lastPath.split("/"); mParents.clear(); - for (String dir : dir_names) + for (String dir : dir_names) { mParents.add(dir); + } } //Make sure that path still exists, if it doesn't pop the stack and try the previous path while (!getStorageManager().fileExists(generatePath(mParents)) && mParents.size() > 1) { @@ -752,8 +756,7 @@ public class ReceiveExternalFilesActivity extends FileActivity currentFile = currentDir; } - if (synchFolderRemotePath != null && - currentDir.getRemotePath().equals(synchFolderRemotePath)) { + if (currentDir.getRemotePath().equals(synchFolderRemotePath)) { populateDirectoryList(); } mFile = currentFile; diff --git a/src/com/owncloud/android/ui/activity/UploadFilesActivity.java b/src/com/owncloud/android/ui/activity/UploadFilesActivity.java index 1b87294e3b..9e33b1f5db 100644 --- a/src/com/owncloud/android/ui/activity/UploadFilesActivity.java +++ b/src/com/owncloud/android/ui/activity/UploadFilesActivity.java @@ -256,8 +256,9 @@ public class UploadFilesActivity extends FileActivity implements // the next operation triggers a new call to this method, but it's necessary to // ensure that the name exposed in the action bar is the current directory when the // user selected it in the navigation list - if (itemPosition != 0) + if (itemPosition != 0) { getSupportActionBar().setSelectedNavigationItem(0); + } return true; } diff --git a/src/com/owncloud/android/ui/adapter/DiskLruImageCache.java b/src/com/owncloud/android/ui/adapter/DiskLruImageCache.java index 0f2536f551..03331d7f43 100644 --- a/src/com/owncloud/android/ui/adapter/DiskLruImageCache.java +++ b/src/com/owncloud/android/ui/adapter/DiskLruImageCache.java @@ -43,6 +43,7 @@ public class DiskLruImageCache { private static final int CACHE_VERSION = 1; private static final int VALUE_COUNT = 1; private static final int IO_BUFFER_SIZE = 8 * 1024; + private static final String CACHE_TEST_DISK = "cache_test_DISK_"; private static final String TAG = DiskLruImageCache.class.getSimpleName(); @@ -85,17 +86,17 @@ public class DiskLruImageCache { mDiskCache.flush(); editor.commit(); if ( BuildConfig.DEBUG ) { - Log_OC.d( "cache_test_DISK_", "image put on disk cache " + validKey ); + Log_OC.d( CACHE_TEST_DISK, "image put on disk cache " + validKey ); } } else { editor.abort(); if ( BuildConfig.DEBUG ) { - Log_OC.d( "cache_test_DISK_", "ERROR on: image put on disk cache " + validKey ); + Log_OC.d( CACHE_TEST_DISK, "ERROR on: image put on disk cache " + validKey ); } } } catch (IOException e) { if ( BuildConfig.DEBUG ) { - Log_OC.d( "cache_test_DISK_", "ERROR on: image put on disk cache " + validKey ); + Log_OC.d( CACHE_TEST_DISK, "ERROR on: image put on disk cache " + validKey ); } try { if ( editor != null ) { @@ -125,15 +126,15 @@ public class DiskLruImageCache { bitmap = BitmapFactory.decodeStream( buffIn ); } } catch ( IOException e ) { - e.printStackTrace(); + Log_OC.d(TAG, e.getMessage(), e); } finally { - if ( snapshot != null ) { + if (snapshot != null) { snapshot.close(); } } if ( BuildConfig.DEBUG ) { - Log_OC.d("cache_test_DISK_", bitmap == null ? + Log_OC.d(CACHE_TEST_DISK, bitmap == null ? "not found" : "image read from disk " + validKey); } @@ -150,9 +151,9 @@ public class DiskLruImageCache { snapshot = mDiskCache.get( validKey ); contained = snapshot != null; } catch (IOException e) { - e.printStackTrace(); + Log_OC.d(TAG, e.getMessage(), e); } finally { - if ( snapshot != null ) { + if (snapshot != null) { snapshot.close(); } } @@ -163,12 +164,12 @@ public class DiskLruImageCache { public void clearCache() { if ( BuildConfig.DEBUG ) { - Log_OC.d( "cache_test_DISK_", "disk cache CLEARED"); + Log_OC.d( CACHE_TEST_DISK, "disk cache CLEARED"); } try { mDiskCache.delete(); } catch ( IOException e ) { - e.printStackTrace(); + Log_OC.d(TAG, e.getMessage(), e); } } @@ -190,7 +191,7 @@ public class DiskLruImageCache { mDiskCache.remove(validKey); Log_OC.d(TAG, "removeKey from cache: " + validKey); } catch (IOException e) { - e.printStackTrace(); + Log_OC.d(TAG, e.getMessage(), e); } } } \ No newline at end of file diff --git a/src/com/owncloud/android/ui/adapter/FileListListAdapter.java b/src/com/owncloud/android/ui/adapter/FileListListAdapter.java index 2a22073a9b..f314757191 100644 --- a/src/com/owncloud/android/ui/adapter/FileListListAdapter.java +++ b/src/com/owncloud/android/ui/adapter/FileListListAdapter.java @@ -112,15 +112,17 @@ public class FileListListAdapter extends BaseAdapter implements FilterableListAd @Override public Object getItem(int position) { - if (mFiles == null || mFiles.size() <= position) + if (mFiles == null || mFiles.size() <= position) { return null; + } return mFiles.get(position); } @Override public long getItemId(int position) { - if (mFiles == null || mFiles.size() <= position) + if (mFiles == null || mFiles.size() <= position) { return 0; + } return mFiles.get(position).getFileId(); } @@ -384,7 +386,7 @@ public class FileListListAdapter extends BaseAdapter implements FilterableListAd */ public void swapDirectory(OCFile directory, FileDataStorageManager updatedStorageManager , boolean onlyOnDevice) { - if (updatedStorageManager != null && updatedStorageManager != mStorageManager) { + if (updatedStorageManager != null && updatedStorageManager.equals(mStorageManager)) { mStorageManager = updatedStorageManager; mAccount = AccountUtils.getCurrentOwnCloudAccount(mContext); } diff --git a/src/com/owncloud/android/ui/adapter/LocalFileListAdapter.java b/src/com/owncloud/android/ui/adapter/LocalFileListAdapter.java index cd0f892fc7..f69cf9fcff 100644 --- a/src/com/owncloud/android/ui/adapter/LocalFileListAdapter.java +++ b/src/com/owncloud/android/ui/adapter/LocalFileListAdapter.java @@ -43,6 +43,7 @@ import com.owncloud.android.utils.MimeTypeUtil; import java.io.File; import java.util.ArrayList; import java.util.Arrays; +import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Vector; @@ -56,7 +57,6 @@ public class LocalFileListAdapter extends BaseAdapter implements FilterableListA private static final String TAG = LocalFileListAdapter.class.getSimpleName(); private Context mContext; - private File mDirectory; private File[] mFiles = null; private Vector mFilesAll = new Vector(); @@ -87,8 +87,9 @@ public class LocalFileListAdapter extends BaseAdapter implements FilterableListA @Override public Object getItem(int position) { - if (mFiles == null || mFiles.length <= position) + if (mFiles == null || mFiles.length <= position) { return null; + } return mFiles[position]; } @@ -267,9 +268,8 @@ public class LocalFileListAdapter extends BaseAdapter implements FilterableListA * Change the adapted directory for a new one * @param directory New file to adapt. Can be NULL, meaning "no content to adapt". */ - public void swapDirectory(File directory) { - mDirectory = directory; - mFiles = (mDirectory != null ? mDirectory.listFiles() : null); + public void swapDirectory(final File directory) { + mFiles = (directory != null ? directory.listFiles() : null); if (mFiles != null) { Arrays.sort(mFiles, new Comparator() { @Override @@ -298,9 +298,7 @@ public class LocalFileListAdapter extends BaseAdapter implements FilterableListA mFilesAll.clear(); - for (File mFile : mFiles) { - mFilesAll.add(mFile); - } + Collections.addAll(mFilesAll, mFiles); } notifyDataSetChanged(); } diff --git a/src/com/owncloud/android/ui/adapter/UploaderAdapter.java b/src/com/owncloud/android/ui/adapter/UploaderAdapter.java index 3e9f8c6313..8eeac8409d 100644 --- a/src/com/owncloud/android/ui/adapter/UploaderAdapter.java +++ b/src/com/owncloud/android/ui/adapter/UploaderAdapter.java @@ -63,8 +63,9 @@ public class UploaderAdapter extends SimpleAdapter { @Override public View getView(int position, View convertView, ViewGroup parent) { View vi = convertView; - if (convertView == null) + if (convertView == null) { vi = inflater.inflate(R.layout.uploader_list_item_layout, null); + } HashMap data = (HashMap) getItem(position); OCFile file = data.get("dirname"); diff --git a/src/com/owncloud/android/ui/adapter/X509CertificateViewAdapter.java b/src/com/owncloud/android/ui/adapter/X509CertificateViewAdapter.java index 742d6d821a..48acd77f62 100644 --- a/src/com/owncloud/android/ui/adapter/X509CertificateViewAdapter.java +++ b/src/com/owncloud/android/ui/adapter/X509CertificateViewAdapter.java @@ -128,7 +128,7 @@ public class X509CertificateViewAdapter implements SslUntrustedCertDialog.Certif final int loVal = b & 0x0F; hex.append((char) ('0' + (hiVal + (hiVal / 10 * 7)))); hex.append((char) ('0' + (loVal + (loVal / 10 * 7)))); - hex.append(":"); + hex.append(':'); } return digestType + ":" + newLine + hex.toString().replaceFirst("\\:$","") + newLine + newLine; } diff --git a/src/com/owncloud/android/ui/asynctasks/CopyAndUploadContentUrisTask.java b/src/com/owncloud/android/ui/asynctasks/CopyAndUploadContentUrisTask.java index 3717ad5de4..e6f8a3b8ff 100644 --- a/src/com/owncloud/android/ui/asynctasks/CopyAndUploadContentUrisTask.java +++ b/src/com/owncloud/android/ui/asynctasks/CopyAndUploadContentUrisTask.java @@ -88,7 +88,7 @@ public class CopyAndUploadContentUrisTask extends AsyncTask= 0) ? extensionStart : currentName.length(); if (selectionStart >= 0 && selectionEnd >= 0) { inputText.setSelection( diff --git a/src/com/owncloud/android/ui/dialog/SamlWebViewDialog.java b/src/com/owncloud/android/ui/dialog/SamlWebViewDialog.java index 4081fbd7ad..cb2f5330f2 100644 --- a/src/com/owncloud/android/ui/dialog/SamlWebViewDialog.java +++ b/src/com/owncloud/android/ui/dialog/SamlWebViewDialog.java @@ -51,8 +51,6 @@ import com.owncloud.android.lib.common.utils.Log_OC; */ public class SamlWebViewDialog extends DialogFragment { - public final String SAML_DIALOG_TAG = "SamlWebViewDialog"; - private final static String TAG = SamlWebViewDialog.class.getSimpleName(); private static final String ARG_INITIAL_URL = "INITIAL_URL"; @@ -63,8 +61,6 @@ public class SamlWebViewDialog extends DialogFragment { private String mInitialUrl; private String mTargetUrl; - - private Handler mHandler; private SsoWebViewClientListener mSsoWebViewClientListener; @@ -97,7 +93,7 @@ public class SamlWebViewDialog extends DialogFragment { super.onAttach(activity); try { mSsoWebViewClientListener = (SsoWebViewClientListener) activity; - mHandler = new Handler(); + Handler mHandler = new Handler(); mWebViewClient = new SsoWebViewClient(activity, mHandler, mSsoWebViewClientListener); } catch (ClassCastException e) { diff --git a/src/com/owncloud/android/ui/dialog/SslUntrustedCertDialog.java b/src/com/owncloud/android/ui/dialog/SslUntrustedCertDialog.java index 12f595a683..d4b496ec4a 100644 --- a/src/com/owncloud/android/ui/dialog/SslUntrustedCertDialog.java +++ b/src/com/owncloud/android/ui/dialog/SslUntrustedCertDialog.java @@ -179,8 +179,9 @@ public class SslUntrustedCertDialog extends DialogFragment { @Override public void onDestroyView() { Log_OC.d(TAG, "onDestroyView"); - if (getDialog() != null && getRetainInstance()) + if (getDialog() != null && getRetainInstance()) { getDialog().setDismissMessage(null); + } super.onDestroyView(); } diff --git a/src/com/owncloud/android/ui/dialog/SslValidatorDialog.java b/src/com/owncloud/android/ui/dialog/SslValidatorDialog.java index 1e31c0ca41..cbcbad27f3 100644 --- a/src/com/owncloud/android/ui/dialog/SslValidatorDialog.java +++ b/src/com/owncloud/android/ui/dialog/SslValidatorDialog.java @@ -71,8 +71,7 @@ public class SslValidatorDialog extends Dialog { */ public static SslValidatorDialog newInstance(Context context, RemoteOperationResult result, OnSslValidatorListener listener) { if (result != null && result.isSslRecoverableException()) { - SslValidatorDialog dialog = new SslValidatorDialog(context, listener); - return dialog; + return new SslValidatorDialog(context, listener); } else { return null; } @@ -109,22 +108,19 @@ public class SslValidatorDialog extends Dialog { try { saveServerCert(); dismiss(); - if (mListener != null) + if (mListener != null) { mListener.onSavedCertificate(); - else + } else { Log_OC.d(TAG, "Nobody there to notify the certificate was saved"); + } - } catch (GeneralSecurityException e) { + } catch (GeneralSecurityException | IOException e) { dismiss(); - if (mListener != null) + if (mListener != null) { mListener.onFailedSavingCertificate(); + } Log_OC.e(TAG, "Server certificate could not be saved in the known servers trust store ", e); - } catch (IOException e) { - dismiss(); - if (mListener != null) - mListener.onFailedSavingCertificate(); - Log_OC.e(TAG, "Server certificate could not be saved in the known servers trust store ", e); } } }); @@ -145,7 +141,6 @@ public class SslValidatorDialog extends Dialog { if (detailsScroll.getVisibility() == View.VISIBLE) { detailsScroll.setVisibility(View.GONE); ((Button) v).setText(R.string.ssl_validator_btn_details_see); - } else { detailsScroll.setVisibility(View.VISIBLE); ((Button) v).setText(R.string.ssl_validator_btn_details_hide); @@ -198,8 +193,8 @@ public class SslValidatorDialog extends Dialog { showSignature(cert); } else { - // this should not happen - // TODO + // this should not happen, TODO + Log_OC.d("certNull", "This should not happen"); } } diff --git a/src/com/owncloud/android/ui/errorhandling/ExceptionHandler.java b/src/com/owncloud/android/ui/errorhandling/ExceptionHandler.java index 080017146d..f32c44ea3b 100755 --- a/src/com/owncloud/android/ui/errorhandling/ExceptionHandler.java +++ b/src/com/owncloud/android/ui/errorhandling/ExceptionHandler.java @@ -29,7 +29,6 @@ import android.util.Log; public class ExceptionHandler implements java.lang.Thread.UncaughtExceptionHandler { private final Activity mContext; - private final String LINE_SEPARATOR = "\n"; private static final String TAG = ExceptionHandler.class.getSimpleName(); @@ -41,36 +40,34 @@ public class ExceptionHandler implements java.lang.Thread.UncaughtExceptionHandl Log.e(TAG, "ExceptionHandler caught UncaughtException", exception); StringWriter stackTrace = new StringWriter(); exception.printStackTrace(new PrintWriter(stackTrace)); - StringBuilder errorReport = new StringBuilder(); - errorReport.append("************ CAUSE OF ERROR ************\n\n"); - errorReport.append(stackTrace.toString()); - - errorReport.append("\n************ DEVICE INFORMATION ***********\n"); - errorReport.append("Brand: "); - errorReport.append(Build.BRAND); - errorReport.append(LINE_SEPARATOR); - errorReport.append("Device: "); - errorReport.append(Build.DEVICE); - errorReport.append(LINE_SEPARATOR); - errorReport.append("Model: "); - errorReport.append(Build.MODEL); - errorReport.append(LINE_SEPARATOR); - errorReport.append("Id: "); - errorReport.append(Build.ID); - errorReport.append(LINE_SEPARATOR); - errorReport.append("Product: "); - errorReport.append(Build.PRODUCT); - errorReport.append(LINE_SEPARATOR); - errorReport.append("\n************ FIRMWARE ************\n"); - errorReport.append("SDK: "); - errorReport.append(Build.VERSION.SDK_INT); - errorReport.append(LINE_SEPARATOR); - errorReport.append("Release: "); - errorReport.append(Build.VERSION.RELEASE); - errorReport.append(LINE_SEPARATOR); - errorReport.append("Incremental: "); - errorReport.append(Build.VERSION.INCREMENTAL); - errorReport.append(LINE_SEPARATOR); + final StringBuilder errorReport = new StringBuilder(192); + final String LINE_SEPARATOR = "\n"; + errorReport.append("************ CAUSE OF ERROR ************\n\n") + .append(stackTrace.toString()) + .append("\n************ DEVICE INFORMATION ***********\nBrand: ") + .append(Build.BRAND) + .append(LINE_SEPARATOR) + .append("Device: ") + .append(Build.DEVICE) + .append(LINE_SEPARATOR) + .append("Model: ") + .append(Build.MODEL) + .append(LINE_SEPARATOR) + .append("Id: ") + .append(Build.ID) + .append(LINE_SEPARATOR) + .append("Product: ") + .append(Build.PRODUCT) + .append(LINE_SEPARATOR) + .append("\n************ FIRMWARE ************\nSDK: ") + .append(Build.VERSION.SDK_INT) + .append(LINE_SEPARATOR) + .append("Release: ") + .append(Build.VERSION.RELEASE) + .append(LINE_SEPARATOR) + .append("Incremental: ") + .append(Build.VERSION.INCREMENTAL) + .append(LINE_SEPARATOR); Log.e(TAG, "An exception was thrown and handled by ExceptionHandler:", exception); diff --git a/src/com/owncloud/android/ui/fragment/EditShareFragment.java b/src/com/owncloud/android/ui/fragment/EditShareFragment.java index 042dd677bc..f046b560fe 100644 --- a/src/com/owncloud/android/ui/fragment/EditShareFragment.java +++ b/src/com/owncloud/android/ui/fragment/EditShareFragment.java @@ -64,9 +64,6 @@ public class EditShareFragment extends Fragment { /** File bound to mShare, received as a parameter in construction time */ private OCFile mFile; - /** OC account holding the shared file, received as a parameter in construction time */ - private Account mAccount; - /** Listener for changes on privilege checkboxes */ private CompoundButton.OnCheckedChangeListener mOnPrivilegeChangeListener; @@ -106,7 +103,8 @@ public class EditShareFragment extends Fragment { if (getArguments() != null) { mShare = getArguments().getParcelable(ARG_SHARE); mFile = getArguments().getParcelable(ARG_FILE); - mAccount = getArguments().getParcelable(ARG_ACCOUNT); + /* OC account holding the shared file, received as a parameter in construction time */ + Account mAccount = getArguments().getParcelable(ARG_ACCOUNT); } } diff --git a/src/com/owncloud/android/ui/fragment/ExtendedListFragment.java b/src/com/owncloud/android/ui/fragment/ExtendedListFragment.java index ad58be1d53..73b44ca102 100644 --- a/src/com/owncloud/android/ui/fragment/ExtendedListFragment.java +++ b/src/com/owncloud/android/ui/fragment/ExtendedListFragment.java @@ -137,7 +137,7 @@ public class ExtendedListFragment extends Fragment } public boolean isGridEnabled(){ - return (mCurrentListView == mGridView); + return mCurrentListView.equals(mGridView); } @Override @@ -283,7 +283,7 @@ public class ExtendedListFragment extends Fragment Log_OC.v(TAG, "Setting selection to position: " + firstPosition + "; top: " + top + "; index: " + index); - if (mCurrentListView == mListView) { + if (mCurrentListView.equals(mListView)) { if (mHeightCell*index <= mListView.getHeight()) { mListView.setSelectionFromTop(firstPosition, top); } else { diff --git a/src/com/owncloud/android/ui/fragment/LocalFileListFragment.java b/src/com/owncloud/android/ui/fragment/LocalFileListFragment.java index cf30f0ec67..4c54342132 100644 --- a/src/com/owncloud/android/ui/fragment/LocalFileListFragment.java +++ b/src/com/owncloud/android/ui/fragment/LocalFileListFragment.java @@ -195,7 +195,9 @@ public class LocalFileListFragment extends ExtendedListFragment { } else { directory = Environment.getExternalStorageDirectory(); // TODO be careful with the state of the storage; could not be available - if (directory == null) return; // no files to show + if (directory == null) { + return; // no files to show + } } } diff --git a/src/com/owncloud/android/ui/fragment/OCFileListFragment.java b/src/com/owncloud/android/ui/fragment/OCFileListFragment.java index 559545b08e..5938836574 100644 --- a/src/com/owncloud/android/ui/fragment/OCFileListFragment.java +++ b/src/com/owncloud/android/ui/fragment/OCFileListFragment.java @@ -94,7 +94,7 @@ public class OCFileListFragment extends ExtendedListFragment { private static final String GRID_IS_PREFERED_PREFERENCE = "gridIsPrefered"; - private static String DIALOG_CREATE_FOLDER = "DIALOG_CREATE_FOLDER"; + private static final String DIALOG_CREATE_FOLDER = "DIALOG_CREATE_FOLDER"; private FileFragment.ContainerActivity mContainerActivity; @@ -586,7 +586,7 @@ public class OCFileListFragment extends ExtendedListFragment { } // exit is granted because storageManager.getFileByPath("/") never returns null mFile = parentDir; - listDirectory(mFile, MainApp.getOnlyOnDevice()); + listDirectory(mFile, MainApp.isOnlyOnDevice()); onRefresh(false); @@ -604,7 +604,7 @@ public class OCFileListFragment extends ExtendedListFragment { if (file != null) { if (file.isFolder()) { // update state and view of this fragment - listDirectory(file, MainApp.getOnlyOnDevice()); + listDirectory(file, MainApp.isOnlyOnDevice()); // then, notify parent activity to let it update its state and view mContainerActivity.onBrowsedDownTo(file); // save index and top position @@ -645,7 +645,9 @@ public class OCFileListFragment extends ExtendedListFragment { */ public boolean onFileActionChosen(int menuId) { final ArrayList checkedFiles = mAdapter.getCheckedItems(getListView()); - if (checkedFiles.size() <= 0) return false; + if (checkedFiles.size() <= 0) { + return false; + } if (checkedFiles.size() == 1) { /// action only possible on a single file @@ -745,7 +747,7 @@ public class OCFileListFragment extends ExtendedListFragment { } public void refreshDirectory(){ - listDirectory(getCurrentFile(), MainApp.getOnlyOnDevice()); + listDirectory(getCurrentFile(), MainApp.isOnlyOnDevice()); } /** @@ -765,7 +767,9 @@ public class OCFileListFragment extends ExtendedListFragment { directory = mFile; } else { directory = storageManager.getFileByPath("/"); - if (directory == null) return; // no files, wait for sync + if (directory == null) { + return; // no files, wait for sync + } } } diff --git a/src/com/owncloud/android/ui/fragment/UploadListFragment.java b/src/com/owncloud/android/ui/fragment/UploadListFragment.java index 73808e87df..9487c5dfde 100755 --- a/src/com/owncloud/android/ui/fragment/UploadListFragment.java +++ b/src/com/owncloud/android/ui/fragment/UploadListFragment.java @@ -38,7 +38,7 @@ import com.owncloud.android.ui.adapter.ExpandableUploadListAdapter; * */ public class UploadListFragment extends ExpandableListFragment { - static private String TAG = UploadListFragment.class.getSimpleName(); + private static final String TAG = UploadListFragment.class.getSimpleName(); /** * Reference to the Activity which this fragment is attached to. For diff --git a/src/com/owncloud/android/ui/preview/FileDownloadFragment.java b/src/com/owncloud/android/ui/preview/FileDownloadFragment.java index e63b324528..e4cbe96d5f 100644 --- a/src/com/owncloud/android/ui/preview/FileDownloadFragment.java +++ b/src/com/owncloud/android/ui/preview/FileDownloadFragment.java @@ -279,26 +279,22 @@ public class FileDownloadFragment extends FileFragment implements OnClickListene public void listenForTransferProgress() { - if (mProgressListener != null && !mListening) { - if (mContainerActivity.getFileDownloaderBinder() != null) { - mContainerActivity.getFileDownloaderBinder().addDatatransferProgressListener( - mProgressListener, mAccount, getFile() - ); - mListening = true; - setButtonsForTransferring(); - } + if (mProgressListener != null && !mListening && mContainerActivity.getFileDownloaderBinder() != null) { + mContainerActivity.getFileDownloaderBinder().addDatatransferProgressListener( + mProgressListener, mAccount, getFile() + ); + mListening = true; + setButtonsForTransferring(); } } public void leaveTransferProgress() { - if (mProgressListener != null) { - if (mContainerActivity.getFileDownloaderBinder() != null) { - mContainerActivity.getFileDownloaderBinder().removeDatatransferProgressListener( - mProgressListener, mAccount, getFile() - ); - mListening = false; - } + if (mProgressListener != null && mContainerActivity.getFileDownloaderBinder() != null) { + mContainerActivity.getFileDownloaderBinder().removeDatatransferProgressListener( + mProgressListener, mAccount, getFile() + ); + mListening = false; } } diff --git a/src/com/owncloud/android/ui/preview/PreviewImageActivity.java b/src/com/owncloud/android/ui/preview/PreviewImageActivity.java index fd70dddd56..9edcb38f4e 100644 --- a/src/com/owncloud/android/ui/preview/PreviewImageActivity.java +++ b/src/com/owncloud/android/ui/preview/PreviewImageActivity.java @@ -65,6 +65,7 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; /** * Holds a swiping galley where image files contained in an ownCloud directory are shown */ +@SuppressWarnings("PMD.AvoidDuplicateLiterals") public class PreviewImageActivity extends FileActivity implements FileFragment.ContainerActivity, ViewPager.OnPageChangeListener, OnRemoteOperationListener { @@ -154,7 +155,7 @@ public class PreviewImageActivity extends FileActivity implements } mPreviewImagePagerAdapter = new PreviewImagePagerAdapter(getSupportFragmentManager(), - parentFolder, getAccount(), getStorageManager(), MainApp.getOnlyOnDevice()); + parentFolder, getAccount(), getStorageManager(), MainApp.isOnlyOnDevice()); mViewPager = (ExtendedViewPager) findViewById(R.id.fragmentPager); int position = mHasSavedPosition ? mSavedPosition : @@ -393,10 +394,9 @@ public class PreviewImageActivity extends FileActivity implements OCFile currentFile = mPreviewImagePagerAdapter.getFileAt(position); getSupportActionBar().setTitle(currentFile.getFileName()); setDrawerIndicatorEnabled(false); - if (!currentFile.isDown()) { - if (!mPreviewImagePagerAdapter.pendingErrorAt(position)) { - requestForDownload(currentFile); - } + if (!currentFile.isDown() + && !mPreviewImagePagerAdapter.pendingErrorAt(position)) { + requestForDownload(currentFile); } // Call to reset image zoom to initial state @@ -522,8 +522,9 @@ public class PreviewImageActivity extends FileActivity implements } // Update file according to DB file, if it is possible - if (file.getFileId() > FileDataStorageManager.ROOT_PARENT_ID) + if (file.getFileId() > FileDataStorageManager.ROOT_PARENT_ID) { file = getStorageManager().getFileById(file.getFileId()); + } if (file != null) { /// Refresh the activity according to the Account and OCFile set diff --git a/src/com/owncloud/android/ui/preview/PreviewImageFragment.java b/src/com/owncloud/android/ui/preview/PreviewImageFragment.java index c781a37581..f9c106d00b 100644 --- a/src/com/owncloud/android/ui/preview/PreviewImageFragment.java +++ b/src/com/owncloud/android/ui/preview/PreviewImageFragment.java @@ -413,7 +413,9 @@ public class PreviewImageFragment extends FileFragment { @Override protected LoadImage doInBackground(OCFile... params) { Bitmap result = null; - if (params.length != 1) return null; + if (params.length != 1) { + return null; + } OCFile ocFile = params[0]; String storagePath = ocFile.getStoragePath(); try { @@ -423,12 +425,16 @@ public class PreviewImageFragment extends FileFragment { int minWidth = screenSize.x; int minHeight = screenSize.y; for (int i = 0; i < maxDownScale && result == null; i++) { - if (isCancelled()) return null; + if (isCancelled()) { + return null; + } try { result = BitmapUtils.decodeSampledBitmapFromFile(storagePath, minWidth, minHeight); - if (isCancelled()) return new LoadImage(result, ocFile); + if (isCancelled()) { + return new LoadImage(result, ocFile); + } if (result == null) { mErrorMessageId = R.string.preview_image_error_unknown_format; diff --git a/src/com/owncloud/android/ui/preview/PreviewMediaFragment.java b/src/com/owncloud/android/ui/preview/PreviewMediaFragment.java index 6e8de5f57e..ff2d66bf96 100644 --- a/src/com/owncloud/android/ui/preview/PreviewMediaFragment.java +++ b/src/com/owncloud/android/ui/preview/PreviewMediaFragment.java @@ -543,7 +543,7 @@ public class PreviewMediaFragment extends FileFragment implements @Override public boolean onTouch(View v, MotionEvent event) { - if (event.getAction() == MotionEvent.ACTION_DOWN && v == mVideoPreview) { + if (event.getAction() == MotionEvent.ACTION_DOWN && v.equals(mVideoPreview)) { // added a margin on the left to avoid interfering with gesture to open navigation drawer if (event.getX() / Resources.getSystem().getDisplayMetrics().density > 24.0) { startFullScreenVideo(); @@ -614,21 +614,18 @@ public class PreviewMediaFragment extends FileFragment implements @Override public void onServiceConnected(ComponentName component, IBinder service) { - if (getActivity() != null) { - if (component.equals( - new ComponentName(getActivity(), MediaService.class))) { - Log_OC.d(TAG, "Media service connected"); - mMediaServiceBinder = (MediaServiceBinder) service; - if (mMediaServiceBinder != null) { - prepareMediaController(); - playAudio(); // do not wait for the touch of nobody to play audio + if (getActivity() != null + && component.equals(new ComponentName(getActivity(), MediaService.class))) { + Log_OC.d(TAG, "Media service connected"); + mMediaServiceBinder = (MediaServiceBinder) service; + if (mMediaServiceBinder != null) { + prepareMediaController(); + playAudio(); // do not wait for the touch of nobody to play audio - Log_OC.d(TAG, "Successfully bound to MediaService, MediaController ready"); + Log_OC.d(TAG, "Successfully bound to MediaService, MediaController ready"); - } - else { - Log_OC.e(TAG, "Unexpected response from MediaService while binding"); - } + } else { + Log_OC.e(TAG, "Unexpected response from MediaService while binding"); } } } diff --git a/src/com/owncloud/android/ui/preview/PreviewTextFragment.java b/src/com/owncloud/android/ui/preview/PreviewTextFragment.java index 27f3d2014c..e2953d918d 100644 --- a/src/com/owncloud/android/ui/preview/PreviewTextFragment.java +++ b/src/com/owncloud/android/ui/preview/PreviewTextFragment.java @@ -156,7 +156,7 @@ public class PreviewTextFragment extends FileFragment { * Reads the file to preview and shows its contents. Too critical to be anonymous. */ private class TextLoadAsyncTask extends AsyncTask { - private final String DIALOG_WAIT_TAG = "DIALOG_WAIT"; + private static final String DIALOG_WAIT_TAG = "DIALOG_WAIT"; private final WeakReference mTextViewReference; private TextLoadAsyncTask(WeakReference textView) { @@ -185,11 +185,15 @@ public class PreviewTextFragment extends FileFragment { sc = new Scanner(inputStream); while (sc.hasNextLine()) { bufferedWriter.append(sc.nextLine()); - if (sc.hasNextLine()) bufferedWriter.append("\n"); + if (sc.hasNextLine()) { + bufferedWriter.append("\n"); + } } bufferedWriter.close(); IOException exc = sc.ioException(); - if (exc != null) throw exc; + if (exc != null) { + throw exc; + } } catch (IOException e) { Log_OC.e(TAG, e.getMessage(), e); finish(); diff --git a/src/com/owncloud/android/utils/BitmapUtils.java b/src/com/owncloud/android/utils/BitmapUtils.java index c198db4187..7c7194f37b 100644 --- a/src/com/owncloud/android/utils/BitmapUtils.java +++ b/src/com/owncloud/android/utils/BitmapUtils.java @@ -171,7 +171,7 @@ public class BitmapUtils { // Rotate the bitmap resultBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true); - if (resultBitmap != bitmap) { + if (!resultBitmap.equals(bitmap)) { bitmap.recycle(); } } @@ -192,6 +192,7 @@ public class BitmapUtils { * adapted from https://svn.codehaus.org/griffon/builders/gfxbuilder/tags/GFXBUILDER_0.2/ * gfxbuilder-core/src/main/com/camick/awt/HSLColor.java */ + @SuppressWarnings("PMD.MethodNamingConventions") public static int[] HSLtoRGB(float h, float s, float l, float alpha) { if (s <0.0f || s > 100.0f) @@ -221,10 +222,11 @@ public class BitmapUtils { float q = 0; - if (l < 0.5) + if (l < 0.5) { q = l * (1 + s); - else + } else { q = (l + s) - (s * l); + } float p = 2 * l - q; @@ -232,27 +234,28 @@ public class BitmapUtils { int g = Math.round(Math.max(0, HueToRGB(p, q, h) * 256)); int b = Math.round(Math.max(0, HueToRGB(p, q, h - (1.0f / 3.0f)) * 256)); - int[] array = {r, g, b}; - return array; + return new int[]{r, g, b}; } + @SuppressWarnings("PMD.MethodNamingConventions") private static float HueToRGB(float p, float q, float h){ - if (h < 0) h += 1; + if (h < 0) { + h += 1; + } - if (h > 1 ) h -= 1; + if (h > 1 ) { + h -= 1; + } - if (6 * h < 1) - { + if (6 * h < 1) { return p + ((q - p) * 6 * h); } - if (2 * h < 1 ) - { + if (2 * h < 1 ) { return q; } - if (3 * h < 2) - { + if (3 * h < 2) { return p + ( (q - p) * 6 * ((2.0f / 3.0f) - h) ); } diff --git a/src/com/owncloud/android/utils/DisplayUtils.java b/src/com/owncloud/android/utils/DisplayUtils.java index 8fb657fcf5..ec2ef5a82f 100644 --- a/src/com/owncloud/android/utils/DisplayUtils.java +++ b/src/com/owncloud/android/utils/DisplayUtils.java @@ -111,7 +111,7 @@ public class DisplayUtils { suffixIndex++; } - return new BigDecimal(result).setScale( + return new BigDecimal(String.valueOf(result)).setScale( sizeScales[suffixIndex], BigDecimal.ROUND_HALF_UP) + " " + sizeSuffixes[suffixIndex]; } } @@ -127,8 +127,9 @@ public class DisplayUtils { if (mimeType2HumanReadable.containsKey(mimetype)) { return mimeType2HumanReadable.get(mimetype); } - if (mimetype.split("/").length >= 2) + if (mimetype.split("/").length >= 2) { return mimetype.split("/")[1].toUpperCase() + " file"; + } return MIME_TYPE_UNKNOWN; } @@ -167,7 +168,7 @@ public class DisplayUtils { if (urlNoDots.contains("//")) { hostStart = url.indexOf("//") + "//".length(); } else if (url.contains("@")) { - hostStart = url.indexOf("@") + "@".length(); + hostStart = url.indexOf('@') + "@".length(); } int hostEnd = url.substring(hostStart).indexOf("/"); @@ -197,7 +198,7 @@ public class DisplayUtils { try { return new OwnCloudAccount(savedAccount, context).getDisplayName() + " @ " - + convertIdn(accountName.substring(accountName.lastIndexOf("@") + 1), false); + + convertIdn(accountName.substring(accountName.lastIndexOf('@') + 1), false); } catch (Exception e) { Log_OC.w(TAG, "Couldn't get display name for account, using old style"); return fallbackString; @@ -382,8 +383,9 @@ public class DisplayUtils { public static void setAvatar(Account account, AvatarGenerationListener listener, float avatarRadius, Resources resources, FileDataStorageManager storageManager, Object callContext) { if (account != null) { - if (callContext instanceof View) - ((View)callContext).setContentDescription(account.name); + if (callContext instanceof View) { + ((View) callContext).setContentDescription(account.name); + } // Thumbnail in Cache? Bitmap thumbnail = ThumbnailsCacheManager.getBitmapFromDiskCache("a_" + account.name); diff --git a/src/com/owncloud/android/utils/ErrorMessageAdapter.java b/src/com/owncloud/android/utils/ErrorMessageAdapter.java index 8a6a94a81b..82dfd05356 100644 --- a/src/com/owncloud/android/utils/ErrorMessageAdapter.java +++ b/src/com/owncloud/android/utils/ErrorMessageAdapter.java @@ -313,7 +313,8 @@ public class ErrorMessageAdapter { code == ResultCode.TIMEOUT || code == ResultCode.HOST_NOT_AVAILABLE) { return true; - } else + } else { return false; + } } } diff --git a/src/com/owncloud/android/utils/FileStorageUtils.java b/src/com/owncloud/android/utils/FileStorageUtils.java index 937bd912dd..8155b464c9 100644 --- a/src/com/owncloud/android/utils/FileStorageUtils.java +++ b/src/com/owncloud/android/utils/FileStorageUtils.java @@ -292,7 +292,7 @@ public class FileStorageUtils { List files = new ArrayList(Arrays.asList(filesArray)); Collections.sort(files, new Comparator() { - @SuppressFBWarnings(value = "Bx", justification = "Would require stepping up API level") + @SuppressFBWarnings(value = "Bx") public int compare(File o1, File o2) { Long obj1 = o1.lastModified(); return multiplier * obj1.compareTo(o2.lastModified()); @@ -310,7 +310,7 @@ public class FileStorageUtils { final int multiplier = mSortAscending ? 1 : -1; Collections.sort(files, new Comparator() { - @SuppressFBWarnings(value = "Bx", justification = "Would require stepping up API level") + @SuppressFBWarnings(value = "Bx") public int compare(OCFile o1, OCFile o2) { if (o1.isFolder() && o2.isFolder()) { Long obj1 = o1.getFileLength(); @@ -339,7 +339,7 @@ public class FileStorageUtils { List files = new ArrayList(Arrays.asList(filesArray)); Collections.sort(files, new Comparator() { - @SuppressFBWarnings(value = "Bx", justification = "Would require stepping up API level") + @SuppressFBWarnings(value = "Bx") public int compare(File o1, File o2) { if (o1.isDirectory() && o2.isDirectory()) { Long obj1 = getFolderSize(o1); @@ -363,7 +363,7 @@ public class FileStorageUtils { * Sorts list by Name * @param files files to sort */ - @SuppressFBWarnings(value = "Bx", justification = "Would require stepping up API level") + @SuppressFBWarnings(value = "Bx") public static Vector sortOCFilesByName(Vector files){ final int multiplier = mSortAscending ? 1 : -1; diff --git a/src/com/owncloud/android/utils/MimeTypeUtil.java b/src/com/owncloud/android/utils/MimeTypeUtil.java index 62050af0ba..8b80c7b5e1 100644 --- a/src/com/owncloud/android/utils/MimeTypeUtil.java +++ b/src/com/owncloud/android/utils/MimeTypeUtil.java @@ -55,6 +55,7 @@ import java.util.Map; * * */ +@SuppressWarnings("PMD.AvoidDuplicateLiterals") public class MimeTypeUtil { /** Mapping: icon for mime type */ private static final Map MIMETYPE_TO_ICON_MAPPING = new HashMap<>(); @@ -291,7 +292,7 @@ public class MimeTypeUtil { * @return the file extension */ private static String getExtension(String filename) { - return filename.substring(filename.lastIndexOf(".") + 1).toLowerCase(); + return filename.substring(filename.lastIndexOf('.') + 1).toLowerCase(); } /** diff --git a/src/com/owncloud/android/utils/RecursiveFileObserver.java b/src/com/owncloud/android/utils/RecursiveFileObserver.java index 4a70631ad7..e85b30d18a 100644 --- a/src/com/owncloud/android/utils/RecursiveFileObserver.java +++ b/src/com/owncloud/android/utils/RecursiveFileObserver.java @@ -29,17 +29,16 @@ import android.os.FileObserver; public class RecursiveFileObserver extends FileObserver { - public static int CHANGES_ONLY = CLOSE_WRITE | MOVE_SELF | MOVED_FROM; - - List mObservers; - String mPath; - int mMask; + private final List mObservers = new ArrayList<>(); + private boolean watching = false; + private String mPath; + private int mMask; public RecursiveFileObserver(String path) { this(path, ALL_EVENTS); } - public RecursiveFileObserver(String path, int mask) { + RecursiveFileObserver(String path, int mask) { super(path, mask); mPath = path; mMask = mask; @@ -47,9 +46,11 @@ public class RecursiveFileObserver extends FileObserver { @Override public void startWatching() { - if (mObservers != null) return; - mObservers = new ArrayList(); - Stack stack = new Stack(); + if (watching) { + return; + } + watching = true; + final Stack stack = new Stack(); stack.push(mPath); while (!stack.empty()) { @@ -57,27 +58,32 @@ public class RecursiveFileObserver extends FileObserver { mObservers.add(new SingleFileObserver(parent, mMask)); File path = new File(parent); File[] files = path.listFiles(); - if (files == null) continue; - for (int i = 0; i < files.length; ++i) { - if (files[i].isDirectory() && !files[i].getName().equals(".") - && !files[i].getName().equals("..")) { - stack.push(files[i].getPath()); + if (files == null) { + continue; + } + for (final File file : files) { + if (file.isDirectory() && !file.getName().equals(".") + && !file.getName().equals("..")) { + stack.push(file.getPath()); } } } - for (int i = 0; i < mObservers.size(); i++) + for (int i = 0; i < mObservers.size(); i++) { mObservers.get(i).startWatching(); + } } @Override public void stopWatching() { - if (mObservers == null) return; - - for (int i = 0; i < mObservers.size(); ++i) - mObservers.get(i).stopWatching(); + if (!watching) { + return; + } + for (int i = 0; i < mObservers.size(); ++i) { + mObservers.get(i).stopWatching(); + } mObservers.clear(); - mObservers = null; + watching = false; } @Override @@ -88,7 +94,7 @@ public class RecursiveFileObserver extends FileObserver { private class SingleFileObserver extends FileObserver { private String mPath; - public SingleFileObserver(String path, int mask) { + SingleFileObserver(String path, int mask) { super(path, mask); mPath = path; } diff --git a/src/com/owncloud/android/utils/UriUtils.java b/src/com/owncloud/android/utils/UriUtils.java index b0ebd809cd..2269b9c522 100644 --- a/src/com/owncloud/android/utils/UriUtils.java +++ b/src/com/owncloud/android/utils/UriUtils.java @@ -70,8 +70,9 @@ public class UriUtils { return cursor.getString(column_index); } } finally { - if (cursor != null) + if (cursor != null) { cursor.close(); + } } return null; } @@ -179,8 +180,9 @@ public class UriUtils { else if ("content".equalsIgnoreCase(uri.getScheme())) { // Return the remote address - if (UriUtils.isGooglePhotosUri(uri)) + if (UriUtils.isGooglePhotosUri(uri)) { return uri.getLastPathSegment(); + } return UriUtils.getDataColumn(context, uri, null, null); } @@ -216,7 +218,7 @@ public class UriUtils { } // Add best possible extension - int index = displayName.lastIndexOf("."); + int index = displayName.lastIndexOf('.'); if (index == -1 || MimeTypeMap.getSingleton(). getMimeTypeFromExtension(displayName.substring(index + 1)) == null) { String mimeType = context.getContentResolver().getType(uri); diff --git a/src/com/owncloud/android/widgets/ActionEditText.java b/src/com/owncloud/android/widgets/ActionEditText.java index cb0dac4f19..563221a516 100644 --- a/src/com/owncloud/android/widgets/ActionEditText.java +++ b/src/com/owncloud/android/widgets/ActionEditText.java @@ -24,6 +24,7 @@ import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import com.owncloud.android.R; +import com.owncloud.android.lib.common.utils.Log_OC; import android.content.Context; import android.content.res.TypedArray; @@ -45,6 +46,7 @@ public class ActionEditText extends EditText { private String badgeClickCallback; private Rect btn_rect; + private static final String TAG = ActionEditText.class.getSimpleName(); public ActionEditText(Context context, AttributeSet attrs) { super(context, attrs); @@ -77,10 +79,11 @@ public class ActionEditText extends EditText { mButtonRect.right = getWidth() - 10; btn_rect = mButtonRect; - if (s.equals(optionOneString)) + if (s.equals(optionOneString)) { p.setColor(optionOneColor); - else + } else { p.setColor(optionTwoColor); + } canvas.drawRect(mButtonRect, p); p.setColor(Color.GRAY); @@ -95,36 +98,29 @@ public class ActionEditText extends EditText { int touchX = (int) event.getX(); int touchY = (int) event.getY(); boolean r = super.onTouchEvent(event); - if (event.getAction() == MotionEvent.ACTION_UP) { - if (btn_rect.contains(touchX, touchY)) { - if (s.equals(optionTwoString)) - s = optionOneString; - else - s = optionTwoString; - if (badgeClickCallback != null) { - @SuppressWarnings("rawtypes") - Class[] paramtypes = new Class[2]; - paramtypes[0] = android.view.View.class; - paramtypes[1] = String.class; - Method method; - try { + if (event.getAction() == MotionEvent.ACTION_UP && btn_rect.contains(touchX, touchY)) { + if (s.equals(optionTwoString)) { + s = optionOneString; + } else { + s = optionTwoString; + } + if (badgeClickCallback != null) { + @SuppressWarnings("rawtypes") + Class[] paramtypes = new Class[2]; + paramtypes[0] = android.view.View.class; + paramtypes[1] = String.class; + Method method; + try { - method = getContext().getClass().getMethod( - badgeClickCallback, paramtypes); - method.invoke(getContext(), this, s); + method = getContext().getClass().getMethod( + badgeClickCallback, paramtypes); + method.invoke(getContext(), this, s); - } catch (NoSuchMethodException e) { - e.printStackTrace(); - } catch (IllegalArgumentException e) { - e.printStackTrace(); - } catch (IllegalAccessException e) { - e.printStackTrace(); - } catch (InvocationTargetException e) { - e.printStackTrace(); - } - - invalidate(); + } catch (NoSuchMethodException | IllegalArgumentException | InvocationTargetException | IllegalAccessException e) { + Log_OC.d(TAG, e.getMessage(), e); } + + invalidate(); } } return r; diff --git a/src/org/nextcloud/providers/DocumentsStorageProvider.java b/src/org/nextcloud/providers/DocumentsStorageProvider.java index 261a427f3b..2341de0085 100644 --- a/src/org/nextcloud/providers/DocumentsStorageProvider.java +++ b/src/org/nextcloud/providers/DocumentsStorageProvider.java @@ -57,8 +57,9 @@ public class DocumentsStorageProvider extends DocumentsProvider { final RootCursor result = new RootCursor(projection); - for (Account account : AccountUtils.getAccounts(getContext())) + for (Account account : AccountUtils.getAccounts(getContext())) { result.addRoot(account, getContext()); + } return result; } @@ -70,8 +71,9 @@ public class DocumentsStorageProvider extends DocumentsProvider { final FileCursor result = new FileCursor(projection); OCFile file = mCurrentStorageManager.getFileById(docId); - if (file != null) + if (file != null) { result.addFile(file); + } return result; } @@ -167,10 +169,11 @@ public class DocumentsStorageProvider extends DocumentsProvider { } private void updateCurrentStorageManagerIfNeeded(String rootId) { - for (FileDataStorageManager data : mRootIdToStorageManager.values()) + for (FileDataStorageManager data : mRootIdToStorageManager.values()) { if (data.getAccount().name.equals(rootId)) { mCurrentStorageManager = data; } + } } private void initiateStorageMap() { diff --git a/src/org/nextcloud/providers/cursors/FileCursor.java b/src/org/nextcloud/providers/cursors/FileCursor.java index e8e75cd5f7..6e89797800 100644 --- a/src/org/nextcloud/providers/cursors/FileCursor.java +++ b/src/org/nextcloud/providers/cursors/FileCursor.java @@ -42,7 +42,9 @@ public class FileCursor extends MatrixCursor { } public void addFile(OCFile file) { - if (file == null) return; + if (file == null) { + return; + } final int iconRes = MimeTypeUtil.getFileTypeIconId(file.getMimetype(), file.getFileName()); final String mimeType = file.isFolder() ? Document.MIME_TYPE_DIR : file.getMimetype(); diff --git a/src/third_parties/daveKoeller/AlphanumComparator.java b/src/third_parties/daveKoeller/AlphanumComparator.java index d087957640..45d060fa1e 100644 --- a/src/third_parties/daveKoeller/AlphanumComparator.java +++ b/src/third_parties/daveKoeller/AlphanumComparator.java @@ -60,8 +60,9 @@ public class AlphanumComparator implements Comparator while (marker < slength) { c = s.charAt(marker); - if (!isDigit(c)) + if (!isDigit(c)) { break; + } chunk.append(c); marker++; } @@ -70,8 +71,9 @@ public class AlphanumComparator implements Comparator while (marker < slength) { c = s.charAt(marker); - if (isDigit(c)) + if (isDigit(c)) { break; + } chunk.append(c); marker++; } @@ -131,8 +133,9 @@ public class AlphanumComparator implements Comparator result = thisChunk.compareTo(thatChunk); } - if (result != 0) + if (result != 0) { return result; + } } return s1Length - s2Length; diff --git a/src/third_parties/in/srain/cube/GridViewWithHeaderAndFooter.java b/src/third_parties/in/srain/cube/GridViewWithHeaderAndFooter.java index 51c0249481..dbbbb4fcdd 100644 --- a/src/third_parties/in/srain/cube/GridViewWithHeaderAndFooter.java +++ b/src/third_parties/in/srain/cube/GridViewWithHeaderAndFooter.java @@ -97,7 +97,7 @@ public class GridViewWithHeaderAndFooter extends GridView { protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); ListAdapter adapter = getAdapter(); - if (adapter != null && adapter instanceof HeaderViewGridAdapter) { + if (adapter instanceof HeaderViewGridAdapter) { ((HeaderViewGridAdapter) adapter).setNumColumns(getNumColumnsCompatible()); invalidateRowHeight(); ((HeaderViewGridAdapter) adapter).setRowHeight(getRowHeight()); @@ -291,9 +291,7 @@ public class GridViewWithHeaderAndFooter extends GridView { Field numColumns = getClass().getSuperclass().getDeclaredField("mColumnWidth"); numColumns.setAccessible(true); return numColumns.getInt(this); - } catch (NoSuchFieldException e) { - throw new RuntimeException(e); - } catch (IllegalAccessException e) { + } catch (NoSuchFieldException | IllegalAccessException e) { throw new RuntimeException(e); } } @@ -407,7 +405,7 @@ public class GridViewWithHeaderAndFooter extends GridView { super.setNumColumns(numColumns); mNumColumns = numColumns; ListAdapter adapter = getAdapter(); - if (adapter != null && adapter instanceof HeaderViewGridAdapter) { + if (adapter instanceof HeaderViewGridAdapter) { ((HeaderViewGridAdapter) adapter).setNumColumns(numColumns); } } @@ -545,8 +543,7 @@ public class GridViewWithHeaderAndFooter extends GridView { } private int getAdapterAndPlaceHolderCount() { - final int adapterCount = (int) (Math.ceil(1f * mAdapter.getCount() / mNumColumns) * mNumColumns); - return adapterCount; + return (int) (Math.ceil(1f * mAdapter.getCount() / mNumColumns) * mNumColumns); } @Override @@ -659,8 +656,7 @@ public class GridViewWithHeaderAndFooter extends GridView { adapterCount = getAdapterAndPlaceHolderCount(); if (adjPosition < adapterCount) { if (adjPosition < mAdapter.getCount()) { - View view = mAdapter.getView(adjPosition, convertView, parent); - return view; + return mAdapter.getView(adjPosition, convertView, parent); } else { if (convertView == null) { convertView = new View(parent.getContext()); @@ -698,17 +694,14 @@ public class GridViewWithHeaderAndFooter extends GridView { final int numHeadersAndPlaceholders = getHeadersCount() * mNumColumns; final int adapterViewTypeStart = mAdapter == null ? 0 : mAdapter.getViewTypeCount() - 1; int type = AdapterView.ITEM_VIEW_TYPE_HEADER_OR_FOOTER; - if (mCachePlaceHoldView) { + if (mCachePlaceHoldView + && position < numHeadersAndPlaceholders) { // Header - if (position < numHeadersAndPlaceholders) { - if (position == 0) { - if (mCacheFirstHeaderView) { - type = adapterViewTypeStart + mHeaderViewInfos.size() + mFooterViewInfos.size() + 1 + 1; - } - } - if (position % mNumColumns != 0) { - type = adapterViewTypeStart + (position / mNumColumns + 1); - } + if (position == 0 && mCacheFirstHeaderView) { + type = adapterViewTypeStart + mHeaderViewInfos.size() + mFooterViewInfos.size() + 1 + 1; + } + if (position % mNumColumns != 0) { + type = adapterViewTypeStart + (position / mNumColumns + 1); } } diff --git a/src/third_parties/michaelOrtiz/TouchImageViewCustom.java b/src/third_parties/michaelOrtiz/TouchImageViewCustom.java index 9b0f5a05e6..85bc4d8c8c 100644 --- a/src/third_parties/michaelOrtiz/TouchImageViewCustom.java +++ b/src/third_parties/michaelOrtiz/TouchImageViewCustom.java @@ -386,7 +386,7 @@ public class TouchImageViewCustom extends ImageViewCustom { return; } - if (scaleType != mScaleType) { + if (!scaleType.equals(mScaleType)) { setScaleType(scaleType); } resetZoom(); @@ -489,10 +489,12 @@ public class TouchImageViewCustom extends ImageViewCustom { maxTrans = 0; } - if (trans < minTrans) + if (trans < minTrans) { return -trans + minTrans; - if (trans > maxTrans) + } + if (trans > maxTrans) { return -trans + maxTrans; + } return 0; } @@ -832,8 +834,9 @@ public class TouchImageViewCustom extends ImageViewCustom { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: last.set(curr); - if (fling != null) - fling.cancelFling(); + if (fling != null) { + fling.cancelFling(); + } setState(State.DRAG); break;