Hi all
(I have coders block )
I am looking to write a robust generic command line interface class for Java. I have hacked together something that is working quite well. I am hoping that I can get a few people to try different commands and see how well it works on machines other than my own. Also suggestions on how the code could be tuned are appreciated.
Im not 100% happy with the “processErrorMessage” and “processResultMessage” methods.
Who knows, maybe it works well and people will actually like it...?
Code:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class CLIProcess implements Runnable {
private static final int INIT_WAIT = 1000;
private static final int STREAM_WAIT = 1000;
public static final int IN_PROGRESS = -1;
private boolean running;
private int result = IN_PROGRESS;
private String command;
private String errorMessage;
private String successMessage;
private Process process;
public CLIProcess(String command) {
this.command = command;
running = false;
}
public void run() {
running = true;
try {
Runtime runTime = Runtime.getRuntime();
process = runTime.exec(command);
try {
Thread.sleep(INIT_WAIT);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
errorMessage = processStream(process.getErrorStream());
successMessage = processStream(process.getInputStream());
result = process.waitFor();
} catch (InterruptedException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
running = false;
}
}
private String processStream(InputStream is) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuilder bs = new StringBuilder();
while (br.ready()) {
bs.append(br.readLine());
try {
Thread.sleep(STREAM_WAIT);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
return bs.toString().trim();
}
public int getResult() {
return result;
}
public boolean isRunning() {
return running;
}
public String getErrorMessage() {
return errorMessage;
}
public String getSuccessMessage() {
return successMessage;
}
}
Code:
public class Main {
public static void main(String[] args) {
try {
CLIProcess pro = new CLIProcess("gksu apt-get update");
Thread thread = new Thread(pro);
thread.start();
Thread.sleep(500);
while (pro.isRunning()) {
Thread.sleep(500);
}
System.out.println("Result Code: " + pro.getResult());
System.out.println("Result: " + pro.getSuccessMessage());
System.out.println("Error: " + pro.getErrorMessage());
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
}
Cheers
Bookmarks