int exitValue;
void setExitValue(int value) {
exitValue=value;
}
int getExitValue(){
return exitValue;
}
private String error;
/**
* @return the error
*/
public String getError() {
return error;
}
/**
* @param error the error to set
*/
public void setError(String error) {
this.error = error;
}
}
最重要的Command.java代码:
[plain]
package command;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* Describe class Command here.
*
*/
public class Command {
private long startTime;
private long timeout;
private static final long INTERVAL = 500;
/*
* command is one system command represented by string
* timeout is milliseconds for waiting the command execution
* throw CommandError if the system command can't be executed
* return CommandResult when the system command is executed no matter what the command returns(succeed or failed)
*/
public CommandResult exec(final String command, long timeout) throws CommandError {
this.timeout = timeout;
try {
Process process = Runtime.getRuntime().exec(command);
CommandResult result = wait(process);
if (process != null) {
process.destroy();
}
return result;
} catch (Exception ex) {
throw new CommandError(ex);
}
}
private boolean isTimeout() {
return System.currentTimeMillis() - startTime >= timeout;
}
private CommandResult wait(final Process process) throws InterruptedException, IOException {
BufferedReader errorStreamReader = null;
BufferedReader inputStreamReader = null;
try {
errorStreamReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
inputStreamReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
//timeout control
startTime = System.currentTimeMillis();
boolean isFinished = false;
for (;;) {
if (isTimeout()) {
CommandResult result = new CommandResult();
result.setExitValue(CommandResult.EXIT_VALUE_TIMEOUT);
result.setOutput("Command process timeout");
return result;
}
if (isFinished) {
CommandResult result = new CommandResult();
result.setExitValue(process.waitFor());
//parse error info
if (errorStreamReader.ready()) {
StringBuilder buffer = new StringBuilder();
String line;
while ((line = errorStreamReader.readLine()) != null) {
buffer.append(line);
}
result.setError(buffer.toString());
}
if (inputStreamReader.ready()) {
StringBuilder buffer = new StringBuilder();
String line;
while ((line = inputStreamReader.readLine()) != null) {