刘光辉
4 小时以前 06f314545ac3514d7ce28939920866ae8188d31c
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
package jnpf.elnService.impl;
 
import com.huaban.analysis.jieba.JiebaSegmenter;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
 
import java.util.Locale;
import java.util.function.Supplier;
 
public final class ElnFieldCodeGenerator {
 
    private static final int MAX_CODE_LENGTH = 80;
    private static final int DEFAULT_SUFFIX_LENGTH = 6;
    private final Supplier<String> suffixSupplier;
    private final int suffixLength;
 
    public ElnFieldCodeGenerator(Supplier<String> suffixSupplier) {
        this(suffixSupplier, DEFAULT_SUFFIX_LENGTH);
    }
 
    public ElnFieldCodeGenerator(Supplier<String> suffixSupplier, int suffixLength) {
        this.suffixSupplier = suffixSupplier;
        if (suffixLength < 1) {
            throw new IllegalArgumentException("字段编码随机后缀长度必须大于 0");
        }
        this.suffixLength = suffixLength;
    }
 
    public String generate(String label, boolean templateField) {
        return buildCode(normalizeSegmented(label), "field", "f", templateField);
    }
 
    public String generate(String label, String fallback, String numericPrefix) {
        return generate(label, fallback, numericPrefix, false);
    }
 
    public String generateSegmented(String label, String fallback, String numericPrefix) {
        return buildCode(normalizeSegmented(label), fallback, numericPrefix, false);
    }
 
    public static String suggestSegmentedCode(String text) {
        String normalized = normalizeSegmented(text);
        if (normalized.length() <= MAX_CODE_LENGTH) {
            return normalized;
        }
        int segmentBoundary = normalized.lastIndexOf('_', MAX_CODE_LENGTH);
        if (segmentBoundary > 0) {
            return normalized.substring(0, segmentBoundary);
        }
        return trimTrailingUnderscore(normalized.substring(0, MAX_CODE_LENGTH));
    }
 
    private String generate(String label, String fallback, String numericPrefix,
                            boolean alwaysPrefix) {
        return buildCode(normalize(label), fallback, numericPrefix, alwaysPrefix);
    }
 
    private String buildCode(String normalizedLabel, String fallback, String numericPrefix,
                             boolean alwaysPrefix) {
        String base = normalizedLabel;
        if (base.isEmpty()) {
            base = fallback;
        }
        if (Character.isDigit(base.charAt(0))) {
            base = numericPrefix + "_" + base;
        }
        if (alwaysPrefix) {
            base = "p_" + base;
        }
        String suffix = normalizeSuffix(suffixSupplier.get());
        int baseLimit = MAX_CODE_LENGTH - suffixLength - 1;
        if (base.length() > baseLimit) {
            base = trimTrailingUnderscore(base.substring(0, baseLimit));
        }
        return base + "_" + suffix;
    }
 
    private static String normalizeSegmented(String value) {
        if (value == null) {
            return "";
        }
        StringBuilder result = new StringBuilder();
        for (String segment : SegmenterHolder.INSTANCE.sentenceProcess(value)) {
            String normalized = normalizeWord(segment);
            if (!normalized.isEmpty()) {
                appendSeparator(result);
                result.append(normalized);
            }
        }
        return trimTrailingUnderscore(result.toString()).replaceAll("_+", "_");
    }
 
    private static String normalizeWord(String value) {
        HanyuPinyinOutputFormat format = pinyinFormat();
        StringBuilder result = new StringBuilder();
        for (char character : value.toCharArray()) {
            if (character < 128 && Character.isLetterOrDigit(character)) {
                result.append(Character.toLowerCase(character));
                continue;
            }
            String[] pinyin = toPinyin(character, format);
            if (pinyin != null && pinyin.length > 0) {
                result.append(pinyin[0]);
            }
        }
        return result.toString();
    }
 
    private static String normalize(String value) {
        if (value == null) {
            return "";
        }
        HanyuPinyinOutputFormat format = pinyinFormat();
        StringBuilder result = new StringBuilder();
        for (char character : value.toCharArray()) {
            if (character < 128 && Character.isLetterOrDigit(character)) {
                result.append(Character.toLowerCase(character));
                continue;
            }
            String[] pinyin = toPinyin(character, format);
            if (pinyin != null && pinyin.length > 0) {
                appendSeparator(result);
                result.append(pinyin[0]);
                appendSeparator(result);
            } else {
                appendSeparator(result);
            }
        }
        return trimTrailingUnderscore(result.toString()).replaceAll("_+", "_");
    }
 
    private static HanyuPinyinOutputFormat pinyinFormat() {
        HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
        format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        format.setVCharType(HanyuPinyinVCharType.WITH_V);
        return format;
    }
 
    private static String[] toPinyin(char character, HanyuPinyinOutputFormat format) {
        try {
            return PinyinHelper.toHanyuPinyinStringArray(character, format);
        } catch (BadHanyuPinyinOutputFormatCombination ignored) {
            // format is fixed and valid
            return null;
        }
    }
 
    private String normalizeSuffix(String suffix) {
        String value = suffix == null ? "" : suffix.toLowerCase(Locale.ROOT)
                .replaceAll("[^a-z0-9]", "");
        if (value.length() < suffixLength) {
            throw new IllegalStateException("字段编码随机后缀必须至少包含 " + suffixLength + " 位字母或数字");
        }
        return value.substring(0, suffixLength);
    }
 
    private static void appendSeparator(StringBuilder value) {
        if (value.length() > 0 && value.charAt(value.length() - 1) != '_') {
            value.append('_');
        }
    }
 
    private static String trimTrailingUnderscore(String value) {
        int end = value.length();
        while (end > 0 && value.charAt(end - 1) == '_') {
            end--;
        }
        return value.substring(0, end);
    }
 
    private static final class SegmenterHolder {
        private static final JiebaSegmenter INSTANCE = new JiebaSegmenter();
    }
}