1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.orekit.files.sinex;
18
19 import java.util.ArrayList;
20 import java.util.List;
21 import java.util.function.Predicate;
22 import java.util.regex.Matcher;
23 import java.util.regex.Pattern;
24
25
26
27
28
29
30 class BlockParser<T extends ParseInfo<?>> implements LineParser<T> {
31
32
33 private final Pattern startPattern;
34
35
36 private Pattern endPattern;
37
38
39 private final List<LineParser<T>> inBlockParsers;
40
41
42 private List<LineParser<T>> siblingParsers;
43
44
45
46
47
48 protected BlockParser(final String blockId, final List<Predicate<T>> predicates) {
49 this.startPattern = Pattern.compile("^\\+(" + blockId + ") *$");
50 this.endPattern = null;
51 this.inBlockParsers = new ArrayList<>(1 + predicates.size());
52 for (final Predicate<T> predicate : predicates) {
53 inBlockParsers.add(new LineParser<T>() {
54
55
56 @Override
57 public boolean parseIfRecognized(final T parseInfo) {
58 return predicate.test(parseInfo);
59 }
60
61
62 @Override
63 public Iterable<LineParser<T>> allowedNextParsers(final T parseInfo) {
64 return inBlockParsers;
65 }
66
67 });
68 }
69 this.inBlockParsers.add(this);
70 }
71
72
73
74
75 public void setSiblingParsers(final List<LineParser<T>> siblingParsers) {
76 this.siblingParsers = siblingParsers;
77 }
78
79
80 @Override
81 public boolean parseIfRecognized(final T parseInfo) {
82 return outsideBlock() ? checkEntering(parseInfo) : checkLeaving(parseInfo);
83 }
84
85
86 @Override
87 public Iterable<LineParser<T>> allowedNextParsers(final T parseInfo) {
88 return outsideBlock() ? siblingParsers : inBlockParsers;
89 }
90
91
92
93
94 protected boolean outsideBlock() {
95 return endPattern == null;
96 }
97
98
99
100
101
102 protected boolean checkEntering(final T parseInfo) {
103 final Matcher matcher = startPattern.matcher(parseInfo.getLine());
104 if (matcher.matches()) {
105
106 endPattern = Pattern.compile("^-" + matcher.group(1) + " *$");
107 return true;
108 } else {
109 return false;
110 }
111 }
112
113
114
115
116
117 protected boolean checkLeaving(final T parseInfo) {
118 if (endPattern != null && endPattern.matcher(parseInfo.getLine()).matches()) {
119 endPattern = null;
120 return true;
121 } else {
122 return false;
123 }
124 }
125
126 }
127