1 package fr.in2p3.jsaga.adaptor.data;
2
3 import java.io.UnsupportedEncodingException;
4 import java.net.URLEncoder;
5
6
7
8
9
10
11
12
13
14
15
16
17
18 public class PathEncoder {
19 static String encode(String path) throws UnsupportedEncodingException {
20 StringBuffer buffer = new StringBuffer();
21 char[] array = path.toCharArray();
22 for (int i=0; i<array.length; i++) {
23 char c = array[i];
24 if (c < 128) {
25 if (c=='%' && (isEncodedQuestionMark(array,i) || isEncodedSharp(array,i))) {
26 buffer.append(c);
27 } else if (isIllegalASCII(c)) {
28 appendHex(buffer, c);
29 } else {
30 buffer.append(c);
31 }
32 } else {
33 if (c <= 160) {
34 appendHex(buffer, 0xC0 | (c >> 6));
35 appendHex(buffer, 0x80 | (c & 0x3F));
36 } else {
37 buffer.append(URLEncoder.encode(Character.toString(c), "UTF-8"));
38 }
39 }
40 }
41 return buffer.toString();
42 }
43 private static boolean isIllegalASCII(char c) {
44 if (c <= 32) {
45 return true;
46 } else {
47 switch(c) {
48
49 case '"': case '%': case '<': case '>': case '[': case '\\': case ']':
50 case '^': case '`': case '{': case '|': case '}': case 127:
51 return true;
52
53 case '#': case '?':
54 return true;
55
56 default:
57 return false;
58 }
59 }
60 }
61 private static boolean isEncodedQuestionMark(char[] array, int pos) {
62 return pos+2<array.length && array[pos+1]=='3' && array[pos+2]=='F';
63 }
64 private static boolean isEncodedSharp(char[] array, int pos) {
65 return pos+2<array.length && array[pos+1]=='2' && array[pos+2]=='3';
66 }
67 private static void appendHex(StringBuffer buffer, int c) {
68 final char[] HEX = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
69 buffer.append('%');
70 buffer.append(HEX[c/16]);
71 buffer.append(HEX[c%16]);
72 }
73 }