package net.fusejna;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * Run a process, grab all from stdout, return that.
 */
final class ProcessGobbler
{
	private static final class Gobbler extends Thread
	{
		private final InputStream stream;
		private String contents = null;
		private boolean failed = false;

		Gobbler(final InputStream stream)
		{
			this.stream = stream;
			start();
		}

		private final String getContents()
		{
			if (failed) {
				return null;
			}
			return contents;
		}

		@Override
		public final void run()
		{
			final BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
			final StringBuilder contents = new StringBuilder();
			String line;
			try {
				while ((line = reader.readLine()) != null) {
					contents.append(line);
				}
			}
			catch (final IOException e) {
				failed = true;
				return;
			}
			this.contents = contents.toString();
		}
	}

	private final Process process;
	private final Gobbler stdout;
	private final Gobbler stderr;
	private Integer returnCode = null;

	ProcessGobbler(final String... args) throws IOException
	{
		process = new ProcessBuilder(args).start();
		stdout = new Gobbler(process.getInputStream());
		stderr = new Gobbler(process.getErrorStream());
	}

	int getReturnCode()
	{
		join();
		return returnCode;
	}

	String getStderr()
	{
		join();
		return stderr.getContents();
	}

	String getStdout()
	{
		join();
		return stdout.getContents();
	}

	private void join()
	{
		try {
			returnCode = process.waitFor();
		}
		catch (final InterruptedException e) {
			// Too bad
		}
	}
}

@@ -1343,39 +1343,135 @@
 turnCode()%0A%09%7B%0A%09%09
-join();
+try %7B%0A%09%09%09returnCode = process.waitFor();%0A%09%09%7D%0A%09%09catch (final InterruptedException e) %7B%0A%09%09%09// Too bad%0A%09%09%7D
 %0A%09%09return return
@@ -1509,83 +1509,96 @@
 %7B%0A%09%09
-join();%0A%09%09return stderr.getContents
+try %7B%0A%09%09%09stderr.join
 ();%0A
+%09
 %09%7D%0A
-%0A%09String getStdout()%0A%09%7B%0A%09%09join();
+%09%09catch (final InterruptedException e) %7B%0A%09%09%09return null;%0A%09%09%7D
 %0A%09%09r
@@ -1606,19 +1606,19 @@
 turn std
-out
+err
 .getCont
@@ -1634,70 +1634,52 @@
 %7D%0A%0A%09
-private void join()%0A%09%7B%0A%09%09try %7B%0A%09%09%09returnCode = process.waitFor
+String getStdout()%0A%09%7B%0A%09%09try %7B%0A%09%09%09stdout.join
 ();%0A
@@ -1726,28 +1726,61 @@
 e) %7B%0A%09%09%09
-// Too bad%0A%09%09%7D
+return null;%0A%09%09%7D%0A%09%09return stdout.getContents();
 %0A%09%7D%0A%7D%0A

Remove race condition reading process output