com.github.kaisle.util.RuntimeUtil Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of DotA2-Wrapper Show documentation
Show all versions of DotA2-Wrapper Show documentation
A wrapper for the DotA2 WebAPI written in Java.
package com.github.kaisle.util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
/**
* Created by Anders Borum on 03-06-2015.
*/
public class RuntimeUtil {
private final Logger log = LoggerFactory.getLogger(RuntimeUtil.class.getPackage().getClass());
/**
* Build a process from an array of commands and the directory in which to execute it.
* @param commands An array of commands.
* @param directory Target directory.
* @return An executable process.
*/
public ProcessBuilder buildProcess(String[] commands, File directory) {
log.info("Building process.");
ProcessBuilder process = new ProcessBuilder(commands);
process.directory(directory);
process.redirectErrorStream(true);
return process;
}
/**
* Execute a process.
* @param processBuilder The process to execute.
* @return A list of input lines received in the console during the process.
*/
public ArrayList executeWithTimeout(ProcessBuilder processBuilder, int timeout, TimeUnit timeUnit) {
final ArrayList inputString = new ArrayList();
try {
log.info("Starting process.");
final Process process = processBuilder.start();
final Thread ioThread = inputReader(process.getInputStream(), inputString);
ioThread.start();
try {
log.info("Waiting for process.");
process.waitFor(timeout, timeUnit);
} catch (InterruptedException e) {
e.printStackTrace();
}
finally {
log.info("Timing out process.");
process.destroy();
log.info("Process terminated.");
}
} catch (IOException e) {
e.printStackTrace();
}
return inputString;
}
/**
* Write each line of an input stream to a list.
* @param inputStream
* @param inputString
* @return
*/
public Thread inputReader(InputStream inputStream, List inputString) {
Runnable runnable = () -> {
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line = null;
log.info("Reading input.");
try {
while ((line = reader.readLine()) != null) {
inputString.add(line);
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
};
return new Thread(runnable);
}
}