1
2
3
4
5
6
7
8
9
10 package ch.qos.logback.core.helpers;
11
12
13
14
15
16
17
18 public class Transform {
19 private static final String CDATA_START = "<![CDATA[";
20 private static final String CDATA_END = "]]>";
21 private static final String CDATA_PSEUDO_END = "]]>";
22 private static final String CDATA_EMBEDED_END = CDATA_END + CDATA_PSEUDO_END
23 + CDATA_START;
24 private static final int CDATA_END_LEN = CDATA_END.length();
25
26
27
28
29
30
31
32
33
34 public static String escapeTags(final String input) {
35
36
37 if ((input == null) || (input.length() == 0)
38 || (input.indexOf("<") == -1 && input.indexOf(">") == -1)) {
39 return input;
40 }
41
42 StringBuffer buf = new StringBuffer(input);
43 return escapeTags(buf);
44 }
45
46
47
48
49
50
51
52
53
54 public static String escapeTags(final StringBuffer buf) {
55 for (int i = 0; i < buf.length(); i++) {
56 char ch = buf.charAt(i);
57 if (ch == '<') {
58 buf.replace(i, i + 1, "<");
59 } else if (ch == '>') {
60 buf.replace(i, i + 1, ">");
61 }
62 }
63 return buf.toString();
64 }
65
66
67
68
69
70
71
72
73
74
75
76
77
78 public static void appendEscapingCDATA(StringBuilder output, String str) {
79 if (str == null) {
80 return;
81 }
82
83 int end = str.indexOf(CDATA_END);
84
85 if (end < 0) {
86 output.append(str);
87
88 return;
89 }
90
91 int start = 0;
92
93 while (end > -1) {
94 output.append(str.substring(start, end));
95 output.append(CDATA_EMBEDED_END);
96 start = end + CDATA_END_LEN;
97
98 if (start < str.length()) {
99 end = str.indexOf(CDATA_END, start);
100 } else {
101 return;
102 }
103 }
104
105 output.append(str.substring(start));
106 }
107 }