jline.console.completer.StringsCompleter Java Examples

The following examples show how to use jline.console.completer.StringsCompleter. 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: CmdlineHelper.java    From clue with Apache License 2.0 7 votes vote down vote up
public CmdlineHelper(Supplier<Collection<String>> commandNameSupplier,
                     Supplier<Collection<String>> fieldNameSupplier) throws IOException {
    consoleReader = new ConsoleReader();
    consoleReader.setBellEnabled(false);

    Collection<String> commands = commandNameSupplier != null
            ? commandNameSupplier.get() : Collections.emptyList();

    Collection<String> fields = fieldNameSupplier != null
            ? fieldNameSupplier.get() : Collections.emptyList();

    LinkedList<Completer> completors = new LinkedList<Completer>();
    completors.add(new StringsCompleter(commands));
    completors.add(new StringsCompleter(fields));
    completors.add(new FileNameCompleter());
    consoleReader.addCompleter(new ArgumentCompleter(completors));
}
 
Example #2
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 #3
Source File: TajoShellCommand.java    From tajo with Apache License 2.0 5 votes vote down vote up
@Override
public int complete(String s, int i, List<CharSequence> list) {
  List<CatalogProtos.FunctionDescProto> functionProtos = client.getFunctions("");
  if (functionProtos.isEmpty()) {
    return -1;
  }

  List<String> names = functionProtos.stream().map(
      (proto) -> proto.getSignature().getName()).collect(Collectors.toList());

  return new StringsCompleter(names.toArray(new String [1])).complete(s, i, list);
}
 
Example #4
Source File: ClueCommandClient.java    From clue with Apache License 2.0 5 votes vote down vote up
public void run() throws Exception {
    ConsoleReader consoleReader = new ConsoleReader();
    consoleReader.setBellEnabled(false);

    Collection<String> commands = getCommands();

    LinkedList<Completer> completors = new LinkedList<Completer>();
    completors.add(new StringsCompleter(commands));

    completors.add(new FileNameCompleter());

    consoleReader.addCompleter(new ArgumentCompleter(completors));



    while(true){
        String line = readCommand();
        if (line == null || line.isEmpty()) continue;
        line = line.trim();
        if ("exit".equals(line)) {
            System.exit(0);
        }
        String[] parts = line.split("\\s");
        if (parts.length > 0){
            String cmd = parts[0];
            String[] cmdArgs = new String[parts.length - 1];
            System.arraycopy(parts, 1, cmdArgs, 0, cmdArgs.length);
            handleCommand(cmd, cmdArgs, System.out);
        }
    }
}
 
Example #5
Source File: Terminal.java    From cloudml with GNU Lesser General Public License v3.0 5 votes vote down vote up
private List<Completer> selectCompleters() {
    final List<Completer> selection = new ArrayList<Completer>();
    for (Command eachCommand: configuration.getCommands()) {
        selection.add(new StringsCompleter(eachCommand.getSyntax()));
    }
    selection.add(new FileNameCompleter());
    return selection;
}
 
Example #6
Source File: CommandCompleter.java    From attic-stratos with Apache License 2.0 5 votes vote down vote up
public CommandCompleter(Map<String, Command<StratosCommandContext>> commands) {
    if (logger.isDebugEnabled()) {
        logger.debug("Creating auto complete for {} commands", commands.size());
    }
    fileNameCompleter = new StratosFileNameCompleter();
    argumentMap = new HashMap<String, Collection<String>>();
    defaultCommandCompleter = new StringsCompleter(commands.keySet());
    helpCommandCompleter = new ArgumentCompleter(new StringsCompleter(CliConstants.HELP_ACTION),
            defaultCommandCompleter);
    for (String action : commands.keySet()) {

        Command<StratosCommandContext> command = commands.get(action);
        Options commandOptions = command.getOptions();
        if (commandOptions != null) {
            if (logger.isDebugEnabled()) {
                logger.debug("Creating argument completer for command: {}", action);
            }
            List<String> arguments = new ArrayList<String>();
            Collection<?> allOptions = commandOptions.getOptions();
            for (Object o : allOptions) {
                Option option = (Option) o;
                String longOpt = option.getLongOpt();
                String opt = option.getOpt();
                if (StringUtils.isNotBlank(longOpt)) {
                    arguments.add("--" + longOpt);
                } else if (StringUtils.isNotBlank(opt)) {
                    arguments.add("-" + opt);
                }
            }

            argumentMap.put(action, arguments);
        }
    }
}
 
