예제 #1
0
  public void refreshCommands() {
    for (Object c : new ArrayList(reader.getCompletors())) {
      reader.removeCompletor((Completor) c);
    }

    Completor[] list =
        new Completor[] {new SimpleCompletor(server.getAllCommands()), new NullCompletor()};
    reader.addCompletor(new ArgumentCompletor(list));
    sender.recalculatePermissions();
  }
예제 #2
0
  @SuppressWarnings("unchecked")
  void run() throws IOException {
    inConsole = true;
    myCommands = buildMyCommands();
    if (cl.getCommand() == null) {
      System.out.println("Welcome to Hedwig!");
      System.out.println("JLine support is enabled");

      console = new ConsoleReader();
      JLineHedwigCompletor completor = new JLineHedwigCompletor(admin);
      console.addCompletor(completor);

      // load history file
      History history = new History();
      File file =
          new File(
              System.getProperty(
                  "hw.history",
                  new File(System.getProperty("user.home"), HW_HISTORY_FILE).toString()));
      if (LOG.isDebugEnabled()) {
        LOG.debug("History file is " + file.toString());
      }
      history.setHistoryFile(file);
      // set history to console reader
      console.setHistory(history);
      // load history from history file
      history.moveToFirstEntry();

      while (history.next()) {
        String entry = history.current();
        if (!entry.equals("")) {
          addToHistory(commandCount, entry);
        }
        commandCount++;
      }
      System.out.println("JLine history support is enabled");

      String line;
      while ((line = console.readLine(getPrompt())) != null) {
        executeLine(line);
        history.addToHistory(line);
      }
    }

    inConsole = false;
    processCmd(cl);
    try {
      myCommands.get(EXIT).runCmd(new String[0]);
    } catch (Exception e) {
    }
  }
예제 #3
0
  public static void main(String[] args) throws Exception {

    final jline.ConsoleReader console = initConsoleReader();

    final CommandContextImpl cmdCtx = new CommandContextImpl(console);
    SecurityActions.addShutdownHook(
        new Thread(
            new Runnable() {
              @Override
              public void run() {
                cmdCtx.disconnectController();
              }
            }));
    console.addCompletor(cmdCtx.cmdCompleter);

    String[] commands = null;
    String fileName = null;
    boolean connect = false;
    for (String arg : args) {
      if (arg.startsWith("controller=")) {
        String value = arg.substring(11);
        String portStr = null;
        int colonIndex = value.indexOf(':');
        if (colonIndex < 0) {
          // default port
          cmdCtx.defaultControllerHost = value;
        } else if (colonIndex == 0) {
          // default host
          portStr = value.substring(1);
        } else {
          cmdCtx.defaultControllerHost = value.substring(0, colonIndex);
          portStr = value.substring(colonIndex + 1);
        }

        if (portStr != null) {
          int port = -1;
          try {
            port = Integer.parseInt(portStr);
            if (port < 0) {
              cmdCtx.printLine("The port must be a valid non-negative integer: '" + args + "'");
            } else {
              cmdCtx.defaultControllerPort = port;
            }
          } catch (NumberFormatException e) {
            cmdCtx.printLine("The port must be a valid non-negative integer: '" + arg + "'");
          }
        }
      } else if ("--connect".equals(arg)) {
        connect = true;
      } else if (arg.startsWith("file=")) {
        fileName = arg.substring(5);
      } else if (arg.startsWith("commands=")) {
        commands = arg.substring(9).split(",+");
      } else if (arg.startsWith("command=")) {
        commands = new String[] {arg.substring(8)};
      }
    }

    if (connect) {
      cmdCtx.connectController(null, -1);
    } else {
      cmdCtx.printLine(
          "You are disconnected at the moment."
              + " Type 'connect' to connect to the server or"
              + " 'help' for the list of supported commands.");
    }

    if (fileName != null && !fileName.isEmpty()) {
      File f = new File(fileName);
      if (!f.exists()) {
        cmdCtx.printLine("File " + f.getAbsolutePath() + " doesn't exist.");
      } else {
        BufferedReader reader = new BufferedReader(new FileReader(f));
        try {
          String line = reader.readLine();
          while (!cmdCtx.terminate && line != null) {
            processLine(cmdCtx, line.trim());
            line = reader.readLine();
          }
        } finally {
          StreamUtils.safeClose(reader);
          if (!cmdCtx.terminate) {
            cmdCtx.terminateSession();
          }
          cmdCtx.disconnectController();
        }
        return;
      }
    }

    if (commands != null) {
      for (int i = 0; i < commands.length && !cmdCtx.terminate; ++i) {
        processLine(cmdCtx, commands[i]);
      }
      if (!cmdCtx.terminate) {
        cmdCtx.terminateSession();
      }
      cmdCtx.disconnectController();
      return;
    }

    try {
      while (!cmdCtx.terminate) {
        String line = console.readLine(cmdCtx.getPrompt()).trim();
        processLine(cmdCtx, line);
      }
    } finally {
      cmdCtx.disconnectController();
    }
  }
