Search in sources :

Example 1 with History

use of jline.History in project SQLWindowing by hbutani.

the class WindowingHiveCliDriver method run.

public static int run(String[] args) throws Exception {
    OptionsProcessor oproc = new OptionsProcessor();
    if (!oproc.process_stage1(args)) {
        return 1;
    }
    // NOTE: It is critical to do this here so that log4j is reinitialized
    // before any of the other core hive classes are loaded
    boolean logInitFailed = false;
    String logInitDetailMessage;
    try {
        logInitDetailMessage = LogUtils.initHiveLog4j();
    } catch (LogInitializationException e) {
        logInitFailed = true;
        logInitDetailMessage = e.getMessage();
    }
    CliSessionState ss = new CliSessionState(new HiveConf(SessionState.class));
    ss.in = System.in;
    try {
        ss.out = new PrintStream(System.out, true, "UTF-8");
        ss.info = new PrintStream(System.err, true, "UTF-8");
        ss.err = new CachingPrintStream(System.err, true, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        return 3;
    }
    if (!oproc.process_stage2(ss)) {
        return 2;
    }
    if (!ss.getIsSilent()) {
        if (logInitFailed) {
            System.err.println(logInitDetailMessage);
        } else {
            SessionState.getConsole().printInfo(logInitDetailMessage);
        }
    }
    // set all properties specified via command line
    HiveConf conf = ss.getConf();
    for (Map.Entry<Object, Object> item : ss.cmdProperties.entrySet()) {
        conf.set((String) item.getKey(), (String) item.getValue());
        ss.getOverriddenConfigurations().put((String) item.getKey(), (String) item.getValue());
    }
    SessionState.start(ss);
    // connect to Hive Server
    if (ss.getHost() != null) {
        ss.connect();
        if (ss.isRemoteMode()) {
            prompt = "[" + ss.getHost() + ':' + ss.getPort() + "] " + prompt;
            char[] spaces = new char[prompt.length()];
            Arrays.fill(spaces, ' ');
            prompt2 = new String(spaces);
        }
    }
    // CLI remote mode is a thin client: only load auxJars in local mode
    if (!ss.isRemoteMode() && !ShimLoader.getHadoopShims().usesJobShell()) {
        // hadoop-20 and above - we need to augment classpath using hiveconf
        // components
        // see also: code in ExecDriver.java
        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);
    }
    WindowingHiveCliDriver cli = new WindowingHiveCliDriver();
    cli.setHiveVariables(oproc.getHiveVariables());
    // use the specified database if specified
    cli.processSelectDatabase(ss);
    // Execute -i init files (always in silent mode)
    cli.processInitFiles(ss);
    cli.setupWindowing();
    if (ss.execString != null) {
        return cli.processLine(ss.execString);
    }
    try {
        if (ss.fileName != null) {
            return cli.processFile(ss.fileName);
        }
    } catch (FileNotFoundException e) {
        System.err.println("Could not open input file for reading. (" + e.getMessage() + ")");
        return 3;
    }
    ConsoleReader reader = new ConsoleReader();
    reader.setBellEnabled(false);
    // true)));
    for (Completor completor : getCommandCompletor()) {
        reader.addCompletor(completor);
    }
    String line;
    final String HISTORYFILE = ".hivehistory";
    String historyDirectory = System.getProperty("user.home");
    try {
        if ((new File(historyDirectory)).exists()) {
            String historyFile = historyDirectory + File.separator + HISTORYFILE;
            reader.setHistory(new History(new File(historyFile)));
        } else {
            System.err.println("WARNING: Directory for Hive history file: " + historyDirectory + " does not exist.   History will not be available during this session.");
        }
    } catch (Exception e) {
        System.err.println("WARNING: Encountered an error while trying to initialize Hive's " + "history file.  History will not be available during this session.");
        System.err.println(e.getMessage());
    }
    int ret = 0;
    String prefix = "";
    String curDB = getFormattedDb(conf, ss);
    String curPrompt = prompt + curDB;
    String dbSpaces = spacesForString(curDB);
    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, true);
            prefix = "";
            curDB = getFormattedDb(conf, ss);
            curPrompt = prompt + curDB;
            dbSpaces = dbSpaces.length() == curDB.length() ? dbSpaces : spacesForString(curDB);
        } else {
            prefix = prefix + line;
            curPrompt = prompt2 + dbSpaces;
            continue;
        }
    }
    ss.close();
    return ret;
}
Also used : CliSessionState(org.apache.hadoop.hive.cli.CliSessionState) SessionState(org.apache.hadoop.hive.ql.session.SessionState) PrintStream(java.io.PrintStream) CachingPrintStream(org.apache.hadoop.hive.common.io.CachingPrintStream) ConsoleReader(jline.ConsoleReader) FileNotFoundException(java.io.FileNotFoundException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) History(jline.History) OptionsProcessor(org.apache.hadoop.hive.cli.OptionsProcessor) CliSessionState(org.apache.hadoop.hive.cli.CliSessionState) FileNotFoundException(java.io.FileNotFoundException) WindowingException(com.sap.hadoop.windowing.WindowingException) LogInitializationException(org.apache.hadoop.hive.common.LogUtils.LogInitializationException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) CachingPrintStream(org.apache.hadoop.hive.common.io.CachingPrintStream) LogInitializationException(org.apache.hadoop.hive.common.LogUtils.LogInitializationException) HiveConf(org.apache.hadoop.hive.conf.HiveConf) Completor(jline.Completor) Map(java.util.Map) File(java.io.File)

