package org.simantics.gnuplot; import java.io.BufferedReader; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; 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, boolean drainStdout, boolean drainStderr, Process process) { this.process = process; this.out = new PrintStream(process.getOutputStream()); if (drainStdout) { stdoutDumper = new Thread(new InputStreamToFileCopier(process.getInputStream(), null)); stdoutDumper.start(); } if (drainStderr) { stderrDumper = new Thread(new InputStreamToFileCopier(process.getErrorStream(), null)); 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 evaluateStream(InputStream input, String charset) throws IOException { try (BufferedReader br = new BufferedReader(new InputStreamReader(input, charset))) { for (String line = br.readLine(); null != line; line = br.readLine()) { out.println(line); out.println(); } } } 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. if (stdoutDumper != null) stdoutDumper.join(); if (stderrDumper != null) stderrDumper.join(); p.waitFor(); //System.out.println("gnuplot process ended"); } catch (InterruptedException e) { throw new IOException(e); } } }