PatternLayout.java
1.57 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
package com.diligrp.assistant.uid.pattern;
import com.diligrp.assistant.uid.domain.SequenceKey;
import java.util.ArrayList;
import java.util.List;
public class PatternLayout {
private final Converter<SequenceKey> head;
public PatternLayout(String pattern) {
this.head = compile(pattern);
}
public String doLayout(SequenceKey context) {
StringBuilder writer = new StringBuilder();
Converter<SequenceKey> converter = head;
while (converter != null) {
writer.append(converter.convert(context));
converter = converter.getNext();
}
return writer.toString();
}
private Converter<SequenceKey> compile(String pattern) {
PatternParser parser = new PatternParser(pattern);
List<Token> tokens = new ArrayList<>();
Token previous = null;
for (Token token : parser.parse()) {
if (token instanceof KeywordToken || token instanceof LiteralToken) {
previous = token;
tokens.add(token);
} else if (token instanceof OptionToken) {
if (previous != null) {
previous.setOption(((OptionToken) token).getToken());
}
}
}
Converter<SequenceKey> first = tokens.get(0).getConverter();
Converter<SequenceKey> current = first;
for (int i = 1; i < tokens.size(); i++) {
Token token = tokens.get(i);
current.setNext(token.getConverter());
current = current.getNext();
}
return first;
}
}