Write output to separate streams (error and output)

This will allow to write errors and output to the console handler as usual, but will help to handle errors from external binaries (such as aapt, executed by exec method) in all initialized logger handlers, not only console, but text handler, for ex.
This commit is contained in:
Andrei Zhukouski 2016-01-05 10:39:07 +03:00
parent 47076ebaba
commit 74e0aa0bd2

View File

@ -19,6 +19,7 @@ package brut.util;
import brut.common.BrutException;
import java.io.*;
import java.util.Arrays;
import java.util.logging.Logger;
import org.apache.commons.io.IOUtils;
@ -26,6 +27,9 @@ import org.apache.commons.io.IOUtils;
* @author Ryszard Wiśniewski <brut.alll@gmail.com>
*/
public class OS {
private static final Logger LOGGER = Logger.getLogger("");
public static void rmdir(File dir) throws BrutException {
if (! dir.exists()) {
return;
@ -80,21 +84,19 @@ public class OS {
public static void exec(String[] cmd) throws BrutException {
Process ps = null;
int exitValue = -99;
try {
ps = Runtime.getRuntime().exec(cmd);
new StreamForwarder(ps.getInputStream(), System.err).start();
new StreamForwarder(ps.getErrorStream(), System.err).start();
if (ps.waitFor() != 0) {
throw new BrutException(
"could not exec command: " + Arrays.toString(cmd));
}
ProcessBuilder builder = new ProcessBuilder(cmd);
ps = builder.start();
new StreamForwarder(ps.getErrorStream(), "ERROR").start();
new StreamForwarder(ps.getInputStream(), "OUTPUT").start();
exitValue = ps.waitFor();
if (exitValue != 0)
throw new BrutException("could not exec (exit code = " + exitValue + "): " + Arrays.toString(cmd));
} catch (IOException ex) {
throw new BrutException(
"could not exec command: " + Arrays.toString(cmd), ex);
throw new BrutException("could not exec: " + Arrays.toString(cmd), ex);
} catch (InterruptedException ex) {
throw new BrutException(
"could not exec command: " + Arrays.toString(cmd), ex);
throw new BrutException("could not exec : " + Arrays.toString(cmd), ex);
}
}
@ -115,30 +117,29 @@ public class OS {
static class StreamForwarder extends Thread {
public StreamForwarder(InputStream in, OutputStream out) {
mIn = in;
mOut = out;
StreamForwarder(InputStream is, String type) {
mIn = is;
mType = type;
}
@Override
public void run() {
try {
BufferedReader in = new BufferedReader(
new InputStreamReader(mIn));
BufferedWriter out = new BufferedWriter(
new OutputStreamWriter(mOut));
BufferedReader br = new BufferedReader(new InputStreamReader(mIn));
String line;
while ((line = in.readLine()) != null) {
out.write(line);
out.newLine();
while ((line = br.readLine()) != null) {
if (mType.equals("OUTPUT")) {
LOGGER.info(line);
} else {
LOGGER.warning(line);
}
}
out.flush();
} catch (IOException ex) {
ex.printStackTrace();
}
}
private final InputStream mIn;
private final OutputStream mOut;
private final String mType;
}
}