| 1 10 package org.mmbase.util; 11 import org.mmbase.util.logging.*; 12 13 20 public class URLEscape { 21 22 private static Logger log = Logging.getLoggerInstance(URLEscape.class.getName()); 24 25 29 static boolean isacceptable[] = { 30 false, false, false, false, false, false, false, false, false, false, true, true, true, true, true, false, true, true, true, true, true, true, true, true, true, true, true, false, false, false, false, false, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, false, false, false, false, true, false, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, false, false, false, false, false }; 43 44 47 static char hex[] = { 48 '0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F' 49 }; 50 51 54 static char HEX_ESCAPE='%'; 55 56 63 public static String escapeurl(String str) { 64 StringBuffer esc = new StringBuffer (); 65 byte buf[]; 66 try { 67 buf = str.getBytes("UTF-8"); 68 } catch (java.io.UnsupportedEncodingException uee) { 69 return str; } 71 72 for (int i = 0; i<buf.length;i++) { 73 int a = (int)buf[i] & 0xff; 74 if (a>=32 && a<128 && isacceptable[a-32]) { 75 esc.append((char)a); 76 } else { 77 esc.append(HEX_ESCAPE); 78 esc.append(hex[a >> 4]); 79 esc.append(hex[a & 15]); 80 } 81 } 82 return esc.toString(); 83 } 84 85 91 private static char from_hex(char c) { 92 return (char)(c >= '0' && c <= '9' ? c - '0' 93 : c >= 'A' && c <= 'F' ? c - 'A' + 10 94 : c - 'a' + 10); 95 } 96 97 104 public static String unescapeurl(String str) { 105 int i; 106 char j,t; 107 StringBuffer esc=new StringBuffer (); 108 109 if (str!=null) { 110 for (i=0;i<str.length();i++) { 111 t=str.charAt(i); 112 if (t==HEX_ESCAPE) { 113 t=str.charAt(++i); 114 j=(char)(from_hex(t)*16); 115 t=str.charAt(++i); 116 j+=from_hex(t); 117 esc.append(j); 118 } else { 119 esc.append(t); 120 } 121 } 122 } else { 123 log.warn("Unescapeurl -> Bogus parameter"); 124 } 125 return esc.toString(); 126 } 127 128 131 public static void main(String args[]) { 132 for (int i=0;i<args.length;i++) { 133 log.info("Original : '"+args[i]+"'"); 134 log.info("Escaped : '"+escapeurl(args[i])+"'"); 135 log.info("Unescaped again : '"+unescapeurl(escapeurl(args[i]))+"'"); 136 } 137 138 } 139 } 140 | Popular Tags |