Pete
Pete

Reputation: 1561

Implement Command History within Java Program?

I need some coding advice. I've written a simple Java program which runs within one of my company's internal websites. Its a command line program where users enter commands like copy file1 to remote1 and compare file1 to file2 archive diff and so on. My colleagues like it and use it frequently.

The problem is the users' commands tend to be long and repetitive. They have asked me if it is possible to implement a command history in the program. This way, they can use the up arrow or something to scroll through, edit, and resubmit previous commands. There's no need to remember commands entered in previous sessions, only the current session.

I've thought about it, and I think I could come up with a solution from scratch... but it would take a few weeks to develop. I'd much rather implement an available package or module, if one exists and isn't too much trouble. I know this is an open-ended question, but can anyone recommend such a resource?

Upvotes: 1

Views: 2001

Answers (4)

weberjn
weberjn

Reputation: 1985

Æsh (Another Extendable SHell) Readline

JShell with jshell-maven-plugin

Upvotes: 1

anand1st
anand1st

Reputation: 1176

I've used CRaSH in my project. It's basically a SSH shell that the user is expected to connect to (supports username/password too) and yes, supports history in commands. Commands are written in Groovy.

Upvotes: 1

shmosel
shmosel

Reputation: 50746

I don't see why it should take so long to develop. Here's a rudimentary solution:

class CommandSession {
    private List<Command> commands = new ArrayList<>();
    private ListIterator<Command> scroller;

    public void execute(Command command) {
        scroller = null;
        commands.add(command);
        command.execute();
    }

    public Command scrollUp() {
        if (scroller == null) {
            scroller = commands.listIterator(commands.size());
        }
        if (scroller.hasPrevious()) {
            return scroller.previous();
        }
        return null;
    }
}

You could tweak this in various ways for more advanced functionality, but overall it's a pretty basic concept.

Upvotes: 2

yaitloutou
yaitloutou

Reputation: 1791

if you are using a *nix environment then rlwrap may be what's you're looking for.

rlwrap tries to be completely transparent - you (or your shell) shouldn't notice any difference between command and rlwrap command - except the added readline functionality, of course. This should even hold true when you are re-directing, piping and sending signals from and to command, or when command manipulates its terminal settings.

There are many options to add (programmable) completion, handle multi-line input, colour and re-write prompts. If you don't need them (and you probably don't), you can skip the rest of this manpage.

if not, you can use cygwin to be able to use it

Upvotes: 1

Related Questions