1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.jboss.netty.util.internal;
17
18 import java.util.Formatter;
19
20
21
22
23 public final class StringUtil {
24
25 private StringUtil() {
26
27 }
28
29 public static final String NEWLINE;
30
31 static {
32 String newLine = null;
33
34 try {
35 newLine = new Formatter().format("%n").toString();
36 } catch (Exception e) {
37 newLine = "\n";
38 }
39
40 NEWLINE = newLine;
41 }
42
43
44
45
46
47
48
49
50
51
52
53
54 public static String stripControlCharacters(Object value) {
55 if (value == null) {
56 return null;
57 }
58
59 return stripControlCharacters(value.toString());
60 }
61
62
63
64
65
66
67
68
69
70
71
72 public static String stripControlCharacters(String value) {
73 if (value == null) {
74 return null;
75 }
76
77 boolean hasControlChars = false;
78 for (int i = value.length() - 1; i >= 0; i --) {
79 if (Character.isISOControl(value.charAt(i))) {
80 hasControlChars = true;
81 break;
82 }
83 }
84
85 if (!hasControlChars) {
86 return value;
87 }
88
89 StringBuilder buf = new StringBuilder(value.length());
90 int i = 0;
91
92
93 for (; i < value.length(); i ++) {
94 if (!Character.isISOControl(value.charAt(i))) {
95 break;
96 }
97 }
98
99
100
101 boolean suppressingControlChars = false;
102 for (; i < value.length(); i ++) {
103 if (Character.isISOControl(value.charAt(i))) {
104 suppressingControlChars = true;
105 continue;
106 } else {
107 if (suppressingControlChars) {
108 suppressingControlChars = false;
109 buf.append(' ');
110 }
111 buf.append(value.charAt(i));
112 }
113 }
114
115 return buf.toString();
116 }
117 }