|
3 | 3 | import org.apache.commons.lang3.RandomStringUtils;
|
4 | 4 | import org.apache.commons.lang3.RandomUtils;
|
5 | 5 | import org.apache.commons.text.StringEscapeUtils;
|
| 6 | +import org.apache.commons.text.translate.AggregateTranslator; |
| 7 | +import org.apache.commons.text.translate.CharSequenceTranslator; |
| 8 | +import org.apache.commons.text.translate.JavaUnicodeEscaper; |
| 9 | +import org.apache.commons.text.translate.LookupTranslator; |
6 | 10 |
|
7 |
| -import java.util.HashMap; |
8 | 11 | import java.util.List;
|
9 | 12 | import java.util.Map;
|
10 |
| -import java.util.regex.Matcher; |
11 | 13 |
|
12 | 14 | import static java.lang.Character.MAX_CODE_POINT;
|
13 | 15 | import static java.lang.Character.isBmpCodePoint;
|
|
16 | 18 |
|
17 | 19 | public class StringTestData {
|
18 | 20 |
|
19 |
| - private static final Map<String, String> CONTROL_CHARACTER_ESCAPE = new HashMap<>(); |
20 |
| - |
21 |
| - static { |
22 |
| - for (int codePoint = 0; codePoint <= 0x001F; codePoint++) { |
23 |
| - String controlCharacter = String.valueOf((char) codePoint); |
24 |
| - CONTROL_CHARACTER_ESCAPE.put(controlCharacter, toUnicodeEscape(codePoint)); |
25 |
| - } |
26 |
| - } |
| 21 | + public static final CharSequenceTranslator ESCAPE_JSON = new AggregateTranslator( |
| 22 | + new LookupTranslator(Map.of("\"", "\\\"", "\\", "\\\\")), |
| 23 | + JavaUnicodeEscaper.below(0x20) |
| 24 | + ); |
27 | 25 |
|
28 | 26 | public static String randomString(int minChars, int maxChars) {
|
29 | 27 | int stringLen = RandomUtils.nextInt(minChars, maxChars + 1);
|
30 |
| - var string = RandomStringUtils.random(stringLen) |
31 |
| - .replaceAll("\"", "\\\\\"") |
32 |
| - .replaceAll("\\\\", "\\\\\\\\"); |
33 |
| - for (Map.Entry<String, String> entry : CONTROL_CHARACTER_ESCAPE.entrySet()) { |
34 |
| - string = string.replaceAll(entry.getKey(), Matcher.quoteReplacement(entry.getValue())); |
35 |
| - } |
36 |
| - System.out.println("Generated string: " + string + " [" + StringEscapeUtils.escapeJava(string) + "]"); |
37 |
| - return string; |
| 28 | + var rawString = RandomStringUtils.random(stringLen); |
| 29 | + var jsonString = ESCAPE_JSON.translate(rawString); |
| 30 | + System.out.println("Generated string: " + jsonString + " [" + StringEscapeUtils.escapeJava(jsonString) + "]"); |
| 31 | + return jsonString; |
38 | 32 | }
|
39 | 33 |
|
40 | 34 | /**
|
|
0 commit comments