KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > update > internal > core > URLEncoder


1 /*******************************************************************************
2  * Copyright (c) 2000, 2007 IBM Corporation and others.
3  * All rights reserved. This program and the accompanying materials
4  * are made available under the terms of the Eclipse Public License v1.0
5  * which accompanies this distribution, and is available at
6  * http://www.eclipse.org/legal/epl-v10.html
7  *
8  * Contributors:
9  * IBM Corporation - initial API and implementation
10  * James D Miles (IBM Corp.) - bug 191368, Policy URL doesn't support UTF-8 characters
11  *******************************************************************************/

12 package org.eclipse.update.internal.core;
13
14
15 import java.io.UnsupportedEncodingException JavaDoc;
16 import java.net.MalformedURLException JavaDoc;
17 import java.net.URL JavaDoc;
18 import java.net.URLDecoder JavaDoc;
19 import java.util.StringTokenizer JavaDoc;
20
21 import org.eclipse.core.runtime.Assert;
22 /**
23  * Encodes a <code>URL</code> into an <code>ASCII</code> readable
24  * <code>URL</code> that is safe for transport. Encoded
25  * <code>URL</code>s can be decoded using the <code>URLDecoder</code>.
26  *
27  * @see URLDecoder
28  */

29 public final class URLEncoder {
30     /**
31      * Prevents instances from being created.
32      */

33     private URLEncoder() {
34     }
35     /**
36      * Encodes the given file and reference parts of a <code>URL</code> into
37      * an <code>ASCII</code> readable <code>String</code> that is safe for
38      * transport. Returns the result.
39      *
40      * @return the result of encoding the given file and reference parts of
41      * a <code>URL</code> into an <code>ASCII</code> readable
42      * <code>String</code> that is safe for transport
43      */

44     public static String JavaDoc encode(String JavaDoc file, String JavaDoc query, String JavaDoc ref) {
45         StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
46         StringTokenizer JavaDoc tokenizer = new StringTokenizer JavaDoc(file, "/", true); //$NON-NLS-1$
47

48         while (tokenizer.hasMoreTokens()) {
49             String JavaDoc token = tokenizer.nextToken();
50             if (token.equals("/")) { //$NON-NLS-1$
51
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     /**
70      * Encodes the given <code>URL</code> into an <code>ASCII</code>
71      * readable <code>URL</code> that is safe for transport. Returns the
72      * result.
73      *
74      * @return the result of encoding the given <code>URL</code> into an
75      * <code>ASCII</code> readable <code>URL</code> that is safe for
76      * transport
77      */

78     public static URL JavaDoc encode(URL JavaDoc url) throws MalformedURLException JavaDoc {
79         // encode the path not the file as the URL may contain a query
80
String JavaDoc file = url.getPath();
81         String JavaDoc query = url.getQuery();
82         String JavaDoc ref = url.getRef();
83         String JavaDoc auth = url.getAuthority();
84         String JavaDoc host = url.getHost();
85         int port = url.getPort();
86         String JavaDoc userinfo = url.getUserInfo();
87
88         // do not encode if there is an authority, such as in
89
// ftp://user:password@host:port/path
90
// because the URL constructor does not allow it
91
URL JavaDoc result = url;
92         if (auth == null || auth.equals("") || userinfo == null) // $NON-NLS-1$ $NON-NLS-2$ //$NON-NLS-1$//$NON-NLS-2$
93
result = new URL JavaDoc(url.getProtocol(), host, port, encode(file, query, ref));
94         return result;
95     }
96     private static String JavaDoc encodeSegment(String JavaDoc segment) {
97         
98         // if we find a '%' in the string, consider the URL to be already encoded
99
if (segment.indexOf('%')!=-1) return segment;
100         
101         StringBuffer JavaDoc result = new StringBuffer JavaDoc(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 JavaDoc(c).toString().getBytes("UTF8"); //$NON-NLS-1$
109
} catch (UnsupportedEncodingException JavaDoc 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         // needed otherwise file:///c:/file/ becomes file:///C%3a/file/
147
if (c ==':'){
148             return false;
149         }
150         return true;
151     }
152 }
153
Popular Tags