use of jline.ConsoleReader 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;
}
use of jline.ConsoleReader in project spring-roo by spring-projects.
the class JLineShell method run.
public void run() {
try {
if (JANSI_AVAILABLE && SystemUtils.IS_OS_WINDOWS) {
try {
reader = createAnsiWindowsReader();
} catch (final Exception e) {
// Try again using default ConsoleReader constructor
logger.warning("Can't initialize jansi AnsiConsole, falling back to default: " + e);
}
}
if (reader == null) {
reader = new ConsoleReader();
}
} catch (final IOException ioe) {
throw new IllegalStateException("Cannot start console class", ioe);
}
final JLineLogHandler handler = new JLineLogHandler(reader, this);
// Affects this thread only
JLineLogHandler.prohibitRedraw();
final Logger mainLogger = Logger.getLogger("");
removeHandlers(mainLogger);
mainLogger.addHandler(handler);
reader.addCompletor(new JLineCompletorAdapter(getParser()));
reader.setBellEnabled(true);
if (Boolean.getBoolean("jline.nobell")) {
reader.setBellEnabled(false);
}
// reader.setDebug(new PrintWriter(new FileWriter("writer.debug",
// true)));
openFileLogIfPossible();
// Try to build previous command history from the project's log
try {
final String logFileContents = FileUtils.readFileToString(new File("log.roo"));
final String[] logEntries = logFileContents.split(IOUtils.LINE_SEPARATOR);
// LIFO
for (final String logEntry : logEntries) {
if (!logEntry.startsWith("//")) {
reader.getHistory().addToHistory(logEntry);
}
}
} catch (final IOException ignored) {
}
flashMessageRenderer();
logger.info(version(null));
flash(Level.FINE, "Spring Roo " + versionInfo(), Shell.WINDOW_TITLE_SLOT);
logger.info("Welcome to Spring Roo. For assistance press " + completionKeys + " or type \"hint\" then hit ENTER.");
final String startupNotifications = getStartupNotifications();
if (StringUtils.isNotBlank(startupNotifications)) {
logger.info(startupNotifications);
}
setShellStatus(Status.STARTED);
// Monitor CTRL+C initiated shutdowns (ROO-1599)
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
public void run() {
shutdownHookFired = true;
// We don't need to closeShell(), as the shutdown hook in
// o.s.r.bootstrap.Main calls stop() which calls
// JLineShellComponent.deactivate() and that calls closeShell()
}
}, "Spring Roo JLine Shutdown Hook"));
// Handle any "execute-then-quit" operation
final String rooArgs = System.getProperty("roo.args");
if (rooArgs != null && !"".equals(rooArgs)) {
setShellStatus(Status.USER_INPUT);
final boolean success = executeCommand(rooArgs);
if (exitShellRequest == null) {
// The command itself did not specify an exit shell code, so
// we'll fall back to something sensible here
// ROO-839
executeCommand("quit");
exitShellRequest = success ? ExitShellRequest.NORMAL_EXIT : ExitShellRequest.FATAL_EXIT;
}
setShellStatus(Status.SHUTTING_DOWN);
} else {
// ROO-3622: Validate if version change
if (isDifferentVersion()) {
logger.warning("WARNING: You are using Spring Roo " + versionInfoWithoutGit() + ", but " + "project was generated using Spring Roo " + getRooProjectVersion() + ".");
logger.warning("If you continue with the execution " + "your project might suffer some changes.");
// Ask a question about if Spring Roo should apply its prepared changes
List<String> options = new ArrayList<String>();
options.add("Yes");
options.add("No");
String answer = askAQuestion("Do you want to continue opening Spring Roo Shell?", options, "Yes");
if ("yes".equals(answer.toLowerCase())) {
showGoodLuckMessage();
updateRooVersion(versionInfoWithoutGit());
} else if ("no".equals(answer.toLowerCase())) {
System.exit(0);
}
promptLoop();
} else {
// Normal RPEL processing
promptLoop();
}
}
}
use of jline.ConsoleReader in project min by macournoyer.
the class Min method repl.
private static void repl() throws MinException, IOException {
// Boolean LoopAgain = true;
ConsoleReader console = new ConsoleReader();
console.setDefaultPrompt("min> ");
String input;
Message message;
System.out.println("REPL (experimental)");
System.out.println("-------------------");
System.out.println("Type 'bye' to exit\n");
while (true) {
input = console.readLine();
if (input.equals("bye"))
break;
try {
message = Message.parse(input, "<eval>");
if (debug)
System.out.println("debug >> " + message.fullName());
System.out.print(">> ");
message.evalOn(MinObject.lobby);
System.out.println("");
} catch (Exception e) {
System.err.println(e);
}
}
System.out.println("Bye!\n");
System.exit(1);
}
use of jline.ConsoleReader in project databus by linkedin.
the class InteractiveSchemaGenerator method run.
public void run() throws Exception {
printWelcomeMessage();
_reader = new ConsoleReader();
_reader.setDefaultPrompt("SchemaGen>");
_reader.setBellEnabled(false);
processInput();
}
use of jline.ConsoleReader in project jackrabbit by apache.
the class Login method execute.
/**
* {@inheritDoc}
*/
public boolean execute(Context ctx) throws Exception {
String anon = "anonymous";
String user = (String) ctx.get(this.userKey);
String password = (String) ctx.get(this.passwordKey);
String workspace = (String) ctx.get(this.workspaceKey);
if (user == null) {
user = anon;
}
if (password == null || (password.equals(anon) && !user.equals(anon))) {
ConsoleReader reader = new ConsoleReader();
password = reader.readLine("Password: ", (char) 0);
}
if (log.isDebugEnabled()) {
log.debug("logging in as " + user);
}
Session session = null;
Repository repo = CommandHelper.getRepository(ctx);
Credentials credentials = new SimpleCredentials(user, password.toCharArray());
if (workspace == null) {
session = repo.login(credentials);
} else {
session = repo.login(credentials, workspace);
}
CommandHelper.setSession(ctx, session);
CommandHelper.setCurrentNode(ctx, session.getRootNode());
return false;
}
Aggregations