1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package org.apache.mina.util;
21
22 import java.io.IOException;
23 import java.io.LineNumberReader;
24 import java.io.PrintWriter;
25 import java.io.StringReader;
26 import java.io.StringWriter;
27 import java.util.ArrayList;
28
29
30
31
32
33
34
35
36
37 public class Transform {
38
39 private static final String CDATA_START = "<![CDATA[";
40 private static final String CDATA_END = "]]>";
41 private static final String CDATA_PSEUDO_END = "]]>";
42 private static final String CDATA_EMBEDED_END = CDATA_END + CDATA_PSEUDO_END + CDATA_START;
43 private static final int CDATA_END_LEN = CDATA_END.length();
44
45
46
47
48
49
50
51
52
53
54 static public String escapeTags(final String input) {
55
56
57
58 if(input == null
59 || input.length() == 0
60 || (input.indexOf('"') == -1 &&
61 input.indexOf('&') == -1 &&
62 input.indexOf('<') == -1 &&
63 input.indexOf('>') == -1)) {
64 return input;
65 }
66
67 StringBuffer buf = new StringBuffer(input.length() + 6);
68 char ch;
69
70 int len = input.length();
71 for(int i=0; i < len; i++) {
72 ch = input.charAt(i);
73 if (ch > '>') {
74 buf.append(ch);
75 } else if(ch == '<') {
76 buf.append("<");
77 } else if(ch == '>') {
78 buf.append(">");
79 } else if(ch == '&') {
80 buf.append("&");
81 } else if(ch == '"') {
82 buf.append(""");
83 } else {
84 buf.append(ch);
85 }
86 }
87 return buf.toString();
88 }
89
90
91
92
93
94
95
96
97
98
99 static public void appendEscapingCDATA(final StringBuffer buf,
100 final String str) {
101 if (str != null) {
102 int end = str.indexOf(CDATA_END);
103 if (end < 0) {
104 buf.append(str);
105 } else {
106 int start = 0;
107 while (end > -1) {
108 buf.append(str.substring(start, end));
109 buf.append(CDATA_EMBEDED_END);
110 start = end + CDATA_END_LEN;
111 if (start < str.length()) {
112 end = str.indexOf(CDATA_END, start);
113 } else {
114 return;
115 }
116 }
117 buf.append(str.substring(start));
118 }
119 }
120 }
121
122
123
124
125
126
127 public static String[] getThrowableStrRep(Throwable throwable) {
128 StringWriter sw = new StringWriter();
129 PrintWriter pw = new PrintWriter(sw);
130 throwable.printStackTrace(pw);
131 pw.flush();
132 LineNumberReader reader = new LineNumberReader(new StringReader(sw.toString()));
133 ArrayList<String> lines = new ArrayList<String>();
134 try {
135 String line = reader.readLine();
136 while(line != null) {
137 lines.add(line);
138 line = reader.readLine();
139 }
140 } catch(IOException ex) {
141 lines.add(ex.toString());
142 }
143 String[] rep = new String[lines.size()];
144 lines.toArray(rep);
145 return rep;
146 }
147
148 }