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