From a0ae31899cc596026fa1a7564421896c0ccce65e Mon Sep 17 00:00:00 2001 From: vincent Bourgmayer Date: Mon, 3 Oct 2022 17:33:53 +0200 Subject: [PATCH 1/5] Remove logging from foundation.e.drive.models package: - Remove logging from SyncWrapper class - Remove dead class: FileObserver --- .../e/drive/models/FileObserver.java | 33 ------------------- .../e/drive/models/SyncWrapper.java | 9 ----- 2 files changed, 42 deletions(-) delete mode 100644 app/src/main/java/foundation/e/drive/models/FileObserver.java diff --git a/app/src/main/java/foundation/e/drive/models/FileObserver.java b/app/src/main/java/foundation/e/drive/models/FileObserver.java deleted file mode 100644 index 1fe4ef23..00000000 --- a/app/src/main/java/foundation/e/drive/models/FileObserver.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright © ECORP SAS 2022. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - */ - -package foundation.e.drive.models; - -import java.io.File; -import java.io.Serializable; -import java.util.List; - -/** - * @author Narinder Rana - */ -public class FileObserver implements Serializable { - - private List files; - public FileObserver(List files) { - this.files = files; - - } - - public List getFiles() { - return files; - } - - public void setFiles(List files) { - this.files = files; - } -} diff --git a/app/src/main/java/foundation/e/drive/models/SyncWrapper.java b/app/src/main/java/foundation/e/drive/models/SyncWrapper.java index 240352ea..40b3e3db 100644 --- a/app/src/main/java/foundation/e/drive/models/SyncWrapper.java +++ b/app/src/main/java/foundation/e/drive/models/SyncWrapper.java @@ -9,11 +9,9 @@ package foundation.e.drive.models; import android.accounts.Account; import android.content.Context; -import android.util.Log; import com.owncloud.android.lib.common.operations.RemoteOperation; -import java.io.File; import foundation.e.drive.operations.DownloadFileOperation; import foundation.e.drive.operations.RemoveFileOperation; @@ -25,7 +23,6 @@ import foundation.e.drive.operations.UploadFileOperation; * @author Vincent Bourgmayer */ public class SyncWrapper { - private final static String TAG = SyncWrapper.class.getSimpleName(); private final SyncRequest request; private final RemoteOperation remoteOperation; private boolean isRunning; @@ -64,12 +61,6 @@ public class SyncWrapper { switch (request.getOperationType()) { case UPLOAD: final SyncedFileState sfs = request.getSyncedFileState(); - final File file = new File(sfs.getLocalPath()); - if (!file.exists()) { - operation = null; - Log.w(TAG, "createRemoteOperation: local file doesn't. Can't upload"); - break; - } operation = new UploadFileOperation(sfs, account, context); break; case DOWNLOAD: -- GitLab From b4f3e63e0d44402b004484752f52552d060114c1 Mon Sep 17 00:00:00 2001 From: vincent Bourgmayer Date: Mon, 3 Oct 2022 18:11:49 +0200 Subject: [PATCH 2/5] operations pacakage: Replace android logging by Timber logging --- .../operations/DownloadFileOperation.java | 28 ++++++++--------- .../e/drive/operations/GetAliasOperation.java | 6 ++-- .../operations/ListFileRemoteOperation.java | 16 +++++----- .../drive/operations/UploadFileOperation.java | 30 +++++++------------ 4 files changed, 34 insertions(+), 46 deletions(-) diff --git a/app/src/main/java/foundation/e/drive/operations/DownloadFileOperation.java b/app/src/main/java/foundation/e/drive/operations/DownloadFileOperation.java index cc4115ee..9fe4a53c 100644 --- a/app/src/main/java/foundation/e/drive/operations/DownloadFileOperation.java +++ b/app/src/main/java/foundation/e/drive/operations/DownloadFileOperation.java @@ -10,17 +10,16 @@ package foundation.e.drive.operations; import android.content.Context; -import android.util.Log; import com.owncloud.android.lib.common.OwnCloudClient; import com.owncloud.android.lib.common.operations.RemoteOperation; import com.owncloud.android.lib.common.operations.RemoteOperationResult; import com.owncloud.android.lib.resources.files.DownloadFileRemoteOperation; -import com.owncloud.android.lib.resources.files.FileUtils; import com.owncloud.android.lib.resources.files.model.RemoteFile; import java.io.File; import foundation.e.drive.database.DbHelper; import foundation.e.drive.models.SyncedFileState; import foundation.e.drive.utils.CommonUtils; +import timber.log.Timber; /** * @author Vincent Bourgmayer @@ -28,7 +27,6 @@ import foundation.e.drive.utils.CommonUtils; * /!\ Doesn't require NextcloudClient yet */ public class DownloadFileOperation extends RemoteOperation { - private final static String TAG = DownloadFileOperation.class.getSimpleName(); private final RemoteFile remoteFile; private final Context context; @@ -38,11 +36,12 @@ public class DownloadFileOperation extends RemoteOperation { private final String previousEtag; /** - * COnstructor of download operation where syncedFileState is already known + * Constructor of download operation where syncedFileState is already known * @param remoteFile remote file to Download * @param syncedFileState SyncedFileState corresponding to remote file */ public DownloadFileOperation(RemoteFile remoteFile, SyncedFileState syncedFileState, Context context) { + Timber.tag(DownloadFileOperation.class.getSimpleName()); this.remoteFile = remoteFile; this.syncedFileState = syncedFileState; this.previousEtag = syncedFileState.getLastETAG(); @@ -52,15 +51,14 @@ public class DownloadFileOperation extends RemoteOperation { @Override protected RemoteOperationResult run(OwnCloudClient ownCloudClient) { - Log.i(TAG, "run(client) for "+remoteFile.getRemotePath()); + Timber.v( "run() for %s", remoteFile.getRemotePath()); if (syncedFileState.getId() == -1) { this.syncedFileState.setId(DbHelper.manageSyncedFileStateDB(this.syncedFileState, "INSERT", context)); } if (syncedFileState.getLastETAG().equals(remoteFile.getEtag()) && syncedFileState.getLocalLastModified() > 0L) { - //file is up to date - Log.w(TAG, "File already up-to-date"); + Timber.v( "%s already up-to-date", remoteFile.getRemotePath()); return new RemoteOperationResult(RemoteOperationResult.ResultCode.ETAG_UNCHANGED); } @@ -78,11 +76,11 @@ public class DownloadFileOperation extends RemoteOperation { final File tmpFile = new File(tmpFilePath); if (!tmpFile.exists()) { - Log.e(TAG, "Downloaded file doesn't exist or is null"); + Timber.d( "Missing downloaded temporary file for %s", remoteFile.getRemotePath()); resultCode = RemoteOperationResult.ResultCode.FILE_NOT_FOUND; } else if (tmpFile.length() != remoteFile.getLength()) { - Log.e(TAG, "Local and remote file doesn't have the same size"); + Timber.d( "Local and remote version of %s doesn't match", remoteFile.getRemotePath()); resultCode = RemoteOperationResult.ResultCode.INVALID_OVERWRITE; tmpFile.delete(); } else { //file has been correctly download. @@ -95,10 +93,10 @@ public class DownloadFileOperation extends RemoteOperation { } if (!tmpFile.renameTo(localFile)) { - Log.d(TAG, "failed to move " + tmpFile.getAbsolutePath() + " to " + targetPath); + Timber.d("failed to move %s to %s", tmpFile.getAbsolutePath(), targetPath); return new RemoteOperationResult(RemoteOperationResult.ResultCode.FORBIDDEN); } - Log.d(TAG, "File moved to: "+localFile.getAbsolutePath()); + syncedFileState.setLocalLastModified(localFile.lastModified()) .setLastETAG(remoteFile.getEtag()); @@ -108,13 +106,12 @@ public class DownloadFileOperation extends RemoteOperation { CommonUtils.doActionMediaScannerConnexionScanFile(context, syncedFileState.getLocalPath()); } } else { //If download failed - Log.e(TAG, "Download failed: "+downloadResult.getLogMessage()); + Timber.d("Download failed: %s, %s", downloadResult.getCode(), downloadResult.getLogMessage()); resultCode = RemoteOperationResult.ResultCode.UNKNOWN_ERROR; } if (mustRestart) { - Log.w(TAG, restartCounter+" unsuccessfull trial.s of downloading" - + remoteFile.getRemotePath()); + Timber.v("%s unsuccessfull trial.s of downloading %s", restartCounter, remoteFile.getRemotePath()); syncedFileState.setLastETAG(this.previousEtag); if (this.restartCounter < 3) { this.restartCounter += 1; @@ -125,8 +122,7 @@ public class DownloadFileOperation extends RemoteOperation { } //So now, we can update instance of SyncedState and save it to DB if (DbHelper.manageSyncedFileStateDB(syncedFileState, "UPDATE", context) <= 0) { - Log.e(TAG, "DB update failed: 0 affected row"); - //@TODO : do smtg + //todo : define what to do in this case. Is this test even relevant ? } return new RemoteOperationResult(resultCode); } diff --git a/app/src/main/java/foundation/e/drive/operations/GetAliasOperation.java b/app/src/main/java/foundation/e/drive/operations/GetAliasOperation.java index c73473d0..253127e8 100644 --- a/app/src/main/java/foundation/e/drive/operations/GetAliasOperation.java +++ b/app/src/main/java/foundation/e/drive/operations/GetAliasOperation.java @@ -11,7 +11,6 @@ package foundation.e.drive.operations; import com.owncloud.android.lib.common.OwnCloudClient; import com.owncloud.android.lib.common.operations.RemoteOperation; import com.owncloud.android.lib.common.operations.RemoteOperationResult; -import com.owncloud.android.lib.common.utils.Log_OC; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.NameValuePair; @@ -22,6 +21,8 @@ import org.json.JSONObject; import java.util.ArrayList; +import timber.log.Timber; + /** * @author TheScarastic * /!\ Doesn't require NextcloudClient yet @@ -29,7 +30,6 @@ import java.util.ArrayList; public class GetAliasOperation extends RemoteOperation { - private static final String TAG = GetAliasOperation.class.getSimpleName(); private static final String ALIAS_PATH = "/ocs/v1.php/cloud/hide-my-email/"; // JSON Node names @@ -78,7 +78,7 @@ public class GetAliasOperation extends RemoteOperation { } catch (Exception e) { e.printStackTrace(); result = new RemoteOperationResult<>(e); - Log_OC.e(TAG, "Fetching aliases failed"); + Timber.tag(GetAliasOperation.class.getSimpleName()).d("Fetching aliases failed"); } finally { if (get != null) get.releaseConnection(); diff --git a/app/src/main/java/foundation/e/drive/operations/ListFileRemoteOperation.java b/app/src/main/java/foundation/e/drive/operations/ListFileRemoteOperation.java index 4867176e..0ab10daa 100644 --- a/app/src/main/java/foundation/e/drive/operations/ListFileRemoteOperation.java +++ b/app/src/main/java/foundation/e/drive/operations/ListFileRemoteOperation.java @@ -10,7 +10,6 @@ package foundation.e.drive.operations; import android.content.Context; -import android.util.Log; import com.owncloud.android.lib.common.OwnCloudClient; import com.owncloud.android.lib.common.operations.RemoteOperation; import com.owncloud.android.lib.common.operations.RemoteOperationResult; @@ -23,6 +22,7 @@ import java.util.ListIterator; import foundation.e.drive.database.DbHelper; import foundation.e.drive.models.SyncedFolder; import foundation.e.drive.utils.CommonUtils; +import timber.log.Timber; /** @@ -30,7 +30,6 @@ import foundation.e.drive.utils.CommonUtils; * @author Vincent Bourgmayer */ public class ListFileRemoteOperation extends RemoteOperation> { - private final String TAG = ListFileRemoteOperation.class.getSimpleName(); private static final int HTTP_404 = 404; private final List syncedFolders; @@ -39,6 +38,7 @@ public class ListFileRemoteOperation extends RemoteOperation remoteFiles; public ListFileRemoteOperation(List syncedFolders, Context context, int initialFolderNumber) { + Timber.tag(ListFileRemoteOperation.class.getSimpleName()); this.syncedFolders = syncedFolders; this.context = context; this.initialFolderNumber = initialFolderNumber; @@ -60,8 +60,8 @@ public class ListFileRemoteOperation extends RemoteOperation Ignored"); + Timber.d("ReadFolderRemoteOperation failed : http %s, %s => ignored", result.getHttpCode(), result.getLogMessage()); } } finalResult = new RemoteOperationResult<>(RemoteOperationResult.ResultCode.OK); @@ -130,7 +130,7 @@ public class ListFileRemoteOperation extends RemoteOperation uploadResult; if (file.length() >= FILE_SIZE_FLOOR_FOR_CHUNKED) { - Log.d(TAG, "upload " + file.getName() + " as chunked file"); + Timber.d("Upload %s as chunked file", file.getName()); uploadResult = uploadChunkedFile(file, client); } else { uploadResult = uploadFile(file, client); @@ -107,7 +107,7 @@ public class UploadFileOperation extends RemoteOperation { private ResultCode onUploadFailure(final ResultCode uploadResult, final String fileName) { if (uploadResult != ResultCode.CONFLICT && uploadResult != ResultCode.QUOTA_EXCEEDED) { - Log.e(TAG, "UploadFileRemoteOperation for : " + fileName + " failed => code: " + uploadResult); + Timber.d("Upload for %s failed : %s", fileName, uploadResult); return ResultCode.UNKNOWN_ERROR; } return uploadResult; @@ -125,21 +125,21 @@ public class UploadFileOperation extends RemoteOperation { */ private ResultCode checkCondition(final File file, final OwnCloudClient client) { if (file == null || !file.exists()) { - Log.w(TAG, "Can't get the file. It might have been deleted"); + Timber.d("Can't get the file. It might have been deleted"); return ResultCode.FORBIDDEN; } //If file already up-to-date & synced if (syncedState.isLastEtagStored() && syncedState.getLocalLastModified() == file.lastModified()) { - Log.d(TAG, "syncedState last modified: "+ syncedState.getLocalLastModified()+" <=> file last modified: "+file.lastModified() +": So return sync_conflict"); + Timber.d("Synchronization conflict because: last modified from DB(%s) and from file (%s) are different ", syncedState.getLocalLastModified(), file.lastModified()); return ResultCode.SYNC_CONFLICT; } final NextcloudClient ncClient = DavClientProvider.getInstance().getNcClientInstance(account, context); final RemoteOperationResult checkQuotaResult = checkAvailableSpace(ncClient, file.length()); if (checkQuotaResult.getCode() != ResultCode.OK) { - Log.e(TAG, "Impossible to check quota. Upload of " + syncedState.getLocalPath() + "cancelled"); + Timber.d("Impossible to check quota. Cancels upload of %s", syncedState.getLocalPath()); return checkQuotaResult.getCode(); } @@ -242,7 +242,7 @@ public class UploadFileOperation extends RemoteOperation { * Upload a file * note: this has been extracted from run(...) for * testing purpose - * @param client client to run the method. @TODO will be replaced by NextcloudClient in future. + * @param client client to run the method. TODO will be replaced by NextcloudClient in future. * @return RemoteOperationResult the instance must contains etag in resultData if successful. */ @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE) @@ -259,23 +259,15 @@ public class UploadFileOperation extends RemoteOperation { /** * Create remote parent folder of the file if missing * @param targetPath Path of remote directory to create or check for existence - * @param client Client to perform the request. @TODO will be replaced by NextcloudClient in future. + * @param client Client to perform the request. TODO will be replaced by NextcloudClient in future. * @return true if the parent directory has been created, false either */ @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE) public boolean createRemoteFolder(String targetPath, OwnCloudClient client) { final String remoteFolderPath = targetPath.substring(0, targetPath.lastIndexOf(FileUtils.PATH_SEPARATOR) + 1); final CreateFolderRemoteOperation createFolderOperation = new CreateFolderRemoteOperation(remoteFolderPath, true); - try{ - final RemoteOperationResult createFolderResult = createFolderOperation.execute(client); - if (createFolderResult.isSuccess() || createFolderResult.getCode() == ResultCode.FOLDER_ALREADY_EXISTS) { - return true; - } - Log.e(TAG, createFolderResult.getLogMessage()); - } catch(Exception e) { - Log.e(TAG, e.toString()); - } - return false; + final RemoteOperationResult createFolderResult = createFolderOperation.execute(client); + return createFolderResult.isSuccess() || createFolderResult.getCode() == ResultCode.FOLDER_ALREADY_EXISTS; } public SyncedFileState getSyncedState() { -- GitLab From b2c3e6af7e6c07e0577f418f80c77ffc28f7d15d Mon Sep 17 00:00:00 2001 From: vincent Bourgmayer Date: Mon, 3 Oct 2022 18:16:56 +0200 Subject: [PATCH 3/5] receivers package: Replace android logging by Timber logging --- .../e/drive/receivers/BootCompletedReceiver.java | 9 ++++----- .../foundation/e/drive/receivers/DebugCmdReceiver.java | 7 ++++--- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/app/src/main/java/foundation/e/drive/receivers/BootCompletedReceiver.java b/app/src/main/java/foundation/e/drive/receivers/BootCompletedReceiver.java index 779a3f6a..094cfeef 100644 --- a/app/src/main/java/foundation/e/drive/receivers/BootCompletedReceiver.java +++ b/app/src/main/java/foundation/e/drive/receivers/BootCompletedReceiver.java @@ -13,25 +13,24 @@ import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.database.sqlite.SQLiteException; -import android.util.Log; import foundation.e.drive.BuildConfig; import foundation.e.drive.database.DbHelper; import foundation.e.drive.services.InitializerService; import foundation.e.drive.utils.AppConstants; import foundation.e.drive.utils.CommonUtils; +import timber.log.Timber; /** * @author Abhishek Aggarwal */ public class BootCompletedReceiver extends BroadcastReceiver { - public static final String TAG = BootCompletedReceiver.class.getSimpleName(); private static final String DATE_SYSTEM_PROPERTY = "ro.build.date"; private static final String PREF_VERSION_CODE = "VERSION_CODE"; @Override public void onReceive(Context context, Intent intent) { final String action = intent.getAction(); - Log.i(TAG, "onReceive(...)"); + Timber.tag(BootCompletedReceiver.class.getSimpleName()).v("onReceive(...)"); final SharedPreferences pref = context.getSharedPreferences(AppConstants.SHARED_PREFERENCE_NAME, Context.MODE_PRIVATE); if (Intent.ACTION_BOOT_COMPLETED.equals(action)) { if (!CommonUtils.getProp(DATE_SYSTEM_PROPERTY).equals(pref.getString(DATE_SYSTEM_PROPERTY, ""))) { @@ -48,8 +47,8 @@ public class BootCompletedReceiver extends BroadcastReceiver { pref.edit().putInt(PREF_VERSION_CODE, BuildConfig.VERSION_CODE).apply(); try { DbHelper.cleanSyncedFileStateTableAfterUpdate(context); - } catch (SQLiteException e) { - Log.e(TAG, "Can't remove entry for hidden file in Database", e); + } catch (SQLiteException exception) { + Timber.e(exception); } } } diff --git a/app/src/main/java/foundation/e/drive/receivers/DebugCmdReceiver.java b/app/src/main/java/foundation/e/drive/receivers/DebugCmdReceiver.java index 79809dd2..afb752cc 100644 --- a/app/src/main/java/foundation/e/drive/receivers/DebugCmdReceiver.java +++ b/app/src/main/java/foundation/e/drive/receivers/DebugCmdReceiver.java @@ -14,6 +14,7 @@ import android.util.Log; import foundation.e.drive.database.DbHelper; import foundation.e.drive.services.ObserverService; +import timber.log.Timber; /** * @author Jonathan Klee @@ -23,17 +24,17 @@ public class DebugCmdReceiver extends BroadcastReceiver { public static final String ACTION_FORCE_SYNC = "foundation.e.drive.action.FORCE_SYNC"; public static final String ACTION_DUMP_DATABASE = "foundation.e.drive.action.DUMP_DATABASE"; - public static final String TAG = "DebugCmdReceiver"; @Override public void onReceive(Context context, Intent intent) { - Log.d(TAG, "onReceive"); + Timber.tag(DebugCmdReceiver.class.getSimpleName()).v("onReceive"); switch (intent.getAction()) { case ACTION_FORCE_SYNC: - Log.i(TAG, "Force Sync intent received"); + Timber.d("Force Sync intent received"); context.startService(new Intent(ACTION_FORCE_SYNC, null, context, ObserverService.class)); break; case ACTION_DUMP_DATABASE: + Timber.d("Dump database intent received"); DbHelper.dumpDatabase(context); break; default: -- GitLab From e2c8c2fc94a44f96169c501d96a72e9235e7843b Mon Sep 17 00:00:00 2001 From: vincent Bourgmayer Date: Mon, 3 Oct 2022 18:47:24 +0200 Subject: [PATCH 4/5] utils package: replace Android logging by Timber logging --- .../foundation/e/drive/utils/CommonUtils.java | 69 ++++++------------- .../e/drive/utils/DavClientProvider.java | 21 +++--- .../drive/utils/ServiceExceptionHandler.java | 54 ++++++--------- .../SynchronizationServiceConnection.java | 9 +-- 4 files changed, 58 insertions(+), 95 deletions(-) diff --git a/app/src/main/java/foundation/e/drive/utils/CommonUtils.java b/app/src/main/java/foundation/e/drive/utils/CommonUtils.java index 946e5c46..9542f79b 100644 --- a/app/src/main/java/foundation/e/drive/utils/CommonUtils.java +++ b/app/src/main/java/foundation/e/drive/utils/CommonUtils.java @@ -7,7 +7,6 @@ * http://www.gnu.org/licenses/gpl.html */ - package foundation.e.drive.utils; import android.accounts.Account; @@ -26,13 +25,13 @@ import android.net.NetworkCapabilities; import android.net.Uri; import android.os.Build; -import android.util.Log; import android.webkit.MimeTypeMap; import android.widget.Toast; import com.owncloud.android.lib.resources.files.FileUtils; import java.io.File; +import java.io.IOException; import java.lang.reflect.Method; import java.text.CharacterIterator; import java.text.StringCharacterIterator; @@ -45,6 +44,7 @@ import foundation.e.drive.models.SyncedFolder; import foundation.e.drive.work.AccountUserInfoWorker; import foundation.e.drive.work.FullScanWorker; import foundation.e.drive.work.WorkRequestFactory; +import timber.log.Timber; import static foundation.e.drive.utils.AppConstants.MEDIASYNC_PROVIDER_AUTHORITY; import static foundation.e.drive.utils.AppConstants.METERED_NETWORK_ALLOWED_AUTHORITY; @@ -69,14 +69,12 @@ public abstract class CommonUtils { /** * Set ServiceUncaughtExceptionHandler to be the MainThread Exception Handler * Or update the service which use it - * + * todo: check if the ServiceExceptionHandler could be remove * @param service current service */ public static void setServiceUnCaughtExceptionHandler(Service service) { - Thread.UncaughtExceptionHandler defaultUEH = Thread.getDefaultUncaughtExceptionHandler(); if (defaultUEH != null && ServiceExceptionHandler.class.getSimpleName().equals(defaultUEH.getClass().getSimpleName())) { - Log.d("ObserverService", "ServiceExceptionHandler already set!"); ((ServiceExceptionHandler) defaultUEH).setService(service); } else { Thread.setDefaultUncaughtExceptionHandler(new ServiceExceptionHandler(service)); @@ -170,13 +168,9 @@ public abstract class CommonUtils { * @return String, the last part after separator of path or null if invalid path has been provided */ public static String getFileNameFromPath(String path) { - try { - String[] splittedString = path.split(FileUtils.PATH_SEPARATOR); - return splittedString[splittedString.length - 1]; - } catch (Exception e) { - Log.e(TAG, e.toString()); - return null; - } + final String[] splittedString = path.split(FileUtils.PATH_SEPARATOR); + if (splittedString.length <= 0) return null; + return splittedString[splittedString.length - 1]; } /** @@ -187,7 +181,7 @@ public abstract class CommonUtils { * @return True if there is connection, false either */ public static boolean haveNetworkConnection(Context context, boolean meteredNetworkAllowed) { - Log.i(TAG, "haveNetworkConnection()"); + Timber.tag(TAG).v(TAG, "haveNetworkConnection()"); final ConnectivityManager cm = context.getSystemService(ConnectivityManager.class); final NetworkCapabilities capabilities = cm.getNetworkCapabilities(cm.getActiveNetwork()); @@ -210,10 +204,9 @@ public abstract class CommonUtils { * @return String containing mimeType of the file */ public static String getMimeType(File file) { - Log.i(TAG, "getMimeType()"); - String mimetype = MimeTypeMap.getSingleton().getMimeTypeFromExtension( - MimeTypeMap.getFileExtensionFromUrl( - Uri.fromFile(file).toString()).toLowerCase()); + final String mimetype = MimeTypeMap.getSingleton() + .getMimeTypeFromExtension( + MimeTypeMap.getFileExtensionFromUrl(Uri.fromFile(file).toString()).toLowerCase()); if (mimetype == null) { return "*/*"; } @@ -227,15 +220,17 @@ public abstract class CommonUtils { * @param filePath String containing path the file to update by mediaScanner */ public static void doActionMediaScannerConnexionScanFile(Context context, final String filePath) { - Log.i(TAG, "doActionMediaScannerConnexionScanFile(" + filePath + ")"); + Timber.v(TAG, "doActionMediaScannerConnexionScanFile( %s )", filePath); + final String[] filePathArray = new String[] { filePath }; + final String[] mimeType = new String[] {getMimeType(new File(filePath))}; MediaScannerConnection.scanFile(context, - new String[]{filePath}, - new String[]{getMimeType(new File(filePath))}, + filePathArray, + mimeType, new MediaScannerConnection.OnScanCompletedListener() { @Override public void onScanCompleted(String path, Uri uri) { - Log.v("MediaScanWork", "file " + path - + " was scanned successfully: " + uri); + Timber.tag("MediaScannerConnection") + .v("file %s was scanned with success: %s ", path, uri); } }); } @@ -250,35 +245,13 @@ public abstract class CommonUtils { String result; try { result = file.getCanonicalPath(); - } catch (Exception e) { - Log.e(TAG, e.toString()); - result = file.getAbsolutePath(); + } catch (SecurityException | IOException exception ) { + Timber.v(exception); + result = file.getAbsolutePath(); //todo why not simply always use getAbsolutePath? } return result; } - /** - * Used for debug - * - * @param f File to debug - * @return String showing value of file's properties - * @dev-only - */ - public static String debugFile(File f) { - return "File name: " + f.getName() - + "\n File exist?: " + f.exists() - + "\n File absolute path: " + f.getAbsolutePath() - + "\n File path: " + f.getPath() - + "\n File length: " + f.length() - + "\n File last modif: " + f.lastModified() - + "\n File readable?: " + f.canRead() - + "\n File writable?: " + f.canWrite() - + "\n File is file?: " + f.isFile() - + "\n File is Dir?: " + f.isDirectory() - + "\n File can be read?: " + f.canRead() - + "\n File can be written?: " + f.canWrite(); - } - /** * Formatter class is not used since bytes passed by server are in SI unit aka 1kb = 1024byte * https://stackoverflow.com/questions/3758606/how-can-i-convert-byte-size-into-a-human-readable-format-in-java/3758880#3758880 @@ -330,7 +303,7 @@ public abstract class CommonUtils { */ public static void registerInitializationWorkers(List syncedFolders, WorkManager workManager) { if (syncedFolders == null || syncedFolders.isEmpty()) { - Log.e(TAG, "Can't create remote folders. List is empty"); + Timber.tag(TAG).d("registerInitializationWorkers: Can't create remote folders. List is empty"); return; } diff --git a/app/src/main/java/foundation/e/drive/utils/DavClientProvider.java b/app/src/main/java/foundation/e/drive/utils/DavClientProvider.java index 4ca2ce5d..6c88038f 100644 --- a/app/src/main/java/foundation/e/drive/utils/DavClientProvider.java +++ b/app/src/main/java/foundation/e/drive/utils/DavClientProvider.java @@ -13,7 +13,6 @@ import android.accounts.Account; import android.accounts.AccountManager; import android.content.Context; import android.net.Uri; -import android.util.Log; import com.nextcloud.common.NextcloudClient; import com.nextcloud.common.OkHttpCredentialsUtil; @@ -23,12 +22,16 @@ import com.owncloud.android.lib.common.OwnCloudClientFactory; import com.owncloud.android.lib.common.OwnCloudClientManagerFactory; import com.owncloud.android.lib.common.accounts.AccountUtils; +import timber.log.Timber; + /** * @author Vincent Bourgmayer */ public class DavClientProvider { - private static final String TAG = DavClientProvider.class.getSimpleName(); - private DavClientProvider (){} + private DavClientProvider (){ + Timber.tag(DavClientProvider.class.getSimpleName()); + } + @Deprecated private OwnCloudClient ocClientInstance; private NextcloudClient ncClientInstance; @@ -44,11 +47,11 @@ public class DavClientProvider { ocClientInstance = OwnCloudClientFactory.createOwnCloudClient(serverUri, ctx, true); final String pwd = getAcountPwd(account, ctx); - Log.d(TAG, "name: "+account.name+"\n"+AccountManager.get(ctx).getUserData(account, AccountUtils.Constants.KEY_USER_ID)); + Timber.v("name: %s \n%s", account.name, AccountManager.get(ctx).getUserData(account, AccountUtils.Constants.KEY_USER_ID)); ocClientInstance.setCredentials(new OwnCloudBasicCredentials(account.name, pwd)); - } catch (AccountUtils.AccountNotFoundException e) { - Log.e(TAG, "Can't parse serverPath to Uri : " + e.toString()); + } catch (AccountUtils.AccountNotFoundException exception) { + Timber.e(exception); return null; } } @@ -63,15 +66,15 @@ public class DavClientProvider { public NextcloudClient getNcClientInstance(final Account account, final Context ctx) { - Log.i(TAG, "getNcClientInstance()"); + Timber.v("getNcClientInstance()"); if (ncClientInstance == null) { try { final Uri serverUri = Uri.parse(AccountUtils.getBaseUrlForAccount(ctx, account)); final String credentials = OkHttpCredentialsUtil.basic(account.name, getAcountPwd(account, ctx)); ncClientInstance = OwnCloudClientFactory.createNextcloudClient(serverUri, account.name, credentials, ctx, true); - } catch (AccountUtils.AccountNotFoundException e) { - Log.e(TAG, "Can't get server URI for account: "+account.name+"\n"+e.getMessage()); + } catch (AccountUtils.AccountNotFoundException exception) { + Timber.e("Can't get server URI for account: %s\n%s", account.name,exception.getMessage()); return null; } ncClientInstance.setUserId(account.name); diff --git a/app/src/main/java/foundation/e/drive/utils/ServiceExceptionHandler.java b/app/src/main/java/foundation/e/drive/utils/ServiceExceptionHandler.java index fc5c69be..24074649 100644 --- a/app/src/main/java/foundation/e/drive/utils/ServiceExceptionHandler.java +++ b/app/src/main/java/foundation/e/drive/utils/ServiceExceptionHandler.java @@ -9,7 +9,6 @@ package foundation.e.drive.utils; import android.app.Service; import android.os.Environment; -import android.util.Log; import java.io.File; import java.io.FileOutputStream; @@ -19,10 +18,10 @@ import java.io.StringWriter; import java.lang.Thread.UncaughtExceptionHandler; /** + * todo: check if still usefull or if it can be remove * @author Vincent Bourgmayer */ public class ServiceExceptionHandler implements UncaughtExceptionHandler{ - private final static String TAG = ServiceExceptionHandler.class.getSimpleName(); public final static String CRASH_LOG_FOLDER = "crash-logs"; public final static String LOG_FILE_NAME_PREFIX = "eDrive-crash-"; public final static String LOG_FILE_EXTENSION = ".log"; @@ -44,66 +43,53 @@ public class ServiceExceptionHandler implements UncaughtExceptionHandler{ } @Override - public void uncaughtException(Thread t, Throwable e) { - Log.d(TAG, "Service class: "+service.getClass().getSimpleName()); + public void uncaughtException(Thread t, Throwable exception) { if(isExternalStorageAvailable() && !isExternalStorageReadOnly()){ - //Get TimeStamp - Long timestamp = System.currentTimeMillis(); - //Create a new file that user can sent to us - String fileName = LOG_FILE_NAME_PREFIX+timestamp+LOG_FILE_EXTENSION; + final Long timestamp = System.currentTimeMillis(); - File downloadDir = service.getApplication().getExternalFilesDir(CRASH_LOG_FOLDER); - File logFile = new File(downloadDir, fileName); - try { + final String fileName = LOG_FILE_NAME_PREFIX+timestamp+LOG_FILE_EXTENSION; - FileOutputStream fos = new FileOutputStream(logFile); + final File downloadDir = service.getApplication().getExternalFilesDir(CRASH_LOG_FOLDER); + final File logFile = new File(downloadDir, fileName); + try (FileOutputStream fos = new FileOutputStream(logFile)) { fos.write(service.getClass().getSimpleName().getBytes()); - fos.write(getStackTraceAsString(e).getBytes()); - fos.close(); + fos.write(getStackTraceAsString(exception).getBytes()); logFile.setReadable(true, false); - - } catch (IOException exception) { - exception.printStackTrace(); + } catch (IOException ioException) { + ioException.printStackTrace(); } } //source: https://stackoverflow.com/questions/9050962/rethrow-uncaughtexceptionhandler-exception-after-logging-it/9050990#9050990 if(defaultUEH != null){ - defaultUEH.uncaughtException(t, e); + defaultUEH.uncaughtException(t, exception); }else{ - Log.d(TAG, "/e/ Drive has crashed and there is no ExceptionHandler"); System.exit(1); //Kill /e/ Drive... } } //source: https://www.journaldev.com/9400/android-external-storage-read-write-save-file private static boolean isExternalStorageAvailable() { - String extStorageState = Environment.getExternalStorageState(); - if (Environment.MEDIA_MOUNTED.equals(extStorageState)) { - return true; - } - return false; + final String extStorageState = Environment.getExternalStorageState(); + return Environment.MEDIA_MOUNTED.equals(extStorageState); } //source: https://www.journaldev.com/9400/android-external-storage-read-write-save-file private static boolean isExternalStorageReadOnly() { - String extStorageState = Environment.getExternalStorageState(); - if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(extStorageState)) { - return true; - } - return false; + final String extStorageState = Environment.getExternalStorageState(); + return Environment.MEDIA_MOUNTED_READ_ONLY.equals(extStorageState); } /** * Return the stackTrace of the exception as a String - * @param e the exception + * @param exception the exception * @return the Stacktrace as a string */ - private String getStackTraceAsString(Throwable e){ - StringWriter sw = new StringWriter(); - PrintWriter pw = new PrintWriter(sw); - e.printStackTrace(pw); + private String getStackTraceAsString(Throwable exception){ + final StringWriter sw = new StringWriter(); + final PrintWriter pw = new PrintWriter(sw); + exception.printStackTrace(pw); return sw.toString(); } } \ No newline at end of file diff --git a/app/src/main/java/foundation/e/drive/utils/SynchronizationServiceConnection.java b/app/src/main/java/foundation/e/drive/utils/SynchronizationServiceConnection.java index 8820dc2a..5a11626c 100644 --- a/app/src/main/java/foundation/e/drive/utils/SynchronizationServiceConnection.java +++ b/app/src/main/java/foundation/e/drive/utils/SynchronizationServiceConnection.java @@ -11,22 +11,22 @@ package foundation.e.drive.utils; import android.content.ComponentName; import android.content.ServiceConnection; import android.os.IBinder; -import android.util.Log; import foundation.e.drive.services.SynchronizationService; +import timber.log.Timber; /** * @author Vincent Bourgmayer */ public class SynchronizationServiceConnection implements ServiceConnection { - private final static String TAG = SynchronizationServiceConnection.class.getSimpleName(); private SynchronizationService synchronizationService; private boolean boundToSynchronizationService = false; @Override public void onServiceConnected(ComponentName componentName, IBinder iBinder) { - Log.i(TAG, "onServiceConnected: binding to SynchronizationService"); + Timber.tag(SynchronizationServiceConnection.class.getSimpleName()) + .v("binding to SynchronizationService"); SynchronizationService.SynchronizationBinder binder = (SynchronizationService.SynchronizationBinder) iBinder; synchronizationService = binder.getService(); boundToSynchronizationService = true; @@ -34,7 +34,8 @@ public class SynchronizationServiceConnection implements ServiceConnection { @Override public void onServiceDisconnected(ComponentName componentName) { - Log.i(TAG, "onServiceDisconnected: unbinding from SynchronizationService"); + Timber.tag(SynchronizationServiceConnection.class.getSimpleName()) + .v("Unbinding from SynchronizationService"); boundToSynchronizationService = false; } -- GitLab From 0bcd4715b2d60648217e3de2ab91fdc339bedb64 Mon Sep 17 00:00:00 2001 From: vincent Bourgmayer Date: Mon, 3 Oct 2022 18:53:49 +0200 Subject: [PATCH 5/5] widgets package: replace android logging by Timber logging --- .../e/drive/widgets/EDriveWidget.java | 20 ++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/app/src/main/java/foundation/e/drive/widgets/EDriveWidget.java b/app/src/main/java/foundation/e/drive/widgets/EDriveWidget.java index 25d870f7..3eedd267 100644 --- a/app/src/main/java/foundation/e/drive/widgets/EDriveWidget.java +++ b/app/src/main/java/foundation/e/drive/widgets/EDriveWidget.java @@ -28,7 +28,6 @@ import android.net.Network; import android.net.Uri; import android.os.Bundle; import android.provider.Settings; -import android.util.Log; import android.view.View; import android.widget.RemoteViews; @@ -38,13 +37,13 @@ import java.util.Locale; import foundation.e.drive.R; import foundation.e.drive.utils.CommonUtils; +import timber.log.Timber; /** * @author TheScarastic * Implementation of App Widget functionality. */ public class EDriveWidget extends AppWidgetProvider { - private static final String TAG = EDriveWidget.class.getSimpleName(); public static final String WEBPAGE = "https://esolutions.shop/ecloud-subscriptions/?username=%s&token=placeholder¤t-quota=%s&from=wp"; @@ -72,8 +71,8 @@ public class EDriveWidget extends AppWidgetProvider { long convertedBytes = 0; try { convertedBytes = Long.parseLong(bytes); - } catch (NumberFormatException e) { - Log.i(TAG, "Invalid bytes " + bytes); + } catch (NumberFormatException exception) { + Timber.tag(EDriveWidget.class.getSimpleName()).i("Invalid bytes %s", bytes); } final String space = CommonUtils.humanReadableByteCountBin(convertedBytes); final String[] split = space.split(" "); @@ -224,13 +223,16 @@ public class EDriveWidget extends AppWidgetProvider { String totalShownQuota = "?"; String usedShownQuota = "?"; + + Timber.tag(EDriveWidget.class.getSimpleName()); + //todo extract following duplicated code into a dedicated function try { final long totalQuotaLong = Long.parseLong(totalQuota); if (totalQuotaLong >= 0) { totalShownQuota = CommonUtils.humanReadableByteCountBin(totalQuotaLong); } } catch (NumberFormatException ignored) { - Log.i(TAG, "Bad totalQuotaLong " + totalQuota); + Timber.d("Bad totalQuotaLong %s", totalQuota); } try { @@ -239,12 +241,12 @@ public class EDriveWidget extends AppWidgetProvider { usedShownQuota = CommonUtils.humanReadableByteCountBin(usedQuotaLong); } } catch (NumberFormatException ignore) { - Log.i(TAG, "Bad usedQuotaLong " + usedQuota); + Timber.d("Bad usedQuotaLong %s", usedQuota); } views.setTextViewText(R.id.planName, context.getString(R.string.free_plan, totalShownQuota)); - String[] groups = accountManager.getUserData(account, ACCOUNT_DATA_GROUPS).split(","); + final String[] groups = accountManager.getUserData(account, ACCOUNT_DATA_GROUPS).split(","); for (String group : groups) { if (group.contains("premium-")) { views.setTextViewText(R.id.planName, context.getString(R.string.premium_plan, @@ -259,7 +261,7 @@ public class EDriveWidget extends AppWidgetProvider { views.setTextViewText(R.id.sync, context.getString(R.string.last_synced, sdf.format(calender.getTime()))); - String aliases = accountManager.getUserData(account, ACCOUNT_DATA_ALIAS_KEY); + final String aliases = accountManager.getUserData(account, ACCOUNT_DATA_ALIAS_KEY); if (aliases == null || aliases.isEmpty()) { views.setViewVisibility(R.id.show_alias, View.GONE); views.setViewVisibility(R.id.alias1_container, View.GONE); @@ -304,7 +306,7 @@ public class EDriveWidget extends AppWidgetProvider { } private void registerConnectivityCallback(final Context context) { - ConnectivityManager cm = (ConnectivityManager) context.getSystemService( + final ConnectivityManager cm = (ConnectivityManager) context.getSystemService( Context.CONNECTIVITY_SERVICE); cm.registerDefaultNetworkCallback(new ConnectivityManager.NetworkCallback() { @Override -- GitLab