Refactorize string util

This commit is contained in:
J-Jamet
2019-07-19 21:57:50 +02:00
parent c47834f470
commit 38abb9ca49
19 changed files with 67 additions and 171 deletions

View File

@@ -19,18 +19,13 @@
*/
package com.kunzisoft.keepass.tests;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import android.content.Context;
import android.content.res.AssetManager;
import android.net.Uri;
import android.os.Environment;
import com.kunzisoft.keepass.utils.EmptyUtils;
import com.kunzisoft.keepass.utils.UriUtil;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
public class TestUtil {
private static final File sdcard = Environment.getExternalStorageDirectory();

View File

@@ -23,16 +23,10 @@ import android.content.Context;
import android.content.res.AssetManager;
import android.test.AndroidTestCase;
import com.kunzisoft.keepass.database.element.PwDatabase;
import com.kunzisoft.keepass.database.element.PwDatabaseV4;
import com.kunzisoft.keepass.database.element.PwEntryV4;
import com.kunzisoft.keepass.utils.SprEngineV4;
import com.kunzisoft.keepass.utils.Types;
import com.kunzisoft.keepass.database.element.SprEngineV4;
import java.io.InputStream;
import java.util.UUID;
import biz.source_code.base64Coder.Base64Coder;
public class SprEngineTest extends AndroidTestCase {
private PwDatabaseV4 db;
@@ -73,14 +67,4 @@ public class SprEngineTest extends AndroidTestCase {
*/
}
private UUID decodeUUID(String encoded) {
if (encoded == null || encoded.length() == 0 ) {
return PwDatabase.UUID_ZERO;
}
byte[] buf = Base64Coder.decode(encoded);
return Types.bytestoUUID(buf);
}
}

View File

@@ -59,7 +59,6 @@ import com.kunzisoft.keepass.fileselect.database.FileDatabaseHistory
import com.kunzisoft.keepass.magikeyboard.KeyboardHelper
import com.kunzisoft.keepass.settings.PreferencesUtil
import com.kunzisoft.keepass.tasks.ActionRunnable
import com.kunzisoft.keepass.utils.EmptyUtils
import com.kunzisoft.keepass.utils.MenuUtil
import com.kunzisoft.keepass.utils.UriUtil
import net.cachapa.expandablelayout.ExpandableLayout
@@ -176,7 +175,7 @@ class FileDatabaseSelectActivity : StylishActivity(),
if (dbUri != null)
scheme = dbUri.scheme
if (!EmptyUtils.isNullOrEmpty(scheme) && scheme!!.equals("file", ignoreCase = true)) {
if (scheme != null && scheme.isNotEmpty() && scheme.equals("file", ignoreCase = true)) {
val path = dbUri!!.path
val db = File(path!!)

View File

@@ -59,7 +59,6 @@ import com.kunzisoft.keepass.fingerprint.FingerPrintHelper
import com.kunzisoft.keepass.magikeyboard.KeyboardHelper
import com.kunzisoft.keepass.settings.PreferencesUtil
import com.kunzisoft.keepass.tasks.ActionRunnable
import com.kunzisoft.keepass.utils.EmptyUtils
import com.kunzisoft.keepass.utils.MenuUtil
import com.kunzisoft.keepass.utils.UriUtil
import permissions.dispatcher.*
@@ -265,7 +264,7 @@ class PasswordActivity : StylishActivity(),
// Retrieve settings for default database
val defaultFilename = prefs?.getString(KEY_DEFAULT_FILENAME, "")
if (mDatabaseFileUri != null
&& !EmptyUtils.isNullOrEmpty(mDatabaseFileUri!!.path)
&& mDatabaseFileUri!!.path != null && mDatabaseFileUri!!.path!!.isNotEmpty()
&& UriUtil.equalsDefaultfile(mDatabaseFileUri, defaultFilename)) {
checkboxDefaultDatabaseView?.isChecked = true
}
@@ -814,14 +813,14 @@ class PasswordActivity : StylishActivity(),
@Throws(FileNotFoundException::class)
private fun verifyFileNameUriFromLaunch(fileName: String) {
if (EmptyUtils.isNullOrEmpty(fileName)) {
if (fileName.isEmpty()) {
throw FileNotFoundException()
}
val uri = UriUtil.parseDefaultFile(fileName)
val scheme = uri.scheme
if (!EmptyUtils.isNullOrEmpty(scheme) && scheme.equals("file", ignoreCase = true)) {
if (scheme != null && scheme.isNotEmpty() && scheme.equals("file", ignoreCase = true)) {
val dbFile = File(uri.path!!)
if (!dbFile.exists()) {
throw FileNotFoundException()

View File

@@ -35,7 +35,6 @@ import android.widget.TextView
import android.widget.Toast
import com.kunzisoft.keepass.R
import com.kunzisoft.keepass.activities.helpers.KeyFileHelper
import com.kunzisoft.keepass.utils.EmptyUtils
import com.kunzisoft.keepass.utils.UriUtil
class AssignMasterKeyDialogFragment : DialogFragment() {
@@ -184,7 +183,7 @@ class AssignMasterKeyDialogFragment : DialogFragment() {
mKeyFile = keyFile
// Verify that a keyfile is set
if (EmptyUtils.isNullOrEmpty(keyFile)) {
if (keyFile == null || keyFile.toString().isEmpty()) {
error = true
Toast.makeText(context, R.string.error_nokeyfile, Toast.LENGTH_LONG).show()
}

View File

@@ -21,7 +21,9 @@ package com.kunzisoft.keepass.activities.helpers
import android.app.Activity
import android.app.Activity.RESULT_OK
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.support.v4.app.Fragment
@@ -30,7 +32,6 @@ import android.util.Log
import android.view.View
import com.kunzisoft.keepass.activities.dialogs.BrowserDialogFragment
import com.kunzisoft.keepass.fileselect.StorageAF
import com.kunzisoft.keepass.utils.Interaction
import com.kunzisoft.keepass.utils.UriUtil
class KeyFileHelper {
@@ -105,7 +106,7 @@ class KeyFileHelper {
private fun lookForOpenIntentsFilePicker(dataUri: Uri?): Boolean {
var showBrowser = false
try {
if (Interaction.isIntentAvailable(activity!!, OPEN_INTENTS_FILE_BROWSE)) {
if (isIntentAvailable(activity!!, OPEN_INTENTS_FILE_BROWSE)) {
val intent = Intent(OPEN_INTENTS_FILE_BROWSE)
// Get file path parent if possible
if (dataUri != null
@@ -130,6 +131,26 @@ class KeyFileHelper {
return showBrowser
}
/**
* Indicates whether the specified action can be used as an intent. This
* method queries the package manager for installed packages that can
* respond to an intent with the specified action. If no suitable package is
* found, this method returns false.
*
* @param context The application's environment.
* @param action The Intent action to check for availability.
*
* @return True if an Intent with the specified action can be sent and
* responded to, false otherwise.
*/
private fun isIntentAvailable(context: Context, action: String): Boolean {
val packageManager = context.packageManager
val intent = Intent(action)
val list = packageManager.queryIntentActivities(intent,
PackageManager.MATCH_DEFAULT_ONLY)
return list.size > 0
}
/**
* Show Browser dialog to select file picker app
*/

View File

@@ -43,7 +43,6 @@ import com.kunzisoft.keepass.icons.IconDrawableFactory
import com.kunzisoft.keepass.settings.PreferencesUtil
import com.kunzisoft.keepass.stream.LEDataInputStream
import com.kunzisoft.keepass.tasks.ProgressTaskUpdater
import com.kunzisoft.keepass.utils.EmptyUtils
import com.kunzisoft.keepass.utils.UriUtil
import com.kunzisoft.keepass.utils.getUriInputStream
import org.apache.commons.io.FileUtils
@@ -220,7 +219,7 @@ class Database {
private fun dbNameFromPath(dbPath: String): String {
val filename = URLUtil.guessFileName(dbPath, null, null)
if (EmptyUtils.isNullOrEmpty(filename)) {
if (filename == null || filename.isEmpty()) {
return "KeePass Database"
}
val lastExtDot = filename.lastIndexOf(".")

View File

@@ -24,7 +24,6 @@ import android.os.Parcelable
import com.kunzisoft.keepass.database.element.security.ProtectedBinary
import com.kunzisoft.keepass.database.element.security.ProtectedString
import com.kunzisoft.keepass.utils.MemUtil
import com.kunzisoft.keepass.utils.SprEngineV4
import java.util.*
class PwEntryV4 : PwEntry<PwGroupV4, PwEntryV4>, NodeV4Interface {

View File

@@ -17,16 +17,19 @@
* along with KeePass DX. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.kunzisoft.keepass.utils;
package com.kunzisoft.keepass.database.element;
import com.kunzisoft.keepass.database.element.PwEntryV4;
import com.kunzisoft.keepass.database.element.PwGroupV4;
import com.kunzisoft.keepass.database.element.PwDatabase;
import com.kunzisoft.keepass.database.element.PwDatabaseV4;
import com.kunzisoft.keepass.database.search.EntrySearchHandlerV4;
import com.kunzisoft.keepass.database.search.SearchParametersV4;
import com.kunzisoft.keepass.utils.StringUtil;
import java.util.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
public class SprEngineV4 {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2017 Brian Pellin, Jeremy Jamet / Kunzisoft.
* Copyright 2019 Jeremy Jamet / Kunzisoft.
*
* This file is part of KeePass DX.
*
@@ -20,14 +20,8 @@
package com.kunzisoft.keepass.database.exception
import android.net.Uri
import com.kunzisoft.keepass.utils.EmptyUtils
import java.io.FileNotFoundException
/**
* Created by bpellin on 3/14/16.
*/
class ContentFileNotFoundException : FileNotFoundException() {
companion object {
fun getInstance(uri: Uri?): FileNotFoundException {
@@ -36,11 +30,11 @@ class ContentFileNotFoundException : FileNotFoundException() {
}
val scheme = uri.scheme
return if (!EmptyUtils.isNullOrEmpty(scheme) && scheme!!.equals("content", ignoreCase = true)) {
return if (scheme != null
&& scheme.isNotEmpty()
&& scheme.equals("content", ignoreCase = true)) {
ContentFileNotFoundException()
} else FileNotFoundException()
}
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2017 Brian Pellin, Jeremy Jamet / Kunzisoft.
* Copyright 2019 Jeremy Jamet / Kunzisoft.
*
* This file is part of KeePass DX.
*
@@ -17,7 +17,7 @@
* along with KeePass DX. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.kunzisoft.keepass.utils;
package com.kunzisoft.keepass.database.file;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
@@ -25,7 +25,7 @@ import org.joda.time.Duration;
import java.util.Date;
public class DateUtil {
public class KDBX4DateUtil {
private static final DateTime dotNetEpoch = new DateTime(1, 1, 1, 0, 0, 0, DateTimeZone.UTC);
private static final DateTime javaEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeZone.UTC);
@@ -36,14 +36,11 @@ public class DateUtil {
}
public static Date convertKDBX4Time(long seconds) {
DateTime dt = dotNetEpoch.plus(seconds * 1000L);
// Switch corrupted dates to a more recent date that won't cause issues on the client
if (dt.isBefore(javaEpoch)) {
return javaEpoch.toDate();
}
return dt.toDate();
}

View File

@@ -37,8 +37,7 @@ import com.kunzisoft.keepass.stream.HashedBlockInputStream
import com.kunzisoft.keepass.stream.HmacBlockInputStream
import com.kunzisoft.keepass.stream.LEDataInputStream
import com.kunzisoft.keepass.tasks.ProgressTaskUpdater
import com.kunzisoft.keepass.utils.DateUtil
import com.kunzisoft.keepass.utils.EmptyUtils
import com.kunzisoft.keepass.database.file.KDBX4DateUtil
import com.kunzisoft.keepass.utils.MemUtil
import com.kunzisoft.keepass.utils.Types
import org.spongycastle.crypto.StreamCipher
@@ -334,7 +333,7 @@ class ImporterV4(private val streamDir: File) : Importer<PwDatabaseV4>() {
readString(xpp) // Ignore
} else if (name.equals(PwDatabaseV4XML.ElemHeaderHash, ignoreCase = true)) {
val encodedHash = readString(xpp)
if (!EmptyUtils.isNullOrEmpty(encodedHash) && hashOfHeader != null) {
if (encodedHash.isNotEmpty() && hashOfHeader != null) {
val hash = Base64Coder.decode(encodedHash)
if (!Arrays.equals(hash, hashOfHeader)) {
throw InvalidDBException()
@@ -814,7 +813,7 @@ class ImporterV4(private val streamDir: File) : Importer<PwDatabaseV4>() {
}
val seconds = LEDataInputStream.readLong(buf, 0)
utcDate = DateUtil.convertKDBX4Time(seconds)
utcDate = KDBX4DateUtil.convertKDBX4Time(seconds)
} else {

View File

@@ -38,8 +38,7 @@ import com.kunzisoft.keepass.database.element.security.ProtectedString
import com.kunzisoft.keepass.stream.HashedBlockOutputStream
import com.kunzisoft.keepass.stream.HmacBlockOutputStream
import com.kunzisoft.keepass.stream.LEDataOutputStream
import com.kunzisoft.keepass.utils.DateUtil
import com.kunzisoft.keepass.utils.EmptyUtils
import com.kunzisoft.keepass.database.file.KDBX4DateUtil
import com.kunzisoft.keepass.utils.MemUtil
import com.kunzisoft.keepass.utils.Types
import org.joda.time.DateTime
@@ -482,7 +481,7 @@ class PwDbV4Output(private val mDatabaseV4: PwDatabaseV4, outputStream: OutputSt
writeObject(name, PwDatabaseV4XML.dateFormatter.get().format(value))
} else {
val dt = DateTime(value)
val seconds = DateUtil.convertDateToKDBX4Time(dt)
val seconds = KDBX4DateUtil.convertDateToKDBX4Time(dt)
val buf = LEDataOutputStream.writeLongBuf(seconds)
val b64 = String(Base64Coder.encode(buf))
writeObject(name, b64)
@@ -720,7 +719,7 @@ class PwDbV4Output(private val mDatabaseV4: PwDatabaseV4, outputStream: OutputSt
}
private fun safeXmlString(text: String): String {
if (EmptyUtils.isNullOrEmpty(text)) {
if (text.isEmpty()) {
return text
}

View File

@@ -23,7 +23,6 @@ import com.kunzisoft.keepass.database.NodeHandler
import com.kunzisoft.keepass.database.element.PwEntryV4
import com.kunzisoft.keepass.database.search.iterator.EntrySearchStringIteratorV4
import com.kunzisoft.keepass.utils.StringUtil
import com.kunzisoft.keepass.utils.UuidUtil
import java.util.Date
import java.util.Locale

View File

@@ -17,7 +17,9 @@
* along with KeePass DX. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.kunzisoft.keepass.utils;
package com.kunzisoft.keepass.database.search;
import com.kunzisoft.keepass.utils.Types;
import java.util.UUID;

View File

@@ -1,42 +0,0 @@
/*
* Copyright 2017 Brian Pellin, Jeremy Jamet / Kunzisoft.
*
* This file is part of KeePass DX.
*
* KeePass DX is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* KeePass DX 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 KeePass DX. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.kunzisoft.keepass.utils
import android.net.Uri
import com.kunzisoft.keepass.database.element.PwDate
object EmptyUtils {
fun isNullOrEmpty(str: String?): Boolean {
return str == null || str.isEmpty()
}
fun isNullOrEmpty(buf: ByteArray?): Boolean {
return buf == null || buf.isEmpty()
}
fun isNullOrEmpty(date: PwDate?): Boolean {
return date == null || date == PwDate.DEFAULT_PWDATE
}
fun isNullOrEmpty(uri: Uri?): Boolean {
return uri == null || uri.toString().isEmpty()
}
}

View File

@@ -1,50 +0,0 @@
/*
* Copyright 2017 Brian Pellin, Jeremy Jamet / Kunzisoft.
*
* This file is part of KeePass DX.
*
* KeePass DX is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* KeePass DX 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 KeePass DX. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.kunzisoft.keepass.utils;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import java.util.List;
public class Interaction {
/**
* Indicates whether the specified action can be used as an intent. This
* method queries the package manager for installed packages that can
* respond to an intent with the specified action. If no suitable package is
* found, this method returns false.
*
* @param context The application's environment.
* @param action The Intent action to check for availability.
*
* @return True if an Intent with the specified action can be sent and
* responded to, false otherwise.
*/
public static boolean isIntentAvailable(Context context, String action) {
final PackageManager packageManager = context.getPackageManager();
final Intent intent = new Intent(action);
List<ResolveInfo> list =
packageManager.queryIntentActivities(intent,
PackageManager.MATCH_DEFAULT_ONLY);
return list.size() > 0;
}
}

View File

@@ -32,19 +32,19 @@ import java.io.File;
*/
public class UriUtil {
public static Uri parseDefaultFile(String text) {
if (EmptyUtils.INSTANCE.isNullOrEmpty(text)) {
if (text == null || text.isEmpty()) {
return null;
}
Uri uri = Uri.parse(text);
if (EmptyUtils.INSTANCE.isNullOrEmpty(uri.getScheme())) {
if (uri.getScheme() == null || uri.getScheme().isEmpty()) {
uri = uri.buildUpon().scheme("file").authority("").build();
}
return uri;
}
public static Uri parseDefaultFile(Uri uri) {
if (EmptyUtils.INSTANCE.isNullOrEmpty(uri.getScheme())) {
if (uri.getScheme() == null || uri.getScheme().isEmpty()) {
uri = uri.buildUpon().scheme("file").authority("").build();
}
@@ -69,7 +69,7 @@ public class UriUtil {
if (StorageAF.INSTANCE.useStorageFramework(ctx) || hasWritableContentUri(uri)) { return uri; }
String scheme = uri.getScheme();
if (EmptyUtils.INSTANCE.isNullOrEmpty(scheme)) { return uri; }
if (scheme == null || scheme.isEmpty()) { return uri; }
String filepath = null;
@@ -91,7 +91,7 @@ public class UriUtil {
}
// Try using the URI path as a straight file
if (EmptyUtils.INSTANCE.isNullOrEmpty(filepath)) {
if (filepath == null || filepath.isEmpty()) {
filepath = uri.getEncodedPath();
if (!isValidFilePath(filepath)) {
filepath = null;
@@ -104,7 +104,7 @@ public class UriUtil {
}
// Update the file to a file URI
if (!EmptyUtils.INSTANCE.isNullOrEmpty(filepath)) {
if (filepath != null && !filepath.isEmpty()) {
Uri.Builder b = new Uri.Builder();
uri = b.scheme("file").authority("").path(filepath).build();
}
@@ -113,7 +113,7 @@ public class UriUtil {
}
private static boolean isValidFilePath(String filepath) {
if (EmptyUtils.INSTANCE.isNullOrEmpty(filepath)) { return false; }
if (filepath == null || filepath.isEmpty()) { return false; }
File file = new File(filepath);
return file.exists() && file.canRead();
@@ -127,7 +127,7 @@ public class UriUtil {
private static boolean hasWritableContentUri(Uri uri) {
String scheme = uri.getScheme();
if (EmptyUtils.INSTANCE.isNullOrEmpty(scheme)) { return false; }
if (scheme == null || scheme.isEmpty()) { return false; }
if (!scheme.equalsIgnoreCase("content")) { return false; }

View File

@@ -11,7 +11,7 @@ fun getUriInputStream(contentResolver: ContentResolver, uri: Uri?): InputStream?
if (uri == null) return null
val scheme = uri.scheme
return if (EmptyUtils.isNullOrEmpty(scheme) || scheme == "file") {
return if (scheme == null || scheme.isEmpty() || scheme == "file") {
FileInputStream(uri.path!!)
} else if (scheme == "content") {
contentResolver.openInputStream(uri)