Example 2 with History

use of jline.History in project eiger by wlloyd.

the class CliMain method main.

public static void main(String[] args) throws IOException {
    // process command line arguments
    CliOptions cliOptions = new CliOptions();
    cliOptions.processArgs(sessionState, args);
    // connect to cassandra server if host argument specified.
    if (sessionState.hostName != null) {
        try {
            connect(sessionState.hostName, sessionState.thriftPort);
        } catch (RuntimeException e) {
            sessionState.err.println(e.getMessage());
            System.exit(-1);
        }
    }
    if (cliClient == null) {
        // Connection parameter was either invalid or not present.
        // User must connect explicitly using the "connect" CLI statement.
        cliClient = new CliClient(sessionState, null);
    }
    // load statements from file and process them
    if (sessionState.inFileMode()) {
        FileReader fileReader;
        try {
            fileReader = new FileReader(sessionState.filename);
        } catch (IOException e) {
            sessionState.err.println(e.getMessage());
            return;
        }
        evaluateFileStatements(new BufferedReader(fileReader));
        return;
    }
    ConsoleReader reader = new ConsoleReader();
    if (!sessionState.batch) {
        reader.addCompletor(completer);
        reader.setBellEnabled(false);
        String historyFile = System.getProperty("user.home") + File.separator + HISTORYFILE;
        try {
            History history = new History(new File(historyFile));
            reader.setHistory(history);
        } catch (IOException exp) {
            sessionState.err.printf("Unable to open %s for writing %n", historyFile);
        }
    } else if (// if in batch mode but no verbose flag
    !sessionState.verbose) {
        sessionState.out.close();
    }
    cliClient.printBanner();
    String prompt;
    String line = "";
    String currentStatement = "";
    boolean inCompoundStatement = false;
    while (line != null) {
        prompt = (inCompoundStatement) ? "...\t" : getPrompt(cliClient);
        try {
            line = reader.readLine(prompt);
        } catch (IOException e) {
        // retry on I/O Exception
        }
        if (line == null)
            return;
        line = line.trim();
        // skipping empty and comment lines
        if (line.isEmpty() || line.startsWith("--"))
            continue;
        currentStatement += line;
        if (line.endsWith(";") || line.equals("?")) {
            processStatementInteractive(currentStatement);
            currentStatement = "";
            inCompoundStatement = false;
        } else {
            // ready for new line
            currentStatement += " ";
            inCompoundStatement = true;
        }
    }
}
Also used : ConsoleReader(jline.ConsoleReader) BufferedReader(java.io.BufferedReader) FileReader(java.io.FileReader) IOException(java.io.IOException) History(jline.History) File(java.io.File)

Example 3 with History

use of jline.History in project zm-mailbox by Zimbra.

the class CliUtil method enableCommandLineEditing.

