I have the following code and I can't figure out why it won't work:
final ByteArrayOutputStream bos = new ByteArrayOutputStream();
final String p1 = "HELLO WORLD";
process(p1, bos);
Assert.assertEquals("BOS value should be: "+p1, p1, bos.toString("UTF-8"));
It prints:
junit.framework.ComparisonFailure: BOS value should be: HELLO WORLD expected:<[HELLO WORLD]> but was:<[]> at junit.framework.Assert.assertEquals(Assert.java:81) etc...
and process looks like this:
public static void process(final String p1, final OutputStream os) {
final Runtime rt = Runtime.getRuntime();
try {
final String command = "echo " + p1;
log.info("Executing Command: " + command);
final Process proc = rt.exec(command);
// gobble error and output
StreamGobbler.go(proc.getErrorStream(), null);
StreamGobbler.go(proc.getInputStream(), os);
// wait for the exit
try {
final int exitVal = proc.waitFor();
log.info("Command Exit Code: " + exitVal);
} catch (InterruptedException e) {
log.error("Interrupted while waiting for command to execute", e);
}
} catch (IOException e) {
log.error("IO Exception while executing command", e);
}
}
private static class StreamGobbler extends Thread {
private final InputStream is;
private final OutputStream os;
private static StreamGobbler go(InputStream is, OutputStream os) {
final StreamGobbler gob = new StreamGobbler(is, os);
gob.start();
return gob;
}
private StreamGobbler(InputStream is, OutputStream os) {
this.is = is;
this.os = os;
}
public void run() {
try {
final PrintWriter pw = ((os == null) ? null : new PrintWriter(os));
final InputStreamReader isr = new InputStreamReader(is);
final BufferedReader br = new BufferedReader(isr);
String line = null;
while ((line = br.readLine()) != null) {
if (pw != null) {
pw.println(line);
}
log.info(line); // Prints HELLO WORLD to log
}
if (pw != null) {
pw.flush();
}
} catch (IOException ioe) {
log.error("IO error while globbing", ioe);
}
}
When I run the jUnit test I get an empty string as the actual. I don't understand why this wont work.
EDIT: I am using RHEL5 and eclipse 3.6 if that makes a difference at all.
maybe you should wait on the thread filling the stream:
Thread thr = StreamGobbler.go(proc.getInputStream(), os);
// wait for the exit
try {
final int exitVal = proc.waitFor();
log.info("Command Exit Code: " + exitVal);
thr.join();//waits for the gobbler that processes the stdout of the process
} catch (InterruptedException e) {
log.error("Interrupted while waiting for command to execute", e);
}