Example #7
Source File: CmdUtilTest.java    From clamshell-cli with Apache License 2.0 5 votes vote down vote up
public void testGetHintsAsCompleters() {
    List<Command> cmds = new ArrayList<Command>();
    cmds.add(new MockCommand());
    Map<String, List<String>> hints = CmdUtil.extractCommandHints(cmds);
    List<Completer> completers = CmdUtil.getHintsAsCompleters(hints);
    
    Assert.assertNotNull(completers);
    Assert.assertTrue(completers.size() == 1);
    
    StringsCompleter strComp = (StringsCompleter) completers.get(0);
    Assert.assertTrue(strComp.getStrings().size() == 8); // cmd + args
}
 
Example #8
Source File: CmdUtil.java    From clamshell-cli with Apache License 2.0 5 votes vote down vote up
/**
 * Builds a list of jLine completers using the hints map from {@link extractCommandHints}
 * @param hints
 * @return 
 */
public static List<Completer> getHintsAsCompleters(Map<String,List<String>> hints) {
    List<Completer> completors = new ArrayList<Completer>(hints.size());
    for (Map.Entry<String, List<String>> hint : hints.entrySet()){
        List<String> argList = hint.getValue();
        argList.add(0, hint.getKey());
        completors.add(new StringsCompleter(argList));
    }
    return completors;
}
 
Example #9
Source File: TajoCli.java    From tajo with Apache License 2.0 5 votes vote down vote up
private void initCommands() {
  List<Completer> compList = new ArrayList<>();
  for (Class clazz : registeredCommands) {
    TajoShellCommand cmd = null;

    try {
       Constructor cons = clazz.getConstructor(new Class[] {TajoCliContext.class});
       cmd = (TajoShellCommand) cons.newInstance(context);
    } catch (Exception e) {
      System.err.println(e.getMessage());
      throw new RuntimeException(e.getMessage());
    }

    // make completers for console auto-completion
    compList.add(cmd.getArgumentCompleter());

    commands.put(cmd.getCommand(), cmd);
    for (String alias : cmd.getAliases()) {
      commands.put(alias, cmd);
    }
  }

  cliCompleter = new AggregateCompleter(compList);

  sqlCompleter = new ArgumentCompleter(
      new ArgumentCompleter.AbstractArgumentDelimiter() {
        @Override
        public boolean isDelimiterChar(CharSequence buf, int pos) {
          char c = buf.charAt(pos);
          return Character.isWhitespace(c) || !(Character.isLetterOrDigit(c)) && c != '_';
        }
      },
      new StringsCompleter(getKeywords())
  );
}
 
Example #10
Source File: DescFunctionCommand.java    From tajo with Apache License 2.0 5 votes vote down vote up
@Override
public ArgumentCompleter getArgumentCompleter() {
  return new ArgumentCompleter(
      new StringsCompleter(getCommand()),
      new FunctionNameCompleter(),
      NullCompleter.INSTANCE);
}
 
Example #11
Source File: HelpCommand.java    From tajo with Apache License 2.0 5 votes vote down vote up
@Override
public ArgumentCompleter getArgumentCompleter() {
  List<String> cmds = new ArrayList<>(Arrays.asList(getAliases()));
  cmds.add(getCommand());

  return new ArgumentCompleter(
      new StringsCompleter(cmds.toArray(new String[cmds.size()])),
      new StringsCompleter("copyright", "version", "?", "help", "q", "l", "c", "d", "df", "!", "dfs", "admin",
          "set", "unset", "haadmin", "getconf"), // same order as help string
      NullCompleter.INSTANCE);
}
 
