private T getValueFromIndex(String sVal, TextTerminal<?> textTerminal) { try { int optIndex = Integer.parseInt(sVal); if(optIndex > 0 && optIndex <= possibleValues.size()) { return possibleValues.get(optIndex - 1); } } catch (NumberFormatException e) { // Continue the execution. The next statement will print the error message. } textTerminal.executeWithPropertiesPrefix(PROPS_PREFIX_ERROR_MESSAGE, t -> { textTerminal.print(getDefaultErrorMessage(sVal)); textTerminal.println(" Enter a value between 1 and " + possibleValues.size() + "."); }); textTerminal.println(); return null; }
/** * Executes an action while temporarily modifying the terminal properties. * @param propertiesConfigurator the task that is in charge of modifying the TerminalProperties. * The configurator will be applied to the terminal properties before starting the action and * the properties will be reverted to their previous values at the end of the action. * @param action the action to be executed, usually consisting of a series of TextTerminal-related operations. */ default void executeWithPropertiesConfigurator(Consumer<TerminalProperties<?>> propertiesConfigurator, Consumer<TextTerminal<T>> action) { applyWithPropertiesConfigurator(propertiesConfigurator, t -> {action.accept(t); return null;}); }
/** * Prints each message in the list in its raw form, inserting the line separator string between messages. * No separator string is printed after the last message. * The behavior is undefined if one or more strings in the list contain line separators. */ default void rawPrint(List<String> messages) { if(messages != null && !messages.isEmpty()) { rawPrint(messages.get(0)); messages.subList(1, messages.size()).forEach(msg -> { println(); print(msg); }); } }
terminal.setBookmark("COUNTDOWN"); terminal.println("Seconds to start:"); for(int i=5; i>=0; i--) { terminal.resetLine(); delay(500); terminal.print(" " + i); delay(500); terminal.resetToBookmark("COUNTDOWN"); terminal.println("################"); terminal.println("# WEATHER INFO #"); terminal.println("################"); terminal.println(); terminal.setBookmark("MAIN"); while(true) { useCelsius = textIO.newBooleanInputReader().withDefaultValue(true).read("Display temperature in Celsius (Press 'N' for Fahrenheit)"); useKmh = textIO.newBooleanInputReader().withDefaultValue(true).read("Display wind speed in km/h (Press 'N' for mph)"); useMbar = textIO.newBooleanInputReader().withDefaultValue(true).read("Display atmospheric pressure in mbar (Press 'N' for kPa)"); terminal.resetToBookmark("MAIN"); terminal.getProperties().put(PropertiesConstants.PROP_PROMPT_STYLE_CLASS, "textterm-white-space-pre"); terminal.executeWithPropertiesPrefix("pre", t -> { t.println("-------------------------------------------------------"); t.println(" Temperature Wind speed Atmospheric pressure"); t.println("-------------------------------------------------------"); for(int i=0; i<20; i++) { t.moveToLineStart();
boolean registered = terminal.registerHandler(backKeyStroke, t -> new ReadHandlerData(ABORT)); if(registered) { terminal.println("During data entry you can press '" + backKeyStroke + "' to go back to the previous field.\n"); terminal.setBookmark("bookmark_" + step); try { operations.get(step).run(); } catch (ReadAbortedException e) { if(step > 0) step--; terminal.resetToBookmark("bookmark_" + step); continue; terminal.println("\nContact info: " + contact);
boolean registeredReboot = terminal.registerHandler(keyStrokeReboot, t -> { JOptionPane optionPane = new JOptionPane("System reboot in 5 minutes!", JOptionPane.WARNING_MESSAGE); JDialog dialog = optionPane.createDialog("REBOOT"); boolean registeredAutoValue = terminal.registerHandler(keyStrokeAutoValue, t -> { terminal.println(); return new ReadHandlerData(ReadInterruptionStrategy.Action.RETURN) .withReturnValueProvider(partialInput -> partialInput.isEmpty() ? "nothing" : "high-quality-" + partialInput); }); boolean registeredHelp = terminal.registerHandler(keyStrokeHelp, t -> { terminal.executeWithPropertiesPrefix("help", tt -> tt.print("\n\nType the name of a product to be included in your shopping list.")); return new ReadHandlerData(ReadInterruptionStrategy.Action.RESTART).withRedrawRequired(true); }); boolean registeredAbort = terminal.registerHandler(keyStrokeAbort, t -> new ReadHandlerData(ReadInterruptionStrategy.Action.ABORT) .withPayload(System.getProperty("user.name", "nobody"))); terminal.println("No handlers can be registered."); } else { terminal.println("--------------------------------------------------------------------------------"); if(registeredReboot) { terminal.println("Press " + keyStrokeReboot + " to display a 'reboot' message box"); terminal.println("Press " + keyStrokeAutoValue + " to provide a product name based on the current input text"); terminal.println("Press " + keyStrokeHelp + " to print a help message");
/** * Prints a formatted string using the specified locale, format string and arguments. * @param l The {@linkplain java.util.Locale locale} to apply during formatting. If {@code l} is {@code null} then no localization is applied. * @param format A format string as described in {@link java.util.Formatter}. * @param args Arguments referenced by the format specifiers in the format string. */ default void printf(Locale l, String format, Object... args) { print(String.format(l, format, args)); }
/** * Moves the cursor to the start of the current line of text in order to allow overwriting the current line. * Since not all terminals support this feature, the default implementation calls {@link #println()} and returns false. * @return true, if the terminal supports this feature and the cursor has been moved to the start of the current line. */ default boolean moveToLineStart() { println(); return false; }
AppUtil.printGsonMessage(terminal, initData); TerminalProperties<?> props = terminal.getProperties(); terminal.println("Order details"); props.setPromptUnderline(true); props.setPromptColor("green"); terminal.println("\nShipping Information"); props.setPromptUnderline(true); props.setPromptColor("white"); terminal.println("\nPayment Details"); props.setPromptUnderline(true); props.setPromptColor("red"); terminal.println("\nOrder Overview"); terminal.printf("Product: %s\nQuantity: %d\n", product, quantity); terminal.printf("\n%s to %s, %s\n", shippingOptions, street, city); terminal.printf("%s is paying with %s.\n", owner, paymentType);
textTerminal.executeWithPropertiesPrefix(PROPS_PREFIX_ERROR_MESSAGE, t ->t.println(allErrors)); textTerminal.println(); continue;
protected String readWithPrompt(TextTerminal<?> textTerminal, List<String> prompt) { printPrompt(prompt, textTerminal); while(true) { String sInput = null; try { sInput = textTerminal.read(inputMasking); } catch (ReadInterruptionException e) { ReadInterruptionData data = e.getReadInterruptionData(); logger.debug("ReadInterruptionException with data: " + data); switch (data.getAction()) { case CONTINUE: logger.error("ReadInterruptionException with action CONTINUE."); // no break here: handle it as RESTART case RESTART: if(data.isRedrawRequired()) { logger.trace("Re-printing prompt before read restart"); textTerminal.println(); printPrompt(prompt, textTerminal); logger.trace("Prompt re-printed."); } continue; case RETURN: return data.getReturnValue(); case ABORT: throw new ReadAbortedException(data.getPayload(), e.getPartialInput()); } } return sInput; } }
private Holder() { TextTerminal<?> t = getTerminalFromProperty(); if(t == null) { t = getTerminalFromService(); } if(t == null) { t = getDefaultTerminal(); } t.init(); this.terminal = t; this.textIO = new TextIO(t); }
TerminalProperties<?> props = getProperties(); if(propertiesConfigurator != null) { props.addListener(listener);
boolean registered = terminal.registerHandler(backKeyStroke, t -> new ReadHandlerData(ABORT)); if(registered) { terminal.println("During data entry you can press '" + backKeyStroke + "' to go back to the previous field.\n"); terminal.setBookmark("bookmark_" + step); try { operations.get(step).run(); } catch (ReadAbortedException e) { if(step > 0) step--; terminal.resetToBookmark("bookmark_" + step); continue; terminal.println("\nContact info: " + contact);
/** * Prints a formatted string using the default locale and the specified format string and arguments. * @param format A format string as described in {@link java.util.Formatter}. * @param args Arguments referenced by the format specifiers in the format string. */ default void printf(String format, Object... args) { print(String.format(format, args)); }
/** * Clears the text after the given bookmark. * The bookmark name can be subsequently used in a call to {@link #resetToBookmark(String)} in order to clear the text after this bookmark. * Since not all terminals support this feature, the default implementation calls {@link #println()} and returns false. * @return true, if the terminal supports bookmarking, the given bookmark exists and the text after it has been successfully cleared. */ default boolean resetToBookmark(String bookmark) { println(); return false; }
continue; chosenTerminal.init(); return new TextIO(chosenTerminal);
private T getValueFromString(String sVal, TextTerminal<?> textTerminal) { ParseResult<T> result = parseAndCheck(sVal); List<String> errMessages = result.getErrorMessages(); if(errMessages == null) { Optional<T> value = getPossibleValue(result.getValue()); if(value.isPresent()) return value.get(); textTerminal.executeWithPropertiesPrefix(PROPS_PREFIX_ERROR_MESSAGE, t -> { t.print(getDefaultErrorMessage(sVal)); if(inlinePossibleValues) { String options = possibleValues.stream() .map(val -> "'" + valueFormatter.apply(val) + "'") .collect(Collectors.joining(", ")); t.println(" Please enter one of: " + options + "."); } else { t.println(" Please enter one of the displayed values."); } }); textTerminal.println(); } else { textTerminal.executeWithPropertiesPrefix(PROPS_PREFIX_ERROR_MESSAGE, t -> t.println(errMessages)); textTerminal.println(); } return null; }