A utility method to quote a word, if the word contains any characters from the specified 'specials' list. The HeaderTokenizer class defines two special sets of delimiters - MIME and RFC 822. This method is typically used during the generation of RFC 822 and MIME header fields.
(String word, String specials)
| 986 | * @see javax.mail.internet.HeaderTokenizer#RFC822 |
| 987 | */ |
| 988 | public static String quote(String word, String specials) { |
| 989 | int len = word == null ? 0 : word.length(); |
| 990 | if (len == 0) |
| 991 | return "\"\""; // an empty string is handled specially |
| 992 | |
| 993 | /* |
| 994 | * Look for any "bad" characters, Escape and |
| 995 | * quote the entire string if necessary. |
| 996 | */ |
| 997 | boolean needQuoting = false; |
| 998 | for (int i = 0; i < len; i++) { |
| 999 | char c = word.charAt(i); |
| 1000 | if (c == '"' || c == '\\' || c == '\r' || c == '\n') { |
| 1001 | // need to escape them and then quote the whole string |
| 1002 | StringBuilder sb = new StringBuilder(len + 3); |
| 1003 | sb.append('"'); |
| 1004 | sb.append(word.substring(0, i)); |
| 1005 | int lastc = 0; |
| 1006 | for (int j = i; j < len; j++) { |
| 1007 | char cc = word.charAt(j); |
| 1008 | if ((cc == '"') || (cc == '\\') || |
| 1009 | (cc == '\r') || (cc == '\n')) |
| 1010 | if (cc == '\n' && lastc == '\r') |
| 1011 | ; // do nothing, CR was already escaped |
| 1012 | else |
| 1013 | sb.append('\\'); // Escape the character |
| 1014 | sb.append(cc); |
| 1015 | lastc = cc; |
| 1016 | } |
| 1017 | sb.append('"'); |
| 1018 | return sb.toString(); |
| 1019 | } else if (c < 040 || (c >= 0177 && !allowUtf8) || |
| 1020 | specials.indexOf(c) >= 0) |
| 1021 | // These characters cause the string to be quoted |
| 1022 | needQuoting = true; |
| 1023 | } |
| 1024 | |
| 1025 | if (needQuoting) { |
| 1026 | StringBuilder sb = new StringBuilder(len + 2); |
| 1027 | sb.append('"').append(word).append('"'); |
| 1028 | return sb.toString(); |
| 1029 | } else |
| 1030 | return word; |
| 1031 | } |
| 1032 | |
| 1033 | /** |
| 1034 | * Fold a string at linear whitespace so that each line is no longer |
no test coverage detected