updated Makefile.common
[org.ibex.core.git] / src / org / ibex / util / FileNameEncoder.java
1 // Copyright (C) 2003 Adam Megacz <adam@ibex.org> all rights reserved.
2 //
3 // You may modify, copy, and redistribute this code under the terms of
4 // the GNU Library Public License version 2.1, with the exception of
5 // the portion of clause 6a after the semicolon (aka the "obnoxious
6 // relink clause")
7
8 package org.ibex.util;
9 import java.util.*;
10 import java.io.*;
11
12 /** provides commands to urlencode and urldecode strings, making sure
13  *  to escape sequences which have special meanings in filenames */
14 public class FileNameEncoder {
15
16     private static final char[] hex =
17         new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
18
19     public static String encode(String s) {
20         StringBuffer sb = new StringBuffer();
21         try {
22             byte[] b = s.getBytes("UTF-8");
23             for(int i=0; i<b.length; i++) {
24                 char c = (char)(b[i] & 0xff);
25                 if (c == File.separatorChar || c < 32 || c > 126 || c == '%' || (i == 0 && c == '.'))
26                     sb.append("%" + hex[(b[i] & 0xf0) >> 8] + hex[b[i] & 0xf]);
27                 else sb.append(c);
28             }
29             return sb.toString();
30         } catch (UnsupportedEncodingException uee) {
31             throw new Error("this should never happen; Java spec mandates UTF-8 support");
32         }
33     }
34
35     public static String decode(String s) {
36         StringBuffer sb = new StringBuffer();
37         byte[] b = new byte[s.length() * 2];
38         int bytes = 0;
39         for(int i=0; i<s.length(); i++) {
40             char c = s.charAt(i);
41             if (c == '%') b[bytes++] = (byte)Integer.parseInt(("" + s.charAt(++i) + s.charAt(++i)), 16);
42             else b[bytes++] = (byte)c;
43         }
44         try {
45             return new String(b, 0, bytes, "UTF-8");
46         } catch (UnsupportedEncodingException uee) {
47             throw new Error("this should never happen; Java spec mandates UTF-8 support");
48         }
49     }
50 }