licensing update to APSL 2.0
[org.ibex.util.git] / src / org / ibex / util / FileNameEncoder.java
1 // Copyright 2000-2005 the Contributors, as shown in the revision logs.
2 // Licensed under the Apache Public Source License 2.0 ("the License").
3 // You may not use this file except in compliance with the License.
4
5 package org.ibex.util;
6 import java.util.*;
7 import java.io.*;
8
9 /** provides commands to urlencode and urldecode strings, making sure
10  *  to escape sequences which have special meanings in filenames */
11 public class FileNameEncoder {
12
13     private static final char[] hex =
14         new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
15
16     public static String encode(String s) {
17         StringBuffer sb = new StringBuffer();
18         try {
19             byte[] b = s.getBytes("UTF-8");
20             for(int i=0; i<b.length; i++) {
21                 char c = (char)(b[i] & 0xff);
22                 if (c == File.separatorChar || c < 32 || c > 126 || c == '%' || (i == 0 && c == '.'))
23                     sb.append("%" + hex[(b[i] & 0xf0) >> 8] + hex[b[i] & 0xf]);
24                 else sb.append(c);
25             }
26             return sb.toString();
27         } catch (UnsupportedEncodingException uee) {
28             throw new Error("this should never happen; Java spec mandates UTF-8 support");
29         }
30     }
31
32     public static String decode(String s) {
33         StringBuffer sb = new StringBuffer();
34         byte[] b = new byte[s.length() * 2];
35         int bytes = 0;
36         for(int i=0; i<s.length(); i++) {
37             char c = s.charAt(i);
38             if (c == '%') b[bytes++] = (byte)Integer.parseInt(("" + s.charAt(++i) + s.charAt(++i)), 16);
39             else b[bytes++] = (byte)c;
40         }
41         try {
42             return new String(b, 0, bytes, "UTF-8");
43         } catch (UnsupportedEncodingException uee) {
44             throw new Error("this should never happen; Java spec mandates UTF-8 support");
45         }
46     }
47 }