01: package com.flexive.war.webdav.catalina;
02:
03: import java.io.ByteArrayOutputStream;
04: import java.io.IOException;
05: import java.io.OutputStreamWriter;
06: import java.util.BitSet;
07:
08: /**
09: * Catalina sources cloned for packaging issues to the flexive source tree.
10: * Refactored to JDK 1.5 compatibility.
11: * Licensed under the Apache License, Version 2.0
12: * <p/>
13: * This class is very similar to the java.net.URLEncoder class.
14: * <p/>
15: * Unfortunately, with java.net.URLEncoder there is no way to specify to the
16: * java.net.URLEncoder which characters should NOT be encoded.
17: * <p/>
18: * This code was moved from DefaultServlet.java
19: *
20: * @author Craig R. McClanahan
21: * @author Remy Maucherat
22: * @author Markus Plesser (markus.plesser@flexive.com), UCS - unique computing solutions gmbh (http://www.ucs.at)
23: */
24: public class URLEncoder {
25: protected static final char[] hexadecimal = { '0', '1', '2', '3',
26: '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
27:
28: //Array containing the safe characters set.
29: protected BitSet safeCharacters = new BitSet(256);
30:
31: public URLEncoder() {
32: for (char i = 'a'; i <= 'z'; i++) {
33: addSafeCharacter(i);
34: }
35: for (char i = 'A'; i <= 'Z'; i++) {
36: addSafeCharacter(i);
37: }
38: for (char i = '0'; i <= '9'; i++) {
39: addSafeCharacter(i);
40: }
41: }
42:
43: public void addSafeCharacter(char c) {
44: safeCharacters.set(c);
45: }
46:
47: public String encode(String path) {
48: int maxBytesPerChar = 10;
49: StringBuffer rewrittenPath = new StringBuffer(path.length());
50: ByteArrayOutputStream buf = new ByteArrayOutputStream(
51: maxBytesPerChar);
52: OutputStreamWriter writer;
53: try {
54: writer = new OutputStreamWriter(buf, "UTF8");
55: } catch (Exception e) {
56: e.printStackTrace();
57: writer = new OutputStreamWriter(buf);
58: }
59:
60: for (int i = 0; i < path.length(); i++) {
61: int c = (int) path.charAt(i);
62: if (safeCharacters.get(c)) {
63: rewrittenPath.append((char) c);
64: } else {
65: // convert to external encoding before hex conversion
66: try {
67: writer.write((char) c);
68: writer.flush();
69: } catch (IOException e) {
70: buf.reset();
71: continue;
72: }
73: byte[] ba = buf.toByteArray();
74: for (byte toEncode : ba) {
75: // Converting each byte in the buffer
76: rewrittenPath.append('%');
77: int low = toEncode & 0x0f;
78: int high = (toEncode & 0xf0) >> 4;
79: rewrittenPath.append(hexadecimal[high]);
80: rewrittenPath.append(hexadecimal[low]);
81: }
82: buf.reset();
83: }
84: }
85: return rewrittenPath.toString();
86: }
87: }
|