mardi 7 novembre 2017

Capturing stdout from java.lang.reflect method invocation

I have an application that, among other things, runs Java methods via java.lang.reflect. It normally functions as normal; however, a user used it with one of their JARs, and it broke somewhat.

As you can see in the below code, I attempt to capture both stdout and stdin from the method. However, when the method is invoked, only the first line of what the method streams to stdout is actually captured.

Here's the relevant code. If you need to see more of the code, let me know, and I'll add some more:

String retVal = "";
ByteArrayOutputStream out = new ByteArrayOutputStream();
ByteArrayOutputStream err = new ByteArrayOutputStream();

PrintStream origOut = System.out;
PrintStream origErr = System.err;

System.setOut(new PrintStream(out));
System.setErr(new PrintStream(err));

Exception myException = null;

try {
    Object myRetVal = null;
    myRetVal = m.invoke(obj, convertedMethodArguments);

    if (myRetVal != null)
        retVal = myRetVal.toString();
} catch (Exception e) {
    myException = e;
}

returnObj.addProperty("stdout", out.toString());
returnObj.addProperty("stderr", err.toString());
returnObj.addProperty("rv", retVal);
returnObj.addProperty("rt", m.getReturnType().toString());

if (myException != null && myException.getCause() != null)
    returnObj.addProperty("exception", myException.getCause().toString());
else
    returnObj.addProperty("exception", "");

System.setOut(origOut);
System.setErr(origErr);

System.out.print(new Gson().toJson(returnObj));

// TODO: remove, debug purposes only
// Should use normal stdout
try {
    System.out.println();
    m.invoke(obj, convertedMethodArguments);
} catch (Exception e) {
    System.out.println(e.toString());
}

When I execute the above code, it only prints out the first line of stdout. However, at the bottom of the code block, I invoke the method again, but this time without any redirection, and I get all of the stdout from the method.

Any help would be greatly appreciated!





Aucun commentaire:

Enregistrer un commentaire