Example #12
Source File: ConnectDatabaseCommand.java    From tajo with Apache License 2.0 5 votes vote down vote up
@Override
public ArgumentCompleter getArgumentCompleter() {
  return new ArgumentCompleter(
      new StringsCompleter(getCommand()),
      new DbNameCompleter(),
      NullCompleter.INSTANCE);
}
 
Example #13
Source File: CompleterTest.java    From enkan with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void testStringsCompleter() {
    StringsCompleter completer = new StringsCompleter("abc", "abd", "ac");
    List<CharSequence> candidates = new ArrayList<>();
    completer.complete("a", 1, candidates);
    System.out.println(candidates);
    candidates.clear();
    completer.complete("ab", 2, candidates);
    System.out.println(candidates);
}
 
Example #14
Source File: TajoShellCommand.java    From tajo with Apache License 2.0 5 votes vote down vote up
@Override
public int complete(String s, int i, List<CharSequence> list) {
  List<String> tableList = client.getTableList(client.getCurrentDatabase());

  if (tableList.isEmpty()) {
    return -1;
  }

  return new StringsCompleter(tableList.toArray(new String[1])).complete(s, i, list);
}
 
Example #15
Source File: TajoGetConfCommand.java    From tajo with Apache License 2.0 5 votes vote down vote up
@Override
public ArgumentCompleter getArgumentCompleter() {
  TajoConf.ConfVars[] vars = TajoConf.ConfVars.values();
  List<String> confNames = new ArrayList<>();

  for(TajoConf.ConfVars varname: vars) {
    confNames.add(varname.varname);
  }

  return new ArgumentCompleter(
      new StringsCompleter(getCommand()),
      new ConfCompleter(confNames.toArray(new String[confNames.size()])),
      NullCompleter.INSTANCE);
}
 
Example #16
Source File: SetCommand.java    From tajo with Apache License 2.0 5 votes vote down vote up
@Override
public ArgumentCompleter getArgumentCompleter() {
  return new ArgumentCompleter(
      new StringsCompleter(getCommand()),
      new SessionVarCompleter(),
      NullCompleter.INSTANCE);
}
 
Example #17
Source File: DescTableCommand.java    From tajo with Apache License 2.0 5 votes vote down vote up
@Override
public ArgumentCompleter getArgumentCompleter() {
  return new ArgumentCompleter(
      new StringsCompleter(getCommand()),
      new TableNameCompleter(),
      NullCompleter.INSTANCE);
}
 
Example #18
Source File: UnsetCommand.java    From tajo with Apache License 2.0 5 votes vote down vote up
@Override
public ArgumentCompleter getArgumentCompleter() {
  return new ArgumentCompleter(
      new StringsCompleter(getCommand()),
      new SessionVarCompleter(),
      NullCompleter.INSTANCE);
}
 
Example #19
Source File: TajoShellCommand.java    From tajo with Apache License 2.0 4 votes vote down vote up
@Override
public int complete(String s, int i, List<CharSequence> list) {
  return new StringsCompleter(client.getAllDatabaseNames().toArray(new String[1]))
      .complete(s, i, list);
}
 
Example #20
Source File: TajoShellCommand.java    From tajo with Apache License 2.0 4 votes vote down vote up
@Override
public int complete(String s, int i, List<CharSequence> list) {
  return new StringsCompleter(client.getAllSessionVariables().keySet().toArray(new String[1]))
      .complete(s, i, list);

}
 
Example #21
Source File: TajoShellCommand.java    From tajo with Apache License 2.0 4 votes vote down vote up
public ArgumentCompleter getArgumentCompleter() {
  List<String> cmds = new ArrayList<>(Arrays.asList(getAliases()));
  cmds.add(getCommand());

  return new ArgumentCompleter(new StringsCompleter(cmds.toArray(new String[cmds.size()])), NullCompleter.INSTANCE);
}
 
