1
2
3
4
5 package org.astrogrid.io.trace;
6
7
8 import java.io.DataOutputStream;
9 import java.io.File;
10 import java.io.FileNotFoundException;
11 import java.io.FileOutputStream;
12 import java.io.IOException;
13
14 /***
15 * Copies the data coming through the stream to a trace window, for debug
16 * purposes.
17 *
18 * @author: M Hill
19 */
20
21 public class TraceInputStream extends java.io.FilterInputStream
22 {
23 private TraceWindow traceWindow = null;
24 private boolean on = false;
25 private DataOutputStream copyStream = null;
26
27 /***
28 * Constructor - pass in the stream to monitor
29 */
30 public TraceInputStream(java.io.InputStream in) {
31 super(in);
32 }
33
34 /***
35 * Returns the trace window. Creates it if it does not yet exist.
36 */
37 private TraceWindow getTraceWindow() {
38
39 if (traceWindow == null) {
40 traceWindow = new TraceWindow();
41 traceWindow.setTitle(toString());
42 traceWindow.show();
43 }
44
45 return traceWindow;
46 }
47
48 /***
49 * Reads (and returns) a byte, and displays if the trace is 'on'
50 * @return int
51 */
52 public int read() throws java.io.IOException {
53
54 if (!on) {
55 return super.read();
56 } else {
57 int i = super.read();
58
59 if (getTraceWindow().isShowing())
60 getTraceWindow().write(i);
61 else {
62 setState(false);
63 traceWindow = null;
64 }
65
66 if (copyStream != null)
67 {
68 copyStream.write(i);
69
70
71 }
72
73 return i;
74 }
75 }
76
77 /***
78 * Overrides normal read() to display data
79 * @return int
80 */
81 public int read(byte[] b, int off, int len) throws java.io.IOException
82 {
83 if (!on) {
84 return super.read(b, off, len);
85 } else {
86 int i = super.read(b, off, len);
87
88 if (getTraceWindow().isShowing())
89 for (int j=0;j<len;j++) getTraceWindow().write(b[j+off]);
90 else {
91 setState(false);
92 traceWindow = null;
93 }
94
95 if (copyStream != null)
96 {
97 copyStream.write(i);
98
99
100 }
101
102 return i;
103 }
104 }
105
106 /***
107 * Switches the trace on/off
108 */
109 public void setState(boolean newOn)
110 {
111 on = newOn;
112 }
113
114 /***
115 * Copies throughput to given file
116 */
117 public void copy2File(File givenFile) throws FileNotFoundException, IOException
118 {
119 copyStream = new DataOutputStream(new FileOutputStream(givenFile, true));
120 copyStream.writeChars("\n");
121 copyStream.writeChars("\n");
122 }
123 }
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142