Repository navigation
Expand file tree
/
Copy pathPropertiesParser.java
More file actions
388 lines (355 loc) · 12.4 KB
/
Copy pathPropertiesParser.java
File metadata and controls
388 lines (355 loc) · 12.4 KB
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
package org.codejive.properties;
import java.io.IOException;
import java.io.Reader;
import java.util.Objects;
import java.util.Spliterators;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
/**
* A parser that given a text input that follows the standard Java Properties file format will
* return a stream of tokens. These tokens will contain _all_ characters that were read from the
* input which makes it possible to exactly recreate the original, including all whitespace and
* comments.
*/
public class PropertiesParser {
/** The type of token. */
public enum Type {
/** The key part of a key-value pair */
KEY,
/**
* The separator between a key and a value. This will include any whitespace that exists
* before and after the separator!
*/
SEPARATOR,
/** The value part of a key-value pair */
VALUE,
/** A comment, both # and ! */
COMMENT,
/**
* Any whitespace. Multiple consecutive lines will be split into separate tokens at the
* end-of-line character(s).
*/
WHITESPACE
}
/**
* Tokens are returned by the parser for each part if the input. Their type is defined by <code>
* Type</code> and they have both a raw value, meaning the exact value as it was encountered in
* the input, and a text value, which is the raw value after all escape sequences have been
* processed.
*/
public static class Token {
final Type type;
final String raw;
final String text;
/**
* Constructor for tokens where the raw value and the text value are exactly the same.
*
* @param type The token's type
* @param raw The token's value
*/
public Token(Type type, String raw) {
this(type, raw, null);
}
/**
* The constructor for tokens that have a raw value and a processed value where escape
* sequences have been turned into their actual values.
*
* @param type The token's type
* @param raw The token's raw value (including escape sequences)
* @param text The token's processed value (no escape sequences)
*/
public Token(Type type, String raw, String text) {
this.type = type;
this.raw = raw;
if (raw.equals(text)) {
text = null;
}
this.text = text;
}
/**
* Returns the token's type
*
* @return The token's type
*/
public Type getType() {
return type;
}
/**
* Returns the token's unprocessed/raw value. Meaning this value can contain escape
* sequences.
*
* @return a string containing the token's raw value
*/
public String getRaw() {
return raw;
}
/**
* Returns the token's processed value. Meaning this value will not contain any escape
* sequences but only actual characters.
*
* @return a string containing the token's processed value
*/
public String getText() {
return text != null ? text : raw;
}
/**
* Determines if this token is a whitespace ending with an EOL marker.
*
* @return true if whitespace ending in EOL, false otherwise
*/
public boolean isEol() {
if (raw.isEmpty()) return false;
int ch = raw.charAt(raw.length() - 1);
return type == Type.WHITESPACE && PropertiesParser.isEol(ch);
}
/**
* Determines if this token is a whitespace NOT ending with an EOL marker.
*
* @return true if whitespace NOT ending in EOL, false otherwise
*/
public boolean isWs() {
if (raw.isEmpty()) return false;
int ch = raw.charAt(raw.length() - 1);
return type == Type.WHITESPACE && !PropertiesParser.isEol(ch);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Token)) return false;
Token token = (Token) o;
return type == token.type && Objects.equals(getText(), token.getText());
}
@Override
public int hashCode() {
return Objects.hash(type, getText());
}
@Override
public String toString() {
if (text == null) {
return "Token(" + type + ", '" + raw + "')";
} else {
return "Token(" + type + ", '" + raw + "'" + ", '" + text + "')";
}
}
}
private final Reader rdr;
private Type state;
private int pch;
private StringBuilder str;
private boolean hasEscapes;
/**
* Constructor that takes a <code>Reader</code> for reading the input to parse.
*
* @param rdr a <code>Reader</code> object
* @throws IOException Thrown when any IO error occurs during parsing
*/
public PropertiesParser(Reader rdr) throws IOException {
this.rdr = rdr;
state = null;
str = new StringBuilder();
readChar();
}
/**
* Returns a stream of tokens for the given input.
*
* @param rdr a <code>Reader</code> object
* @return a <code>Stream</code> of <code>Token</code>
* @throws IOException Thrown when any IO error occurs during parsing
*/
public static Stream<Token> tokens(Reader rdr) throws IOException {
return StreamSupport.stream(
new Spliterators.AbstractSpliterator<Token>(0, 0) {
final PropertiesParser p = new PropertiesParser(rdr);
@Override
public boolean tryAdvance(Consumer<? super Token> action) {
try {
Token token = p.nextToken();
if (token != null) {
action.accept(token);
return true;
} else {
return false;
}
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
},
false);
}
/**
* Returns the next token in the input or <code>null</code> if the end of the input was reached.
*
* @return a <code>Token</code> or <code>null</code>
* @throws IOException Thrown when any IO error occurs during parsing
*/
public Token nextToken() throws IOException {
int ch = peekChar();
if (isEof(ch)) {
return null;
}
Function<Integer, Boolean> isValid = (c) -> false;
Type nextState = null;
if (state == null) {
if (isCommentChar(ch)) {
state = Type.COMMENT;
isValid = (c) -> !isEol(c) && !isEof(c);
} else if (isWhitespaceEolChar(ch)) {
state = Type.WHITESPACE;
final AtomicInteger oldc = new AtomicInteger(-1);
isValid = (c) -> isWhitespaceEolChar(c) && !isEol(oldc.getAndSet(c));
} else {
state = Type.KEY;
isValid =
(c) ->
!isSeparatorChar(c)
&& !isWhitespaceChar(c)
&& !isEol(c)
&& !isEof(c);
nextState = Type.SEPARATOR;
}
} else if (state == Type.SEPARATOR) {
final AtomicBoolean once = new AtomicBoolean(true);
isValid = (c) -> isWhitespaceChar(c) || (isSeparatorChar(c) && once.getAndSet(false));
nextState = Type.VALUE;
} else if (state == Type.VALUE) {
isValid = (c) -> !isEol(c) && !isEof(c);
}
while (true) {
if (isValid.apply(ch)) {
addChar(readChar());
ch = peekChar();
} else {
String text = string();
Token token =
hasEscapes
? new Token(state, text, unescape(text))
: new Token(state, text);
hasEscapes = false;
state = nextState;
return token;
}
}
}
private int peekChar() {
return pch;
}
private int readChar() throws IOException {
int ch = pch;
pch = rdr.read();
return ch;
}
private void addChar(int ch) throws IOException {
str.append((char) ch);
if (ch == '\\') {
hasEscapes = true;
int ch2 = readChar();
str.append((char) ch2);
if (ch2 == 'u') {
for (int i = 0; i < 4; i++) {
int chu = readChar();
if (!isHexDigitChar(chu)) {
throw new IOException("Invalid unicode escape character: " + chu);
}
str.append((char) chu);
}
} else {
readEol(ch2);
}
} else {
readEol(ch);
}
}
private void readEol(int ch) throws IOException {
if (ch == '\r') {
if (peekChar() == '\n') {
str.append((char) readChar());
}
}
}
private String string() {
String result = str.toString();
str.setLength(0);
return result;
}
/**
* Returns a copy of the given string where all escape sequences have been turned into their
* representative values.
*
* @param escape Input string
* @return Decoded string
*/
public static String unescape(String escape) {
StringBuilder txt = new StringBuilder();
for (int i = 0; i < escape.length(); i++) {
char ch = escape.charAt(i);
if (ch == '\\') {
ch = escape.charAt(++i);
switch (ch) {
case 't':
txt.append('\t');
break;
case 'f':
txt.append('\f');
break;
case 'n':
txt.append('\n');
break;
case 'r':
txt.append('\r');
break;
case 'u':
String num = escape.substring(i + 1, i + 5);
txt.append((char) Integer.parseInt(num, 16));
i += 4;
break;
case '\r':
// Skip the next character if it's a '\n'
if (i < (escape.length() - 1) && escape.charAt(i + 1) == '\n') {
i++;
}
// fall-through!
case '\n':
// Skip any leading whitespace
while (i < (escape.length() - 1)
&& isWhitespaceChar(ch = escape.charAt(i + 1))) {
i++;
}
break;
default:
txt.append(ch);
break;
}
} else {
txt.append(ch);
}
}
return txt.toString();
}
public static boolean isSeparatorChar(int ch) {
return ch == '=' || ch == ':';
}
private static boolean isWhitespaceChar(int ch) {
return ch == ' ' || ch == '\t' || ch == '\f';
}
private static boolean isWhitespaceEolChar(int ch) {
return isWhitespaceChar(ch) || isEol(ch);
}
public static boolean isCommentChar(int ch) {
return ch == '#' || ch == '!';
}
private static boolean isHexDigitChar(int ch) {
int uch = Character.toUpperCase(ch);
return Character.isDigit(ch) || (uch >= 'A' && uch <= 'F');
}
private static boolean isEol(int ch) {
return ch == '\n' || ch == '\r';
}
private static boolean isEof(int ch) {
return ch == -1;
}
}