This is the abstract main class for the starter classes. @author BaseX Team, BSD License @author Christian Gruen
| 23 | * @author Christian Gruen |
| 24 | */ |
| 25 | public abstract class CLI extends Main { |
| 26 | /** Database context. */ |
| 27 | public Context context; |
| 28 | |
| 29 | /** Cached initial commands. */ |
| 30 | protected final ArrayList<Entry<String, String>> commands = new ArrayList<>(); |
| 31 | /** Output stream. */ |
| 32 | protected PrintOutput out = PrintOutput.get(System.out); |
| 33 | /** Output is written to a file. */ |
| 34 | protected boolean fileOutput; |
| 35 | /** Verbose mode. */ |
| 36 | protected boolean verbose; |
| 37 | |
| 38 | /** Password reader. */ |
| 39 | private static final PasswordReader PWREADER = () -> { |
| 40 | Util.print(PASSWORD + COLS); |
| 41 | return Util.password(); |
| 42 | }; |
| 43 | /** Session. */ |
| 44 | private Session session; |
| 45 | |
| 46 | /** |
| 47 | * Constructor, assigning the specified context. |
| 48 | * @param args command-line arguments |
| 49 | * @param ctx database context (if {@code null}, must be assigned later on) |
| 50 | * @throws IOException I/O exception |
| 51 | */ |
| 52 | protected CLI(final Context ctx, final String... args) throws IOException { |
| 53 | super(args); |
| 54 | context = ctx; |
| 55 | parseArgs(); |
| 56 | // guarantee correct shutdown of database context |
| 57 | if(context != null) Runtime.getRuntime().addShutdownHook(new Thread(context::close)); |
| 58 | } |
| 59 | |
| 60 | /** |
| 61 | * Parses and executes the input string. |
| 62 | * @param command base URI (name) and command string (value) |
| 63 | * @return {@code false} if the exit command was sent |
| 64 | * @throws IOException database exception |
| 65 | */ |
| 66 | protected final boolean execute(final Entry<String, String> command) throws IOException { |
| 67 | final CommandParser cp = CommandParser.get(command.getValue(), context); |
| 68 | return execute(cp.path(command.getKey()).pwReader(PWREADER)); |
| 69 | } |
| 70 | |
| 71 | /** |
| 72 | * Execute the commands from the given command parser. |
| 73 | * @param parser command parser |
| 74 | * @return {@code false} if the exit command was sent |
| 75 | * @throws IOException database exception |
| 76 | */ |
| 77 | protected final boolean execute(final CommandParser parser) throws IOException { |
| 78 | try { |
| 79 | for(final Command cmd : parser.parse()) { |
| 80 | if(cmd instanceof Exit) return false; |
| 81 | execute(cmd, verbose); |
| 82 | } |