01: package uk.org.ponder.stringutil;
02:
03: import uk.org.ponder.util.UniversalRuntimeException;
04:
05: /**
06: * A light wrapper for <CODE>java.net.URLEncoder</CODE>. Consult SVN rev 194
07: * for the historical implementation described in the following comment, which
08: * refers to a bug that was fixed in JDK 1.4.
09: * <p>
10: * This class is similar to <CODE>java.net.URLEncoder</CODE> except that it
11: * can handle non-Latin characters, whereas Java's version is <A
12: * HREF="http://developer.java.sun.com/developer/bugParade/bugs/4257115.html">
13: * documented</A> to use only <CODE>ISO 8859-1</CODE>.
14: */
15:
16: public abstract class URLEncoder {
17:
18: /** Encode the supplied URL into a UTF-8 based URL encoding */
19:
20: public static String encode(String s) {
21: try {
22: return java.net.URLEncoder.encode(s, "UTF-8");
23: } catch (Exception e) { // should never happen
24: throw UniversalRuntimeException.accumulate(e,
25: "Error encoding URL " + s);
26: }
27: }
28:
29: /**
30: * URL-encodes a string using any available encoding.
31: *
32: * @param s
33: * what to encode
34: * @param encoding
35: * name of the encoding to use;
36: * @return URL-encoded version of <CODE>s</CODE>
37: * @throws java.io.UnsupportedEncodingException
38: * if <CODE>encoding</CODE> isn't supported by the Java VM and/or
39: * class-libraries
40: * @pre s != null
41: * @pre encoding != null
42: */
43: public static String encode(String s, String encoding) {
44: try {
45: return java.net.URLEncoder.encode(s, encoding);
46: } catch (Exception e) {
47: throw UniversalRuntimeException.accumulate(e,
48: "Error encoding URL " + s);
49: }
50: }
51:
52: static final int caseDiff = ('a' - 'A');
53:
54: /**
55: * Converts a single character (byte) into its upper-case URL hex
56: * representation %E0, say.
57: */
58:
59: public static void appendURLHex(char c, CharWrap target) {
60: target.append('%');
61: char ch = Character.forDigit((c >> 4) & 0xF, 16);
62: // converting to use uppercase letter as part of
63: // the hex value if ch is a letter.
64: if (Character.isLetter(ch)) {
65: ch -= caseDiff;
66: }
67: target.append(ch);
68: ch = Character.forDigit(c & 0xF, 16);
69: if (Character.isLetter(ch)) {
70: ch -= caseDiff;
71: }
72: target.append(ch);
73: }
74:
75: }
|