Class DefaultHistory
- All Implemented Interfaces:
Iterable<History.Entry>, History
History with file-based persistent storage.
This class provides a complete implementation of the History interface with the following features:
- In-memory storage of history entries with configurable size limits
- Persistent storage in a text file with configurable location and size limits
- Support for timestamped history entries
- Filtering of entries based on patterns defined in the
LineReader.HISTORY_IGNOREvariable - Options to ignore duplicates, reduce blanks, and ignore commands starting with spaces
- Incremental saving of history entries
- History navigation (previous/next, first/last, etc.)
The history file format is either plain text with one command per line, or if
LineReader.Option.HISTORY_TIMESTAMPED is set, each line starts with a timestamp
in milliseconds since epoch, followed by a colon and the command text.
Applications using this class should install a shutdown hook to call save()
to ensure history is saved to disk when the application exits.
Example usage:
LineReader reader = LineReaderBuilder.builder()
.variable(LineReader.HISTORY_FILE, Paths.get(System.getProperty("user.home"), ".myapp_history"))
.build();
// History is automatically attached to the reader
// To save history manually:
((DefaultHistory) reader.getHistory()).save();
- See Also:
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionprotected static classDefault implementation of theHistory.Entryinterface.Nested classes/interfaces inherited from interface History
History.Entry -
Field Summary
FieldsModifier and TypeFieldDescriptionstatic final intDefault maximum number of history entries to keep in the history file.static final intDefault maximum number of history entries to keep in memory. -
Constructor Summary
ConstructorsConstructorDescriptionCreates a new DefaultHistory instance.DefaultHistory(LineReader reader) Creates a new DefaultHistory instance and attaches it to the specified LineReader. -
Method Summary
Modifier and TypeMethodDescriptionvoidAdds a new entry to the history.protected voidaddHistoryLine(Path path, String line) Adds a history line to the specified history file.protected voidaddHistoryLine(Path path, String line, boolean checkDuplicates) Adds a history line to the specified history file with an option to check for duplicates.voidAppends history entries to the specified file.voidattach(LineReader reader) Attaches this history to a LineReader.protected DefaultHistory.EntryImplcreateEntry(int index, Instant time, String line) Create a history entry.current()Returns the text of the history entry at the current cursor position.intfirst()Returns the index of the first element in the history.get(int index) Returns the history item at the specified index.intindex()Returns the current index in the history.protected voidinternalAdd(Instant time, String line) Adds a line to the history with the specified timestamp.protected voidinternalAdd(Instant time, String line, boolean checkDuplicates) Adds a line to the history with the specified timestamp and an option to check for duplicates.booleanisEmpty()Checks if the history is empty.iterator(int index) Returns a list iterator over the history entries starting at the specified index.intlast()Returns the index of the last element in the history.voidload()Loads history from the file specified by theLineReader.HISTORY_FILEvariable.protected booleanmatchPatterns(String patterns, String line) Checks if a line matches any of the specified patterns.booleanmoveTo(int index) Moves the history cursor to the specified index.voidMoves the history cursor to the end of the history buffer.booleanMoves the history cursor to the first entry.booleanMoves the history cursor to the last entry.booleannext()Moves the history cursor to the next (newer) entry.booleanprevious()Moves the history cursor to the previous (older) entry.voidpurge()Clears the history and deletes the history file.voidReads history entries from the specified file and adds them to the current history.voidReset index after removevoidsave()Saves the history to the default history file.intsize()Returns the number of items in the history.toString()protected voidtrimHistory(Path path, int max) Trims the history file to the specified maximum number of entries.voidWrites the history to the specified file, optionally replacing the existing file.Methods inherited from class Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, waitMethods inherited from interface History
add, isPersistable, iterator, reverseIterator, reverseIterator
-
Field Details
-
DEFAULT_HISTORY_SIZE
public static final int DEFAULT_HISTORY_SIZEDefault maximum number of history entries to keep in memory. This value is used when theLineReader.HISTORY_SIZEvariable is not set.- See Also:
-
DEFAULT_HISTORY_FILE_SIZE
public static final int DEFAULT_HISTORY_FILE_SIZEDefault maximum number of history entries to keep in the history file. This value is used when theLineReader.HISTORY_FILE_SIZEvariable is not set.- See Also:
-
-
Constructor Details
-
DefaultHistory
public DefaultHistory()Creates a new DefaultHistory instance. -
DefaultHistory
Creates a new DefaultHistory instance and attaches it to the specified LineReader.- Parameters:
reader- the LineReader to attach to
-
-
Method Details
-
attach
Attaches this history to a LineReader.This method associates the history with a LineReader and loads the history from the file specified by the
LineReader.HISTORY_FILEvariable. If the history is already attached to the given reader, this method does nothing. -
load
Loads history from the file specified by theLineReader.HISTORY_FILEvariable.This method clears the current history and loads entries from the history file. If the file doesn't exist or can't be read, the history will be cleared. If individual lines in the history file are malformed, they will be skipped.
- Specified by:
loadin interfaceHistory- Throws:
IOException- if an I/O error occurs while reading the history file
-
read
Reads history entries from the specified file and adds them to the current history.Unlike
load(), this method does not clear the existing history before adding entries from the file. If the file doesn't exist or can't be read, the history will be cleared. If individual lines in the history file are malformed, they will be skipped.- Specified by:
readin interfaceHistory- Parameters:
file- the file to read history from, or null to use the default history filecheckDuplicates- whether to check for and skip duplicate entries- Throws:
IOException- if an I/O error occurs while reading the history file
-
addHistoryLine
-
addHistoryLine
-
purge
Clears the history and deletes the history file.This method removes all history entries from memory and deletes the history file if it exists.
- Specified by:
purgein interfaceHistory- Throws:
IOException- if an I/O error occurs while deleting the history file
-
write
Writes the history to the specified file, optionally replacing the existing file.If the file exists, it will be deleted and recreated. If incremental is true, only entries that haven't been saved before will be written.
- Specified by:
writein interfaceHistory- Parameters:
file- the file to write history to, or null to use the default history fileincremental- whether to write only new entries (true) or all entries (false)- Throws:
IOException- if an I/O error occurs while writing the history file
-
append
Appends history entries to the specified file.Unlike
write(Path, boolean), this method does not delete the existing file before writing. If incremental is true, only entries that haven't been saved before will be appended.- Specified by:
appendin interfaceHistory- Parameters:
file- the file to append history to, or null to use the default history fileincremental- whether to append only new entries (true) or all entries (false)- Throws:
IOException- if an I/O error occurs while appending to the history file
-
save
Saves the history to the default history file.This method appends any new history entries (those that haven't been saved before) to the history file. It's typically called when the application exits to ensure that history is preserved.
- Specified by:
savein interfaceHistory- Throws:
IOException- if an I/O error occurs while saving the history file
-
trimHistory
Trims the history file to the specified maximum number of entries.- Parameters:
path- the path to the history filemax- the maximum number of entries to keep- Throws:
IOException- if an I/O error occurs
-
createEntry
Create a history entry. Subclasses may override to use their own entry implementations.- Parameters:
index- index of history entrytime- entry creation timeline- the entry text- Returns:
- entry object
-
size
-
isEmpty
-
index
-
first
-
last
-
get
-
add
Adds a new entry to the history.This method adds a new entry to the history with the specified timestamp and command text. The entry may be filtered based on various criteria such as:
- If history is disabled (
LineReader.DISABLE_HISTORYis true) - If the line starts with a space and
LineReader.Option.HISTORY_IGNORE_SPACEis set - If the line is a duplicate of the previous entry and
LineReader.Option.HISTORY_IGNORE_DUPSis set - If the line matches a pattern in
LineReader.HISTORY_IGNORE
If
LineReader.Option.HISTORY_INCREMENTALis set, the history will be saved to disk after adding the entry.- Specified by:
addin interfaceHistory- Parameters:
time- the timestamp for the new entryline- the command text for the new entry- Throws:
NullPointerException- if time or line is null
- If history is disabled (
-
matchPatterns
-
internalAdd
-
internalAdd
Adds a line to the history with the specified timestamp and an option to check for duplicates.- Parameters:
time- the timestamp for the history entryline- the line to addcheckDuplicates- whether to check for duplicate entries
-
iterator
Description copied from interface:HistoryReturns a list iterator over the history entries starting at the specified index. -
spliterator
- Specified by:
spliteratorin interfaceIterable<History.Entry>
-
resetIndex
public void resetIndex()Description copied from interface:HistoryReset index after remove- Specified by:
resetIndexin interfaceHistory
-
moveToLast
public boolean moveToLast()Moves the history cursor to the last entry.This positions the cursor at the most recent history entry, which is one position before the position set by
moveToEnd(). This is typically used when starting to navigate backward through history.- Specified by:
moveToLastin interfaceHistory- Returns:
- true if the cursor was moved, false if there were no history entries or the cursor was already at the last entry
-
moveTo
public boolean moveTo(int index) Moves the history cursor to the specified index.This positions the cursor at the history entry with the given index, if it exists. The index is absolute, taking into account the offset of the history buffer.
-
moveToFirst
public boolean moveToFirst()Moves the history cursor to the first entry.This positions the cursor at the oldest history entry in the buffer. This is typically used when starting to navigate forward through history.
- Specified by:
moveToFirstin interfaceHistory- Returns:
- true if the cursor was moved, false if there were no history entries or the cursor was already at the first entry
-
moveToEnd
public void moveToEnd()Moves the history cursor to the end of the history buffer.This positions the cursor after the last history entry, which represents the current input line (not yet in history). This is the default position when not navigating through history.
-
current
Returns the text of the history entry at the current cursor position.If the cursor is at the end of the history (after the last entry), this method returns an empty string.
-
previous
public boolean previous()Moves the history cursor to the previous (older) entry.This is typically called when the user presses the up arrow key to navigate backward through history. If the cursor is already at the first entry, this method does nothing and returns false.
-
next
public boolean next()Moves the history cursor to the next (newer) entry.This is typically called when the user presses the down arrow key to navigate forward through history. If the cursor is already at the end of history, this method does nothing and returns false.
-
toString
-