jline.console.ConsoleReader Java Examples

The following examples show how to use jline.console.ConsoleReader. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ApexCli.java    From attic-apex-core with Apache License 2.0 6 votes vote down vote up
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
  String streamName = args[1];
  String sourceOperatorName = args[2];
  String sourcePortName = args[3];
  String sinkOperatorName = args[4];
  String sinkPortName = args[5];
  CreateStreamRequest request = new CreateStreamRequest();
  request.setStreamName(streamName);
  request.setSourceOperatorName(sourceOperatorName);
  request.setSinkOperatorName(sinkOperatorName);
  request.setSourceOperatorPortName(sourcePortName);
  request.setSinkOperatorPortName(sinkPortName);
  logicalPlanRequestQueue.add(request);
}
 
Example #2
Source File: Util.java    From ecosys with Apache License 2.0 6 votes vote down vote up
/**
 * Create a prompt with color and customized prompt text.
 * @param text, the prompt text
 * @return input string
 */
public static String ColorPrompt(String text) {
  String ANSI_BLUE = "\u001B[1;34m";
  String ANSI_RESET = "\u001B[0m";
  String input = null;
  try {
    ConsoleReader tempConsole = new ConsoleReader();
    String prmpt = ANSI_BLUE + text + ANSI_RESET;
    tempConsole.setPrompt(prmpt);
    input = tempConsole.readLine();
  } catch (IOException e) {
    LogExceptions(e);
    System.out.println("Prompt input error!");
  }
  return input;
}
 
Example #3
Source File: WorfInteractive.java    From warp10-platform with Apache License 2.0 6 votes vote down vote up
private static String readHost(ConsoleReader reader, PrintWriter out, String prompt) {
  try {
    String inputString = readInputString(reader, out, prompt);

    if (InetAddresses.isInetAddress(inputString)) {
      return inputString;
    }
    out.println("Error, " + inputString + " is not a valid inet address");
  } catch (Exception exp) {
    if (WorfCLI.verbose) {
      exp.printStackTrace();
    }
    out.println("Error, unable to read the host. error=" + exp.getMessage());
  }
  return null;
}
 
Example #4
Source File: ConsoleShellFactory.java    From Bukkit-SSHD with Apache License 2.0 6 votes vote down vote up
public void start(Environment env) throws IOException {
    try {
        consoleReader = new ConsoleReader(in, new FlushyOutputStream(out), new SshTerminal());
        consoleReader.setExpandEvents(true);
        consoleReader.addCompleter(new ConsoleCommandCompleter());

        StreamHandler streamHandler = new FlushyStreamHandler(out, new ConsoleLogFormatter(), consoleReader);
        streamHandlerAppender = new StreamHandlerAppender(streamHandler);

        ((Logger) LogManager.getRootLogger()).addAppender(streamHandlerAppender);

        environment = env;
        thread = new Thread(this, "SSHD ConsoleShell " + env.getEnv().get(Environment.ENV_USER));
        thread.start();
    } catch (Exception e) {
        throw new IOException("Error starting shell", e);
    }
}
 
Example #5
Source File: ApexCli.java    From Bats with Apache License 2.0 6 votes vote down vote up
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
  if (currentApp == null) {
    throw new CliException("No application selected");
  }
  StramAgent.StramUriSpec uriSpec = new StramAgent.StramUriSpec();
  uriSpec = uriSpec.path(StramWebServices.PATH_LOGICAL_PLAN_OPERATORS).path(URLEncoder.encode(args[1], "UTF-8")).path("attributes");
  if (args.length > 2) {
    uriSpec = uriSpec.queryParam("attributeName", args[2]);
  }
  try {
    JSONObject response = getResource(uriSpec, currentApp);
    printJson(response);
  } catch (Exception e) {
    throw new CliException("Failed web service request for appid " + currentApp.getApplicationId().toString(), e);
  }
}
 
