use of org.apache.commons.exec.PumpStreamHandler in project elasticsearch-maven-plugin by alexcojocaru.
the class ProcessUtil method executeScript.
/**
* Run the given command as a process within the supplied instance config context
* and wait until it finalizes. An ElasticsearchSetupException is thrown if the exit code
* is not 0.
* @param config - the instance config
* @param command - the command to execute
* @param environment - a map of environment variables; can be null
* @param processDestroyer - a destroyer handler for the spawned process; can be null
* @param disableLogging - whether to disable the logging of the command or not
* @return the output (not trimmed of whitespaces) of the given command, as separate lines
*/
public static List<String> executeScript(InstanceConfiguration config, CommandLine command, Map<String, String> environment, ProcessDestroyer processDestroyer, boolean disableLogging) {
Log log = config.getClusterConfiguration().getLog();
int instanceId = config.getId();
File baseDir = new File(config.getBaseDir());
Map<String, String> completeEnvironment = createEnvironment(environment);
DefaultExecutor executor = new DefaultExecutor();
executor.setWorkingDirectory(baseDir);
// allows null
executor.setProcessDestroyer(processDestroyer);
// set up a tap on the output stream, to collect to output and return it from this method
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ByteArrayOutputStream errorStream = new ByteArrayOutputStream();
executor.setStreamHandler(new PumpStreamHandler(disableLogging ? outputStream : new TeeOutputStream(System.out, outputStream), disableLogging ? errorStream : new TeeOutputStream(System.err, errorStream)));
try {
log.debug(String.format("Using environment: %s", completeEnvironment));
String commandMessage = String.format("Elasticsearch[%d]: Executing command '%s' in directory '%s'", instanceId, command.toString(), baseDir);
if (disableLogging) {
log.debug(commandMessage);
} else {
log.info(commandMessage);
}
int exitCode = executor.execute(command, completeEnvironment);
if (exitCode != 0) {
throw new ElasticsearchSetupException(String.format("Elasticsearch [%d]: Command '%s' in directory '%s' finished with exit code %d; see above for details", instanceId, command, baseDir, exitCode));
}
String resultMessage = String.format("Elasticsearch[%d]: The process finished with exit code %d", instanceId, exitCode);
if (disableLogging) {
log.debug(resultMessage);
} else {
log.info(resultMessage);
}
} catch (IOException e) {
List<String> output = readBuffer(outputStream);
List<String> error = readBuffer(errorStream);
String lineSeparator = System.getProperty("line.separator");
StringBuilder message = new StringBuilder();
message.append("Elasticsearch [");
message.append(instanceId);
message.append("]: Cannot execute command '");
message.append(command);
message.append("' in directory '");
message.append(baseDir);
message.append("'");
message.append(lineSeparator);
message.append("Output:");
message.append(lineSeparator);
message.append(StringUtils.join(output, lineSeparator));
message.append(lineSeparator);
message.append("Error:");
message.append(lineSeparator);
message.append(StringUtils.join(error, lineSeparator));
throw new ElasticsearchSetupException(message.toString(), e);
}
return readBuffer(outputStream);
}
use of org.apache.commons.exec.PumpStreamHandler in project alliance by codice.
the class MpegTsUdpClient method getVideoDuration.
private static Duration getVideoDuration(final String videoFilePath) {
try (final ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
final PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
final CommandLine command = getFFmpegInfoCommand(videoFilePath);
final DefaultExecuteResultHandler resultHandler = executeFFmpeg(command, 3, streamHandler);
resultHandler.waitFor();
final String output = outputStream.toString(StandardCharsets.UTF_8.name());
return parseVideoDuration(output);
} catch (InterruptedException e) {
LOGGER.error("Thread interrupted while executing ffmpeg command.", e);
} catch (UnsupportedEncodingException e) {
LOGGER.error("Unsupported encoding in ffmpeg output.", e);
} catch (IllegalArgumentException e) {
LOGGER.error("Unable to parse video duration.", e);
} catch (IOException | IllegalStateException e) {
LOGGER.error("Unable to execute ffmpeg command.", e);
}
return null;
}
use of org.apache.commons.exec.PumpStreamHandler in project openj9 by eclipse.
the class SoftmxRASTest1 method startSecondJVM.
/**
* Starts a JVM in a subproces
* @param xmxVal : -Xmx value to use in the command line of the JVM to be spawned
* @param softmxVal : -Xsoftmx value to use in the command line of the JVM to be spawned
* @param classToRun : The class that should be run using java
* @return : return code of the sub-process which runs the JVM
* @throws IOException
* @throws InterruptedException
*/
public static int startSecondJVM(long xmxVal, long softmxVal, Class<?> classToRun) throws IOException, InterruptedException {
List<String> arguments = new ArrayList<String>();
/* pass parent JVM options to the child JVMs. */
List<String> inputArgs = ManagementFactory.getRuntimeMXBean().getInputArguments();
// Include -X, but not -Xdump, arguments from parent first to allow for later overrides.
for (String arg : inputArgs) {
if (arg.startsWith("-X") && !arg.startsWith("-Xdump")) {
arguments.add(arg);
}
}
// We're only interested in generating javacore files: disable other dumps.
// first disable all dump agents
arguments.add("-Xdump:none");
// now enable javacore files for systhrow of OutOfMemoryError
arguments.add("-Xdump:java:events=systhrow,filter=java/lang/OutOfMemoryError");
String classpath = System.getProperty("java.class.path");
arguments.add("-cp");
arguments.add(classpath);
arguments.add("-Xmx" + xmxVal + "M");
if (softmxVal != -1) {
arguments.add("-Xsoftmx" + softmxVal + "M");
}
arguments.add("-Xmn1M");
arguments.add(classToRun.getCanonicalName());
StringBuilder cmdLineBuffer = new StringBuilder();
String javaPath = System.getProperty("java.home") + "/bin/java";
cmdLineBuffer.append(javaPath);
for (String argument : arguments) {
cmdLineBuffer.append(' ').append(argument);
}
String cmdLineStr = cmdLineBuffer.toString();
logger.debug("Executing cmd: " + cmdLineStr);
CommandLine cmdLine = CommandLine.parse(cmdLineStr);
DefaultExecutor executor = new DefaultExecutor();
PumpStreamHandler strmHndlr = new PumpStreamHandler(System.out);
executor.setWorkingDirectory(new File("."));
executor.setStreamHandler(strmHndlr);
int exitValue;
try {
exitValue = executor.execute(cmdLine);
} catch (ExecuteException e) {
exitValue = -1;
}
return exitValue;
}
use of org.apache.commons.exec.PumpStreamHandler in project vespa by vespa-engine.
the class CommandExecutor method writeToOutputStream.
private void writeToOutputStream(ByteArrayOutputStream outputStream, String command) throws IOException {
CommandLine cmdLine = new CommandLine("/bin/bash");
cmdLine.addArgument("-c", false);
cmdLine.addArgument(command, false);
DefaultExecutor executor = new DefaultExecutor();
PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
executor.setStreamHandler(streamHandler);
executor.execute(cmdLine);
}
use of org.apache.commons.exec.PumpStreamHandler in project oxCore by GluuFederation.
the class ProcessHelper method executeProgram.
public static boolean executeProgram(CommandLine commandLine, String workingDirectory, boolean executeInBackground, int successExitValue, OutputStream outputStream) {
long printJobTimeout = PRINT_JOB_TIMEOUT;
ExecuteStreamHandler streamHandler = null;
if (outputStream != null) {
streamHandler = new PumpStreamHandler(outputStream);
}
PrintResultHandler printResult = null;
try {
LOG.debug(String.format("Preparing to start process %s", commandLine.toString()));
printResult = executeProgram(commandLine, workingDirectory, printJobTimeout, executeInBackground, successExitValue, streamHandler);
LOG.debug(String.format("Successfully start process %s", commandLine.toString()));
} catch (Exception ex) {
LOG.trace(String.format("Problem during starting process %s", commandLine.toString()), ex);
ex.printStackTrace();
return false;
}
// come back to check the print result
LOG.debug(String.format("Waiting for the proces %s finish", commandLine.toString()));
try {
if (printResult == null) {
return false;
}
printResult.waitFor();
} catch (InterruptedException ex) {
LOG.error(String.format("Problem during process execution %s", commandLine.toString()), ex);
}
LOG.debug(String.format("Process %s has finished", commandLine.toString()));
return true;
}
Aggregations