]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.gnuplot/src/org/simantics/gnuplot/GnuplotSession.java
32534e0cf8baff32b0c4e4d9640966fdc50becac
[simantics/platform.git] / bundles / org.simantics.gnuplot / src / org / simantics / gnuplot / GnuplotSession.java
1 package org.simantics.gnuplot;
2
3 import java.io.Closeable;
4 import java.io.IOException;
5 import java.io.PrintStream;
6 import java.nio.file.Files;
7 import java.nio.file.Path;
8
9 /**
10  * @author Tuukka Lehtonen
11  * @since 1.24
12  */
13 public class GnuplotSession implements Closeable {
14
15     private Process process;
16     private PrintStream out;
17
18     private Thread stdoutDumper;
19     private Thread stderrDumper;
20
21     GnuplotSession(Path workingDirectory, Path stdout, Path stderr, Process process) {
22         this.process = process;
23         this.out = new PrintStream(process.getOutputStream());
24         stdoutDumper = new Thread(new InputStreamToFileCopier(process.getInputStream(), stdout));
25         stderrDumper = new Thread(new InputStreamToFileCopier(process.getErrorStream(), stderr));
26         stdoutDumper.start();
27         stderrDumper.start();
28     }
29
30     private void assertAlive() {
31         if (process == null)
32             throw new IllegalStateException("session has been closed already");
33     }
34
35     public void evaluate(String commands) throws IOException {
36         assertAlive();
37         out.println(commands);
38     }
39
40     public void evaluateFile(Path file) throws IOException {
41         try {
42             Files.lines(file).forEachOrdered(l -> {
43                 try {
44                     evaluate(l);
45                 } catch (IOException e) {
46                     throw new RuntimeException(e);
47                 }
48             });
49         } catch (RuntimeException e) {
50             Throwable t = e.getCause();
51             if (t instanceof IOException)
52                 throw (IOException) t;
53             throw e;
54         }
55     }
56
57     @Override
58     public void close() throws IOException {
59         Process p = process;
60         synchronized (this) {
61             if (process == null)
62                 return;
63             process = null;
64         }
65
66         // Inform the process that its stdin has closed, i.e. is done.
67         out.close();
68         try {
69             // Wait for the outputs to be closed by the process itself.
70             stdoutDumper.join();
71             stderrDumper.join();
72             p.waitFor();
73             //System.out.println("gnuplot process ended");
74         } catch (InterruptedException e) {
75             throw new IOException(e);
76         }
77     }
78
79 }