예제 #4
0
  public static void main(String[] args) throws Exception {
    OptionsProcessor oproc = new OptionsProcessor();
    if (!oproc.process_stage1(args)) {
      System.exit(1);
    }

    SessionState.initHiveLog4j();

    CliSessionState ss = new CliSessionState(new HiveConf(SessionState.class));
    ss.in = System.in;
    try {
      ss.out = new PrintStream(System.out, true, "UTF-8");
      ss.err = new PrintStream(System.err, true, "UTF-8");
    } catch (UnsupportedEncodingException e) {
      System.exit(3);
    }

    if (!oproc.process_stage2(ss)) {
      System.exit(2);
    }

    HiveConf conf = ss.getConf();
    for (Map.Entry<Object, Object> item : ss.cmdProperties.entrySet()) {
      conf.set((String) item.getKey(), (String) item.getValue());
    }

    if (!ShimLoader.getHadoopShims().usesJobShell()) {
      ClassLoader loader = conf.getClassLoader();
      String auxJars = HiveConf.getVar(conf, HiveConf.ConfVars.HIVEAUXJARS);
      if (StringUtils.isNotBlank(auxJars)) {
        loader = Utilities.addToClassPath(loader, StringUtils.split(auxJars, ","));
      }
      conf.setClassLoader(loader);
      Thread.currentThread().setContextClassLoader(loader);
    }

    SessionState.start(ss);

    CliDriver cli = new CliDriver();

    Hive hive = Hive.get();

    String username = ss.getUserName();
    String passwd = ss.passwd;
    if (!hive.isAUser(username, passwd)) {
      System.out.println("User or passwd is wrong!");
      System.exit(0);
    } else {
      System.out.println("Connect to TDW successfully!");
    }

    if (ss.getDbName() == null) {
      ss.setDbName(MetaStoreUtils.DEFAULT_DATABASE_NAME);
    }
    if (ss.execString != null) {
      System.exit(cli.processLine(ss.execString));
    }

    try {
      if (ss.fileName != null) {
        System.exit(cli.processReader(new BufferedReader(new FileReader(ss.fileName))));
      }
    } catch (FileNotFoundException e) {
      System.err.println("Could not open input file for reading. (" + e.getMessage() + ")");
      System.exit(3);
    }

    ConsoleReader reader = new ConsoleReader();
    reader.setBellEnabled(false);

    List<SimpleCompletor> completors = new LinkedList<SimpleCompletor>();
    completors.add(
        new SimpleCompletor(
            new String[] {"set", "from", "create", "load", "describe", "quit", "exit"}));
    reader.addCompletor(new ArgumentCompletor(completors));

    String line;
    final String HISTORYFILE = ".hivehistory";
    String historyFile = System.getProperty("user.home") + File.separator + HISTORYFILE;
    reader.setHistory(new History(new File(historyFile)));
    int ret = 0;

    String prefix = "";
    String curPrompt = prompt;
    while ((line = reader.readLine(curPrompt + "> ")) != null) {
      if (!prefix.equals("")) {
        prefix += '\n';
      }
      if (line.trim().endsWith(";") && !line.trim().endsWith("\\;")) {
        line = prefix + line;
        ret = cli.processLine(line);
        prefix = "";
        curPrompt = prompt;
      } else {
        prefix = prefix + line;
        curPrompt = prompt2;
        continue;
      }
    }

    System.exit(ret);
  }