Example #22
Source File: CommandCompleter.java    From attic-stratos with Apache License 2.0 4 votes vote down vote up
@Override
public int complete(String buffer, int cursor, List<CharSequence> candidates) {

    if (buffer.contains(CliConstants.RESOURCE_PATH_LONG_OPTION)) {
        return fileNameCompleter.complete(buffer, cursor, candidates);
    }
    if (logger.isTraceEnabled()) {
        logger.trace("Buffer: {}, cursor: {}", buffer, cursor);
        logger.trace("Candidates {}", candidates);
    }
    if (StringUtils.isNotBlank(buffer)) {
        // User is typing a command
        StrTokenizer strTokenizer = new StrTokenizer(buffer);
        String action = strTokenizer.next();
        Collection<String> arguments = argumentMap.get(action);
        if (arguments != null) {
            if (logger.isTraceEnabled()) {
                logger.trace("Arguments found for {}, Tokens: {}", action, strTokenizer.getTokenList());
                logger.trace("Arguments for {}: {}", action, arguments);
            }
            List<String> args = new ArrayList<String>(arguments);
            List<Completer> completers = new ArrayList<Completer>();
            for (String token : strTokenizer.getTokenList()) {
                boolean argContains = arguments.contains(token);
                if (token.startsWith("-") && !argContains) {
                    continue;
                }
                if (argContains) {
                    if (logger.isTraceEnabled()) {
                        logger.trace("Removing argument {}", token);
                    }
                    args.remove(token);
                }
                completers.add(new StringsCompleter(token));
            }
            completers.add(new StringsCompleter(args));
            Completer completer = new ArgumentCompleter(completers);
            return completer.complete(buffer, cursor, candidates);
        } else if (CliConstants.HELP_ACTION.equals(action)) {
            // For help action, we need to display available commands as arguments
            return helpCommandCompleter.complete(buffer, cursor, candidates);
        }
    }
    if (logger.isTraceEnabled()) {
        logger.trace("Using Default Completer...");
    }
    return defaultCommandCompleter.complete(buffer, cursor, candidates);
}
 
Example #23
Source File: PromptBuilderTest.java    From consoleui with Apache License 2.0 4 votes vote down vote up
@Test
public void testBuilder() throws Exception {
  ConsolePrompt prompt = new ConsolePrompt();
  PromptBuilder promptBuilder = prompt.getPromptBuilder();

  promptBuilder.createConfirmPromp()
          .name("wantapizza")
          .message("Do you want to order a pizza?")
          .defaultValue(ConfirmChoice.ConfirmationValue.YES)
          .addPrompt();

  promptBuilder.createInputPrompt()
          .name("name")
          .message("Please enter your name")
          .defaultValue("John Doe")
          .addCompleter(new StringsCompleter("Jim", "Jack", "John"))
          .addPrompt();

  promptBuilder.createListPrompt()
          .name("pizzatype")
          .message("Which pizza do you want?")
          .newItem().text("Margherita").add()  // without name (name defaults to text)
          .newItem("veneziana").text("Veneziana").add()
          .newItem("hawai").text("Hawai").add()
          .newItem("quattro").text("Quattro Stagioni").add()
          .addPrompt();

  promptBuilder.createCheckboxPrompt()
          .name("topping")
          .message("Please select additional toppings:")

          .newSeparator("standard toppings")
          .add()

          .newItem().name("cheese").text("Cheese").add()
          .newItem("bacon").text("Bacon").add()
          .newItem("onions").text("Onions").disabledText("Sorry. Out of stock.").add()

          .newSeparator().text("special toppings").add()

          .newItem("salami").text("Very hot salami").check().add()
          .newItem("salmon").text("Smoked Salmon").add()

          .newSeparator("and our speciality...").add()

          .newItem("special").text("Anchovies, and olives").checked(true).add()
          .addPrompt();

  assertNotNull(promptBuilder);
  promptBuilder.createChoicePrompt()
          .name("payment")
          .message("How do you want to pay?")

          .newItem().name("cash").message("Cash").key('c').asDefault().add()
          .newItem("visa").message("Visa Card").key('v').add()
          .newItem("master").message("Master Card").key('m').add()
          .newSeparator("online payment").add()
          .newItem("paypal").message("Paypal").key('p').add()
          .addPrompt();

  List<PromptableElementIF> promptableElementList = promptBuilder.build();

  // only for test. reset the default reader to a test reader to automate the input
  //promptableElementList.get(0)

  //HashMap<String, Object> result = prompt.prompt(promptableElementList);

}