1 package org.simantics.gnuplot;
3 import java.io.BufferedReader;
4 import java.io.Closeable;
5 import java.io.IOException;
6 import java.io.InputStream;
7 import java.io.InputStreamReader;
8 import java.io.PrintStream;
9 import java.nio.file.Files;
10 import java.nio.file.Path;
13 * @author Tuukka Lehtonen
16 public class GnuplotSession implements Closeable {
18 private Process process;
19 private PrintStream out;
21 private Thread stdoutDumper;
22 private Thread stderrDumper;
24 GnuplotSession(Path workingDirectory, boolean drainStdout, boolean drainStderr, Process process) {
25 this.process = process;
26 this.out = new PrintStream(process.getOutputStream());
28 stdoutDumper = new Thread(new InputStreamToFileCopier(process.getInputStream(), null));
32 stderrDumper = new Thread(new InputStreamToFileCopier(process.getErrorStream(), null));
37 private void assertAlive() {
39 throw new IllegalStateException("session has been closed already");
42 public void evaluate(String commands) throws IOException {
44 out.println(commands);
47 public void evaluateStream(InputStream input, String charset) throws IOException {
48 try (BufferedReader br = new BufferedReader(new InputStreamReader(input, charset))) {
49 for (String line = br.readLine(); null != line; line = br.readLine()) {
56 public void evaluateFile(Path file) throws IOException {
58 Files.lines(file).forEachOrdered(l -> {
61 } catch (IOException e) {
62 throw new RuntimeException(e);
65 } catch (RuntimeException e) {
66 Throwable t = e.getCause();
67 if (t instanceof IOException)
68 throw (IOException) t;
74 public void close() throws IOException {
82 // Inform the process that its stdin has closed, i.e. is done.
85 // Wait for the outputs to be closed by the process itself.
86 if (stdoutDumper != null)
88 if (stderrDumper != null)
91 //System.out.println("gnuplot process ended");
92 } catch (InterruptedException e) {
93 throw new IOException(e);