/**
     * Turns on command line editing with JLine.  
     * @param histFilePath path to the history file, or {@code null} to not save history
     * @throws IOException if the history file is not writable or cannot be created
     */
public static void enableCommandLineEditing(String histFilePath) throws IOException {
    File histFile = null;
    if (histFilePath != null) {
        histFile = new File(histFilePath);
        if (!histFile.exists()) {
            if (!histFile.createNewFile()) {
                throw new IOException("Unable to create history file " + histFilePath);
            }
        }
        if (!histFile.canWrite()) {
            throw new IOException(histFilePath + " is not writable");
        }
    }
    ConsoleReader reader = new ConsoleReader();
    if (histFile != null) {
        reader.setHistory(new History(histFile));
    }
    ConsoleReaderInputStream.setIn(reader);
}
Also used : ConsoleReader(jline.ConsoleReader) IOException(java.io.IOException) History(jline.History) File(java.io.File)

Example 4 with History

use of jline.History in project jackrabbit by apache.

the class JcrClient method runInteractive.

/**
     * Run in interactive mode
     * @throws Exception
     *         if an Exception occurs
     */
public void runInteractive() throws Exception {
    // built jline console reader with history + tab completion
    ConsoleReader reader = new ConsoleReader();
    reader.setHistory(new History());
    reader.setUseHistory(true);
    // get all available commands for command tab completion
    Collection<CommandLine> commands = CommandLineFactory.getInstance().getCommandLines();
    List<String> commandNames = new ArrayList<String>();
    for (CommandLine c : commands) {
        commandNames.add(c.getName());
        for (Object alias : c.getAlias()) {
            commandNames.add((String) alias);
        }
    }
    commandNames.add("exit");
    commandNames.add("quit");
    // first part is the command, then all arguments will get children tab completion
    reader.addCompletor(new ArgumentCompletor(new Completor[] { new SimpleCompletor(commandNames.toArray(new String[] {})), new JcrChildrenCompletor() }));
    while (!exit) {
        try {
            String input = reader.readLine("[" + this.getPrompt() + "] > ");
            if (input == null) {
                input = "exit";
            } else {
                input = input.trim();
            }
            log.debug("running: " + input);
            if (input.equals("exit") || input.equals("quit")) {
                // exit?
                exit = true;
                System.out.println("Good bye...");
            } else if (input.length() > 0) {
                this.runCommand(input);
            }
        } catch (JcrParserException e) {
            System.out.println(e.getLocalizedMessage());
            System.out.println();
        } catch (Exception e) {
            handleException(reader, e);
        }
    }
}
Also used : ConsoleReader(jline.ConsoleReader) ArrayList(java.util.ArrayList) ArgumentCompletor(jline.ArgumentCompletor) History(jline.History) RepositoryException(javax.jcr.RepositoryException) InvalidItemStateException(javax.jcr.InvalidItemStateException) CommandException(org.apache.jackrabbit.standalone.cli.CommandException) IOException(java.io.IOException) ParseException(org.apache.commons.cli.ParseException) SimpleCompletor(jline.SimpleCompletor) SimpleCompletor(jline.SimpleCompletor) ArgumentCompletor(jline.ArgumentCompletor) Completor(jline.Completor)

Aggregations

ConsoleReader (jline.ConsoleReader)4 History (jline.History)4 File (java.io.File)3 IOException (java.io.IOException)3 Completor (jline.Completor)2 WindowingException (com.sap.hadoop.windowing.WindowingException)1 BufferedReader (java.io.BufferedReader)1 FileNotFoundException (java.io.FileNotFoundException)1 FileReader (java.io.FileReader)1 PrintStream (java.io.PrintStream)1 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1 ArrayList (java.util.ArrayList)1 Map (java.util.Map)1 InvalidItemStateException (javax.jcr.InvalidItemStateException)1 RepositoryException (javax.jcr.RepositoryException)1 ArgumentCompletor (jline.ArgumentCompletor)1 SimpleCompletor (jline.SimpleCompletor)1 ParseException (org.apache.commons.cli.ParseException)1 CliSessionState (org.apache.hadoop.hive.cli.CliSessionState)1 OptionsProcessor (org.apache.hadoop.hive.cli.OptionsProcessor)1