Example #6
Source File: ApexCli.java    From Bats with Apache License 2.0 6 votes vote down vote up
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
  if (currentApp == null) {
    throw new CliException("No application selected");
  }
  StramAgent.StramUriSpec uriSpec = new StramAgent.StramUriSpec();
  uriSpec = uriSpec.path(StramWebServices.PATH_LOGICAL_PLAN).path("attributes");
  if (args.length > 1) {
    uriSpec = uriSpec.queryParam("attributeName", args[1]);
  }
  try {
    JSONObject response = getResource(uriSpec, currentApp);
    printJson(response);
  } catch (Exception e) {
    throw new CliException("Failed web service request for appid " + currentApp.getApplicationId().toString(), e);
  }
}
 
Example #7
Source File: Main.java    From incubator-retired-blur with Apache License 2.0 6 votes vote down vote up
@Override
public void doit(PrintWriter out, Blur.Iface client, String[] args) throws CommandException, TException,
    BlurException {
  ConsoleReader reader = getConsoleReader();
  if (reader != null) {
    try {
      reader.setPrompt("");
      reader.clearScreen();
    } catch (IOException e) {
      if (debug) {
        e.printStackTrace();
      }
      throw new CommandException(e.getMessage());
    }
  }
}
 
Example #8
Source File: HeroicInteractiveShell.java    From heroic with Apache License 2.0 6 votes vote down vote up
public static HeroicInteractiveShell buildInstance(
    final List<CommandDefinition> commands, FileInputStream input
) throws Exception {
    final ConsoleReader reader = new ConsoleReader("heroicsh", input, System.out, null);

    final FileHistory history = setupHistory(reader);

    if (history != null) {
        reader.setHistory(history);
    }

    reader.setPrompt(String.format("heroic> "));
    reader.addCompleter(new StringsCompleter(
        ImmutableList.copyOf(commands.stream().map((d) -> d.getName()).iterator())));
    reader.setHandleUserInterrupt(true);

    return new HeroicInteractiveShell(reader, commands, history);
}
 
Example #9
Source File: WatchCommands.java    From incubator-retired-blur with Apache License 2.0 6 votes vote down vote up
@Override
public void doit(PrintWriter out, Blur.Iface client, String[] args) throws CommandException, TException,
    BlurException {
  ConsoleReader reader = this.getConsoleReader();
  try {
    doitInternal(client, reader);
  } catch (IOException e) {
    if (Main.debug) {
      e.printStackTrace();
    }
    throw new CommandException(e.getMessage());
  } finally {
    if (reader != null) {
      reader.setPrompt(Main.PROMPT);
    }
  }
}
 
Example #10
Source File: ApexCli.java    From Bats with Apache License 2.0 6 votes vote down vote up
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
  String files = expandCommaSeparatedFiles(args[1]);
  if (files == null) {
    throw new CliException("File " + args[1] + " is not found");
  }
  String[] jarFiles = files.split(",");
  File tmpDir = copyToLocal(jarFiles);
  try {
    OperatorDiscoverer operatorDiscoverer = new OperatorDiscoverer(jarFiles);
    Class<? extends Operator> operatorClass = operatorDiscoverer.getOperatorClass(args[2]);
    printJson(operatorDiscoverer.describeOperator(operatorClass.getName()));
  } finally {
    FileUtils.deleteDirectory(tmpDir);
  }
}
 
Example #11
Source File: ApexCli.java    From attic-apex-core with Apache License 2.0 6 votes vote down vote up
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
  ApplicationReport appReport = currentApp;
  String target = args[1];
  String logLevel = args[2];

  StramAgent.StramUriSpec uriSpec = new StramAgent.StramUriSpec();
  uriSpec = uriSpec.path(StramWebServices.PATH_LOGGERS);
  final JSONObject request = buildRequest(target, logLevel);

  JSONObject response = getResource(uriSpec, appReport, new WebServicesClient.WebServicesHandler<JSONObject>()
  {
    @Override
    public JSONObject process(WebResource.Builder webResource, Class<JSONObject> clazz)
    {
      return webResource.accept(MediaType.APPLICATION_JSON).post(JSONObject.class, request);
    }

  });

  printJson(response);
}
 
