2 * Licensed to the Apache Software Foundation (ASF) under one or more
3 * contributor license agreements. See the NOTICE file distributed with
4 * this work for additional information regarding copyright ownership.
5 * The ASF licenses this file to You under the Apache License, Version 2.0
6 * (the "License"); you may not use this file except in compliance with
7 * the License. You may obtain a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
17 package gr.ebs.gss.server.webdav;
19 import java.io.ByteArrayOutputStream;
20 import java.io.IOException;
21 import java.io.OutputStreamWriter;
22 import java.util.BitSet;
26 * This class is very similar to the java.net.URLEncoder class.
28 * Unfortunately, with java.net.URLEncoder there is no way to specify to the
29 * java.net.URLEncoder which characters should NOT be encoded.
31 * This code was moved from DefaultServlet.java
33 * @author Craig R. McClanahan
34 * @author Remy Maucherat
36 public class URLEncoder {
40 protected static final char[] hexadecimal =
41 {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
42 'A', 'B', 'C', 'D', 'E', 'F'};
45 * Array containing the safe characters set.
47 protected BitSet safeCharacters = new BitSet(256);
53 for (char i = 'a'; i <= 'z'; i++)
55 for (char i = 'A'; i <= 'Z'; i++)
57 for (char i = '0'; i <= '9'; i++)
64 public void addSafeCharacter( char c ) {
65 safeCharacters.set( c );
70 * @return the encoded string
72 public String encode( String path ) {
73 int maxBytesPerChar = 10;
74 StringBuffer rewrittenPath = new StringBuffer(path.length());
75 ByteArrayOutputStream buf = new ByteArrayOutputStream(maxBytesPerChar);
76 OutputStreamWriter writer = null;
78 writer = new OutputStreamWriter(buf, "UTF8");
79 } catch (Exception e) {
81 writer = new OutputStreamWriter(buf);
84 for (int i = 0; i < path.length(); i++) {
85 int c = path.charAt(i);
86 if (safeCharacters.get(c))
87 rewrittenPath.append((char)c);
89 // convert to external encoding before hex conversion
91 writer.write((char)c);
93 } catch(IOException e) {
97 byte[] ba = buf.toByteArray();
98 for (int j = 0; j < ba.length; j++) {
99 // Converting each byte in the buffer
100 byte toEncode = ba[j];
101 rewrittenPath.append('%');
102 int low = toEncode & 0x0f;
103 int high = (toEncode & 0xf0) >> 4;
104 rewrittenPath.append(hexadecimal[high]);
105 rewrittenPath.append(hexadecimal[low]);
110 return rewrittenPath.toString();