use of org.jline.terminal.Terminal in project tesb-studio-se by Talend.
the class RuntimeClient method connect.
public void connect(String[] args) throws Exception {
ClientConfig config = new ClientConfig(args);
SimpleLogger.setLevel(config.getLevel());
if (config.getFile() != null) {
StringBuilder sb = new StringBuilder();
sb.setLength(0);
try (Reader reader = new BufferedReader(new InputStreamReader(new FileInputStream(config.getFile())))) {
for (int c = reader.read(); c >= 0; c = reader.read()) {
sb.append((char) c);
}
}
config.setCommand(sb.toString());
} else if (config.isBatch()) {
StringBuilder sb = new StringBuilder();
sb.setLength(0);
Reader reader = new BufferedReader(new InputStreamReader(System.in));
for (int c = reader.read(); c >= 0; c = reader.read()) {
sb.append((char) c);
}
config.setCommand(sb.toString());
}
SshClient client = ClientBuilder.builder().build();
// setupAgent(config.getUser(), config.getKeyFile(), client);
// client.getProperties().put(FactoryManager.IDLE_TIMEOUT, String.valueOf(config.getIdleTimeout()));
final Console console = System.console();
if (console != null) {
client.setUserInteraction(new UserInteraction() {
@Override
public void welcome(ClientSession s, String banner, String lang) {
System.err.println(banner);
}
@Override
public String[] interactive(ClientSession s, String name, String instruction, String lang, String[] prompt, boolean[] echo) {
String[] answers = new String[prompt.length];
try {
for (int i = 0; i < prompt.length; i++) {
if (echo[i]) {
answers[i] = console.readLine(prompt[i] + " ");
} else {
answers[i] = new String(console.readPassword(prompt[i] + " "));
}
if (answers[i] == null) {
return null;
}
}
return answers;
} catch (IOError e) {
return null;
}
}
@Override
public boolean isInteractionAllowed(ClientSession session) {
return true;
}
@Override
public void serverVersionInfo(ClientSession session, List<String> lines) {
}
@Override
public String getUpdatedPassword(ClientSession session, String prompt, String lang) {
return null;
}
});
}
client.start();
ClientSession session = connectWithRetries(client, config);
if (config.getPassword() != null) {
session.addPasswordIdentity(config.getPassword());
}
session.auth().verify();
int exitStatus = 0;
Terminal terminal = TerminalBuilder.terminal();
Attributes attributes = terminal.enterRawMode();
IOConsoleOutputStream outputStream = RuntimeConsoleUtil.getOutputStream();
try {
ClientChannel channel;
if (config.getCommand().length() > 0) {
channel = session.createChannel("exec", config.getCommand() + "\n");
channel.setIn(new ByteArrayInputStream(new byte[0]));
} else {
ChannelShell shell = session.createShellChannel();
channel = shell;
channel.setIn(new NoCloseInputStream(inputStream));
Map<PtyMode, Integer> modes = new HashMap<>();
// Control chars
modes.put(PtyMode.VINTR, attributes.getControlChar(ControlChar.VINTR));
modes.put(PtyMode.VQUIT, attributes.getControlChar(ControlChar.VQUIT));
modes.put(PtyMode.VERASE, attributes.getControlChar(ControlChar.VERASE));
modes.put(PtyMode.VKILL, attributes.getControlChar(ControlChar.VKILL));
modes.put(PtyMode.VEOF, attributes.getControlChar(ControlChar.VEOF));
modes.put(PtyMode.VEOL, attributes.getControlChar(ControlChar.VEOL));
modes.put(PtyMode.VEOL2, attributes.getControlChar(ControlChar.VEOL2));
modes.put(PtyMode.VSTART, attributes.getControlChar(ControlChar.VSTART));
modes.put(PtyMode.VSTOP, attributes.getControlChar(ControlChar.VSTOP));
modes.put(PtyMode.VSUSP, attributes.getControlChar(ControlChar.VSUSP));
modes.put(PtyMode.VDSUSP, attributes.getControlChar(ControlChar.VDSUSP));
modes.put(PtyMode.VREPRINT, attributes.getControlChar(ControlChar.VREPRINT));
modes.put(PtyMode.VWERASE, attributes.getControlChar(ControlChar.VWERASE));
modes.put(PtyMode.VLNEXT, attributes.getControlChar(ControlChar.VLNEXT));
modes.put(PtyMode.VSTATUS, attributes.getControlChar(ControlChar.VSTATUS));
modes.put(PtyMode.VDISCARD, attributes.getControlChar(ControlChar.VDISCARD));
// Input flags
modes.put(PtyMode.IGNPAR, getFlag(attributes, InputFlag.IGNPAR));
modes.put(PtyMode.PARMRK, getFlag(attributes, InputFlag.PARMRK));
modes.put(PtyMode.INPCK, getFlag(attributes, InputFlag.INPCK));
modes.put(PtyMode.ISTRIP, getFlag(attributes, InputFlag.ISTRIP));
modes.put(PtyMode.INLCR, getFlag(attributes, InputFlag.INLCR));
modes.put(PtyMode.IGNCR, getFlag(attributes, InputFlag.IGNCR));
modes.put(PtyMode.ICRNL, getFlag(attributes, InputFlag.ICRNL));
modes.put(PtyMode.IXON, getFlag(attributes, InputFlag.IXON));
modes.put(PtyMode.IXANY, getFlag(attributes, InputFlag.IXANY));
modes.put(PtyMode.IXOFF, getFlag(attributes, InputFlag.IXOFF));
// Local flags
modes.put(PtyMode.ISIG, getFlag(attributes, LocalFlag.ISIG));
modes.put(PtyMode.ICANON, getFlag(attributes, LocalFlag.ICANON));
modes.put(PtyMode.ECHO, getFlag(attributes, LocalFlag.ECHO));
modes.put(PtyMode.ECHOE, getFlag(attributes, LocalFlag.ECHOE));
modes.put(PtyMode.ECHOK, getFlag(attributes, LocalFlag.ECHOK));
modes.put(PtyMode.ECHONL, getFlag(attributes, LocalFlag.ECHONL));
modes.put(PtyMode.NOFLSH, getFlag(attributes, LocalFlag.NOFLSH));
modes.put(PtyMode.TOSTOP, getFlag(attributes, LocalFlag.TOSTOP));
modes.put(PtyMode.IEXTEN, getFlag(attributes, LocalFlag.IEXTEN));
// Output flags
modes.put(PtyMode.OPOST, getFlag(attributes, OutputFlag.OPOST));
modes.put(PtyMode.ONLCR, getFlag(attributes, OutputFlag.ONLCR));
modes.put(PtyMode.OCRNL, getFlag(attributes, OutputFlag.OCRNL));
modes.put(PtyMode.ONOCR, getFlag(attributes, OutputFlag.ONOCR));
modes.put(PtyMode.ONLRET, getFlag(attributes, OutputFlag.ONLRET));
shell.setPtyModes(modes);
shell.setPtyColumns(terminal.getWidth());
shell.setPtyLines(terminal.getHeight());
shell.setAgentForwarding(true);
String ctype = System.getenv("LC_CTYPE");
if (ctype == null) {
ctype = Locale.getDefault().toString() + "." + System.getProperty("input.encoding", Charset.defaultCharset().name());
}
shell.setEnv("LC_CTYPE", ctype);
}
channel.setOut(outputStream);
channel.setErr(outputStream);
channel.open().verify();
if (channel instanceof PtyCapableChannelSession) {
registerSignalHandler(terminal, (PtyCapableChannelSession) channel);
}
connected = true;
channel.waitFor(EnumSet.of(ClientChannelEvent.CLOSED), 0);
if (channel.getExitStatus() != null) {
exitStatus = channel.getExitStatus();
}
channel.close();
} finally {
terminal.setAttributes(attributes);
client.stop();
client.close();
connected = false;
if (!outputStream.isClosed()) {
outputStream.close();
}
}
}
use of org.jline.terminal.Terminal in project felix by apache.
the class Main method main.
public static void main(String[] args) throws IOException {
try (Terminal terminal = TerminalBuilder.builder().name("gogo").system(true).nativeSignals(true).signalHandler(Terminal.SignalHandler.SIG_IGN).build()) {
ThreadIOImpl tio = new ThreadIOImpl();
tio.start();
try {
CommandProcessorImpl processor = new CommandProcessorImpl(tio);
Context context = new MyContext();
Shell shell = new Shell(context, processor, tio, null);
processor.addCommand("gogo", processor, "addCommand");
processor.addCommand("gogo", processor, "removeCommand");
processor.addCommand("gogo", processor, "eval");
processor.addConverter(new BaseConverters());
register(processor, new Builtin(), Builtin.functions);
register(processor, new Procedural(), Procedural.functions);
register(processor, new Posix(processor), Posix.functions);
register(processor, shell, Shell.functions);
InputStream in = new FilterInputStream(terminal.input()) {
@Override
public void close() throws IOException {
}
};
OutputStream out = new FilterOutputStream(terminal.output()) {
@Override
public void close() throws IOException {
}
};
CommandSession session = processor.createSession(in, out, out);
session.put(Shell.VAR_CONTEXT, context);
session.put(Shell.VAR_TERMINAL, terminal);
try {
String[] argv = new String[args.length + 1];
argv[0] = "--login";
System.arraycopy(args, 0, argv, 1, args.length);
shell.gosh(session, argv);
} catch (Exception e) {
Object loc = session.get(".location");
if (null == loc || !loc.toString().contains(":")) {
loc = "gogo";
}
System.err.println(loc + ": " + e.getClass().getSimpleName() + ": " + e.getMessage());
e.printStackTrace();
} finally {
session.close();
}
} finally {
tio.stop();
}
}
}
use of org.jline.terminal.Terminal in project felix by apache.
the class Posix method toColumn.
private void toColumn(CommandSession session, Process process, PrintStream out, Stream<String> ansi, boolean horizontal) {
Terminal terminal = Shell.getTerminal(session);
int width = process.isTty(1) ? terminal.getWidth() : 80;
List<AttributedString> strings = ansi.map(AttributedString::fromAnsi).collect(Collectors.toList());
if (!strings.isEmpty()) {
int max = strings.stream().mapToInt(AttributedString::columnLength).max().getAsInt();
int c = Math.max(1, width / max);
while (c > 1 && c * max + (c - 1) >= width) {
c--;
}
int columns = c;
int lines = (strings.size() + columns - 1) / columns;
IntBinaryOperator index;
if (horizontal) {
index = (i, j) -> i * columns + j;
} else {
index = (i, j) -> j * lines + i;
}
AttributedStringBuilder sb = new AttributedStringBuilder();
for (int i = 0; i < lines; i++) {
for (int j = 0; j < columns; j++) {
int idx = index.applyAsInt(i, j);
if (idx < strings.size()) {
AttributedString str = strings.get(idx);
boolean hasRightItem = j < columns - 1 && index.applyAsInt(i, j + 1) < strings.size();
sb.append(str);
if (hasRightItem) {
for (int k = 0; k <= max - str.length(); k++) {
sb.append(' ');
}
}
}
}
sb.append('\n');
}
out.print(sb.toAnsi(terminal));
}
}
use of org.jline.terminal.Terminal in project felix by apache.
the class Posix method watch.
protected void watch(final CommandSession session, Process process, String[] argv) throws Exception {
final String[] usage = { "watch - watches & refreshes the output of a command", "Usage: watch [OPTIONS] COMMAND", " -? --help Show help", " -n --interval Interval between executions of the command in seconds", " -a --append The output should be appended but not clear the console" };
Options opt = parseOptions(session, usage, argv);
List<String> args = opt.args();
if (args.isEmpty()) {
throw new IllegalArgumentException("usage: watch COMMAND");
}
ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
final Terminal terminal = Shell.getTerminal(session);
final CommandProcessor processor = Shell.getProcessor(session);
try {
int interval = 1;
if (opt.isSet("interval")) {
interval = opt.getNumber("interval");
if (interval < 1) {
interval = 1;
}
}
final String cmd = String.join(" ", args);
Runnable task = () -> {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream os = new PrintStream(baos);
InputStream is = new ByteArrayInputStream(new byte[0]);
if (opt.isSet("append") || !terminal.puts(Capability.clear_screen)) {
terminal.writer().println();
}
try {
CommandSession ns = processor.createSession(is, os, os);
Set<String> vars = Shell.getCommands(session);
for (String n : vars) {
ns.put(n, session.get(n));
}
ns.execute(cmd);
} catch (Throwable t) {
t.printStackTrace(os);
}
os.flush();
terminal.writer().print(baos.toString());
terminal.writer().flush();
};
executorService.scheduleAtFixedRate(task, 0, interval, TimeUnit.SECONDS);
Attributes attr = terminal.enterRawMode();
terminal.reader().read();
terminal.setAttributes(attr);
} finally {
executorService.shutdownNow();
}
}
use of org.jline.terminal.Terminal in project felix by apache.
the class Shell method gosh.
public Object gosh(CommandSession currentSession, String[] argv) throws Exception {
final String[] usage = { "gosh - execute script with arguments in a new session", " args are available as session variables $1..$9 and $args.", "Usage: gosh [OPTIONS] [script-file [args..]]", " -c --command pass all remaining args to sub-shell", " --nointeractive don't start interactive session", " --nohistory don't save the command history", " --login login shell (same session, reads etc/gosh_profile)", " -s --noshutdown don't shutdown framework when script completes", " -x --xtrace echo commands before execution", " -? --help show help", "If no script-file, an interactive shell is started, type $D to exit." };
Options opt = Options.compile(usage).setOptionsFirst(true).parse(argv);
List<String> args = opt.args();
boolean login = opt.isSet("login");
boolean interactive = !opt.isSet("nointeractive");
if (opt.isSet("help")) {
opt.usage(System.err);
if (login && !opt.isSet("noshutdown")) {
shutdown();
}
return null;
}
if (opt.isSet("command") && args.isEmpty()) {
throw opt.usageError("option --command requires argument(s)");
}
CommandSession session;
if (login) {
session = currentSession;
} else {
session = createChildSession(currentSession);
}
if (opt.isSet("xtrace")) {
session.put("echo", true);
}
Terminal terminal = getTerminal(session);
session.put(Shell.VAR_CONTEXT, context);
session.put(Shell.VAR_PROCESSOR, processor);
session.put(Shell.VAR_SESSION, session);
session.put("#TERM", (Function) (s, arguments) -> terminal.getType());
session.put("#COLUMNS", (Function) (s, arguments) -> terminal.getWidth());
session.put("#LINES", (Function) (s, arguments) -> terminal.getHeight());
session.put("#PWD", (Function) (s, arguments) -> s.currentDir().toString());
if (!opt.isSet("nohistory")) {
session.put(LineReader.HISTORY_FILE, Paths.get(System.getProperty("user.home"), ".gogo.history"));
}
if (tio != null) {
PrintWriter writer = terminal.writer();
PrintStream out = new PrintStream(new OutputStream() {
@Override
public void write(int b) throws IOException {
write(new byte[] { (byte) b }, 0, 1);
}
public void write(byte[] b, int off, int len) throws IOException {
writer.write(new String(b, off, len));
}
public void flush() throws IOException {
writer.flush();
}
public void close() throws IOException {
writer.close();
}
});
tio.setStreams(terminal.input(), out, out);
}
try {
LineReader reader;
if (args.isEmpty() && interactive) {
CompletionEnvironment completionEnvironment = new CompletionEnvironment() {
@Override
public Map<String, List<CompletionData>> getCompletions() {
return Shell.getCompletions(session);
}
@Override
public Set<String> getCommands() {
return Shell.getCommands(session);
}
@Override
public String resolveCommand(String command) {
return Shell.resolve(session, command);
}
@Override
public String commandName(String command) {
int idx = command.indexOf(':');
return idx >= 0 ? command.substring(idx + 1) : command;
}
@Override
public Object evaluate(LineReader reader, ParsedLine line, String func) throws Exception {
session.put(Shell.VAR_COMMAND_LINE, line);
return session.execute(func);
}
};
reader = LineReaderBuilder.builder().terminal(terminal).variables(((CommandSessionImpl) session).getVariables()).completer(new org.jline.builtins.Completers.Completer(completionEnvironment)).highlighter(new Highlighter(session)).parser(new Parser()).expander(new Expander(session)).build();
reader.setOpt(LineReader.Option.AUTO_FRESH_LINE);
session.put(Shell.VAR_READER, reader);
session.put(Shell.VAR_COMPLETIONS, new HashMap());
} else {
reader = null;
}
if (login || interactive) {
URI uri = baseURI.resolve("etc/" + profile);
if (!new File(uri).exists()) {
URL url = getClass().getResource("/ext/" + profile);
if (url == null) {
url = getClass().getResource("/" + profile);
}
uri = (url == null) ? null : url.toURI();
}
if (uri != null) {
source(session, uri.toString());
}
}
Object result = null;
if (args.isEmpty()) {
if (interactive) {
result = runShell(session, terminal, reader);
}
} else {
CharSequence program;
if (opt.isSet("command")) {
StringBuilder buf = new StringBuilder();
for (String arg : args) {
if (buf.length() > 0) {
buf.append(' ');
}
buf.append(arg);
}
program = buf;
} else {
URI script = session.currentDir().toUri().resolve(args.remove(0));
// set script arguments
session.put("0", script);
session.put("args", args);
for (int i = 0; i < args.size(); ++i) {
session.put(String.valueOf(i + 1), args.get(i));
}
program = readScript(script);
}
result = session.execute(program);
}
if (login && interactive && !opt.isSet("noshutdown")) {
if (terminal != null) {
terminal.writer().println("gosh: stopping framework");
terminal.flush();
}
shutdown();
}
return result;
} finally {
if (tio != null) {
tio.close();
}
}
}
Aggregations