Example #12
Source File: ApexCli.java    From attic-apex-core with Apache License 2.0 6 votes vote down vote up
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
  if (currentApp == null) {
    throw new CliException("No application selected");
  }
  if (!NumberUtils.isDigits(args[1])) {
    throw new CliException("Operator ID must be a number");
  }
  StramAgent.StramUriSpec uriSpec = new StramAgent.StramUriSpec();
  uriSpec = uriSpec.path(StramWebServices.PATH_PHYSICAL_PLAN_OPERATORS).path(args[1]).path("properties");
  final JSONObject request = new JSONObject();
  request.put(args[2], args[3]);
  JSONObject response = getResource(uriSpec, currentApp, new WebServicesClient.WebServicesHandler<JSONObject>()
  {
    @Override
    public JSONObject process(WebResource.Builder webResource, Class<JSONObject> clazz)
    {
      return webResource.accept(MediaType.APPLICATION_JSON).post(JSONObject.class, request);
    }

  });
  printJson(response);

}
 
Example #13
Source File: CommandReader.java    From Jupiter with GNU General Public License v3.0 6 votes vote down vote up
public CommandReader() {
    if (instance != null) {
        throw new RuntimeException("CommandReader is already initialized!");
    }
    try {
        this.reader = new ConsoleReader();
        reader.setPrompt("> ");
        instance = this;
        
        reader.addCompleter(new PlayersCompleter()); // Add player TAB completer
        reader.addCompleter(new CommandsCompleter()); // Add command TAB completer
    } catch (IOException e) {
        Server.getInstance().getLogger().error("Unable to start CommandReader", e);
    }
    this.setName("Console");
}
 
Example #14
Source File: Util.java    From ecosys with Apache License 2.0 5 votes vote down vote up
/**
 * function to generate a prompt for user to input username
 * @param doubleCheck, notes whether the password should be confirmed one more time.
 * @param isNew, indicates whether it is inputting a new password
 * @return SHA-1 hashed password on success, null on error
 */
public static String Prompt4Password(boolean doubleCheck, boolean isNew, String username) {
  String ANSI_BLUE = "\u001B[1;34m";
  String ANSI_RESET = "\u001B[0m";
  String pass = null;
  try {
    ConsoleReader tempConsole = new ConsoleReader();
    String prompttext = isNew ? "New Password : " : "Password for " + username + " : ";
    String prompt = ANSI_BLUE + prompttext + ANSI_RESET;
    tempConsole.setPrompt(prompt);
    tempConsole.setExpandEvents(false);
    String pass1 = tempConsole.readLine(new Character('*'));
    if (doubleCheck) {
      String pass2 = pass1;
      prompt = ANSI_BLUE + "Re-enter Password : " + ANSI_RESET;
      tempConsole.setPrompt(prompt);
      pass2 = tempConsole.readLine(new Character('*'));
      if (!pass1.equals(pass2)) {
        System.out.println("The two passwords do not match.");
        return null;
      }
    }
    // need to hash the password so that we do not store it as plain text
    pass = pass1;
  } catch (Exception e) {
    LogExceptions(e);
    System.out.println("Error while inputting password.");
  }
  return pass;
}
 
Example #15
Source File: CloudConfig.java    From CloudNet with Apache License 2.0 5 votes vote down vote up
public CloudConfig(ConsoleReader consoleReader) throws Exception {

        for (File directory : new File[] {new File("local/servers"), new File("local/templates"), new File("local/plugins"), new File(
            "local/servers"), new File("local/cache"), new File("groups"), new File("modules")}) {
            directory.mkdirs();
        }

        NetworkUtils.writeWrapperKey();

        defaultInit(consoleReader);
        defaultInitDoc(consoleReader);
        defaultInitUsers(consoleReader);
        load();
    }
 
