blob: 88e166ab933c7f631088b99b0198200de05345a9 (
plain) (
blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
|
package derms.replica.replica1;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
public abstract class CLI implements Runnable {
protected Map<String, Command> commands = new HashMap<String, Command>();
protected List<Description> cmdDescriptions = new ArrayList<Description>();
protected List<Description> argDescriptions = new ArrayList<Description>();
protected CLI() {
commands.put("quit", new Quit());
cmdDescriptions.add(new Description("quit", "Exit the program"));
commands.put("help", new Help());
cmdDescriptions.add(new Description("help", "List commands"));
}
@Override
public void run() {
Scanner scanner = new Scanner(System.in);
System.out.println("Type 'help' for a list of commands.");
for (;;) {
System.out.print("Command: ");
String input = scanner.nextLine();
String[] fields = input.split(" ");
if (fields.length < 1 || fields[0] == "") {
continue;
}
Command cmd = commands.get(fields[0]);
if (cmd == null) {
System.out.println("Invalid command '"+fields[0]+"'");
System.out.println("Type 'help' for a list of commands.");
continue;
}
String[] args = null;
if (fields.length < 2) {
args = new String[0];
} else {
args = Arrays.copyOfRange(fields, 1, fields.length);
}
cmd.exec(args);
}
}
protected interface Command {
public void exec(String[] args);
}
protected class Quit implements Command {
@Override
public void exec(String[] args) {
System.out.println("Shutting down...");
System.exit(1);
}
}
protected class Help implements Command {
@Override
public void exec(String[] args) {
System.out.println("\nCommands:");
for (Description d : cmdDescriptions) {
System.out.println(d);
}
System.out.println("\nArguments:");
for (Description d : argDescriptions) {
System.out.println(d);
}
System.out.println();
}
}
protected class Description {
String object; /// The thing being described
String description;
protected Description(String object, String description) {
this.object = object;
this.description = description;
}
@Override
public String toString() {
return object+"\n\t"+description;
}
}
}
|