1 package org.apache.maven.doxia.util;
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 import java.io.IOException;
28 import java.io.LineNumberReader;
29 import java.io.Reader;
30
31 import org.apache.maven.doxia.parser.ParseException;
32 import org.codehaus.plexus.util.IOUtil;
33
34
35
36
37
38
39 public class ByLineReaderSource implements ByLineSource
40 {
41
42
43
44 private LineNumberReader reader;
45
46
47
48
49 private int lineNumber;
50
51
52
53
54 private String lastLine;
55
56
57
58
59
60 private boolean ungetted = false;
61
62 private String name;
63
64
65
66
67
68
69 public ByLineReaderSource( final Reader in )
70 {
71 this( in, "" );
72 }
73
74 public ByLineReaderSource( final Reader in, final String name )
75 {
76 this.reader = new LineNumberReader( in );
77
78 this.name = name;
79
80 this.lineNumber = -1;
81 }
82
83
84 public final String getNextLine() throws ParseException
85 {
86 if ( reader == null )
87 {
88 return null;
89 }
90
91 if ( ungetted )
92 {
93 ungetted = false;
94 return lastLine;
95 }
96
97 String line;
98
99 try
100 {
101 line = reader.readLine();
102 if ( line == null )
103 {
104 reader.close();
105 reader = null;
106 }
107 else
108 {
109 lineNumber = reader.getLineNumber();
110 }
111 }
112 catch ( IOException e )
113 {
114 throw new ParseException( e, lineNumber, 0 );
115 }
116
117 lastLine = line;
118
119 return line;
120 }
121
122
123 public final String getName()
124 {
125 return name;
126 }
127
128
129 public final int getLineNumber()
130 {
131 return lineNumber;
132 }
133
134
135 public final void close()
136 {
137 IOUtil.close( reader );
138 reader = null;
139 }
140
141
142 public final void ungetLine()
143 {
144 if ( ungetted )
145 {
146 throw new IllegalStateException( "we support only one level of ungetLine()" );
147 }
148 ungetted = true;
149 }
150
151
152 public final void unget( final String s )
153 {
154 if ( s == null )
155 {
156 throw new IllegalArgumentException( "argument can't be null" );
157 }
158 if ( s.length() != 0 )
159 {
160 ungetLine();
161 lastLine = s;
162 }
163 }
164 }