use of com.jcraft.jsch.ChannelExec in project winery by eclipse.
the class InstanceModelUtils method executeCommand.
public static String executeCommand(Session session, String command) {
ChannelExec channelExec = null;
try {
logger.info("Executing script: \"{}\"", command);
channelExec = (ChannelExec) session.openChannel("exec");
channelExec.setCommand(command);
StringBuilder outputBuffer = new StringBuilder();
StringBuilder errorBuffer = new StringBuilder();
InputStream in = channelExec.getInputStream();
InputStream err = channelExec.getExtInputStream();
channelExec.connect();
byte[] tmp = new byte[1024];
int timer = 0;
while (true) {
while (in.available() > 0) {
int i = in.read(tmp, 0, 1024);
if (i < 0)
break;
outputBuffer.append(new String(tmp, 0, i));
}
while (err.available() > 0) {
int i = err.read(tmp, 0, 1024);
if (i < 0)
break;
errorBuffer.append(new String(tmp, 0, i));
}
if (channelExec.isClosed() && in.available() == 0 && err.available() == 0) {
break;
}
if (timer++ % 5 == 0) {
logger.info("Still executing...");
}
// noinspection BusyWait
Thread.sleep(1000);
}
if (!errorBuffer.toString().isEmpty()) {
logger.error(errorBuffer.toString());
}
if (!outputBuffer.toString().isEmpty()) {
logger.info(outputBuffer.toString());
}
logger.info("\"{}\" exited with code '{}'", command, channelExec.getExitStatus());
return outputBuffer.toString().trim();
} catch (JSchException | InterruptedException | IOException e) {
throw new RuntimeException("Failed to execute command \"" + command + "\"");
} finally {
if (channelExec != null) {
channelExec.disconnect();
}
}
}
Aggregations