1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47 package org.codehaus.groovy.control.io;
48
49 import java.io.BufferedReader;
50 import java.io.IOException;
51
52 import org.codehaus.groovy.control.CompilerConfiguration;
53 import org.codehaus.groovy.control.Janitor;
54
55
56 /***
57 * For ReaderSources that can choose a parent class, a base that
58 * provides common functionality.
59 *
60 * @author <a href="mailto:cpoirier@dreaming.org">Chris Poirier</a>
61 *
62 * @version $Id: AbstractReaderSource.java,v 1.1 2004/04/19 07:29:44 cpoirier Exp $
63 */
64
65 public abstract class AbstractReaderSource implements ReaderSource
66 {
67 protected CompilerConfiguration configuration;
68
69
70 /***
71 * Standard construction stuff.
72 */
73
74 public AbstractReaderSource( CompilerConfiguration configuration )
75 {
76 this.configuration = configuration;
77 }
78
79
80 /***
81 * Returns true if the source can be restarted (ie. if getReader()
82 * will return non-null on subsequent calls.
83 */
84
85 public boolean canReopenSource()
86 {
87 return true;
88 }
89
90
91
92
93
94
95
96 private BufferedReader lineSource = null;
97 private String line = null;
98 private int number = 0;
99
100
101 /***
102 * Returns a line from the source, or null, if unavailable. If
103 * you supply a Janitor, resources will be cached.
104 */
105
106 public String getLine( int lineNumber, Janitor janitor )
107 {
108
109
110
111
112 if( lineSource != null && number > lineNumber )
113 {
114 cleanup();
115 }
116
117
118
119
120
121 if( lineSource == null )
122 {
123 try { lineSource = new BufferedReader( getReader() ); } catch( Exception e ) {}
124 number = 0;
125 }
126
127
128
129
130
131 if( lineSource != null )
132 {
133 while( number < lineNumber )
134 {
135 try
136 {
137 line = lineSource.readLine();
138 number++;
139 }
140 catch( IOException e )
141 {
142 cleanup();
143 }
144 }
145
146 if( janitor == null )
147 {
148 cleanup();
149 }
150 else
151 {
152 janitor.register( this );
153 }
154 }
155
156 return line;
157 }
158
159
160
161 /***
162 * Cleans up any cached resources used by getLine().
163 */
164
165 public void cleanup()
166 {
167 if( lineSource != null )
168 {
169 try { lineSource.close(); } catch( Exception e ) {}
170 }
171
172 lineSource = null;
173 line = null;
174 number = 0;
175 }
176
177 }