예제 #5
0
파일: Main.java 프로젝트: TomGebhardt/k
  // execute krun in debug mode (i.e. step by step execution)
  // isSwitch variable is true if we enter in debug execution from normal
  // execution (we use the search command with --graph option)
  @SuppressWarnings("unchecked")
  public static void debugExecution(
      Term kast,
      String lang,
      KRunResult<SearchResults> state,
      org.kframework.kil.loader.Context context) {
    try {
      // adding autocompletion and history feature to the stepper internal
      // commandline by using the JLine library
      ConsoleReader reader = new ConsoleReader();
      reader.setBellEnabled(false);

      List<Completor> argCompletor = new LinkedList<Completor>();
      argCompletor.add(
          new SimpleCompletor(
              new String[] {
                "help",
                "abort",
                "resume",
                "step",
                "step-all",
                "select",
                "show-search-graph",
                "show-node",
                "show-edge",
                "save",
                "load",
                "read"
              }));
      argCompletor.add(new FileNameCompletor());
      List<Completor> completors = new LinkedList<Completor>();
      completors.add(new ArgumentCompletor(argCompletor));
      reader.addCompletor(new MultiCompletor(completors));

      new File(K.compiled_def + K.fileSeparator + "main.maude").getCanonicalPath();
      RunProcess rp = new RunProcess();
      KRun krun = obtainKRun(context);
      krun.setBackendOption("io", false);
      KRunDebugger debugger;
      try {
        if (state == null) {
          Term t = makeConfiguration(kast, "", rp, (K.term != null), context);
          debugger = krun.debug(t);
          System.out.println("After running one step of execution the result is:");
          AnsiConsole.out.println(debugger.printState(debugger.getCurrentState()));
        } else {
          debugger = krun.debug(state.getResult().getGraph());
        }
      } catch (UnsupportedBackendOptionException e) {
        Error.report("Backend \"" + K.backend + "\" does not support option " + e.getMessage());
        throw e; // unreachable
      }
      while (true) {
        System.out.println();
        String input = reader.readLine("Command > ");
        if (input == null) {
          // probably pressed ^D
          System.out.println();
          System.exit(0);
        }

        // construct the right command line input when we specify the
        // "step" option with an argument (i.e. step=3)
        input = input.trim();
        String[] tokens = input.split(" ");
        // store the tokens that are not a blank space
        List<String> items = new ArrayList<String>();
        for (int i = 0; i < tokens.length; i++) {
          if ((!(tokens[i].equals(" ")) && (!tokens[i].equals("")))) {
            items.add(tokens[i]);
          }
        }
        StringBuilder aux = new StringBuilder();
        // excepting the case of a command like: help
        if (items.size() > 1) {
          for (int i = 0; i < items.size(); i++) {
            if (i > 0) {
              aux.append("=");
              aux.append(items.get(i));
            } else if (i == 0) {
              aux.append(items.get(i));
            }
          }
          input = aux.toString();
        }
        // apply trim to remove possible blank spaces from the inserted
        // command
        String[] cmds = new String[] {"--" + input};
        CommandlineOptions cmd_options = new CommandlineOptions();
        CommandLine cmd = cmd_options.parse(cmds);
        // when an error occurred during parsing the commandline
        // continue the execution of the stepper
        if (cmd == null) {
          continue;
        } else {
          if (cmd.hasOption("help")) {
            printDebugUsage(cmd_options);
          }
          if (cmd.hasOption("abort")) {
            System.exit(0);
          }
          if (cmd.hasOption("resume")) {
            try {
              debugger.resume();
              AnsiConsole.out.println(debugger.printState(debugger.getCurrentState()));
            } catch (IllegalStateException e) {
              Error.silentReport(
                  "Wrong command: If you previously used the step-all command you must"
                      + K.lineSeparator
                      + "seletc first a solution with step command before executing steps of rewrites!");
            }
          }
          // one step execution (by default) or more if you specify an
          // argument
          if (cmd.hasOption("step")) {
            // by default execute only one step at a time
            String arg = new String("1");
            String[] remainingArguments = null;
            remainingArguments = cmd.getArgs();
            if (remainingArguments.length > 0) {
              arg = remainingArguments[0];
            }
            try {
              int steps = Integer.parseInt(arg);
              debugger.step(steps);
              AnsiConsole.out.println(debugger.printState(debugger.getCurrentState()));
            } catch (NumberFormatException e) {
              Error.silentReport("Argument to step must be an integer.");
            } catch (IllegalStateException e) {
              Error.silentReport(
                  "Wrong command: If you previously used the step-all command you must"
                      + K.lineSeparator
                      + "select first a solution with step command before executing steps of rewrites!");
            }
          }
          if (cmd.hasOption("step-all")) {
            // by default compute all successors in one transition
            String arg = new String("1");
            String[] remainingArguments = null;
            remainingArguments = cmd.getArgs();
            if (remainingArguments.length > 0) {
              arg = remainingArguments[0];
            }
            try {
              int steps = Integer.parseInt(arg);
              SearchResults states = debugger.stepAll(steps);
              AnsiConsole.out.println(states);

            } catch (NumberFormatException e) {
              Error.silentReport("Argument to step-all must be an integer.");
            } catch (IllegalStateException e) {
              Error.silentReport(
                  "Wrong command: If you previously used the step-all command you must"
                      + K.lineSeparator
                      + "select first a solution with step command before executing steps of rewrites!");
            }
          }
          // "select n7" or "select 3" are both valid commands
          if (cmd.hasOption("select")) {
            String arg = new String();
            arg = cmd.getOptionValue("select").trim();
            try {
              int stateNum = Integer.parseInt(arg);
              debugger.setCurrentState(stateNum);
              AnsiConsole.out.println(debugger.printState(debugger.getCurrentState()));
            } catch (NumberFormatException e) {
              Error.silentReport("Argument to select must bean integer.");
            } catch (IllegalArgumentException e) {
              System.out.println(
                  "A node with the specified state number could not be found in the"
                      + K.lineSeparator
                      + "search graph");
            }
          }
          if (cmd.hasOption("show-search-graph")) {
            System.out.println(K.lineSeparator + "The search graph is:" + K.lineSeparator);
            System.out.println(debugger.getGraph());
          }
          if (cmd.hasOption("show-node")) {
            String nodeId = cmd.getOptionValue("show-node").trim();
            try {
              int stateNum = Integer.parseInt(nodeId);
              AnsiConsole.out.println(debugger.printState(stateNum));
            } catch (NumberFormatException e) {
              Error.silentReport("Argument to select node to show must be an integer.");
            } catch (IllegalArgumentException e) {
              System.out.println(
                  "A node with the specified state number could not be found in the"
                      + K.lineSeparator
                      + "search graph");
            }
          }
          if (cmd.hasOption("show-edge")) {
            String[] vals = cmd.getOptionValues("show-edge");
            vals = vals[0].split("=", 2);
            try {
              int state1 = Integer.parseInt(vals[0].trim());
              int state2 = Integer.parseInt(vals[1].trim());
              AnsiConsole.out.println(debugger.printEdge(state1, state2));
            } catch (ArrayIndexOutOfBoundsException e) {
              Error.silentReport("Must specify two nodes with an edge between them.");
            } catch (NumberFormatException e) {
              Error.silentReport("Arguments to select edge to show must be integers.");
            } catch (IllegalArgumentException e) {
              System.out.println(
                  "An edge with the specified endpoints could not be found in the"
                      + K.lineSeparator
                      + "search graph");
            }
          }

          DirectedGraph<KRunState, Transition> savedGraph = null;
          if (cmd.hasOption("save")) {
            BinaryLoader.save(
                new File(cmd.getOptionValue("save")).getCanonicalPath(), debugger.getGraph());
            System.out.println("File successfully saved.");
          }
          if (cmd.hasOption("load")) {
            savedGraph =
                (DirectedGraph<KRunState, Transition>)
                    BinaryLoader.load(cmd.getOptionValue("load"));
            krun = new MaudeKRun(context);
            debugger = krun.debug(savedGraph);
            debugger.setCurrentState(1);
            System.out.println("File successfully loaded.");
          }
          if (cmd.hasOption("read")) {
            try {
              debugger.readFromStdin(
                  StringBuiltin.valueOf("\"" + cmd.getOptionValue("read") + "\"").stringValue());
              AnsiConsole.out.println(debugger.printState(debugger.getCurrentState()));
            } catch (IllegalStateException e) {
              Error.silentReport(e.getMessage());
            }
          }
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
      System.exit(1);
    }
  }