01: package com.sun.portal.netlet.util;
02:
03: import java.io.UnsupportedEncodingException;
04:
05: /**
06: * UrlDecoder: java.net.URLDecoder (jdk ver 1.3) doesn't handle multibyte
07: * (japanese) characters properly. The encode method assumes platform default
08: * encoding which does not help our case. Hence the code has been borrowed from
09: * jdk1.4's implementation of URLDecoder where the encoding to be used is a
10: * parameter. This class handles those multibyte characters and encodes the
11: * input string based on the character encoding input.
12: *
13: * input: encoded string, character encoding. output: the newly decoded string.
14: *
15: */
16: public class UrlDecoder {
17:
18: private static final String defaultEncoding = "UTF8";
19:
20: public static String decode(String s) {
21: return decode(s, defaultEncoding);
22: }
23:
24: public static String decode(String s, String enc) {
25: try {
26: boolean needToChange = false;
27: StringBuffer sb = new StringBuffer();
28: int numChars = s.length();
29: int i = 0;
30:
31: if (enc.length() == 0) {
32: throw new UnsupportedEncodingException(
33: "UrlDecoder: empty string enc parameter");
34: }
35:
36: while (i < numChars) {
37: char c = s.charAt(i);
38: switch (c) {
39: case '+':
40: sb.append(' ');
41: i++;
42: needToChange = true;
43: break;
44: case '%':
45: try {
46:
47: // (numChars-i)/3 is an upper bound for the number
48: // of remaining bytes
49: byte[] bytes = new byte[(numChars - i) / 3];
50: int pos = 0;
51:
52: while (((i + 2) < numChars) && (c == '%')) {
53: bytes[pos++] = (byte) Integer.parseInt(s
54: .substring(i + 1, i + 3), 16);
55: i += 3;
56: if (i < numChars)
57: c = s.charAt(i);
58: }
59:
60: // A trailing, incomplete byte encoding such as
61: // "%x" will cause an exception to be thrown
62:
63: if ((i < numChars) && (c == '%'))
64: throw new IllegalArgumentException(
65: "UrlDecoder: Incomplete trailing escape (%) pattern");
66:
67: sb.append(new String(bytes, 0, pos, enc));
68: } catch (NumberFormatException e) {
69: throw new IllegalArgumentException(
70: "UrlDecoder: Illegal hex characters in escape (%) pattern - "
71: + e.getMessage());
72: }
73: needToChange = true;
74: break;
75: default:
76: sb.append(c);
77: i++;
78: break;
79: }
80: }
81:
82: return (needToChange ? sb.toString() : s);
83: } catch (Exception e) {
84: e.printStackTrace();
85: return s; // Return back original string . Any other solution ??
86: }
87: }
88: }
|