public static void main(String args[]) throws IOException { // process command line args CliOptions cliOptions = new CliOptions(); cliOptions.processArgs(css_, args); // connect to cassandra server if host argument specified. if (css_.hostName != null) { connect(css_.hostName, css_.thriftPort); } else { // If not, client must connect explicitly using the "connect" CLI statement. cliClient_ = new CliClient(css_, null); } ConsoleReader reader = new ConsoleReader(); reader.setBellEnabled(false); String historyFile = System.getProperty("user.home") + File.separator + HISTORYFILE; reader.setHistory(new History(new File(historyFile))); printBanner(); String line; while ((line = reader.readLine(PROMPT + "> ")) != null) { processLine(line); } }
public static void main(String[] args) throws Exception { log.info("* reading config.json"); JSONObject config = ConfigParser.parseConfig(TextFile.get("config.json")); String host = config.<String>get("server-addr"); int port = config.<Integer>get("server-port"); String pass = config.<String>get("password"); MechaClient client = new MechaClient(host, port, pass); ConsoleReader reader = new ConsoleReader(); reader.setBellEnabled(false); String line; while ((line = reader.readLine("mecha-cli> ")) != null) { line = line.trim(); if (line.equals("")) continue; client.exec(line); } }
/** * @param args the command line arguments * @throws Exception */ @SuppressWarnings("unchecked") public static void main(String[] args) throws Exception { if (args.length == 0) { fail(); } OpenCVJNILoader.load(); // Loads the OpenCV JNI (java native interface) // File servo = // ScriptingEngine.fileFromGit("https://github.com/NeuronRobotics/BowlerStudioVitamins.git", // "BowlerStudioVitamins/stl/servo/smallservo.stl"); // // ArrayList<CSG> cad = (ArrayList<CSG> // )ScriptingEngine.inlineGistScriptRun("4814b39ee72e9f590757", "javaCad.groovy" , null); // System.out.println(servo.exists()+" exists: "+servo); boolean startLoadingScripts = false; Object ret = null; for (String s : args) { if (startLoadingScripts) { try { ret = ScriptingEngine.inlineFileScriptRun(new File(s), null); } catch (Error e) { e.printStackTrace(); fail(); } } if (s.contains("script") || s.contains("-s")) { startLoadingScripts = true; } } startLoadingScripts = false; for (String s : args) { if (startLoadingScripts) { try { ret = ScriptingEngine.inlineFileScriptRun(new File(s), (ArrayList<Object>) ret); } catch (Error e) { e.printStackTrace(); fail(); } } if (s.contains("pipe") || s.contains("-p")) { startLoadingScripts = true; } } boolean runShell = false; ShellType shellTypeStorage = ShellType.GROOVY; for (String s : args) { if (runShell) { try { shellTypeStorage = ShellType.getFromSlug(s); } catch (Exception e) { shellTypeStorage = ShellType.GROOVY; } break; } if (s.contains("repl") || s.contains("-r")) { runShell = true; } } System.out.println("Starting Bowler REPL in langauge: " + shellTypeStorage.getNameOfShell()); // sample from // http://jline.sourceforge.net/testapidocs/src-html/jline/example/Example.html if (!Terminal.getTerminal().isSupported()) { System.out.println("Terminal not supported " + Terminal.getTerminal()); } // Terminal.getTerminal().initializeTerminal(); ConsoleReader reader = new ConsoleReader(); reader.addTriggeredAction( Terminal.CTRL_C, e -> { System.exit(0); }); if (!historyFile.exists()) { historyFile.createNewFile(); reader.getHistory().addToHistory("println SDKBuildInfo.getVersion()"); reader.getHistory().addToHistory("for(int i=0;i<100;i++) { println dyio.getValue(0) }"); reader.getHistory().addToHistory("dyio.setValue(0,128)"); reader.getHistory().addToHistory("println dyio.getValue(0)"); reader .getHistory() .addToHistory( "ScriptingEngine.inlineGistScriptRun(\"d4312a0787456ec27a2a\", \"helloWorld.groovy\" , null)"); reader .getHistory() .addToHistory( "DeviceManager.addConnection(new DyIO(ConnectionDialog.promptConnection()),\"dyio\")"); reader .getHistory() .addToHistory( "DeviceManager.addConnection(new DyIO(new SerialConnection(\"/dev/DyIO0\")),\"dyio\")"); reader.getHistory().addToHistory("BowlerKernel.speak(\"Text to speech works like this\")"); reader.getHistory().addToHistory("println \"Hello world!\""); writeHistory(reader.getHistory().getHistoryList()); } else { List<String> history = loadHistory(); for (String h : history) { reader.getHistory().addToHistory(h); } } reader.setBellEnabled(false); reader.setDebug(new PrintWriter(new FileWriter("writer.debug", true))); Runtime.getRuntime() .addShutdownHook( new Thread() { @Override public void run() { writeHistory(reader.getHistory().getHistoryList()); } }); // SpringApplication.run(SpringBowlerUI.class, new String[]{}); String line; try { while ((line = reader.readLine("Bowler " + shellTypeStorage.getNameOfShell() + "> ")) != null) { if (line.equalsIgnoreCase("quit") || line.equalsIgnoreCase("exit")) { break; } if (line.equalsIgnoreCase("history") || line.equalsIgnoreCase("h")) { List<String> h = reader.getHistory().getHistoryList(); for (String s : h) { System.out.println(s); } continue; } if (line.startsWith("shellType")) { try { shellTypeStorage = ShellType.getFromSlug(line.split(" ")[1]); } catch (Exception e) { shellTypeStorage = ShellType.GROOVY; } continue; } try { ret = ScriptingEngine.inlineScriptStringRun(line, null, shellTypeStorage); if (ret != null) System.out.println(ret); } catch (Error e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } } catch (Exception e) { e.printStackTrace(); } }
public static void main(String[] args) throws Exception { Config.hadoop_mode = false; if (args.length == 2 && args[0].equals("args")) // needed for mrql.flink script args = args[1].substring(1).split("!"); for (String arg : args) { Config.hadoop_mode |= arg.equals("-local") || arg.equals("-dist"); Config.bsp_mode |= arg.equals("-bsp"); Config.spark_mode |= arg.equals("-spark"); Config.flink_mode |= arg.equals("-flink"); } ; Config.map_reduce_mode = !Config.bsp_mode && !Config.spark_mode && !Config.flink_mode; initialize_evaluator(); if (Config.hadoop_mode) { conf = Evaluator.evaluator.new_configuration(); GenericOptionsParser gop = new GenericOptionsParser(conf, args); conf = gop.getConfiguration(); args = gop.getRemainingArgs(); } ; Config.parse_args(args, conf); Config.hadoop_mode = Config.local_mode || Config.distributed_mode; if (!Config.info) { for (Enumeration en = LogManager.getCurrentLoggers(); en.hasMoreElements(); ) ((Logger) en.nextElement()).setLevel(Level.WARN); LogManager.getRootLogger().setLevel(Level.WARN); } ; Evaluator.evaluator.init(conf); new TopLevel(); System.out.print("Apache MRQL version " + version + " ("); if (Config.compile_functional_arguments) System.out.print("compiled "); else System.out.print("interpreted "); if (Config.hadoop_mode) { if (Config.local_mode) System.out.print("local "); else if (Config.distributed_mode) System.out.print("distributed "); if (Config.spark_mode) System.out.println("Spark mode using " + Config.nodes + " tasks)"); else if (Config.flink_mode) System.out.println("Flink mode using " + Config.nodes + " tasks)"); else if (Config.bsp_mode) System.out.println("Hama BSP mode over " + Config.nodes + " BSP tasks)"); else if (Config.nodes > 0) System.out.println("Hadoop MapReduce mode with " + Config.nodes + " reducers)"); else if (!Config.local_mode) System.out.println("Hadoop MapReduce mode with 1 reducer, use -nodes to change it)"); else System.out.println("Hadoop MapReduce mode)"); } else if (Config.bsp_mode) System.out.println("in-memory BSP mode)"); else System.out.println("in-memory Java mode)"); if (Config.interactive) { System.out.println("Type quit to exit"); ConsoleReader reader = new ConsoleReader(); reader.setBellEnabled(false); History history = new History(new File(System.getProperty("user.home") + "/.mrqlhistory")); reader.setHistory(history); reader.setUseHistory(false); try { loop: while (true) { String line = ""; String s = ""; try { if (Config.hadoop_mode && Config.bsp_mode) Config.write(Plan.conf); do { s = reader.readLine("> "); if (s != null && (s.equals("quit") || s.equals("exit"))) break loop; if (s != null) line += " " + s; } while (s == null || s.indexOf(";") <= 0); line = line.substring(1); history.addToHistory(line); parser = new MRQLParser(new MRQLLex(new StringReader(line))); MRQLLex.reset(); parser.parse(); } catch (EOFException x) { break; } catch (Exception x) { if (x.getMessage() != null) System.out.println(x); } catch (Error x) { System.out.println(x); } } } finally { if (Config.hadoop_mode) { Plan.clean(); Evaluator.evaluator.shutdown(Plan.conf); } ; if (Config.compile_functional_arguments) Compiler.clean(); } } else try { if (Config.hadoop_mode && Config.bsp_mode) Config.write(Plan.conf); try { parser = new MRQLParser(new MRQLLex(new FileInputStream(query_file))); } catch (Exception e) { // when the query file is in HDFS Path path = new Path(query_file); FileSystem fs = path.getFileSystem(conf); parser = new MRQLParser(new MRQLLex(fs.open(path))); } ; parser.parse(); } finally { if (Config.hadoop_mode) { Plan.clean(); Evaluator.evaluator.shutdown(Plan.conf); } ; if (Config.compile_functional_arguments) Compiler.clean(); } }
public static void main(String[] args) { KeyBinding bind; if ("-tsv".equals(args[0])) { bind = loadKeyBindingFromTsv(args[1], args[2], args[3]); bind.save(args[4]); return; } else { try { bind = KeyBinding.load(args[0]); } catch (LoadingException ex) { throw new RuntimeException(ex); } } if ("-value".equals(args[1])) { KeyBinding ret = KeyBinding.newLike(bind); Output out = new OutputKeyBinding(ret); Pusher p = new Pusher(); for (int i = 2; i < args.length; i++) { p.onlyIf(new IfEquals(bind.getColumnName(1), args[i]), out); } p.push(new InputKeyBinding(bind)); ret.dumpTsv(System.out); } else if ("-count".equals(args[1])) { Pusher p = new Pusher(); for (int i = 2; i < args.length; i++) { p.onlyIf(new IfEquals(bind.getColumnName(1), args[i]), new BreakAfter(args[i])); } p.push(new InputKeyBinding(bind)); } else if ("-dump".equals(args[1])) { bind.dumpTsv(System.out); } else if ("-prompt".equals(args[1])) { try { jline.ConsoleReader reader = new jline.ConsoleReader(); reader.setBellEnabled(false); reader.getHistory().setHistoryFile(new File(".KeyBinding.history")); String line = null; System.err.println("=== Enter Keys ==="); while ((line = reader.readLine("keys> ")) != null) { if (!line.trim().isEmpty()) { for (String k : line.split("\\s+")) { System.out.print(k); System.out.print('\t'); if (bind.contains(k)) { System.out.print(bind.get(k)); } else { System.out.print("false"); } System.out.println(); } } } } catch (IOException ioex) { ioex.printStackTrace(); } } else { int i = 1; if ("-key".equals(args[1])) { i = 2; } for (; i < args.length; i++) { System.out.print(args[i]); System.out.print('\t'); if (bind.contains(args[i])) { System.out.print(bind.get(args[i])); } else { System.out.print("false"); } System.out.println(); } } }
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); }
// 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); } }