1

I am developing an application which needs to call some Jenkins instances, to do this I am using the jenkins-cli .jar
I could be calling the jar using the commandline to easily extract its output. Then however I need to parse exceptions myself.
To properly handle exceptions I am now invoking the main method of the jar via reflection:

URLClassLoader jenkinsClassloader = new URLClassLoader(new URL[]{"UrlToJenkins-Cli.jar"}, getClass().getClassLoader());
Class<?> jenkinsCli = Class.forName ("hudson.cli.CLI", false, jenkinsClassloader);
Method mainMethod = jenkinsCli.getDeclaredMethod("main", String[].class);
mainMethod.invoke (null, (Object) commandArray);

But now I need to somehow get the output the jar prints to System.out
I know I can use System.setOut(). The problem there is that I have other threads logging simultaniously. I read here that System.out is classloader specific, but I couldn't find any additional information about this.
Does someone know a way to get the stdout of the jar without it being interfered with from other threads?

Community
  • 1
  • 1
  • 1
    That other answer is wrong: `System.out` is definitely not class loader specific. Perhaps you could use `System.setOut` so that the `PrintStream` was caller-sensitive, but it doesn't do that by default either. – Brett Kail Apr 18 '17 at 13:09
  • Ah I see, I hoped for there to be an easy solution. Thanks for clearing things up – ElectronicManuel Apr 19 '17 at 19:47

1 Answers1

1

One possibility would be to create a custom class extending PrintStream, that would simply pass whatever is passed to it to another PrintStream, then wrap that around System.out, via System.setOut(); the custom class could have a ThreadLocal private attribute that could be used to tell it if, for the current thread, the text should be intercepted.

Not the most elegant of solutions, but could be a good fallback if no alternative is found.

Haroldo_OK
  • 6,612
  • 3
  • 43
  • 80