-
Notifications
You must be signed in to change notification settings - Fork 337
/
UriTemplateParser.java
801 lines (712 loc) · 30.3 KB
/
UriTemplateParser.java
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
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
/*
* Copyright (c) 2010, 2023 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0, which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* This Source Code may also be made available under the following Secondary
* Licenses when the conditions for such availability set forth in the
* Eclipse Public License v. 2.0 are satisfied: GNU General Public License,
* version 2 with the GNU Classpath Exception, which is available at
* https://www.gnu.org/software/classpath/license.html.
*
* SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
*/
package org.glassfish.jersey.uri.internal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import org.glassfish.jersey.internal.LocalizationMessages;
import org.glassfish.jersey.uri.UriComponent;
/**
* A URI template parser that parses JAX-RS specific URI templates.
*
* @author Paul Sandoz
* @author Gerard Davison (gerard.davison at oracle.com)
*/
public class UriTemplateParser {
/* package */ static final int[] EMPTY_INT_ARRAY = new int[0];
private static final Set<Character> RESERVED_REGEX_CHARACTERS = initReserved();
private static final String[] HEX_TO_UPPERCASE_REGEX = initHexToUpperCaseRegex();
private static Set<Character> initReserved() {
char[] reserved = {
'.', '^', '&', '!',
'?', '-', ':', '<',
'(', '[', '$', '=',
')', ']', ',', '>',
'*', '+', '|'};
Set<Character> s = new HashSet<Character>(reserved.length);
for (char c : reserved) {
s.add(c);
}
return s;
}
/**
* Default URI template value regexp pattern.
*/
public static final Pattern TEMPLATE_VALUE_PATTERN = Pattern.compile("[^/]+");
public static final Pattern TEMPLATE_VALUE_PATTERN_MULTI = Pattern.compile("[^,/]+");
public static final Pattern MATCH_NUMBER_OF_MAX_LENGTH_4 = Pattern.compile("[1-9][0-9]{0,3}");
private final String template;
private final StringBuffer regex = new StringBuffer();
private final StringBuffer normalizedTemplate = new StringBuffer();
private final StringBuffer literalCharactersBuffer = new StringBuffer();
private final Pattern pattern;
private final List<UriPart> names = new ArrayList<>();
private final List<UriPart> parts = new ArrayList<>();
private final List<Integer> groupCounts = new ArrayList<Integer>();
private final Map<String, Pattern> nameToPattern = new HashMap<String, Pattern>();
private int numOfExplicitRegexes;
private int skipGroup;
private int literalCharacters;
/**
* Parse a template.
*
* @param template the template.
* @throws IllegalArgumentException if the template is null, an empty string
* or does not conform to a JAX-RS URI template.
*/
public UriTemplateParser(final String template) throws IllegalArgumentException {
if (template == null || template.isEmpty()) {
throw new IllegalArgumentException("Template is null or has zero length");
}
this.template = template;
parse(new CharacterIterator(template));
try {
pattern = Pattern.compile(regex.toString());
} catch (PatternSyntaxException ex) {
throw new IllegalArgumentException("Invalid syntax for the template expression '"
+ regex + "'",
ex
);
}
}
/**
* Get the template.
*
* @return the template.
*/
public final String getTemplate() {
return template;
}
/**
* Get the pattern.
*
* @return the pattern.
*/
public final Pattern getPattern() {
return pattern;
}
/**
* Get the normalized template.
* <p>
* A normalized template is a template without any explicit regular
* expressions.
*
* @return the normalized template.
*/
public final String getNormalizedTemplate() {
return normalizedTemplate.toString();
}
/**
* Get the map of template names to patterns.
*
* @return the map of template names to patterns.
*/
public final Map<String, Pattern> getNameToPattern() {
return nameToPattern;
}
/**
* Get the list of template names.
*
* @return the list of template names.
*/
public final List<UriPart> getNames() {
return names;
}
/**
* Get a collection of uri parts (static strings and dynamic arguments) as parsed by the parser.
* Can be used to compose the uri. This collection is usually a superset of {@link #getNames() names}
* and other parts that do not have a template.
*
* @return List of parts of the uri.
*/
public List<UriPart> getUriParts() {
return parts;
}
/**
* Get the capturing group counts for each template variable.
*
* @return the capturing group counts.
*/
public final List<Integer> getGroupCounts() {
return groupCounts;
}
/**
* Get the group indexes to capturing groups.
* <p>
* Any nested capturing groups will be ignored and the
* the group index will refer to the top-level capturing
* groups associated with the templates variables.
*
* @return the group indexes to capturing groups.
*/
public final int[] getGroupIndexes() {
if (names.isEmpty()) {
return EMPTY_INT_ARRAY;
}
int[] indexes = new int[names.size()];
indexes[0] = 0 + groupCounts.get(0);
for (int i = 1; i < indexes.length; i++) {
indexes[i] = indexes[i - 1] + groupCounts.get(i);
}
return indexes;
}
/**
* Get the number of explicit regular expressions.
*
* @return the number of explicit regular expressions.
*/
public final int getNumberOfExplicitRegexes() {
return numOfExplicitRegexes;
}
/**
* Get the number of regular expression groups
*
* @return the number of regular expressions groups
*
* @since 2.9
*/
public final int getNumberOfRegexGroups() {
if (groupCounts.isEmpty()) {
return 0;
} else {
int[] groupIndex = getGroupIndexes();
return groupIndex[groupIndex.length - 1] + skipGroup;
}
}
/**
* Get the number of literal characters.
*
* @return the number of literal characters.
*/
public final int getNumberOfLiteralCharacters() {
return literalCharacters;
}
/**
* Encode literal characters of a template.
*
* @param characters the literal characters
* @return the encoded literal characters.
*/
protected String encodeLiteralCharacters(final String characters) {
return characters;
}
private void parse(final CharacterIterator ci) {
try {
while (ci.hasNext()) {
char c = ci.next();
if (c == '{') {
processLiteralCharacters();
skipGroup = parseName(ci, skipGroup);
} else {
literalCharactersBuffer.append(c);
}
}
processLiteralCharacters();
} catch (NoSuchElementException ex) {
throw new IllegalArgumentException(LocalizationMessages.ERROR_TEMPLATE_PARSER_INVALID_SYNTAX_TERMINATED(
template), ex);
}
}
private void processLiteralCharacters() {
if (literalCharactersBuffer.length() > 0) {
literalCharacters += literalCharactersBuffer.length();
String s = encodeLiteralCharacters(literalCharactersBuffer.toString());
normalizedTemplate.append(s);
parts.add(new UriPart(s));
// Escape if reserved regex character
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (RESERVED_REGEX_CHARACTERS.contains(c)) {
regex.append("\\");
regex.append(c);
} else if (c == '%') {
final char c1 = s.charAt(i + 1);
final char c2 = s.charAt(i + 2);
if (UriComponent.isHexCharacter(c1) && UriComponent.isHexCharacter(c2)) {
regex.append("%").append(HEX_TO_UPPERCASE_REGEX[c1]).append(HEX_TO_UPPERCASE_REGEX[c2]);
i += 2;
}
} else {
regex.append(c);
}
}
literalCharactersBuffer.setLength(0);
}
}
private static String[] initHexToUpperCaseRegex() {
String[] table = new String[0x80];
for (int i = 0; i < table.length; i++) {
table[i] = String.valueOf((char) i);
}
for (char c = 'a'; c <= 'f'; c++) {
// initialize table values: table[a] = ([aA]) ...
table[c] = "[" + c + (char) (c - 'a' + 'A') + "]";
}
for (char c = 'A'; c <= 'F'; c++) {
// initialize table values: table[A] = ([aA]) ...
table[c] = "[" + (char) (c - 'A' + 'a') + c + "]";
}
return table;
}
private int parseName(final CharacterIterator ci, int skipGroup) {
Variables variables = new Variables();
variables.parse(ci, template);
Pattern namePattern;
// Make sure we display something useful
String name = variables.getName();
int argIndex = 0;
try {
switch (variables.paramType) {
case '?':
case ';':
case '&':
// Build up the regex for each of these properties
StringBuilder regexBuilder = new StringBuilder();
String separator = null;
switch (variables.paramType) {
case '?':
separator = "\\&";
regexBuilder.append("\\?"); // first symbol
break;
case '&':
separator = "\\&";
regexBuilder.append("\\&"); // first symbol
break;
case ';':
separator = ";/\\?";
regexBuilder.append(";"); // first symbol
break;
}
// Start a group because each parameter could repeat
// names.add("__" + (paramType == '?' ? "query" : "matrix"));
regexBuilder.append('(');
for (String subName : variables.names) {
TemplateVariable.Position position = determinePosition(variables.separatorCount, argIndex);
TemplateVariable templateVariable =
TemplateVariable.createTemplateVariable(variables.paramType, subName, position);
templateVariable.setStar(variables.explodes(argIndex));
regexBuilder.append("(&?");
regexBuilder.append(subName);
regexBuilder.append("(=([^");
regexBuilder.append(separator);
regexBuilder.append(']');
if (variables.hasLength(argIndex)) {
regexBuilder.append('{').append(variables.getLength(argIndex)).append('}');
templateVariable.setLength(variables.getLength(argIndex));
} else {
regexBuilder.append('*');
}
regexBuilder.append("))?");
regexBuilder.append(')');
if (argIndex != 0) {
regexBuilder.append('|');
}
names.add(templateVariable);
parts.add(templateVariable);
groupCounts.add(
argIndex == 0 ? 5 : 3);
argIndex++;
}
// groupCounts.add(1);
skipGroup = 1;
// Knock of last bar
regexBuilder.append(")*");
namePattern = Pattern.compile(regexBuilder.toString());
// Make sure we display something useful
break;
default:
if (variables.separatorCount == 0) {
if (variables.hasRegexp(0)) {
numOfExplicitRegexes++;
}
TemplateVariable templateVariable = TemplateVariable
.createTemplateVariable(variables.paramType, variables.getName(0), TemplateVariable.Position.SINGLE);
templateVariable.setStar(variables.explodes(0));
names.add(templateVariable);
parts.add(templateVariable);
// groupCounts.add(1 + skipGroup);
if (variables.hasLength(0)) {
if (variables.getLength(0) != 0) {
int len = TEMPLATE_VALUE_PATTERN.pattern().length() - 1;
String pattern = TEMPLATE_VALUE_PATTERN.pattern().substring(0, len)
+ '{' + variables.getLength(0) + '}';
namePattern = Pattern.compile(pattern);
} else {
namePattern = TEMPLATE_VALUE_PATTERN;
}
templateVariable.setLength(variables.getLength(0));
} else {
namePattern = (!variables.hasRegexp(0))
? TEMPLATE_VALUE_PATTERN : Pattern.compile(variables.regexp(0));
}
if (nameToPattern.containsKey(name)) {
if (!nameToPattern.get(name).equals(namePattern)) {
throw new IllegalArgumentException(
LocalizationMessages.ERROR_TEMPLATE_PARSER_NAME_MORE_THAN_ONCE(name, template));
}
} else {
nameToPattern.put(name, namePattern);
}
// Determine group count of pattern
Matcher m = namePattern.matcher("");
int g = m.groupCount();
groupCounts.add(1 + skipGroup);
skipGroup = g;
} else {
argIndex = 0;
regexBuilder = new StringBuilder();
for (String subName : variables.names) {
if (argIndex != 0) {
regexBuilder
.append('(')
.append(',');
}
TemplateVariable.Position position = determinePosition(variables.separatorCount, argIndex);
TemplateVariable templateVariable
= TemplateVariable.createTemplateVariable(variables.paramType, subName, position);
templateVariable.setStar(variables.explodes(argIndex));
names.add(templateVariable);
parts.add(templateVariable);
if (variables.hasLength(argIndex)) {
int len = TEMPLATE_VALUE_PATTERN_MULTI.pattern().length() - 1;
String pattern = TEMPLATE_VALUE_PATTERN_MULTI.pattern()
.substring(0, len) + '{' + variables.getLength(argIndex) + '}';
namePattern = Pattern.compile(pattern);
templateVariable.setLength(variables.getLength(argIndex));
} else {
namePattern = (!variables.hasRegexp(argIndex))
? TEMPLATE_VALUE_PATTERN_MULTI : Pattern.compile(variables.regexp(argIndex));
}
// TODO breaks RFC 6570 --backward compatibility with default pattern
if (nameToPattern.containsKey(subName) && variables.paramType == 'p') {
if (!nameToPattern.get(subName).equals(namePattern)) {
throw new IllegalArgumentException(
LocalizationMessages.ERROR_TEMPLATE_PARSER_NAME_MORE_THAN_ONCE(name, template));
}
} else {
nameToPattern.put(subName, namePattern);
}
regexBuilder
.append('(')
.append(namePattern)
.append(')');
if (argIndex != 0) {
regexBuilder.append(")");
}
if (!variables.hasRegexp(argIndex)) {
regexBuilder.append("{0,1}");
}
argIndex++;
groupCounts.add(2);
}
namePattern = Pattern.compile(regexBuilder.toString());
}
break;
}
regex.append('(')
.append(namePattern)
.append(')');
normalizedTemplate.append('{')
.append(name)
.append('}');
} catch (PatternSyntaxException ex) {
throw new IllegalArgumentException(LocalizationMessages
.ERROR_TEMPLATE_PARSER_INVALID_SYNTAX(variables.regexp(argIndex), variables.name, template), ex);
}
// Tell the next time through the loop how many to skip
return skipGroup;
}
private static TemplateVariable.Position determinePosition(int separatorCount, int argIndex) {
TemplateVariable.Position position = separatorCount == 0
? TemplateVariable.Position.SINGLE
: argIndex == 0
? TemplateVariable.Position.FIRST
: argIndex == separatorCount ? TemplateVariable.Position.LAST : TemplateVariable.Position.MIDDLE;
return position;
}
private static class Variables {
private char paramType = 'p';
private List<String> names = new ArrayList<>(); // names
private List<Boolean> explodes = new ArrayList<>(); // *
private List<String> regexps = new ArrayList<>(); // : regexp
private List<Integer> lengths = new ArrayList<>(); // :1-9999
private int separatorCount = 0;
private StringBuilder name = new StringBuilder();
private int getCount() {
return names.size();
}
private boolean explodes(int index) {
return !explodes.isEmpty() && explodes.get(index);
}
private boolean hasRegexp(int index) {
return !regexps.isEmpty() && regexps.get(index) != null;
}
private String regexp(int index) {
return regexps.get(index);
}
private boolean hasLength(int index) {
return !lengths.isEmpty() && lengths.get(index) != null;
}
private Integer getLength(int index) {
return lengths.get(index);
}
private char getParamType() {
return paramType;
}
private int getSeparatorCount() {
return separatorCount;
}
private String getName() {
return name.toString();
}
private String getName(int index) {
return names.get(index);
}
private void parse(CharacterIterator ci, String template) {
name.append('{');
char c = consumeWhiteSpace(ci);
StringBuilder nameBuilder = new StringBuilder();
// Look for query or matrix types
if (c == '?' || c == ';' || c == '.' || c == '+' || c == '#' || c == '/' || c == '&') {
paramType = c;
c = ci.next();
name.append(paramType);
}
if (Character.isLetterOrDigit(c) || c == '_') {
// Template name character
nameBuilder.append(c);
name.append(c);
} else {
throw new IllegalArgumentException(LocalizationMessages.ERROR_TEMPLATE_PARSER_ILLEGAL_CHAR_START_NAME(c, ci.pos(),
template));
}
StringBuilder regexBuilder = new StringBuilder();
State state = State.TEMPLATE;
State previousState;
boolean star = false;
boolean whiteSpace = false;
boolean ignoredLastComma = false;
int bracketDepth = 1; // {
int regExpBracket = 0; // [
int regExpRound = 0; // (
boolean reqExpSlash = false; // \
while ((state.value & (State.ERROR.value | State.EXIT.value)) == 0) {
previousState = state;
c = ci.next();
// "\\{(\\w[-\\w\\.]*)
if (Character.isLetterOrDigit(c)) {
// Template name character
append(c, state, nameBuilder, regexBuilder);
state = state.transition(State.TEMPLATE.value | State.REGEXP.value);
} else switch (c) {
case '_':
case '-':
case '.':
// Template name character
append(c, state, nameBuilder, regexBuilder);
state = state.transition(State.TEMPLATE.value | State.REGEXP.value);
break;
case ',':
switch (state) {
case REGEXP:
if (bracketDepth == 1 && !reqExpSlash && regExpBracket == 0 && regExpRound == 0) {
state = State.COMMA;
} else {
regexBuilder.append(c);
}
break;
case TEMPLATE:
case STAR:
state = State.COMMA;
break;
}
separatorCount++;
break;
case ':':
if (state == State.REGEXP) {
regexBuilder.append(c);
}
state = state.transition(State.TEMPLATE.value | State.REGEXP.value | State.STAR.value, State.REGEXP);
break;
case '*':
state = state.transition(State.TEMPLATE.value | State.REGEXP.value);
if (state == State.TEMPLATE) {
star = true;
state = State.STAR;
} else if (state == State.REGEXP){
regexBuilder.append(c);
}
break;
case '}':
bracketDepth--;
if (bracketDepth == 0) {
state = State.BRACKET;
} else {
regexBuilder.append(c);
}
break;
case '{':
if (state == State.REGEXP) {
bracketDepth++;
regexBuilder.append(c);
} else {
state = State.ERROR; // Error multiple parenthesis
}
break;
default:
if (!Character.isWhitespace(c)) {
if (state != State.REGEXP) {
state = State.ERROR; // Error - unknown symbol
} else {
switch (c) {
case '(' :
regExpRound++;
break;
case ')':
regExpRound--;
break;
case '[':
regExpBracket++;
break;
case ']':
regExpBracket--;
break;
}
if (c == '\\') {
reqExpSlash = true;
} else {
reqExpSlash = false;
}
regexBuilder.append(c);
}
}
whiteSpace = true;
break;
}
// Store parsed name, and associated star, regexp, and length
switch (state) {
case COMMA:
case BRACKET:
if (nameBuilder.length() == 0 && regexBuilder.length() == 0 && !star
&& name.charAt(name.length() - 1) == ',' /* ignore last comma */) {
if (ignoredLastComma) { // Do not ignore twice
state = State.ERROR;
} else {
name.setLength(name.length() - 1);
ignoredLastComma = true;
}
break;
}
if (regexBuilder.length() != 0) {
String regex = regexBuilder.toString();
Matcher matcher = MATCH_NUMBER_OF_MAX_LENGTH_4.matcher(regex);
if (matcher.matches()) {
lengths.add(Integer.parseInt(regex));
regexps.add(null);
} else {
if (paramType != 'p') {
state = State.ERROR; // regular expressions allowed just on path by the REST spec
c = regex.charAt(0); // display proper error values
ci.setPosition(ci.pos() - regex.length());
break;
}
lengths.add(null);
regexps.add(regex);
}
} else {
regexps.add(previousState == State.REGEXP ? "" : null);
lengths.add(previousState == State.REGEXP ? 0 : null);
}
names.add(nameBuilder.toString());
explodes.add(star);
nameBuilder.setLength(0);
regexBuilder.setLength(0);
star = false;
ignoredLastComma = false;
break;
}
if (!whiteSpace) {
name.append(c);
}
whiteSpace = false;
// switch state back or exit
switch (state) {
case COMMA:
state = State.TEMPLATE;
break;
case BRACKET:
state = State.EXIT;
break;
}
}
if (state == State.ERROR) {
throw new IllegalArgumentException(
LocalizationMessages.ERROR_TEMPLATE_PARSER_ILLEGAL_CHAR_AFTER_NAME(c, ci.pos(), template));
}
}
private static void append(char c, State state, StringBuilder templateSb, StringBuilder regexpSb) {
if (state == State.TEMPLATE) {
templateSb.append(c);
} else { // REGEXP
regexpSb.append(c);
}
}
private static char consumeWhiteSpace(final CharacterIterator ci) {
char c;
do {
c = ci.next();
} while (Character.isWhitespace(c));
return c;
}
private enum State {
TEMPLATE/**/(0b000000001), // Template name, before '*', ':', ',' or '}'
REGEXP/* */(0b000000010), // Regular expression inside template, after :
STAR/* */(0b000000100), // *
COMMA/* */(0b000001000), // ,
BRACKET/* */(0b000010000), // }
EXIT/* */(0b001000000), // quit parsing
ERROR/* */(0b100000000); // error when parsing
private final int value;
State(int value) {
this.value = value;
}
/**
* Return error state when in not any of allowed states represented by their combined values
* @param allowed The combined values of states (state1.value | state2.value) not to return error level
* @return this state if in allowed state or {@link State#ERROR} if not
*/
State transition(int allowed) {
return ((value & allowed) != 0) ? this : State.ERROR;
}
/**
* Return error state when in not any of allowed states represented by their combined values
* @param allowed The combined values of states (state1.value | state2.value) not to return error level
* @param next the next state to transition
* @return next state if in allowed state or {@link State#ERROR} if not
*/
State transition(int allowed, State next) {
return ((value & allowed) != 0) ? next : State.ERROR;
}
}
}
}