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