Example #16
Source File: ConsoleIOContext.java    From try-artifact with GNU General Public License v2.0 5 votes vote down vote up
@Override
public FixResult compute(TryJShellTool repl, String code, int cursor) {
    QualifiedNames res = repl.analysis.listQualifiedNames(code, cursor);
    List<Fix> fixes = new ArrayList<>();
    for (String fqn : res.getNames()) {
        fixes.add(new Fix() {
            @Override
            public String displayName() {
                return "import: " + fqn;
            }
            @Override
            public void perform(ConsoleReader in) throws IOException {
                repl.state.eval("import " + fqn + ";");
                in.println("Imported: " + fqn);
                in.redrawLine();
            }
        });
    }
    if (res.isResolvable()) {
        return new FixResult(Collections.emptyList(),
                "\nThe identifier is resolvable in this context.");
    } else {
        String error = "";
        if (fixes.isEmpty()) {
            error = "\nNo candidate fully qualified names found to import.";
        }
        if (!res.isUpToDate()) {
            error += "\nResults may be incomplete; try again later for complete results.";
        }
        return new FixResult(fixes, error);
    }
}
 
Example #17
Source File: SetupSpigotVersion.java    From CloudNet with Apache License 2.0 5 votes vote down vote up
private boolean install(ConsoleReader reader, String spigotType) {
    switch (spigotType) {
        case "spigot":
            return this.installSpigot(reader);
        case "buildtools":
            return SpigotBuilder.start(reader, this.getTarget());
        case "paper":
            return PaperBuilder.start(reader, this.getTarget());
    }
    return false;
}
 
Example #18
Source File: Main.java    From incubator-retired-blur with Apache License 2.0 5 votes vote down vote up
private static void setPrompt(Iface client, ConsoleReader reader, PrintWriter out) throws BlurException, TException,
    CommandException, IOException {
  List<String> shardClusterList;
  try {
    shardClusterList = client.shardClusterList();
  } catch (BlurException e) {
    out.println("Unable to retrieve cluster information - " + e.getMessage());
    out.flush();
    if (debug) {
      e.printStackTrace(out);
    }
    System.exit(1);
    throw e; // will never be called
  }
  String currentPrompt = reader.getPrompt();
  String prompt;
  if (shardClusterList.size() == 1) {
    prompt = "blur (" + getCluster(client) + ")> ";
  } else if (cluster == null) {
    prompt = PROMPT;
  } else {
    prompt = "blur (" + cluster + ")> ";
  }
  if (currentPrompt == null || !currentPrompt.equals(prompt)) {
    reader.setPrompt(prompt);
  }
}
 
Example #19
Source File: CommandReader.java    From BukkitPE with GNU General Public License v3.0 5 votes vote down vote up
public CommandReader() {
    if (instance != null) {
        throw new RuntimeException("Command Reader is already exist");
    }
    try {
        this.reader = new ConsoleReader();
        reader.setPrompt("> ");
        instance = this;
    } catch (IOException e) {
        Server.getInstance().getLogger().error("Unable to start Console Reader", e);
    }
    this.setName("Console");
}
 
Example #20
Source File: CloudLogger.java    From CloudNet with Apache License 2.0 5 votes vote down vote up
/**
 * Constructs a new cloud logger instance that handles logging messages from
 * all sources in an asynchronous matter.
 *
 * @throws IOException            when creating directories or files in {@code local/}
 *                                was not possible
 * @throws NoSuchFieldException   when the default charset could not be set
 * @throws IllegalAccessException when the default charset could not be set
 */
public CloudLogger() throws IOException, NoSuchFieldException, IllegalAccessException {
    super("CloudNetServerLogger", null);
    Field field = Charset.class.getDeclaredField("defaultCharset");
    field.setAccessible(true);
    field.set(null, StandardCharsets.UTF_8);

    if (!Files.exists(Paths.get("local"))) {
        Files.createDirectory(Paths.get("local"));
    }
    if (!Files.exists(Paths.get("local", "logs"))) {
        Files.createDirectory(Paths.get("local", "logs"));
    }

    setLevel(Level.ALL);

    this.reader = new ConsoleReader(System.in, System.out);
    this.reader.setExpandEvents(false);

    FileHandler fileHandler = new FileHandler("local/logs/cloudnet.log", 8000000, 8, true);
    fileHandler.setEncoding(StandardCharsets.UTF_8.name());
    fileHandler.setFormatter(new LoggingFormatter());

    addHandler(fileHandler);

    LoggingHandler loggingHandler = new LoggingHandler();
    loggingHandler.setFormatter(formatter);
    loggingHandler.setEncoding(StandardCharsets.UTF_8.name());
    loggingHandler.setLevel(Level.INFO);
    addHandler(loggingHandler);

    System.setOut(new AsyncPrintStream(new LoggingOutputStream(Level.INFO)));
    System.setErr(new AsyncPrintStream(new LoggingOutputStream(Level.SEVERE)));

    this.reader.setPrompt(NetworkUtils.EMPTY_STRING);
    this.reader.resetPromptLine(NetworkUtils.EMPTY_STRING, "", 0);
}
 
