1 12 package org.eclipse.update.internal.core; 13 14 15 import java.io.UnsupportedEncodingException ; 16 import java.net.MalformedURLException ; 17 import java.net.URL ; 18 import java.net.URLDecoder ; 19 import java.util.StringTokenizer ; 20 21 import org.eclipse.core.runtime.Assert; 22 29 public final class URLEncoder { 30 33 private URLEncoder() { 34 } 35 44 public static String encode(String file, String query, String ref) { 45 StringBuffer buf = new StringBuffer (); 46 StringTokenizer tokenizer = new StringTokenizer (file, "/", true); 48 while (tokenizer.hasMoreTokens()) { 49 String token = tokenizer.nextToken(); 50 if (token.equals("/")) { buf.append(token); 52 } else { 53 buf.append(encodeSegment(token)); 54 } 55 } 56 57 if (query != null){ 58 buf.append('?'); 59 buf.append(query); 60 } 61 62 if (ref != null) { 63 buf.append('#'); 64 buf.append(encodeSegment(ref)); 65 } 66 67 return buf.toString(); 68 } 69 78 public static URL encode(URL url) throws MalformedURLException { 79 String file = url.getPath(); 81 String query = url.getQuery(); 82 String ref = url.getRef(); 83 String auth = url.getAuthority(); 84 String host = url.getHost(); 85 int port = url.getPort(); 86 String userinfo = url.getUserInfo(); 87 88 URL result = url; 92 if (auth == null || auth.equals("") || userinfo == null) result = new URL (url.getProtocol(), host, port, encode(file, query, ref)); 94 return result; 95 } 96 private static String encodeSegment(String segment) { 97 98 if (segment.indexOf('%')!=-1) return segment; 100 101 StringBuffer result = new StringBuffer (segment.length()); 102 103 for (int i = 0; i < segment.length(); ++i) { 104 char c = segment.charAt(i); 105 if (mustEncode(c)) { 106 byte[] bytes = null; 107 try { 108 bytes = new Character (c).toString().getBytes("UTF8"); } catch (UnsupportedEncodingException e) { 110 Assert.isTrue(false, e.getMessage()); 111 } 112 for (int j = 0; j < bytes.length; ++j) { 113 result.append('%'); 114 result.append(Integer.toHexString((bytes[j] >> 4) & 0x0F)); 115 result.append(Integer.toHexString(bytes[j] & 0x0F)); 116 } 117 } else { 118 result.append(c); 119 } 120 } 121 122 return result.toString(); 123 } 124 125 private static boolean mustEncode(char c) { 126 if (c >= 'a' && c <= 'z') { 127 return false; 128 } 129 130 if (c >= 'A' && c <= 'Z') { 131 return false; 132 } 133 134 if (c >= '0' && c <= '9') { 135 return false; 136 } 137 138 if (c >= '\'' && c <= '.') { 139 return false; 140 } 141 142 if (c == '!' || c == '$' || c == '_' || c == '[' || c == ']') { 143 return false; 144 } 145 146 if (c ==':'){ 148 return false; 149 } 150 return true; 151 } 152 } 153 | Popular Tags |