--- /dev/null
+package org.simantics.gnuplot;
+
+import java.io.Closeable;
+import java.io.IOException;
+import java.io.PrintStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+
+/**
+ * @author Tuukka Lehtonen
+ * @since 1.24
+ */
+public class GnuplotSession implements Closeable {
+
+ private Process process;
+ private PrintStream out;
+
+ private Thread stdoutDumper;
+ private Thread stderrDumper;
+
+ GnuplotSession(Path workingDirectory, Path stdout, Path stderr, Process process) {
+ this.process = process;
+ this.out = new PrintStream(process.getOutputStream());
+ stdoutDumper = new Thread(new InputStreamToFileCopier(process.getInputStream(), stdout));
+ stderrDumper = new Thread(new InputStreamToFileCopier(process.getErrorStream(), stderr));
+ stdoutDumper.start();
+ stderrDumper.start();
+ }
+
+ private void assertAlive() {
+ if (process == null)
+ throw new IllegalStateException("session has been closed already");
+ }
+
+ public void evaluate(String commands) throws IOException {
+ assertAlive();
+ out.println(commands);
+ }
+
+ public void evaluateFile(Path file) throws IOException {
+ try {
+ Files.lines(file).forEachOrdered(l -> {
+ try {
+ evaluate(l);
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ });
+ } catch (RuntimeException e) {
+ Throwable t = e.getCause();
+ if (t instanceof IOException)
+ throw (IOException) t;
+ throw e;
+ }
+ }
+
+ @Override
+ public void close() throws IOException {
+ Process p = process;
+ synchronized (this) {
+ if (process == null)
+ return;
+ process = null;
+ }
+
+ // Inform the process that its stdin has closed, i.e. is done.
+ out.close();
+ try {
+ // Wait for the outputs to be closed by the process itself.
+ stdoutDumper.join();
+ stderrDumper.join();
+ p.waitFor();
+ //System.out.println("gnuplot process ended");
+ } catch (InterruptedException e) {
+ throw new IOException(e);
+ }
+ }
+
+}