Example #21
Source File: ApexCli.java    From attic-apex-core with Apache License 2.0 5 votes vote down vote up
private String readLine(ConsoleReader reader)
  throws IOException
{
  if (forcePrompt == null) {
    prompt = "";
    if (consolePresent) {
      if (changingLogicalPlan) {
        prompt = "logical-plan-change";
      } else {
        prompt = "apex";
      }
      if (currentApp != null) {
        prompt += " (";
        prompt += currentApp.getApplicationId().toString();
        prompt += ") ";
      }
      prompt += "> ";
    }
  } else {
    prompt = forcePrompt;
  }
  String line = reader.readLine(prompt, consolePresent ? null : (char)0);
  if (line == null) {
    return null;
  }
  return ltrim(line);
}
 
Example #22
Source File: WorfInteractive.java    From warp10-platform with Apache License 2.0 5 votes vote down vote up
private static String readInputString(ConsoleReader reader, PrintWriter out, String prompt, String defaultString) {
  try {
    // save file
    StringBuilder sb = new StringBuilder("warp10:");
    sb.append(prompt);
    if (!Strings.isNullOrEmpty(defaultString)) {
      sb.append(", default(");
      sb.append(defaultString);
      sb.append(")");
    }
    sb.append(">");
    reader.setPrompt(sb.toString());
    String line;
    while ((line = reader.readLine()) != null) {
      line = line.trim();
      if (Strings.isNullOrEmpty(line) && Strings.isNullOrEmpty(defaultString)) {
        continue;
      }
      if (Strings.isNullOrEmpty(line) && !Strings.isNullOrEmpty(defaultString)) {
        return defaultString;
      }
      if (line.equalsIgnoreCase("cancel")) {
        break;
      }
      return line;
    }
  } catch (Exception exp) {
    if (WorfCLI.verbose) {
      exp.printStackTrace();
    }
    out.println("Error, unable to read the string. error=" + exp.getMessage());
  }
  return null;

}
 
Example #23
Source File: HeroicInteractiveShell.java    From heroic with Apache License 2.0 5 votes vote down vote up
@java.beans.ConstructorProperties({ "reader", "commands", "history" })
public HeroicInteractiveShell(final ConsoleReader reader,
                              final List<CommandDefinition> commands,
                              final FileHistory history) {
    this.reader = reader;
    this.commands = commands;
    this.history = history;
}
 
Example #24
Source File: WorfInteractive.java    From warp10-platform with Apache License 2.0 5 votes vote down vote up
public WorfInteractive() throws WorfException {
  try {
    reader = new ConsoleReader();
    out = new PrintWriter(reader.getOutput());
    out.println("Welcome to warp10 token command line");
    out.println("I am Worf, security chief of the USS Enterprise (NCC-1701-D)");

  } catch (IOException e) {
    throw new WorfException("Unexpected Worf error:" + e.getMessage());
  }
}
 
Example #25
Source File: InstallPrompt.java    From rya with Apache License 2.0 5 votes vote down vote up
/**
 * Prompt the user asking them if they are sure they would like to do the
 * install.
 *
 * @param instanceName - The Rya instance name. (not null)
 * @param installConfig - The configuration that will be presented to the user. (not null)
 * @return The value they entered.
 * @throws IOException There was a problem reading the value.
 */
