Refactor Entry and Group

This commit is contained in:
J-Jamet committed 2019-03-21 17:58:08 +01:00
1 parent 20f7675135
commit a376d2f286
54 files changed
+568 -740

No files matched your search

@@ -27,7 +27,7 @@ public class PwDateTest extends TestCase {
public void testDate() {
PwDate jDate = new PwDate(System.currentTimeMillis());
PwDate intermediate = (PwDate) jDate.clone();
PwDate intermediate = jDate.clone();
PwDate cDate = new PwDate(intermediate.getCDate(), 0);
@@ -42,7 +42,7 @@ public class PwEntryTestV3 extends AndroidTestCase {
}
public void testName() {
assertTrue("Name was " + mPE.getName(), mPE.getName().equals("Amazon"));
assertTrue("Name was " + mPE.getTitle(), mPE.getTitle().equals("Amazon"));
}
public void testPassword() throws UnsupportedEncodingException {
@@ -33,6 +33,8 @@ import java.util.UUID;
public class PwEntryTestV4 extends TestCase {
public void testAssign() {
/*
TODO Test
PwEntryV4 entry = new PwEntryV4();
entry.setAdditional("test223");
@@ -53,7 +55,7 @@ public class PwEntryTestV4 extends TestCase {
entry.setParent(new PwGroupV4());
entry.addExtraField("key2", new ProtectedString(false, "value2"));
entry.setUrl("http://localhost");
entry.setUUID(UUID.randomUUID());
entry.setNodeId(UUID.randomUUID());
PwEntryV4 target = new PwEntryV4();
target.updateWith(entry);
@@ -38,7 +38,7 @@ public class PwGroupTest extends AndroidTestCase {
}
public void testGroupName() {
assertTrue("Name was " + mPG.getName(), mPG.getName().equals("Internet"));
assertTrue("Name was " + mPG.getTitle(), mPG.getTitle().equals("Internet"));
}
}
@@ -85,14 +85,16 @@ public class DeleteEntry extends AndroidTestCase {
}
private PwEntryV3 getEntry(PwDatabaseV3 pm, String name) {
/*
TODO test
List<PwEntryV3> entries = pm.getEntries();
for ( int i = 0; i < entries.size(); i++ ) {
PwEntryV3 entry = entries.get(i);
if ( entry.getName().equals(name) ) {
if ( entry.getTitle().equals(name) ) {
return entry;
}
}
*/
return null;
}
@@ -101,7 +103,7 @@ public class DeleteEntry extends AndroidTestCase {
List<PwGroupInterface> groups = pm.getGroups();
for ( int i = 0; i < groups.size(); i++ ) {
PwGroupInterface group = groups.get(i);
if ( group.getName().equals(name) ) {
if ( group.getTitle().equals(name) ) {
return group;
}
}
@@ -33,21 +33,21 @@ public class EntryV4 extends TestCase {
PwEntryV4 entry = new PwEntryV4();
entry.startToManageFieldReferences(db);
entry.setName("Title1");
entry.setTitle("Title1");
entry.setUsername("User1");
entry.createBackup(db);
entry.setName("Title2");
entry.setTitle("Title2");
entry.setUsername("User2");
entry.createBackup(db);
entry.setName("Title3");
entry.setTitle("Title3");
entry.setUsername("User3");
entry.createBackup(db);
PwEntryV4 backup = entry.getHistory().get(0);
entry.stopToManageFieldReferences();
assertEquals("Title2", backup.getName());
assertEquals("Title2", backup.getTitle());
assertEquals("User2", backup.getUsername());
}
@@ -62,12 +62,15 @@ public class SprEngineTest extends AndroidTestCase {
private final String ENCODE_UUID = "IN7RkON49Ui1UZ2ddqmLcw==";
private final String RESULT = "Password";
public void testRefReplace() {
/*
TODO TEST
UUID entryUUID = decodeUUID(ENCODE_UUID);
PwEntryV4 entry = (PwEntryV4) db.getEntryByUUIDId(entryUUID);
PwEntryV4 entry = (PwEntryV4) db.getEntryById(entryUUID);
assertEquals(RESULT, spr.compile(REF, entry, db));
*/
}
@@ -47,6 +47,7 @@ import com.kunzisoft.keepass.database.ExtraFields;
import com.kunzisoft.keepass.database.element.Database;
import com.kunzisoft.keepass.database.element.PwDatabase;
import com.kunzisoft.keepass.database.element.PwEntryInterface;
import com.kunzisoft.keepass.database.element.PwNodeId;
import com.kunzisoft.keepass.database.security.ProtectedString;
import com.kunzisoft.keepass.notifications.NotificationCopyingService;
import com.kunzisoft.keepass.notifications.NotificationField;
@@ -56,13 +57,11 @@ import com.kunzisoft.keepass.timeout.ClipboardHelper;
import com.kunzisoft.keepass.timeout.TimeoutHelper;
import com.kunzisoft.keepass.utils.EmptyUtils;
import com.kunzisoft.keepass.utils.MenuUtil;
import com.kunzisoft.keepass.utils.Types;
import com.kunzisoft.keepass.utils.Util;
import com.kunzisoft.keepass.view.EntryContentsView;
import java.util.ArrayList;
import java.util.Date;
import java.util.UUID;
import static com.kunzisoft.keepass.settings.PreferencesUtil.isClipboardNotificationsEnable;
import static com.kunzisoft.keepass.settings.PreferencesUtil.isFirstTimeAskAllowCopyPasswordAndProtectedFields;
@@ -88,7 +87,7 @@ public class EntryActivity extends LockingHideActivity {
public static void launch(Activity activity, PwEntryInterface pw, boolean readOnly) {
if (TimeoutHelper.INSTANCE.checkTimeAndLockIfTimeout(activity)) {
Intent intent = new Intent(activity, EntryActivity.class);
intent.putExtra(KEY_ENTRY, Types.UUIDtoBytes(pw.getUUID()));
intent.putExtra(KEY_ENTRY, pw.getNodeId());
ReadOnlyHelper.INSTANCE.putReadOnlyInIntent(intent, readOnly);
activity.startActivityForResult(intent, EntryEditActivity.ADD_OR_UPDATE_ENTRY_REQUEST_CODE);
}
@@ -114,13 +113,19 @@ public class EntryActivity extends LockingHideActivity {
// Get Entry from UUID
Intent i = getIntent();
UUID uuid = Types.bytestoUUID(i.getByteArrayExtra(KEY_ENTRY));
mEntry = db.getPwDatabase().getEntryByUUIDId(uuid);
if (mEntry == null) {
Toast.makeText(this, R.string.entry_not_found, Toast.LENGTH_LONG).show();
finish();
return;
}
PwNodeId keyEntry;
try {
keyEntry = i.getParcelableExtra(KEY_ENTRY);
mEntry = db.getPwDatabase().getEntryById(keyEntry);
} catch (ClassCastException e) {
Log.e(TAG, "Unable to retrieve the entry key");
} finally {
if (mEntry == null) {
Toast.makeText(this, R.string.entry_not_found, Toast.LENGTH_LONG).show();
finish();
return;
}
}
// Retrieve the textColor to tint the icon
int[] attrs = {R.attr.textColorInverse};
@@ -180,8 +185,8 @@ public class EntryActivity extends LockingHideActivity {
// username already copied, waiting for user's action before copy password.
Intent intent = new Intent(this, NotificationCopyingService.class);
intent.setAction(NotificationCopyingService.ACTION_NEW_NOTIFICATION);
if (mEntry.getName() != null)
intent.putExtra(NotificationCopyingService.EXTRA_ENTRY_TITLE, mEntry.getName());
if (mEntry.getTitle() != null)
intent.putExtra(NotificationCopyingService.EXTRA_ENTRY_TITLE, mEntry.getTitle());
// Construct notification fields
ArrayList<NotificationField> notificationFields = new ArrayList<>();
// Add username if exists to notifications
@@ -50,6 +50,7 @@ import com.kunzisoft.keepass.database.element.Database;
import com.kunzisoft.keepass.database.element.PwDatabase;
import com.kunzisoft.keepass.database.element.PwDate;
import com.kunzisoft.keepass.database.element.PwEntryInterface;
import com.kunzisoft.keepass.database.element.PwIcon;
import com.kunzisoft.keepass.database.element.PwNodeId;
import com.kunzisoft.keepass.database.element.PwGroupInterface;
import com.kunzisoft.keepass.database.element.PwIconStandard;
@@ -60,14 +61,11 @@ import com.kunzisoft.keepass.settings.PreferencesUtil;
import com.kunzisoft.keepass.tasks.ActionRunnable;
import com.kunzisoft.keepass.timeout.TimeoutHelper;
import com.kunzisoft.keepass.utils.MenuUtil;
import com.kunzisoft.keepass.utils.Types;
import com.kunzisoft.keepass.utils.Util;
import com.kunzisoft.keepass.view.EntryEditCustomField;
import org.jetbrains.annotations.NotNull;
import java.util.UUID;
import static com.kunzisoft.keepass.dialogs.IconPickerDialogFragment.KEY_ICON_STANDARD;
public class EntryEditActivity extends LockingHideActivity
@@ -117,7 +115,7 @@ public class EntryEditActivity extends LockingHideActivity
public static void launch(Activity activity, PwEntryInterface pwEntry) {
if (TimeoutHelper.INSTANCE.checkTimeAndLockIfTimeout(activity)) {
Intent intent = new Intent(activity, EntryEditActivity.class);
intent.putExtra(KEY_ENTRY, Types.UUIDtoBytes(pwEntry.getUUID()));
intent.putExtra(KEY_ENTRY, pwEntry.getNodeId());
activity.startActivityForResult(intent, ADD_OR_UPDATE_ENTRY_REQUEST_CODE);
}
}
@@ -131,7 +129,7 @@ public class EntryEditActivity extends LockingHideActivity
public static void launch(Activity activity, PwGroupInterface pwGroup) {
if (TimeoutHelper.INSTANCE.checkTimeAndLockIfTimeout(activity)) {
Intent intent = new Intent(activity, EntryEditActivity.class);
intent.putExtra(KEY_PARENT, pwGroup.getId());
intent.putExtra(KEY_PARENT, pwGroup.getNodeId());
activity.startActivityForResult(intent, ADD_OR_UPDATE_ENTRY_REQUEST_CODE);
}
}
@@ -174,7 +172,7 @@ public class EntryEditActivity extends LockingHideActivity
database = App.getDB();
Intent intent = getIntent();
byte[] uuidBytes = intent.getByteArrayExtra(KEY_ENTRY);
PwNodeId keyEntry = intent.getParcelableExtra(KEY_ENTRY);
// Retrieve the textColor to tint the icon
int[] attrs = {android.R.attr.textColorPrimary};
@@ -184,7 +182,7 @@ public class EntryEditActivity extends LockingHideActivity
mSelectedIconStandard = database.getPwDatabase().getIconFactory().getUnknownIcon();
PwDatabase pm = database.getPwDatabase();
if ( uuidBytes == null ) {
if (keyEntry == null) {
PwNodeId parentId = intent.getParcelableExtra(KEY_PARENT);
PwGroupInterface parent = pm.getGroupByGroupId(parentId);
mEntry = database.createEntry(parent);
@@ -192,8 +190,7 @@ public class EntryEditActivity extends LockingHideActivity
// Add the default icon
database.getDrawFactory().assignDefaultDatabaseIconTo(this, entryIconView, iconColor);
} else {
UUID uuid = Types.bytestoUUID(uuidBytes);
mEntry = pm.getEntryByUUIDId(uuid);
mEntry = pm.getEntryById(keyEntry);
mIsNew = false;
fillData();
}
@@ -416,7 +413,7 @@ public class EntryEditActivity extends LockingHideActivity
protected PwEntryInterface populateNewEntry() {
PwDatabase db = App.getDB().getPwDatabase();
PwEntryInterface newEntry = mEntry.clone();
PwEntryInterface newEntry = mEntry.duplicate();
newEntry.startToManageFieldReferences(db);
@@ -425,8 +422,8 @@ public class EntryEditActivity extends LockingHideActivity
newEntry.setLastAccessTime(new PwDate());
newEntry.setLastModificationTime(new PwDate());
newEntry.setName(entryTitleView.getText().toString());
newEntry.setIconStandard(retrieveIcon());
newEntry.setTitle(entryTitleView.getText().toString());
newEntry.setIcon(retrieveIcon());
newEntry.setUrl(entryUrlView.getText().toString());
newEntry.setUsername(entryUserNameView.getText().toString());
@@ -454,7 +451,7 @@ public class EntryEditActivity extends LockingHideActivity
/**
* Retrieve the icon by the selection, or the first icon in the list if the entry is new or the last one
*/
private PwIconStandard retrieveIcon() {
private PwIcon retrieveIcon() {
if (!mSelectedIconStandard.isUnknown())
return mSelectedIconStandard;
@@ -464,7 +461,7 @@ public class EntryEditActivity extends LockingHideActivity
}
else {
// Keep previous icon, if no new one was selected
return mEntry.getIconStandard();
return mEntry.getIcon();
}
}
}
@@ -513,7 +510,7 @@ public class EntryEditActivity extends LockingHideActivity
// Don't start the field reference manager, we want to see the raw ref
mEntry.stopToManageFieldReferences();
entryTitleView.setText(mEntry.getName());
entryTitleView.setText(mEntry.getTitle());
entryUserNameView.setText(mEntry.getUsername());
entryUrlView.setText(mEntry.getUrl());
String password = mEntry.getPassword();
@@ -543,7 +540,7 @@ public class EntryEditActivity extends LockingHideActivity
@Override
public void iconPicked(Bundle bundle) {
mSelectedIconStandard = bundle.getParcelable(KEY_ICON_STANDARD);
mEntry.setIconStandard(mSelectedIconStandard);
mEntry.setIcon(mSelectedIconStandard);
assignIconView();
}
@@ -76,9 +76,7 @@ import com.kunzisoft.keepass.database.element.PwDatabase;
import com.kunzisoft.keepass.database.element.PwEntryInterface;
import com.kunzisoft.keepass.database.element.PwNodeId;
import com.kunzisoft.keepass.database.element.PwGroupInterface;
import com.kunzisoft.keepass.database.element.PwGroupV4;
import com.kunzisoft.keepass.database.element.PwIcon;
import com.kunzisoft.keepass.database.element.PwIconStandard;
import com.kunzisoft.keepass.database.element.PwNodeInterface;
import com.kunzisoft.keepass.dialogs.AssignMasterKeyDialogFragment;
import com.kunzisoft.keepass.dialogs.GroupEditDialogFragment;
@@ -89,6 +87,8 @@ import com.kunzisoft.keepass.dialogs.SortDialogFragment;
import com.kunzisoft.keepass.magikeyboard.KeyboardEntryNotificationService;
import com.kunzisoft.keepass.magikeyboard.KeyboardHelper;
import com.kunzisoft.keepass.magikeyboard.MagikIME;
import com.kunzisoft.keepass.model.Entry;
import com.kunzisoft.keepass.model.Field;
import com.kunzisoft.keepass.settings.PreferencesUtil;
import com.kunzisoft.keepass.timeout.TimeoutHelper;
import com.kunzisoft.keepass.utils.MenuUtil;
@@ -145,7 +145,7 @@ public class GroupActivity extends LockingActivity
if (TimeoutHelper.INSTANCE.checkTimeAndLockIfTimeout(activity)) {
Intent intent = new Intent(activity, GroupActivity.class);
if (group != null) {
intent.putExtra(GROUP_ID_KEY, group.getId());
intent.putExtra(GROUP_ID_KEY, group.getNodeId());
}
ReadOnlyHelper.INSTANCE.putReadOnlyInIntent(intent, readOnly);
intentBuildLauncher.launchActivity(intent);
@@ -364,7 +364,7 @@ public class GroupActivity extends LockingActivity
@Override
protected void onSaveInstanceState(Bundle outState) {
if (mCurrentGroup != null)
outState.putParcelable(GROUP_ID_KEY, mCurrentGroup.getId());
outState.putParcelable(GROUP_ID_KEY, mCurrentGroup.getNodeId());
outState.putParcelable(OLD_GROUP_TO_UPDATE_KEY, oldGroupToUpdate);
if (nodeToCopy != null)
outState.putParcelable(NODE_TO_COPY_KEY, nodeToCopy);
@@ -407,7 +407,7 @@ public class GroupActivity extends LockingActivity
public void assignGroupViewElements() {
// Assign title
if (mCurrentGroup != null) {
String title = mCurrentGroup.getName();
String title = mCurrentGroup.getTitle();
if (title != null && title.length() > 0) {
if (groupNameView != null) {
groupNameView.setText(title);
@@ -502,7 +502,7 @@ public class GroupActivity extends LockingActivity
return null;
},
() -> {
MagikIME.setEntryKey(entry.getEntry());
MagikIME.setEntryKey(getEntry(entry));
// Show the notification if allowed in Preferences
if (PreferencesUtil.enableKeyboardNotificationEntry(GroupActivity.this)) {
startService(new Intent(
@@ -529,6 +529,21 @@ public class GroupActivity extends LockingActivity
}
}
private Entry getEntry(PwEntryInterface entry) {
Entry entryModel = new Entry();
entryModel.setTitle(entry.getTitle());
entryModel.setUsername(entry.getUsername());
entryModel.setPassword(entry.getPassword());
entryModel.setUrl(entry.getUrl());
if (entry.containsCustomFields()) {
entry.getFields()
.doActionToAllCustomProtectedField(
(key, value) -> entryModel.addCustomField(
new Field(key, value.toString())));
}
return entryModel;
}
@Override
public boolean onOpenMenuClick(PwNodeInterface node) {
onNodeClick(node);
@@ -956,18 +971,14 @@ public class GroupActivity extends LockingActivity
String name,
PwIcon icon) {
Database database = App.getDB();
PwIconStandard iconStandard = database.getPwDatabase().getIconFactory().getFolderIcon();
switch (action) {
case CREATION:
// If group creation
// Build the group
PwGroupInterface newGroup = database.createGroup(mCurrentGroup);
newGroup.setName(name);
try {
iconStandard = (PwIconStandard) icon;
} catch (Exception ignored) {} // TODO custom icon
newGroup.setIconStandard(iconStandard);
newGroup.setTitle(name);
newGroup.setIcon(icon);
// If group created save it in the database
new Thread(new AddGroupRunnable(this,
@@ -982,15 +993,9 @@ public class GroupActivity extends LockingActivity
// If update add new elements
if (oldGroupToUpdate != null) {
PwGroupInterface updateGroup = oldGroupToUpdate.duplicate();
try {
iconStandard = (PwIconStandard) icon;
updateGroup = ((PwGroupV4) oldGroupToUpdate).duplicate(); // TODO generalize
} catch (Exception e) {
e.printStackTrace();
}
updateGroup.setName(name);
updateGroup.setTitle(name);
// TODO custom icon
updateGroup.setIconStandard(iconStandard);
updateGroup.setIcon(icon);
if (listNodesFragment != null)
listNodesFragment.removeNode(oldGroupToUpdate);
@@ -91,7 +91,7 @@ public class NodeAdapter extends RecyclerView.Adapter<BasicViewHolder> {
}
@Override public boolean areContentsTheSame(PwNodeInterface oldItem, PwNodeInterface newItem) {
return oldItem.getName().equals(newItem.getName())
return oldItem.getTitle().equals(newItem.getTitle())
&& oldItem.getIcon().equals(newItem.getIcon());
}
@@ -235,7 +235,7 @@ public class NodeAdapter extends RecyclerView.Adapter<BasicViewHolder> {
}
database.getDrawFactory().assignDatabaseIconTo(context, holder.icon, subNode.getIcon(), iconColor);
// Assign text
holder.text.setText(subNode.getName());
holder.text.setText(subNode.getTitle());
// Assign click
holder.container.setOnClickListener(
new OnNodeClickListener(subNode));
@@ -104,7 +104,7 @@ public class SearchEntryCursorAdapter extends CursorAdapter {
database.getDrawFactory().assignDatabaseIconTo(context, viewHolder.imageViewIcon, icon, iconColor);
// Assign title
String showTitle = PwEntryInterface.getVisualTitle(false, title, username, url, uuid);
String showTitle = PwEntryInterface.getVisualTitle(false, title, username, url, uuid.toString());
viewHolder.textViewTitle.setText(showTitle);
if (displayUsername && !username.isEmpty()) {
viewHolder.textViewSubTitle.setText(String.format("(%s)", username));
@@ -52,10 +52,10 @@ object AutofillHelper {
}
private fun makeEntryTitle(entry: PwEntryInterface): String {
if (!entry.name.isEmpty() && !entry.username.isEmpty())
return String.format("%s (%s)", entry.name, entry.username)
if (!entry.name.isEmpty())
return entry.name
if (!entry.title.isEmpty() && !entry.username.isEmpty())
return String.format("%s (%s)", entry.title, entry.username)
if (!entry.title.isEmpty())
return entry.title
if (!entry.username.isEmpty())
return entry.username
return if (!entry.notes.isEmpty()) entry.notes.trim { it <= ' ' } else ""
@@ -67,7 +67,7 @@ object AutofillHelper {
val title = makeEntryTitle(entry)
val views = newRemoteViews(context.packageName, title)
val builder = Dataset.Builder(views)
builder.setId(entry.uuid.toString())
builder.setId(entry.nodeId.toString())
if (entry.password != null) {
val value = AutofillValue.forText(entry.password)
@@ -19,7 +19,9 @@
*/
package com.kunzisoft.keepass.database;
import com.kunzisoft.keepass.database.element.PwEntryInterface;
import com.kunzisoft.keepass.database.element.PwEntryV4;
import com.kunzisoft.keepass.database.element.PwGroupInterface;
import com.kunzisoft.keepass.database.element.PwGroupV4;
import com.kunzisoft.keepass.database.security.ProtectedBinary;
@@ -62,19 +64,6 @@ public class BinaryPool {
return pool.values();
}
private class AddBinaries extends EntryHandler<PwEntryV4> {
@Override
public boolean operate(PwEntryV4 entry) {
for (PwEntryV4 histEntry : entry.getHistory()) {
add(histEntry.getBinaries());
}
add(entry.getBinaries());
return true;
}
}
private void add(Map<String, ProtectedBinary> dict) {
for (ProtectedBinary pb : dict.values()) {
add(pb);
@@ -105,7 +94,17 @@ public class BinaryPool {
}
private void build(PwGroupV4 rootGroup) {
EntryHandler eh = new AddBinaries();
rootGroup.preOrderTraverseTree(null, eh);
PwGroupInterface.preOrderTraverseTree(rootGroup, null, new EntryHandler<PwEntryInterface>() {
@Override
public boolean operate(PwEntryInterface entryInterface) {
PwEntryV4 entry = (PwEntryV4) entryInterface;
for (PwEntryV4 histEntry : entry.getHistory()) {
add(histEntry.getBinaries());
}
add(entry.getBinaries());
return true;
}
});
}
}
@@ -26,5 +26,5 @@ package com.kunzisoft.keepass.database;
*
*/
public abstract class GroupHandler<T> {
public abstract boolean operate(T entry);
public abstract boolean operate(T group);
}
@@ -21,7 +21,7 @@ package com.kunzisoft.keepass.database;
import com.kunzisoft.keepass.database.element.PwDate;
public interface ITimeLogger extends ISmallTimeLogger {
public interface ITimeLogger extends SmallTimeInterface {
long getUsageCount();
void setUsageCount(long count);
@@ -21,7 +21,7 @@ package com.kunzisoft.keepass.database;
import com.kunzisoft.keepass.database.element.PwDate;
public interface ISmallTimeLogger {
public interface SmallTimeInterface {
PwDate getLastModificationTime();
void setLastModificationTime(PwDate date);
@@ -113,8 +113,8 @@ public enum SortNodeEnum {
new EntryNameComparator(ascending),
object1,
object2,
object1.getName()
.compareToIgnoreCase(object2.getName()));
object1.getTitle()
.compareToIgnoreCase(object2.getTitle()));
}
}
@@ -215,7 +215,7 @@ public enum SortNodeEnum {
if (object1.equals(object2))
return 0;
int groupNameComp = object1.getName().compareToIgnoreCase(object2.getName());
int groupNameComp = object1.getTitle().compareToIgnoreCase(object2.getTitle());
// If same name, can be different
if (groupNameComp == 0) {
return object1.hashCode() - object2.hashCode();
@@ -310,7 +310,7 @@ public enum SortNodeEnum {
if (object1.equals(object2))
return 0;
int entryTitleComp = object1.getName().compareToIgnoreCase(object2.getName());
int entryTitleComp = object1.getTitle().compareToIgnoreCase(object2.getTitle());
// If same title, can be different
if (entryTitleComp == 0) {
return object1.hashCode() - object2.hashCode();
@@ -10,6 +10,7 @@ import com.kunzisoft.keepass.database.element.PwEntryV4;
import com.kunzisoft.keepass.database.element.PwIconCustom;
import com.kunzisoft.keepass.database.element.PwIconFactory;
import com.kunzisoft.keepass.database.element.PwIconStandard;
import com.kunzisoft.keepass.database.element.PwNodeIdUUID;
import java.util.UUID;
@@ -48,10 +49,10 @@ public class EntryCursor extends MatrixCursor {
public void addEntry(PwEntryV3 entry) {
addRow(new Object[] {entryId,
entry.getUUID().getMostSignificantBits(),
entry.getUUID().getLeastSignificantBits(),
entry.getName(),
entry.getIconStandard().getIconId(),
entry.getNodeId().getId().getMostSignificantBits(),
entry.getNodeId().getId().getLeastSignificantBits(),
entry.getTitle(),
entry.getIcon().getIconId(),
PwDatabase.UUID_ZERO.getMostSignificantBits(),
PwDatabase.UUID_ZERO.getLeastSignificantBits(),
entry.getUsername(),
@@ -63,10 +64,10 @@ public class EntryCursor extends MatrixCursor {
public void addEntry(PwEntryV4 entry) {
addRow(new Object[] {entryId,
entry.getUUID().getMostSignificantBits(),
entry.getUUID().getLeastSignificantBits(),
entry.getName(),
entry.getIconStandard().getIconId(),
entry.getNodeId().getId().getMostSignificantBits(),
entry.getNodeId().getId().getLeastSignificantBits(),
entry.getTitle(),
entry.getIcon().getIconId(),
entry.getIconCustom().getUUID().getMostSignificantBits(),
entry.getIconCustom().getUUID().getLeastSignificantBits(),
entry.getUsername(),
@@ -82,13 +83,13 @@ public class EntryCursor extends MatrixCursor {
}
private void populateEntryBaseVersion(PwEntryInterface pwEntry, PwIconFactory iconFactory) {
pwEntry.setUUID(
pwEntry.setNodeId(new PwNodeIdUUID(
new UUID(getLong(getColumnIndex(EntryCursor.COLUMN_INDEX_UUID_MOST_SIGNIFICANT_BITS)),
getLong(getColumnIndex(EntryCursor.COLUMN_INDEX_UUID_LEAST_SIGNIFICANT_BITS))));
pwEntry.setName(getString(getColumnIndex(EntryCursor.COLUMN_INDEX_TITLE)));
getLong(getColumnIndex(EntryCursor.COLUMN_INDEX_UUID_LEAST_SIGNIFICANT_BITS)))));
pwEntry.setTitle(getString(getColumnIndex(EntryCursor.COLUMN_INDEX_TITLE)));
PwIconStandard iconStandard = iconFactory.getIcon(getInt(getColumnIndex(EntryCursor.COLUMN_INDEX_ICON_STANDARD)));
pwEntry.setIconStandard(iconStandard);
pwEntry.setIcon(iconStandard);
pwEntry.setUsername(getString(getColumnIndex(EntryCursor.COLUMN_INDEX_USERNAME)));
pwEntry.setPassword(getString(getColumnIndex(EntryCursor.COLUMN_INDEX_PASSWORD)));
@@ -153,17 +153,13 @@ public class Database {
pwDatabase = databaseImporter.openDatabase(bis, password, keyFileInputStream, progressTaskUpdater);
if ( pwDatabase != null ) {
try {
pwDatabase.populateGlobals(pwDatabase.getRootGroup());
passwordEncodingError = !pwDatabase.validatePasswordEncoding(password);
switch (pwDatabase.getVersion()) {
case V3:
PwGroupV3 rootV3 = ((PwDatabaseV3) pwDatabase).getRootGroup();
((PwDatabaseV3) pwDatabase).populateGlobals(rootV3);
passwordEncodingError = !pwDatabase.validatePasswordEncoding(password);
searchHelper = new SearchDbHelper.SearchDbHelperV3(ctx);
break;
case V4:
PwGroupV4 rootV4 = ((PwDatabaseV4) pwDatabase).getRootGroup();
((PwDatabaseV4) pwDatabase).populateGlobals(rootV4);
passwordEncodingError = !pwDatabase.validatePasswordEncoding(password);
searchHelper = new SearchDbHelper.SearchDbHelperV4(ctx);
break;
}
@@ -549,7 +545,7 @@ public class Database {
case V4:
newPwGroup = new PwGroupV4((PwGroupV4) parent);
}
newPwGroup.setId(pwDatabase.newGroupId());
newPwGroup.setNodeId(pwDatabase.newGroupId());
} catch (Exception e) {
Log.e(TAG, "This version of PwGroup can't be created", e);
}
@@ -708,14 +704,14 @@ public class Database {
switch (getPwDatabase().getVersion()) {
case V3:
PwEntryV3 entryV3Copied = ((PwEntryV3) entryToCopy).clone();
entryV3Copied.setUUID(UUID.randomUUID());
entryV3Copied.setParent((PwGroupV3) newParent);
entryV3Copied.setNodeId(new PwNodeIdUUID());
entryV3Copied.setParent(newParent);
addEntryTo(entryV3Copied, newParent);
return entryV3Copied;
case V4:
PwEntryV4 entryV4Copied = ((PwEntryV4) entryToCopy).clone();
entryV4Copied.setUUID(UUID.randomUUID());
entryV4Copied.setParent((PwGroupV4) newParent);
entryV4Copied.setNodeId(new PwNodeIdUUID());
entryV4Copied.setParent(newParent);
addEntryTo(entryV4Copied, newParent);
return entryV4Copied;
}
@@ -49,7 +49,7 @@ public abstract class PwDatabase {
protected PwIconFactory iconFactory = new PwIconFactory();
protected Map<PwNodeId, PwGroupInterface> groups = new HashMap<>();
protected Map<UUID, PwEntryInterface> entries = new HashMap<>();
protected Map<PwNodeId, PwEntryInterface> entries = new HashMap<>();
private static boolean isKDBExtension(String filename) {
if (filename == null) { return false; }
@@ -259,7 +259,7 @@ public abstract class PwDatabase {
parent.addChildGroup(newGroup);
newGroup.setParent(parent);
groups.put(newGroup.getId(), newGroup);
groups.put(newGroup.getNodeId(), newGroup);
parent.touch(true, true);
}
@@ -269,7 +269,7 @@ public abstract class PwDatabase {
if (parent != null) {
parent.removeChildGroup(remove);
}
groups.remove(remove.getId());
groups.remove(remove.getNodeId());
}
public abstract PwNodeId newGroupId();
@@ -290,7 +290,7 @@ public abstract class PwDatabase {
for (int i = 0; i < groups.size(); i++) {
PwGroupInterface group =groups.get(i);
if (group.getId().equals(id)) {
if (group.getNodeId().equals(id)) {
return true;
}
}
@@ -302,7 +302,7 @@ public abstract class PwDatabase {
public abstract List<PwEntryInterface> getEntries();
public PwEntryInterface getEntryByUUIDId(UUID id) {
public PwEntryInterface getEntryById(PwNodeId id) {
return this.entries.get(id);
}
@@ -313,7 +313,7 @@ public abstract class PwDatabase {
}
newEntry.setParent(parent);
entries.put(newEntry.getUUID(), newEntry);
entries.put(newEntry.getNodeId(), newEntry);
}
protected void removeEntryFrom(PwEntryInterface remove, PwGroupInterface parent) {
@@ -321,7 +321,7 @@ public abstract class PwDatabase {
if (parent != null) {
parent.removeChildEntry(remove);
}
entries.remove(remove.getUUID());
entries.remove(remove.getNodeId());
}
public abstract boolean isBackup(PwGroupInterface group);
@@ -333,12 +333,12 @@ public abstract class PwDatabase {
for (int i = 0; i < childEntries.size(); i++ ) {
PwEntryInterface cur = childEntries.get(i);
entries.put(cur.getUUID(), cur);
entries.put(cur.getNodeId(), cur);
}
for (int i = 0; i < childGroups.size(); i++ ) {
PwGroupInterface cur = childGroups.get(i);
groups.put(cur.getId(), cur);
groups.put(cur.getNodeId(), cur);
populateGlobals(cur);
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2017 Brian Pellin, Jeremy Jamet / Kunzisoft.
* Copyright 2019 Jeremy Jamet / Kunzisoft.
*
* This file is part of KeePass DX.
*
@@ -89,9 +89,9 @@ public class PwDatabaseV3 extends PwDatabase {
private void initAndAddGroup(String title, int iconId, PwGroupInterface parent) {
PwGroupV3 group = createGroup();
group.setId(newGroupId());
group.setName(title);
group.setIconStandard(iconFactory.getIcon(iconId));
group.setNodeId(newGroupId());
group.setTitle(title);
group.setIcon(iconFactory.getIcon(iconId));
addGroupTo(group, parent);
}
@@ -153,7 +153,7 @@ public class PwDatabaseV3 extends PwDatabase {
return kids;
}
public List<PwGroupInterface> getGrpChildren(PwGroupInterface parent) {
private List<PwGroupInterface> getGrpChildren(PwGroupInterface parent) {
int idx = groups.indexOf(parent);
int target = parent.getLevel() + 1;
List<PwGroupInterface> kids = new ArrayList<>();
@@ -167,7 +167,7 @@ public class PwDatabaseV3 extends PwDatabase {
return kids;
}
public List<PwEntryInterface> getEntries(PwGroupInterface parent) {
private List<PwEntryInterface> getEntries(PwGroupInterface parent) {
List<PwEntryInterface> kids = new ArrayList<>();
/*
* for( Iterator i = entries.iterator(); i.hasNext(); ) { PwEntryV3 ent
@@ -176,7 +176,7 @@ public class PwDatabaseV3 extends PwDatabase {
*/
for (int i = 0; i < entries.size(); i++) {
PwEntryInterface ent = entries.get(i);
if (ent.getParent().getGroupId() == parent.getGroupId())
if (ent.getParent().getNodeId().equals(parent.getNodeId()))
kids.add(ent);
}
return kids;
@@ -234,10 +234,9 @@ public class PwDatabaseV3 extends PwDatabase {
public PwNodeIdInt newGroupId() {
PwNodeIdInt newId;
Random random = new Random();
while (true) {
do {
newId = new PwNodeIdInt(random.nextInt());
if (!isGroupIdUsed(newId)) break;
}
} while (isGroupIdUsed(newId));
return newId;
}
@@ -359,7 +358,7 @@ public class PwDatabaseV3 extends PwDatabase {
@Override
public boolean isBackup(PwGroupInterface group) {
while (group != null) {
if (group.getLevel() == 0 && group.getName().equalsIgnoreCase("Backup")) {
if (group.getLevel() == 0 && group.getTitle().equalsIgnoreCase("Backup")) {
return true;
}
group = group.getParent();
@@ -553,7 +553,7 @@ public class PwDatabaseV4 extends PwDatabase {
@Override
public void populateGlobals(PwGroupInterface currentGroup) {
groups.put(rootGroup.getId(), rootGroup);
groups.put(rootGroup.getNodeId(), rootGroup);
super.populateGlobals(currentGroup);
}
@@ -572,7 +572,7 @@ public class PwDatabaseV4 extends PwDatabase {
recycleBin.setExpanded(false);
addGroupTo(recycleBin, rootGroup);
recycleBinUUID = recycleBin.getUUID();
recycleBinUUID = recycleBin.getNodeId().getId();
}
}
@@ -684,13 +684,13 @@ public class PwDatabaseV4 extends PwDatabase {
@Override
public void deleteEntry(PwEntryInterface entry) {
super.deleteEntry(entry);
deletedObjects.add(new PwDeletedObject(entry.getUUID()));
deletedObjects.add(new PwDeletedObject((UUID) entry.getNodeId().getId()));
}
@Override
public void undoDeleteEntry(PwEntryInterface entry, PwGroupInterface origParent) {
super.undoDeleteEntry(entry, origParent);
deletedObjects.remove(new PwDeletedObject(entry.getUUID()));
deletedObjects.remove(new PwDeletedObject((UUID) entry.getNodeId().getId()));
}
@Override
@@ -740,7 +740,7 @@ public class PwDatabaseV4 extends PwDatabase {
@Override
public void initNew(String dbPath) {
rootGroup = new PwGroupV4(dbNameFromPath(dbPath), iconFactory.getFolderIcon());
groups.put(rootGroup.getId(), rootGroup);
groups.put(rootGroup.getNodeId(), rootGroup);
}
private String dbNameFromPath(String dbPath) {
@@ -109,12 +109,12 @@ public class PwDbHeaderV4 extends PwDbHeader {
this.version = version;
}
private class GroupHasCustomData extends GroupHandler<PwGroupV4> {
private class GroupHasCustomData extends GroupHandler<PwGroupInterface> {
boolean hasCustomData = false;
@Override
public boolean operate(PwGroupV4 group) {
public boolean operate(PwGroupInterface group) {
if (group == null) {
return true;
}
@@ -127,12 +127,12 @@ public class PwDbHeaderV4 extends PwDbHeader {
}
}
private class EntryHasCustomData extends EntryHandler<PwEntryV4> {
private class EntryHasCustomData extends EntryHandler<PwEntryInterface> {
boolean hasCustomData = false;
@Override
public boolean operate(PwEntryV4 entry) {
public boolean operate(PwEntryInterface entry) {
if (entry == null) {
return true;
}
@@ -164,7 +164,7 @@ public class PwDbHeaderV4 extends PwDbHeader {
if (databaseV4.getRootGroup() == null ) {
return PwDbHeaderV4.FILE_VERSION_32_3;
}
databaseV4.getRootGroup().preOrderTraverseTree(groupHandler, entryHandler);
PwGroupInterface.preOrderTraverseTree(databaseV4.getRootGroup(), groupHandler, entryHandler);
if (groupHandler.hasCustomData || entryHandler.hasCustomData) {
return PwDbHeaderV4.FILE_VERSION_32_4;
}
@@ -23,11 +23,12 @@ import java.util.Date;
import java.util.UUID;
public class PwDeletedObject {
public UUID uuid;
private Date deletionTime;
public PwDeletedObject() {
}
public PwDeletedObject(UUID u) {
@@ -38,6 +39,14 @@ public class PwDeletedObject {
uuid = u;
deletionTime = d;
}
public UUID getUuid() {
return uuid;
}
public void setUuid(UUID uuid) {
this.uuid = uuid;
}
public Date getDeletionTime() {
if ( deletionTime == null ) {
@@ -1,20 +1,13 @@
package com.kunzisoft.keepass.database.element;
import com.kunzisoft.keepass.database.ExtraFields;
import com.kunzisoft.keepass.database.SmallTimeInterface;
import com.kunzisoft.keepass.database.security.ProtectedString;
import com.kunzisoft.keepass.model.Entry;
import com.kunzisoft.keepass.model.Field;
import java.util.UUID;
public interface PwEntryInterface extends PwNodeInterface, SmallTimeInterface {
public interface PwEntryInterface extends PwNodeInterface {
UUID getUUID();
void setUUID(UUID uuid);
String getName();
void setName(String title);
String getTitle();
void setTitle(String title);
String getUsername();
void setUsername(String user);
@@ -91,7 +84,7 @@ public interface PwEntryInterface extends PwNodeInterface {
String PMS_TAN_ENTRY = "<TAN>";
static boolean isTan(PwEntryInterface entry) {
return entry.getName().equals(PMS_TAN_ENTRY)
return entry.getTitle().equals(PMS_TAN_ENTRY)
&& (entry.getUsername().length() > 0);
}
@@ -101,15 +94,18 @@ public interface PwEntryInterface extends PwNodeInterface {
* {@link #startToManageFieldReferences(PwDatabase)} and {@link #stopToManageFieldReferences()} must be called
* before and after {@link #getVisualTitle(PwEntryInterface entry)}
*/
static String getVisualTitle(boolean isTan, String userName, String title, String url, UUID uuid) {
static String getVisualTitle(boolean isTan, String title, String userName, String url, String id) {
if ( isTan ) {
return PMS_TAN_ENTRY + " " + userName;
} else {
if (title.isEmpty())
if (url.isEmpty())
return uuid.toString();
if (userName.isEmpty())
if (url.isEmpty())
return id;
else
return url;
else
return url;
return userName;
else
return title;
}
@@ -117,24 +113,9 @@ public interface PwEntryInterface extends PwNodeInterface {
static String getVisualTitle(PwEntryInterface entry) {
return getVisualTitle(PwEntryInterface.isTan(entry),
entry.getTitle(),
entry.getUsername(),
entry.getName(),
entry.getUrl(),
entry.getUUID());
}
static Entry getEntry(PwEntryInterface entry) {
Entry entryModel = new Entry();
entryModel.setTitle(entry.getName());
entryModel.setUsername(entry.getUsername());
entryModel.setPassword(entry.getPassword());
entryModel.setUrl(entry.getUrl());
if (entry.containsCustomFields()) {
entry.getFields()
.doActionToAllCustomProtectedField(
(key, value) -> entryModel.addCustomField(
new Field(key, value.toString())));
}
return entryModel;
entry.getNodeId().toString());
}
}
@@ -72,7 +72,7 @@ import java.util.UUID;
* @author Dominik Reichl <[email protected]>
* @author Jeremy Jamet <[email protected]>
*/
public class PwEntryV3 extends PwNode implements PwEntryInterface {
public class PwEntryV3 extends PwNode<UUID> implements PwEntryInterface {
/** Size of byte buffer needed to hold this struct. */
private static final String PMS_ID_BINDESC = "bin-stream";
@@ -80,14 +80,19 @@ public class PwEntryV3 extends PwNode implements PwEntryInterface {
private static final String PMS_ID_USER = "SYSTEM";
private static final String PMS_ID_URL = "$";
private String title;
private String username;
private byte[] password;
private String url;
private String additional;
private String title = "";
private String username = "";
private byte[] password = new byte[0];
private String url = "";
private String additional = "";
/** A string describing what is in pBinaryData */
private String binaryDesc;
private byte[] binaryData;
private String binaryDesc = "";
private byte[] binaryData = new byte[0];
@Override
PwNodeId<UUID> initNodeId() {
return new PwNodeIdUUID();
}
public PwEntryV3() {
super();
@@ -188,17 +193,14 @@ public class PwEntryV3 extends PwNode implements PwEntryInterface {
return Type.ENTRY;
}
public void setGroupId(int groupId) {
PwGroupV3 parentGroup = new PwGroupV3();
parentGroup.setGroupId(groupId);
this.parent = parentGroup;
public void setNewParent(int groupId) {
PwGroupV3 pwGroupV3 = new PwGroupV3();
pwGroupV3.setNodeId(new PwNodeIdInt(groupId));
this.parent = pwGroupV3;
}
@Override
public String getUsername() {
if (username == null) {
return "";
}
return username;
}
@@ -208,12 +210,12 @@ public class PwEntryV3 extends PwNode implements PwEntryInterface {
}
@Override
public String getName() {
public String getTitle() {
return title;
}
@Override
public void setName(String title) {
public void setTitle(String title) {
this.title = title;
}
@@ -237,53 +239,11 @@ public class PwEntryV3 extends PwNode implements PwEntryInterface {
this.url = url;
}
public void populateBlankFields(PwDatabaseV3 db) {
// TODO verify and remove
if (icon == null) {
icon = db.getIconFactory().getKeyIcon();
}
if (username == null) {
username = "";
}
if (password == null) {
password = new byte[0];
}
if (uuid == null) {
uuid = UUID.randomUUID();
}
if (title == null) {
title = "";
}
if (url == null) {
url = "";
}
if (additional == null) {
additional = "";
}
if (binaryDesc == null) {
binaryDesc = "";
}
if (binaryData == null) {
binaryData = new byte[0];
}
}
/**
* @return the actual password byte array.
*/
@Override
public String getPassword() {
if (password == null) {
return "";
}
return new String(password);
}
@@ -301,10 +261,7 @@ public class PwEntryV3 extends PwNode implements PwEntryInterface {
/** Securely erase old password before copying new. */
public void setPassword( byte[] buf, int offset, int len ) {
if( password != null ) {
fill( password, (byte)0 );
password = null;
}
fill(password, (byte)0);
password = new byte[len];
System.arraycopy( buf, offset, password, 0, len );
}
@@ -316,7 +273,6 @@ public class PwEntryV3 extends PwNode implements PwEntryInterface {
password = pass.getBytes("UTF-8");
setPassword(password, 0, password.length);
} catch (UnsupportedEncodingException e) {
assert false;
password = pass.getBytes();
setPassword(password, 0, password.length);
}
@@ -350,19 +306,17 @@ public class PwEntryV3 extends PwNode implements PwEntryInterface {
// Determine if this is a MetaStream entry
@Override
public boolean isMetaStream() {
if ( binaryData == null ) return false;
if ( additional == null || additional.length() == 0 ) return false;
if ( ! binaryDesc.equals(PMS_ID_BINDESC) ) return false;
if ( title == null ) return false;
if ( ! title.equals(PMS_ID_TITLE) ) return false;
if ( username == null ) return false;
if ( ! username.equals(PMS_ID_USER) ) return false;
if ( url == null ) return false;
if ( ! url.equals(PMS_ID_URL)) return false;
if ( !icon.isMetaStreamIcon() ) return false;
return true;
}
if (binaryData == new byte[0]) return false;
if (additional.isEmpty()) return false;
if (!binaryDesc.equals(PMS_ID_BINDESC)) return false;
if (title.isEmpty()) return false;
if (!title.equals(PMS_ID_TITLE)) return false;
if (username.isEmpty()) return false;
if (!username.equals(PMS_ID_USER)) return false;
if (url.isEmpty()) return false;
if (!url.equals(PMS_ID_URL)) return false;
return icon.isMetaStreamIcon();
}
@Override
public void createBackup(PwDatabase db) {}
@@ -372,7 +326,12 @@ public class PwEntryV3 extends PwNode implements PwEntryInterface {
return false;
}
@Override
@Override
public boolean containsCustomData() {
return false;
}
@Override
public void startToManageFieldReferences(PwDatabase db) {}
@Override
@@ -34,8 +34,9 @@ import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.UUID;
public class PwEntryV4 extends PwNode implements ITimeLogger, PwEntryInterface {
public class PwEntryV4 extends PwNode<UUID> implements ITimeLogger, PwEntryInterface {
public static final String STR_TITLE = "Title";
public static final String STR_USERNAME = "UserName";
@@ -62,6 +63,11 @@ public class PwEntryV4 extends PwNode implements ITimeLogger, PwEntryInterface {
private String additional = "";
private String tags = "";
@Override
PwNodeId<UUID> initNodeId() {
return new PwNodeIdUUID();
}
public PwEntryV4() {
super();
}
@@ -207,7 +213,7 @@ public class PwEntryV4 extends PwNode implements ITimeLogger, PwEntryInterface {
}
@Override
public String getName() {
public String getTitle() {
return decodeRefKey(mDecodeRef, STR_TITLE);
}
@@ -217,7 +223,7 @@ public class PwEntryV4 extends PwNode implements ITimeLogger, PwEntryInterface {
}
@Override
public void setName(String title) {
public void setTitle(String title) {
boolean protect = (mDatabase != null) && mDatabase.getMemoryProtection().protectTitle;
setProtectedString(STR_TITLE, title, protect);
}
@@ -289,14 +295,26 @@ public class PwEntryV4 extends PwNode implements ITimeLogger, PwEntryInterface {
}
}
public void setIconCustom(PwIconCustom icon) {
this.customIcon = icon;
}
@Override
public void setIcon(PwIcon icon) {
if (icon instanceof PwIconStandard)
setIconStandard((PwIconStandard) icon);
if (icon instanceof PwIconCustom)
setIconCustom((PwIconCustom) icon);
}
public PwIconCustom getIconCustom() {
return customIcon;
}
public void setIconCustom(PwIconCustom icon) {
this.customIcon = icon;
}
public PwIcon getIconStandard() {
return icon;
}
public void setIconStandard(PwIconStandard icon) {
this.icon = icon;
this.customIcon = PwIconCustom.ZERO;
@@ -1,5 +1,7 @@
package com.kunzisoft.keepass.database.element;
import android.support.annotation.NonNull;
import com.kunzisoft.keepass.database.EntryHandler;
import com.kunzisoft.keepass.database.GroupHandler;
@@ -7,9 +9,6 @@ import java.util.List;
public interface PwGroupInterface extends PwNodeInterface {
PwNodeId getId();
void setId(PwNodeId id);
List<PwGroupInterface> getChildGroups();
List<PwEntryInterface> getChildEntries();
@@ -18,6 +17,8 @@ public interface PwGroupInterface extends PwNodeInterface {
void setEntries(List<PwEntryInterface> entries);
int getLevel();
void addChildGroup(PwGroupInterface group);
void addChildEntry(PwEntryInterface entry);
@@ -34,16 +35,30 @@ public interface PwGroupInterface extends PwNodeInterface {
int numbersOfChildEntries();
boolean containsParent();
/**
* Filter MetaStream entries and return children
* @return List of direct children (one level below) as PwNode
*/
public List<PwNodeInterface> getDirectChildren();
List<PwNodeInterface> getDirectChildren();
PwGroupInterface duplicate();
public boolean preOrderTraverseTree(GroupHandler<PwGroupInterface> groupHandler,
EntryHandler<PwEntryInterface> entryHandler);
static boolean preOrderTraverseTree(@NonNull PwGroupInterface root,
GroupHandler<PwGroupInterface> groupHandler,
EntryHandler<PwEntryInterface> entryHandler) {
if (entryHandler != null) {
for (PwEntryInterface entry : root.getChildEntries()) {
if (!entryHandler.operate(entry)) return false;
}
}
for (PwGroupInterface group : root.getChildGroups()) {
if ((groupHandler != null) && !groupHandler.operate(group)) return false;
preOrderTraverseTree(group, groupHandler, entryHandler);
}
return true;
}
public boolean allowAddEntryIfIsRoot();
boolean allowAddEntryIfIsRoot();
}
@@ -1,5 +1,5 @@
/*
* Copyright 2017 Brian Pellin, Jeremy Jamet / Kunzisoft.
* Copyright 2019 Jeremy Jamet / Kunzisoft.
*
* This file is part of KeePass DX.
*
@@ -22,25 +22,26 @@ package com.kunzisoft.keepass.database.element;
import android.os.Parcel;
import com.kunzisoft.keepass.database.EntryHandler;
import com.kunzisoft.keepass.database.GroupHandler;
import java.util.ArrayList;
import java.util.List;
public class PwGroupV3 extends PwNode implements PwGroupInterface {
public class PwGroupV3 extends PwNode<Integer> implements PwGroupInterface {
// TODO verify children not needed
transient private List<PwGroupInterface> childGroups = new ArrayList<>();
transient private List<PwEntryInterface> childEntries = new ArrayList<>();
// for tree traversing
// TODO private int groupId;
private String title = "";
private int level = 0; // short
/** Used by KeePass internally, don't use */
private int flags;
@Override
PwNodeId<Integer> initNodeId() {
return new PwNodeIdInt();
}
public PwGroupV3() {
super();
}
@@ -52,7 +53,6 @@ public class PwGroupV3 extends PwNode implements PwGroupInterface {
public PwGroupV3(Parcel in) {
super(in);
title = in.readString();
groupId = in.readInt();
level = in.readInt();
flags = in.readInt();
}
@@ -61,7 +61,6 @@ public class PwGroupV3 extends PwNode implements PwGroupInterface {
public void writeToParcel(Parcel dest, int flags) {
super.writeToParcel(dest, flags);
dest.writeString(title);
dest.writeInt(groupId);
dest.writeInt(level);
dest.writeInt(flags);
}
@@ -81,7 +80,6 @@ public class PwGroupV3 extends PwNode implements PwGroupInterface {
protected void updateWith(PwGroupV3 source) {
super.assign(source);
title = source.title;
groupId = source.groupId;
level = source.level;
flags = source.flags;
}
@@ -101,15 +99,14 @@ public class PwGroupV3 extends PwNode implements PwGroupInterface {
return clone();
}
@Override
@Override
public Type getType() {
return Type.GROUP;
}
public void setParent(PwGroupInterface parent) {
super.setParent(parent);
if (parent instanceof PwGroupV3) // TODO Change
level = ((PwGroupV3) parent).getLevel() + 1;
level = parent.getLevel() + 1;
}
@Override
@@ -117,12 +114,13 @@ public class PwGroupV3 extends PwNode implements PwGroupInterface {
return false;
}
public int getGroupId() {
return groupId;
@Override
public boolean containsCustomData() {
return false;
}
public void setGroupId(int groupId) {
this.groupId = groupId;
this.setNodeId(new PwNodeIdInt(groupId));
}
public int getLevel() {
@@ -133,17 +131,6 @@ public class PwGroupV3 extends PwNode implements PwGroupInterface {
this.level = level;
}
@Override
public PwNodeId getId() {
return new PwNodeIdInt(groupId);
}
@Override
public void setId(PwNodeId id) {
PwNodeIdInt id3 = (PwNodeIdInt) id;
groupId = id3.getId();
}
public int getFlags() {
return flags;
}
@@ -154,7 +141,7 @@ public class PwGroupV3 extends PwNode implements PwGroupInterface {
@Override
public String toString() {
return getName();
return getTitle();
}
public void populateBlankFields(PwDatabaseV3 db) {
@@ -169,12 +156,12 @@ public class PwGroupV3 extends PwNode implements PwGroupInterface {
}
@Override
public String getName() {
public String getTitle() {
return title;
}
@Override
public void setName(String title) {
public void setTitle(String title) {
this.title = title;
}
@@ -248,20 +235,6 @@ public class PwGroupV3 extends PwNode implements PwGroupInterface {
return children;
}
public boolean preOrderTraverseTree(GroupHandler<PwGroupInterface> groupHandler,
EntryHandler<PwEntryInterface> entryHandler) {
if (entryHandler != null) {
for (PwEntryInterface entry : childEntries) {
if (!entryHandler.operate(entry)) return false;
}
}
for (PwGroupInterface group : childGroups) {
if ((groupHandler != null) && !groupHandler.operate(group)) return false;
group.preOrderTraverseTree(groupHandler, entryHandler);
}
return true;
}
@Override
public boolean allowAddEntryIfIsRoot() {
return false;
@@ -1,5 +1,5 @@
/*
* Copyright 2017 Brian Pellin, Jeremy Jamet / Kunzisoft.
* Copyright 2019 Jeremy Jamet / Kunzisoft.
*
* This file is part of KeePass DX.
*
@@ -21,8 +21,6 @@ package com.kunzisoft.keepass.database.element;
import android.os.Parcel;
import com.kunzisoft.keepass.database.EntryHandler;
import com.kunzisoft.keepass.database.GroupHandler;
import com.kunzisoft.keepass.database.ITimeLogger;
import java.util.ArrayList;
@@ -31,7 +29,7 @@ import java.util.List;
import java.util.Map;
import java.util.UUID;
public class PwGroupV4 extends PwNode implements ITimeLogger, PwGroupInterface {
public class PwGroupV4 extends PwNode<UUID> implements ITimeLogger, PwGroupInterface {
public static final boolean DEFAULT_SEARCHING_ENABLED = true;
@@ -52,6 +50,11 @@ public class PwGroupV4 extends PwNode implements ITimeLogger, PwGroupInterface {
private Boolean enableSearching = null;
private UUID lastTopVisibleEntry = PwDatabase.UUID_ZERO;
@Override
PwNodeId<UUID> initNodeId() {
return new PwNodeIdUUID();
}
public PwGroupV4() {
super();
}
@@ -174,22 +177,10 @@ public class PwGroupV4 extends PwNode implements ITimeLogger, PwGroupInterface {
}
public void addEntry(PwEntryV4 pe) {
assert(pe != null);
addChildEntry(pe);
pe.setParent(this);
}
@Override
public PwNodeId getId() {
return new PwNodeIdUUID(uuid);
}
@Override
public void setId(PwNodeId id) {
PwNodeIdUUID id4 = (PwNodeIdUUID) id;
uuid = id4.getId();
}
@Override
public PwDate getLocationChanged() {
return parentGroupLastMod;
@@ -242,6 +233,10 @@ public class PwGroupV4 extends PwNode implements ITimeLogger, PwGroupInterface {
this.customIcon = icon;
}
public PwIcon getIconStandard() {
return icon;
}
public void setIconStandard(PwIconStandard icon) { // TODO Encapsulate with PwEntryV4
this.icon = icon;
this.customIcon = PwIconCustom.ZERO;
@@ -318,12 +313,12 @@ public class PwGroupV4 extends PwNode implements ITimeLogger, PwGroupInterface {
}
@Override
public String getName() {
public String getTitle() {
return title;
}
@Override
public void setName(String name) {
public void setTitle(String name) {
this.title = name;
}
@@ -347,6 +342,11 @@ public class PwGroupV4 extends PwNode implements ITimeLogger, PwGroupInterface {
childEntries = entries;
}
@Override
public int getLevel() {
return -1; // TODO Level
}
@Override
public void addChildGroup(PwGroupInterface group) {
this.childGroups.add(group);
@@ -396,18 +396,4 @@ public class PwGroupV4 extends PwNode implements ITimeLogger, PwGroupInterface {
}
return children;
}
public boolean preOrderTraverseTree(GroupHandler<PwGroupInterface> groupHandler,
EntryHandler<PwEntryInterface> entryHandler) {
if (entryHandler != null) {
for (PwEntryInterface entry : childEntries) {
if (!entryHandler.operate(entry)) return false;
}
}
for (PwGroupInterface group : childGroups) {
if ((groupHandler != null) && !groupHandler.operate(group)) return false;
group.preOrderTraverseTree(groupHandler, entryHandler);
}
return true;
}
}
@@ -22,7 +22,9 @@ package com.kunzisoft.keepass.database.element;
import android.os.Parcel;
import android.os.Parcelable;
public abstract class PwIcon implements Parcelable {
public abstract class PwIcon implements Parcelable, Cloneable {
public static final int UNKNOWN = -1;
public boolean isMetaStreamIcon() {
return false;
@@ -30,11 +32,16 @@ public abstract class PwIcon implements Parcelable {
protected PwIcon() {}
protected PwIcon(Parcel in) {}
protected PwIcon(Parcel src) {}
public abstract boolean isUnknown();
@Override
public abstract int getIconId();
@Override
protected abstract PwIcon clone() throws CloneNotSupportedException;
@Override
public int describeContents() {
return 0;
}
@@ -53,6 +53,11 @@ public class PwIconCustom extends PwIcon {
return uuid == null || this.equals(ZERO);
}
@Override
public int getIconId() {
return UNKNOWN;
}
public UUID getUUID() {
return uuid;
}
@@ -83,7 +88,12 @@ public class PwIconCustom extends PwIcon {
}
};
@Override
@Override
protected PwIconCustom clone() throws CloneNotSupportedException {
return new PwIconCustom(this);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
@@ -24,7 +24,6 @@ import android.os.Parcel;
public class PwIconStandard extends PwIcon {
private final int iconId;
public static final int UNKNOWN = -1;
public static final int KEY = 0;
public static final int TRASH = 43;
public static final int FOLDER = 48;
@@ -77,7 +76,12 @@ public class PwIconStandard extends PwIcon {
return iconId == 0;
}
@Override
@Override
protected PwIconStandard clone() throws CloneNotSupportedException {
return new PwIconStandard(this);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
@@ -24,30 +24,25 @@ import android.os.Parcel;
import android.os.Parcelable;
import com.kunzisoft.keepass.app.App;
import com.kunzisoft.keepass.database.ISmallTimeLogger;
import org.joda.time.LocalDate;
import java.util.UUID;
/**
* Abstract class who manage Groups and Entries
*/
public abstract class PwNode implements PwNodeInterface, ISmallTimeLogger, Parcelable, Cloneable {
public abstract class PwNode<IdType> implements PwNodeInterface, Parcelable, Cloneable {
protected PwNodeId uuid;
protected PwNodeId<IdType> nodeId = initNodeId();
protected PwGroupInterface parent = null;
protected PwIconStandard icon = new PwIconStandard();
protected PwIcon icon = new PwIconStandard();
protected PwDate creation = new PwDate();
protected PwDate lastMod = new PwDate();
protected PwDate lastAccess = new PwDate();
protected PwDate expireDate = PwDate.PW_NEVER_EXPIRE;
abstract PwNodeId initNodeId();
abstract PwNodeId<IdType> initNodeId();
protected PwNode() {
this.uuid = initNodeId();
}
protected PwNode() {}
protected PwNode(PwGroupInterface parent) {
this();
@@ -55,7 +50,7 @@ public abstract class PwNode implements PwNodeInterface, ISmallTimeLogger, Parce
}
protected PwNode(Parcel in) {
uuid = in.readParcelable(PwNodeId.class.getClassLoader());
nodeId = in.readParcelable(PwNodeId.class.getClassLoader());
// TODO better technique ?
try {
PwNodeId pwGroupId = in.readParcelable(PwNodeId.class.getClassLoader());
@@ -73,11 +68,11 @@ public abstract class PwNode implements PwNodeInterface, ISmallTimeLogger, Parce
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeParcelable(uuid, flags);
dest.writeParcelable(nodeId, flags);
PwNodeId parentId = null;
if (parent != null)
parentId = parent.getId();
parentId = parent.getNodeId();
dest.writeParcelable(parentId, flags);
dest.writeParcelable(icon, flags);
@@ -93,7 +88,7 @@ public abstract class PwNode implements PwNodeInterface, ISmallTimeLogger, Parce
}
protected void assign(PwNode source) {
this.uuid = source.uuid;
this.nodeId = source.nodeId;
this.parent = source.parent;
this.icon = source.icon;
this.creation = source.creation;
@@ -107,9 +102,9 @@ public abstract class PwNode implements PwNodeInterface, ISmallTimeLogger, Parce
PwNode newNode;
try {
newNode = (PwNode) super.clone();
newNode.uuid = uuid.clone();
newNode.nodeId = nodeId.clone();
// newNode.parent stay the same in copy
newNode.icon = new PwIconStandard(this.icon);
newNode.icon = icon.clone();
newNode.creation = creation.clone();
newNode.lastMod = lastMod.clone();
newNode.lastAccess = lastAccess.clone();
@@ -120,32 +115,29 @@ public abstract class PwNode implements PwNodeInterface, ISmallTimeLogger, Parce
return newNode;
}
boolean isSameType(PwNode pwNode) {
return getType().equals(pwNode.getType());
public IdType getId() {
return getNodeId().getId();
}
@Override
public PwNodeId<IdType> getNodeId() {
return nodeId;
}
@Override
public UUID getUUID() {
return uuid;
}
@Override
public void setUUID(UUID uuid) {
this.uuid = uuid;
public void setNodeId(PwNodeId id) {
this.nodeId = id;
}
/**
* @return Visual icon
*/
public PwIcon getIcon() {
return getIconStandard();
}
public PwIconStandard getIconStandard() {
return icon;
}
public void setIconStandard(PwIconStandard icon) {
@Override
public void setIcon(PwIcon icon) {
this.icon = icon;
}
@@ -160,12 +152,12 @@ public abstract class PwNode implements PwNodeInterface, ISmallTimeLogger, Parce
/**
* Assign a parent to this node
*/
public void setParent(PwGroupInterface prt) {
parent = prt;
public void setParent(PwGroupInterface parent) {
this.parent = parent;
}
/**
* @return true if parent is present (can be a root or a detach element)
* @return true if parent is present (false if not present, can be a root or a detach element)
*/
public boolean containsParent() {
return getParent() != null;
@@ -241,18 +233,18 @@ public abstract class PwNode implements PwNodeInterface, ISmallTimeLogger, Parce
}
}
@Override
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
PwNode pwNode = (PwNode) o;
return isSameType(pwNode)
&& (getUUID() != null ? getUUID().equals(pwNode.getUUID()) : pwNode.getUUID() == null);
return getType().equals(pwNode.getType())
&& (getNodeId() != null ? getNodeId().equals(pwNode.getNodeId()) : pwNode.getNodeId() == null);
}
@Override
public int hashCode() {
return getUUID() != null ? getUUID().hashCode() : 0;
return getNodeId() != null ? getNodeId().hashCode() : 0;
}
}
@@ -22,7 +22,7 @@ package com.kunzisoft.keepass.database.element;
import android.os.Parcel;
import android.os.Parcelable;
public abstract class PwNodeId implements Cloneable, Parcelable {
public abstract class PwNodeId<Id> implements Cloneable, Parcelable {
public PwNodeId() {}
@@ -36,6 +36,10 @@ public abstract class PwNodeId implements Cloneable, Parcelable {
return 0;
}
public abstract Id getId();
@Override
public abstract PwNodeId clone() throws CloneNotSupportedException;
public PwNodeId clone() throws CloneNotSupportedException {
return (PwNodeId) super.clone();
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2017 Brian Pellin, Jeremy Jamet / Kunzisoft.
* Copyright 2019 Jeremy Jamet / Kunzisoft.
*
* This file is part of KeePass DX.
*
@@ -21,9 +21,9 @@ package com.kunzisoft.keepass.database.element;
import android.os.Parcel;
public class PwNodeIdInt extends PwNodeId {
public class PwNodeIdInt extends PwNodeId<Integer> {
private int id;
private Integer id;
public PwNodeIdInt() {
this.id = -1;
@@ -35,7 +35,6 @@ public class PwNodeIdInt extends PwNodeId {
}
public PwNodeIdInt(Parcel in) {
super(in);
id = in.readInt();
}
@@ -58,8 +57,8 @@ public class PwNodeIdInt extends PwNodeId {
};
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
public PwNodeIdInt clone() throws CloneNotSupportedException {
return (PwNodeIdInt) super.clone();
}
@Override
@@ -68,16 +67,20 @@ public class PwNodeIdInt extends PwNodeId {
return false;
}
PwNodeIdInt cmp = (PwNodeIdInt) compare;
return id == cmp.id;
return id.equals(cmp.id);
}
@Override
public int hashCode() {
Integer i = id;
return i.hashCode();
return id.hashCode();
}
public int getId() {
@Override
public String toString() {
return id.toString();
}
public Integer getId() {
return id;
}
}
@@ -23,7 +23,7 @@ import android.os.Parcel;
import java.util.UUID;
public class PwNodeIdUUID extends PwNodeId {
public class PwNodeIdUUID extends PwNodeId<UUID> {
private UUID uuid;
@@ -60,8 +60,8 @@ public class PwNodeIdUUID extends PwNodeId {
};
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
public PwNodeIdUUID clone() throws CloneNotSupportedException {
return (PwNodeIdUUID) super.clone();
}
@Override
@@ -78,6 +78,11 @@ public class PwNodeIdUUID extends PwNodeId {
return uuid.hashCode();
}
@Override
public String toString() {
return uuid.toString();
}
public UUID getId() {
return uuid;
}
@@ -1,22 +1,26 @@
package com.kunzisoft.keepass.database.element;
import java.util.UUID;
import android.os.Parcelable;
public interface PwNodeInterface {
import com.kunzisoft.keepass.database.SmallTimeInterface;
UUID getUUID();
public interface PwNodeInterface extends SmallTimeInterface, Parcelable {
void setUUID(UUID uuid);
PwNodeId getNodeId();
String getName();
void setNodeId(PwNodeId id);
void setName(String title);
String getTitle();
void setTitle(String title);
/**
* @return Visual icon
*/
PwIcon getIcon();
void setIcon(PwIcon icon);
/**
* @return Type of Node
*/
@@ -39,6 +43,8 @@ public interface PwNodeInterface {
boolean isSearchingEnabled();
boolean containsCustomData();
/**
* Type of available Nodes
*/
@@ -101,7 +101,7 @@ public class EntrySearchStringIteratorV3 extends EntrySearchStringIterator {
private String getCurrentString() {
switch (current) {
case title:
return entry.getName();
return entry.getTitle();
case url:
return entry.getUrl();
@@ -56,6 +56,7 @@ import com.kunzisoft.keepass.database.element.PwDbHeaderV3;
import com.kunzisoft.keepass.database.element.PwEncryptionAlgorithm;
import com.kunzisoft.keepass.database.element.PwEntryV3;
import com.kunzisoft.keepass.database.element.PwGroupV3;
import com.kunzisoft.keepass.database.element.PwNodeIdUUID;
import com.kunzisoft.keepass.database.exception.InvalidAlgorithmException;
import com.kunzisoft.keepass.database.exception.InvalidDBException;
import com.kunzisoft.keepass.database.exception.InvalidDBSignatureException;
@@ -269,7 +270,6 @@ public class ImporterV3 extends Importer {
if( fieldType == 0xFFFF ) {
// End-Group record. Save group and count it.
newEnt.populateBlankFields(databaseToOpen);
databaseToOpen.addEntry(newEnt);
newEnt = new PwEntryV3();
i++;
@@ -301,7 +301,7 @@ public class ImporterV3 extends Importer {
grp.setGroupId(LEDataInputStream.readInt(buf, offset));
break;
case 0x0002 :
grp.setName(Types.readCString(buf, offset));
grp.setTitle(Types.readCString(buf, offset));
break;
case 0x0003 :
grp.setCreationTime(new PwDate(buf, offset));
@@ -316,7 +316,7 @@ public class ImporterV3 extends Importer {
grp.setExpiryTime(new PwDate(buf, offset));
break;
case 0x0007 :
grp.setIconStandard(db.getIconFactory().getIcon(LEDataInputStream.readInt(buf, offset)));
grp.setIcon(db.getIconFactory().getIcon(LEDataInputStream.readInt(buf, offset)));
break;
case 0x0008 :
grp.setLevel(LEDataInputStream.readUShort(buf, offset));
@@ -340,10 +340,10 @@ public class ImporterV3 extends Importer {
// Ignore field
break;
case 0x0001 :
ent.setUUID(Types.bytestoUUID(buf, offset));
ent.setNodeId(new PwNodeIdUUID(Types.bytestoUUID(buf, offset)));
break;
case 0x0002 :
ent.setGroupId(LEDataInputStream.readInt(buf, offset));
ent.setNewParent(LEDataInputStream.readInt(buf, offset));
break;
case 0x0003 :
int iconId = LEDataInputStream.readInt(buf, offset);
@@ -353,10 +353,10 @@ public class ImporterV3 extends Importer {
iconId = 0;
}
ent.setIconStandard(db.getIconFactory().getIcon(iconId));
ent.setIcon(db.getIconFactory().getIcon(iconId));
break;
case 0x0004 :
ent.setName(Types.readCString(buf, offset));
ent.setTitle(Types.readCString(buf, offset));
break;
case 0x0005 :
ent.setUrl(Types.readCString(buf, offset));
@@ -34,6 +34,7 @@ import com.kunzisoft.keepass.database.element.PwDeletedObject;
import com.kunzisoft.keepass.database.element.PwEntryV4;
import com.kunzisoft.keepass.database.element.PwGroupV4;
import com.kunzisoft.keepass.database.element.PwIconCustom;
import com.kunzisoft.keepass.database.element.PwNodeIdUUID;
import com.kunzisoft.keepass.database.exception.ArcFourException;
import com.kunzisoft.keepass.database.exception.InvalidDBException;
import com.kunzisoft.keepass.database.exception.InvalidPasswordException;
@@ -532,9 +533,10 @@ public class ImporterV4 extends Importer {
if ( name.equalsIgnoreCase(PwDatabaseV4XML.ElemGroup) ) {
if ( ctxGroups.size() != 0 )
throw new IOException("Group list should be empty.");
db.setRootGroup(new PwGroupV4());
ctxGroups.push(db.getRootGroup());
PwGroupV4 rootGroup = new PwGroupV4();
db.setRootGroup(rootGroup);
ctxGroups.push(rootGroup);
ctxGroup = ctxGroups.peek();
return SwitchContext(ctx, KdbContext.Group, xpp);
@@ -547,9 +549,9 @@ public class ImporterV4 extends Importer {
case Group:
if ( name.equalsIgnoreCase(PwDatabaseV4XML.ElemUuid) ) {
ctxGroup.setUUID(ReadUuid(xpp));
ctxGroup.setNodeId(new PwNodeIdUUID(ReadUuid(xpp)));
} else if ( name.equalsIgnoreCase(PwDatabaseV4XML.ElemName) ) {
ctxGroup.setName(ReadString(xpp));
ctxGroup.setTitle(ReadString(xpp));
} else if ( name.equalsIgnoreCase(PwDatabaseV4XML.ElemNotes) ) {
ctxGroup.setNotes(ReadString(xpp));
} else if ( name.equalsIgnoreCase(PwDatabaseV4XML.ElemIcon) ) {
@@ -606,7 +608,7 @@ public class ImporterV4 extends Importer {
case Entry:
if ( name.equalsIgnoreCase(PwDatabaseV4XML.ElemUuid) ) {
ctxEntry.setUUID(ReadUuid(xpp));
ctxEntry.setNodeId(new PwNodeIdUUID(ReadUuid(xpp)));
} else if ( name.equalsIgnoreCase(PwDatabaseV4XML.ElemIcon) ) {
ctxEntry.setIconStandard(db.getIconFactory().getIcon((int)ReadUInt(xpp, 0)));
} else if ( name.equalsIgnoreCase(PwDatabaseV4XML.ElemCustomIconID) ) {
@@ -752,7 +754,7 @@ public class ImporterV4 extends Importer {
case DeletedObject:
if ( name.equalsIgnoreCase(PwDatabaseV4XML.ElemUuid) ) {
ctxDeletedObject.uuid = ReadUuid(xpp);
ctxDeletedObject.setUuid(ReadUuid(xpp));
} else if ( name.equalsIgnoreCase(PwDatabaseV4XML.ElemDeletionTime) ) {
ctxDeletedObject.setDeletionTime(ReadTime(xpp));
} else {
@@ -807,8 +809,8 @@ public class ImporterV4 extends Importer {
return KdbContext.CustomData;
} else if ( ctx == KdbContext.Group && name.equalsIgnoreCase(PwDatabaseV4XML.ElemGroup) ) {
if ( ctxGroup.getUUID() == null || ctxGroup.getUUID().equals(PwDatabase.UUID_ZERO) ) {
ctxGroup.setUUID(UUID.randomUUID());
if ( ctxGroup.getNodeId() == null || ctxGroup.getNodeId().equals(PwDatabase.UUID_ZERO) ) {
ctxGroup.setNodeId(new PwNodeIdUUID());
}
ctxGroups.pop();
@@ -835,8 +837,8 @@ public class ImporterV4 extends Importer {
return KdbContext.GroupCustomData;
} else if ( ctx == KdbContext.Entry && name.equalsIgnoreCase(PwDatabaseV4XML.ElemEntry) ) {
if ( ctxEntry.getUUID() == null || ctxEntry.getUUID().equals(PwDatabase.UUID_ZERO) ) {
ctxEntry.setUUID(UUID.randomUUID());
if ( ctxEntry.getNodeId() == null || ctxEntry.getNodeId().equals(PwDatabase.UUID_ZERO) ) {
ctxEntry.setNodeId(new PwNodeIdUUID());
}
if ( entryInHistory ) {
@@ -25,6 +25,7 @@ import com.kunzisoft.keepass.database.element.PwDbHeader;
import com.kunzisoft.keepass.database.element.PwDbHeaderV3;
import com.kunzisoft.keepass.database.element.PwEncryptionAlgorithm;
import com.kunzisoft.keepass.database.element.PwEntryV3;
import com.kunzisoft.keepass.database.element.PwGroupInterface;
import com.kunzisoft.keepass.database.element.PwGroupV3;
import com.kunzisoft.keepass.database.exception.PwDbOutputException;
import com.kunzisoft.keepass.stream.LEDataOutputStream;
@@ -215,9 +216,9 @@ public class PwDbV3Output extends PwDbOutput<PwDbHeaderV3> {
}
// Groups
List<PwGroupV3> groups = mPM.getGroups();
List<PwGroupInterface> groups = mPM.getGroups();
for ( int i = 0; i < groups.size(); i++ ) {
PwGroupV3 pg = groups.get(i);
PwGroupV3 pg = (PwGroupV3) groups.get(i);
PwGroupOutputV3 pgo = new PwGroupOutputV3(pg, os);
try {
pgo.output();
@@ -239,10 +240,10 @@ public class PwDbV3Output extends PwDbOutput<PwDbHeaderV3> {
}
private void sortGroupsForOutput() {
List<PwGroupV3> groupList = new ArrayList<>();
List<PwGroupInterface> groupList = new ArrayList<>();
// Rebuild list according to coalation sorting order removing any orphaned groups
List<PwGroupV3> roots = mPM.getGrpRoots();
List<PwGroupInterface> roots = mPM.getGrpRoots();
for ( int i = 0; i < roots.size(); i++ ) {
sortGroup(roots.get(i), groupList);
}
@@ -250,7 +251,7 @@ public class PwDbV3Output extends PwDbOutput<PwDbHeaderV3> {
mPM.setGroups(groupList);
}
private void sortGroup(PwGroupV3 group, List<PwGroupV3> groupList) {
private void sortGroup(PwGroupInterface group, List<PwGroupInterface> groupList) {
// Add current tree
groupList.add(group);
@@ -39,7 +39,9 @@ import com.kunzisoft.keepass.database.element.PwDatabaseV4XML;
import com.kunzisoft.keepass.database.element.PwDbHeaderV4;
import com.kunzisoft.keepass.database.element.PwDefsV4;
import com.kunzisoft.keepass.database.element.PwDeletedObject;
import com.kunzisoft.keepass.database.element.PwEntryInterface;
import com.kunzisoft.keepass.database.element.PwEntryV4;
import com.kunzisoft.keepass.database.element.PwGroupInterface;
import com.kunzisoft.keepass.database.element.PwGroupV4;
import com.kunzisoft.keepass.database.element.PwIconCustom;
import com.kunzisoft.keepass.database.exception.PwDbOutputException;
@@ -142,54 +144,6 @@ public class PwDbV4Output extends PwDbOutput<PwDbHeaderV4> {
}
}
private class GroupWriter extends GroupHandler<PwGroupV4> {
private Stack<PwGroupV4> groupStack;
public GroupWriter(Stack<PwGroupV4> gs) {
groupStack = gs;
}
@Override
public boolean operate(PwGroupV4 group) {
assert(group != null);
while(true) {
try {
if (group.getParent() == groupStack.peek()) {
groupStack.push(group);
startGroup(group);
break;
} else {
groupStack.pop();
if (groupStack.size() <= 0) return false;
endGroup();
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return true;
}
}
private class EntryWriter extends EntryHandler<PwEntryV4> {
@Override
public boolean operate(PwEntryV4 entry) {
assert(entry != null);
try {
writeEntry(entry, false);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
return true;
}
}
private void outputDatabase(OutputStream os) throws IllegalArgumentException, IllegalStateException, IOException {
xml = Xml.newSerializer();
@@ -201,14 +155,49 @@ public class PwDbV4Output extends PwDbOutput<PwDbHeaderV4> {
writeMeta();
PwGroupV4 root = mPM.getRootGroup();
PwGroupV4 root = (PwGroupV4) mPM.getRootGroup();
xml.startTag(null, PwDatabaseV4XML.ElemRoot);
startGroup(root);
Stack<PwGroupV4> groupStack = new Stack<>();
groupStack.push(root);
if (!root.preOrderTraverseTree(new GroupWriter(groupStack), new EntryWriter()))
throw new RuntimeException("Writing groups failed");
if (!PwGroupInterface.preOrderTraverseTree(root, new GroupHandler<PwGroupInterface>() {
@Override
public boolean operate(PwGroupInterface groupInterface) {
PwGroupV4 group = (PwGroupV4) groupInterface;
while (true) {
try {
if (group.getParent() == groupStack.peek()) {
groupStack.push(group);
startGroup(group);
break;
} else {
groupStack.pop();
if (groupStack.size() <= 0) return false;
endGroup();
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return true;
}
}, new EntryHandler<PwEntryInterface>() {
@Override
public boolean operate(PwEntryInterface entryInterface) {
PwEntryV4 entry = (PwEntryV4) entryInterface;
try {
writeEntry(entry, false);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
return true;
}
})) throw new RuntimeException("Writing groups failed");
while (groupStack.size() > 1) {
xml.endTag(null, PwDatabaseV4XML.ElemGroup);
@@ -347,8 +336,8 @@ public class PwDbV4Output extends PwDbOutput<PwDbHeaderV4> {
private void startGroup(PwGroupV4 group) throws IllegalArgumentException, IllegalStateException, IOException {
xml.startTag(null, PwDatabaseV4XML.ElemGroup);
writeObject(PwDatabaseV4XML.ElemUuid, group.getUUID());
writeObject(PwDatabaseV4XML.ElemName, group.getName());
writeObject(PwDatabaseV4XML.ElemUuid, group.getNodeId().getId());
writeObject(PwDatabaseV4XML.ElemName, group.getTitle());
writeObject(PwDatabaseV4XML.ElemNotes, group.getNotes());
writeObject(PwDatabaseV4XML.ElemIcon, group.getIconStandard().getIconId());
@@ -374,7 +363,7 @@ public class PwDbV4Output extends PwDbOutput<PwDbHeaderV4> {
xml.startTag(null, PwDatabaseV4XML.ElemEntry);
writeObject(PwDatabaseV4XML.ElemUuid, entry.getUUID());
writeObject(PwDatabaseV4XML.ElemUuid, entry.getNodeId().getId());
writeObject(PwDatabaseV4XML.ElemIcon, entry.getIconStandard().getIconId());
if (!entry.getIconCustom().equals(PwIconCustom.ZERO)) {
@@ -654,7 +643,7 @@ public class PwDbV4Output extends PwDbOutput<PwDbHeaderV4> {
xml.startTag(null, name);
writeObject(PwDatabaseV4XML.ElemUuid, value.uuid);
writeObject(PwDatabaseV4XML.ElemUuid, value.getUuid());
writeObject(PwDatabaseV4XML.ElemDeletionTime, value.getDeletionTime());
xml.endTag(null, name);
@@ -20,6 +20,7 @@
package com.kunzisoft.keepass.database.save;
import com.kunzisoft.keepass.database.element.PwEntryV3;
import com.kunzisoft.keepass.database.element.PwGroupV3;
import com.kunzisoft.keepass.stream.LEDataOutputStream;
import com.kunzisoft.keepass.utils.Types;
@@ -74,22 +75,22 @@ public class PwEntryOutputV3 {
// UUID
mOS.write(UUID_FIELD_TYPE);
mOS.write(UUID_FIELD_SIZE);
mOS.write(Types.UUIDtoBytes(mPE.getUUID()));
mOS.write(Types.UUIDtoBytes(mPE.getNodeId().getId()));
// Group ID
mOS.write(GROUPID_FIELD_TYPE);
mOS.write(LONG_FOUR);
mOS.write(LEDataOutputStream.writeIntBuf(mPE.getParent().getGroupId()));
mOS.write(LEDataOutputStream.writeIntBuf(((PwGroupV3) mPE.getParent()).getNodeId().getId()));
// Image ID
mOS.write(IMAGEID_FIELD_TYPE);
mOS.write(LONG_FOUR);
mOS.write(LEDataOutputStream.writeIntBuf(mPE.getIconStandard().getIconId()));
mOS.write(LEDataOutputStream.writeIntBuf(mPE.getIcon().getIconId()));
// Title
//byte[] title = mPE.title.getBytes("UTF-8");
mOS.write(TITLE_FIELD_TYPE);
int titleLen = Types.writeCString(mPE.getName(), mOS);
int titleLen = Types.writeCString(mPE.getTitle(), mOS);
outputBytes += titleLen;
// URL
@@ -64,11 +64,11 @@ public class PwGroupOutputV3 {
// Group ID
mOS.write(GROUPID_FIELD_TYPE);
mOS.write(GROUPID_FIELD_SIZE);
mOS.write(LEDataOutputStream.writeIntBuf(mPG.getGroupId()));
mOS.write(LEDataOutputStream.writeIntBuf(mPG.getId()));
// Name
mOS.write(NAME_FIELD_TYPE);
Types.writeCString(mPG.getName(), mOS);
Types.writeCString(mPG.getTitle(), mOS);
// Create date
mOS.write(CREATE_FIELD_TYPE);
@@ -93,7 +93,7 @@ public class PwGroupOutputV3 {
// Image ID
mOS.write(IMAGEID_FIELD_TYPE);
mOS.write(IMAGEID_FIELD_SIZE);
mOS.write(LEDataOutputStream.writeIntBuf(mPG.getIconStandard().getIconId()));
mOS.write(LEDataOutputStream.writeIntBuf(mPG.getIcon().getIconId()));
// Level
mOS.write(LEVEL_FIELD_TYPE);
@@ -1,62 +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.database.search;
import com.kunzisoft.keepass.database.EntryHandler;
import com.kunzisoft.keepass.database.element.PwEntryInterface;
import com.kunzisoft.keepass.database.iterator.EntrySearchStringIterator;
import java.util.Date;
import java.util.List;
public abstract class EntrySearchHandler<T extends PwEntryInterface> extends EntryHandler<T> {
protected List<T> listStorage;
protected SearchParameters sp;
protected Date now;
protected EntrySearchHandler(SearchParameters sp, List<T> listStorage) {
this.listStorage = listStorage;
this.sp = sp;
this.now = new Date();
}
protected boolean searchID(PwEntryInterface entry) {
return false;
}
protected boolean searchStrings(PwEntryInterface entry, String term) {
EntrySearchStringIterator iter = EntrySearchStringIterator.getInstance(entry, sp);
while (iter.hasNext()) {
String str = iter.next();
if (str != null && str.length() > 0) {
if (sp.ignoreCase) {
str = str.toLowerCase();
}
if (str.contains(term)) {
return true;
}
}
}
return false;
}
}
@@ -1,54 +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.database.search;
import com.kunzisoft.keepass.database.EntryHandler;
import com.kunzisoft.keepass.database.element.PwEntryInterface;
import java.util.Date;
import java.util.List;
public class EntrySearchHandlerAll<T extends PwEntryInterface> extends EntryHandler<T> {
private List<T> listStorage;
private SearchParameters sp;
private Date now;
public EntrySearchHandlerAll(SearchParameters sp, List<T> listStorage) {
this.sp = sp;
this.listStorage = listStorage;
now = new Date();
}
@Override
public boolean operate(T entry) {
if (sp.respectEntrySearchingDisabled && !entry.isSearchingEnabled()) {
return true;
}
if (sp.excludeExpired && entry.isExpires() && now.after(entry.getExpiryTime().getDate())) {
return true;
}
listStorage.add(entry);
return true;
}
}
@@ -19,26 +19,32 @@
*/
package com.kunzisoft.keepass.database.search;
import com.kunzisoft.keepass.database.EntryHandler;
import com.kunzisoft.keepass.database.element.PwEntryInterface;
import com.kunzisoft.keepass.database.element.PwEntryV4;
import com.kunzisoft.keepass.database.element.PwGroupInterface;
import com.kunzisoft.keepass.database.iterator.EntrySearchStringIterator;
import com.kunzisoft.keepass.utils.StrUtil;
import com.kunzisoft.keepass.utils.UuidUtil;
import java.util.Date;
import java.util.List;
import java.util.Locale;
public class EntrySearchHandlerV4 extends EntrySearchHandler<PwEntryV4> {
public class EntrySearchHandlerV4 extends EntryHandler<PwEntryInterface> {
private SearchParametersV4 sp;
private List<PwEntryInterface> listStorage;
protected SearchParametersV4 sp;
protected Date now;
protected EntrySearchHandlerV4(SearchParameters sp, List<PwEntryV4> listStorage) {
super(sp, listStorage);
this.sp = (SearchParametersV4) sp;
public EntrySearchHandlerV4(SearchParametersV4 sp, List<PwEntryInterface> listStorage) {
this.listStorage = listStorage;
this.sp = sp;
this.now = new Date();
}
@Override
public boolean operate(PwEntryV4 entry) {
public boolean operate(PwEntryInterface entry) {
if (sp.respectEntrySearchingDisabled && !entry.isSearchingEnabled()) {
return true;
}
@@ -60,7 +66,7 @@ public class EntrySearchHandlerV4 extends EntrySearchHandler<PwEntryV4> {
if (sp.searchInGroupNames) {
PwGroupInterface parent = entry.getParent();
if (parent != null) {
String groupName = parent.getName();
String groupName = parent.getTitle();
if (groupName != null) {
if (sp.ignoreCase) {
groupName = groupName.toLowerCase();
@@ -82,16 +88,31 @@ public class EntrySearchHandlerV4 extends EntrySearchHandler<PwEntryV4> {
return true;
}
@Override
protected boolean searchID(PwEntryInterface e) {
private boolean searchID(PwEntryInterface e) {
PwEntryV4 entry = (PwEntryV4) e;
if (sp.searchInUUIDs) {
String hex = UuidUtil.toHexString(entry.getUUID());
String hex = UuidUtil.toHexString(entry.getNodeId().getId());
return StrUtil.indexOfIgnoreCase(hex, sp.searchString, Locale.ENGLISH) >= 0;
}
return false;
}
private boolean searchStrings(PwEntryInterface entry, String term) {
EntrySearchStringIterator iter = EntrySearchStringIterator.getInstance(entry, sp);
while (iter.hasNext()) {
String str = iter.next();
if (str != null && str.length() > 0) {
if (sp.ignoreCase) {
str = str.toLowerCase();
}
if (str.contains(term)) {
return true;
}
}
}
return false;
}
}
@@ -1,104 +0,0 @@
/*
* Copyright 2018 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.database.search;
import com.kunzisoft.keepass.database.EntryHandler;
import com.kunzisoft.keepass.database.element.PwEntryV4;
import com.kunzisoft.keepass.database.element.PwGroupV4;
import com.kunzisoft.keepass.utils.StrUtil;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class EntrySearchV4 {
private PwGroupV4 root;
public EntrySearchV4(PwGroupV4 root) {
this.root = root;
}
public void searchEntries(SearchParameters sp, List<PwEntryV4> listStorage) {
if (sp == null) { return; }
if (listStorage == null) { return; }
List<String> terms = StrUtil.splitSearchTerms(sp.searchString);
if (terms.size() <= 1 || sp.regularExpression) {
searchEntriesSingle(sp, listStorage);
return;
}
// Search longest term first
Comparator<String> stringLengthComparator = (lhs, rhs) -> lhs.length() - rhs.length();
Collections.sort(terms, stringLengthComparator);
String fullSearch = sp.searchString;
List<PwEntryV4> pg = root.getChildEntries();
for (int i = 0; i < terms.size(); i ++) {
List<PwEntryV4> pgNew = new ArrayList<>();
sp.searchString = terms.get(i);
boolean negate = false;
if (sp.searchString.startsWith("-")) {
sp.searchString = sp.searchString.substring(1);
negate = sp.searchString.length() > 0;
}
if (!searchEntriesSingle(sp, pgNew)) {
pg = null;
break;
}
List<PwEntryV4> complement = new ArrayList<>();
if (negate) {
for (PwEntryV4 entry: pg) {
if (!pgNew.contains(entry)) {
complement.add(entry);
}
}
pg = complement;
}
else {
pg = pgNew;
}
}
if (pg != null) {
listStorage.addAll(pg);
}
sp.searchString = fullSearch;
}
private boolean searchEntriesSingle(SearchParameters spIn, List<PwEntryV4> listStorage) {
SearchParameters sp = (SearchParameters) spIn.clone();
EntryHandler<PwEntryV4> eh;
if (sp.searchString.length() <= 0) {
eh = new EntrySearchHandlerAll<>(sp, listStorage);
} else {
eh = new EntrySearchHandlerV4(sp, listStorage);
}
return root.preOrderTraverseTree(null, eh);
}
}
@@ -54,7 +54,7 @@ public class SearchDbHelper<PwDatabaseVersion extends PwDatabase> {
public PwGroupInterface search(PwDatabaseVersion pm, String qStr, int max) {
PwGroupInterface group = pm.createGroup();
group.setName("\"" + qStr + "\"");
group.setTitle("\"" + qStr + "\"");
group.setEntries(new ArrayList<>());
// Search all entries
@@ -81,7 +81,7 @@ public class GroupEditDialogFragment extends DialogFragment
public static GroupEditDialogFragment build(PwGroupInterface group) {
Bundle bundle = new Bundle();
bundle.putString(KEY_NAME, group.getName());
bundle.putString(KEY_NAME, group.getTitle());
bundle.putParcelable(KEY_ICON, group.getIcon());
bundle.putInt(KEY_ACTION_ID, UPDATE.ordinal());
GroupEditDialogFragment fragment = new GroupEditDialogFragment();
@@ -20,6 +20,7 @@
package com.kunzisoft.keepass.utils;
import com.kunzisoft.keepass.database.element.PwDatabaseV4;
import com.kunzisoft.keepass.database.element.PwEntryInterface;
import com.kunzisoft.keepass.database.element.PwEntryV4;
import java.util.HashMap;
@@ -28,7 +29,7 @@ import java.util.Map;
public class SprContextV4 implements Cloneable {
public PwDatabaseV4 db;
public PwEntryV4 entry;
public PwEntryInterface entry;
public Map<String, String> refsCache = new HashMap<>();
public SprContextV4(PwDatabaseV4 db, PwEntryV4 entry) {
@@ -23,10 +23,13 @@ import com.kunzisoft.keepass.database.element.PwDatabase;
import com.kunzisoft.keepass.database.element.PwDatabaseV4;
import com.kunzisoft.keepass.database.element.PwEntryInterface;
import com.kunzisoft.keepass.database.element.PwEntryV4;
import com.kunzisoft.keepass.database.search.EntrySearchV4;
import com.kunzisoft.keepass.database.element.PwGroupInterface;
import com.kunzisoft.keepass.database.search.EntrySearchHandlerV4;
import com.kunzisoft.keepass.database.search.SearchParametersV4;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;
import java.util.Map.Entry;
@@ -37,10 +40,10 @@ public class SprEngineV4 {
private static final String STR_REF_END = "}";
public class TargetResult {
public PwEntryV4 entry;
public PwEntryInterface entry;
public char wanted;
public TargetResult(PwEntryV4 entry, char wanted) {
public TargetResult(PwEntryInterface entry, char wanted) {
this.entry = entry;
this.wanted = wanted;
}
@@ -77,14 +80,14 @@ public class SprEngineV4 {
TargetResult result = findRefTarget(fullRef, ctx);
if (result != null) {
PwEntryV4 found = result.entry;
PwEntryInterface found = result.entry;
char wanted = result.wanted;
if (found != null) {
String data;
switch (wanted) {
case 'T':
data = found.getName();
data = found.getTitle();
break;
case 'U':
data = found.getUsername();
@@ -99,7 +102,7 @@ public class SprEngineV4 {
data = found.getNotes();
break;
case 'I':
data = found.getUUID().toString();
data = found.getNodeId().toString();
break;
default:
offset = start + 1;
@@ -154,11 +157,10 @@ public class SprEngineV4 {
else if (scan == 'I') { sp.searchInUUIDs = true; }
else if (scan == 'O') { sp.searchInOther = true; }
else { return null; }
List<PwEntryV4> list = new ArrayList<>();
List<PwEntryInterface> list = new ArrayList<>();
// TODO type parameter
EntrySearchV4 entrySearchV4 = new EntrySearchV4(ctx.db.getRootGroup());
entrySearchV4.searchEntries(sp, list);
searchEntries(ctx.db.getRootGroup(), sp, list);
if (list.size() > 0) {
return new TargetResult(list.get(0), wanted);
@@ -183,7 +185,57 @@ public class SprEngineV4 {
}
return text;
}
private void searchEntries(PwGroupInterface root, SearchParametersV4 sp, List<PwEntryInterface> listStorage) {
if (sp == null) { return; }
if (listStorage == null) { return; }
List<String> terms = StrUtil.splitSearchTerms(sp.searchString);
if (terms.size() <= 1 || sp.regularExpression) {
PwGroupInterface.preOrderTraverseTree(root, null, new EntrySearchHandlerV4(sp, listStorage));
return;
}
// Search longest term first
Comparator<String> stringLengthComparator = (lhs, rhs) -> lhs.length() - rhs.length();
Collections.sort(terms, stringLengthComparator);
String fullSearch = sp.searchString;
List<PwEntryInterface> pg = root.getChildEntries();
for (int i = 0; i < terms.size(); i ++) {
List<PwEntryInterface> pgNew = new ArrayList<>();
sp.searchString = terms.get(i);
boolean negate = false;
if (sp.searchString.startsWith("-")) {
sp.searchString = sp.searchString.substring(1);
negate = sp.searchString.length() > 0;
}
if (!PwGroupInterface.preOrderTraverseTree(root, null, new EntrySearchHandlerV4(sp, pgNew))) {
pg = null;
break;
}
List<PwEntryInterface> complement = new ArrayList<>();
if (negate) {
for (PwEntryInterface entry: pg) {
if (!pgNew.contains(entry)) {
complement.add(entry);
}
}
pg = complement;
}
else {
pg = pgNew;
}
}
if (pg != null) {
listStorage.addAll(pg);
}
sp.searchString = fullSearch;
}
}