private boolean promptAccumuloVerified(final String instanceName, final InstallConfiguration installConfig)  throws IOException {
    requireNonNull(instanceName);
    requireNonNull(installConfig);

    final ConsoleReader reader = getReader();
    reader.println();
    reader.println("A Rya instance will be installed using the following values:");
    reader.println("   Instance Name: " + instanceName);
    reader.println("   Use Shard Balancing: " + installConfig.isTableHashPrefixEnabled());
    reader.println("   Use Entity Centric Indexing: " + installConfig.isEntityCentrixIndexEnabled());
    reader.println("   Use Free Text Indexing: " + installConfig.isFreeTextIndexEnabled());
    // RYA-215            reader.println("   Use Geospatial Indexing: " + installConfig.isGeoIndexEnabled());
    reader.println("   Use Temporal Indexing: " + installConfig.isTemporalIndexEnabled());
    reader.println("   Use Precomputed Join Indexing: " + installConfig.isPcjIndexEnabled());
    if(installConfig.isPcjIndexEnabled()) {
        if(installConfig.getFluoPcjAppName().isPresent()) {
            reader.println("   PCJ Updater Fluo Application Name: " + installConfig.getFluoPcjAppName().get());
        } else {
            reader.println("   Not using a PCJ Updater Fluo Application");
        }
    }

    reader.println("");

    return promptBoolean("Continue with the install? (y/n) ", Optional.absent());
}
 
Example #26
Source File: ApexCli.java    From Bats with Apache License 2.0 5 votes vote down vote up
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
  String[] tmpArgs = new String[args.length - 2];
  System.arraycopy(args, 2, tmpArgs, 0, args.length - 2);
  GetAppPackageInfoCommandLineInfo commandLineInfo = getGetAppPackageInfoCommandLineInfo(tmpArgs);
  try (AppPackage ap = newAppPackageInstance(new URI(args[1]), true)) {
    JSONSerializationProvider jomp = new JSONSerializationProvider();
    jomp.addSerializer(PropertyInfo.class,
        new AppPackage.PropertyInfoSerializer(commandLineInfo.provideDescription));
    JSONObject apInfo = new JSONObject(jomp.getContext(null).writeValueAsString(ap));
    apInfo.remove("name");
    printJson(apInfo);
  }
}
 
Example #27
Source File: ConsoleUtil.java    From reactive-grpc with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static CursorBuffer stashLine(ConsoleReader console) {
    CursorBuffer stashed = console.getCursorBuffer().copy();
    try {
        console.getOutput().write("\u001b[1G\u001b[K");
        console.flush();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return stashed;
}
 
Example #28
Source File: ApexCli.java    From Bats with Apache License 2.0 5 votes vote down vote up
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
  printJson(logicalPlanRequestQueue, "queue");
  if (consolePresent) {
    System.out.println("Total operations in queue: " + logicalPlanRequestQueue.size());
  }
}
 
Example #29
Source File: ConsoleUtil.java    From reactive-grpc with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static CursorBuffer stashLine(ConsoleReader console) {
    CursorBuffer stashed = console.getCursorBuffer().copy();
    try {
        console.getOutput().write("\u001b[1G\u001b[K");
        console.flush();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return stashed;
}
 
Example #30
Source File: MacroBaseSQLRepl.java    From macrobase with Apache License 2.0 5 votes vote down vote up
/**
 * Main entry point to the SQL CLI interface in MacroBase
 *
 * @param userWantsPaging try to enable paging of results in SQL shell
 * @throws IOException if unable to instantiate ConsoleReader
 */
private MacroBaseSQLRepl(final boolean userWantsPaging) throws IOException {
    // First try to turn paging on
    this.paging = enablePaging(userWantsPaging);
    // Initialize console reader and writer
    reader = new ConsoleReader();
    final CandidateListCompletionHandler handler = new CandidateListCompletionHandler();
    handler.setStripAnsi(true);
    reader.setCompletionHandler(handler);
    reader.addCompleter(new FileNameCompleter());

    parser = new SqlParser();
    queryEngine = new QueryEngine();
}