KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > update > internal > ui > URLCoder


1 /*******************************************************************************
2  * Copyright (c) 2006 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  *******************************************************************************/

11 package org.eclipse.update.internal.ui;
12
13 import java.io.ByteArrayOutputStream JavaDoc;
14 import java.io.UnsupportedEncodingException JavaDoc;
15
16 public class URLCoder {
17
18     public static String JavaDoc encode(String JavaDoc s) throws UnsupportedEncodingException JavaDoc {
19         return urlEncode(s.getBytes("UTF8")); //$NON-NLS-1$
20
}
21
22     public static String JavaDoc decode(String JavaDoc s) throws UnsupportedEncodingException JavaDoc {
23         return new String JavaDoc(urlDecode(s), "UTF8"); //$NON-NLS-1$
24
}
25
26     private static String JavaDoc urlEncode(byte[] data) {
27         StringBuffer JavaDoc buf = new StringBuffer JavaDoc(data.length);
28         for (int i = 0; i < data.length; i++) {
29             buf.append('%');
30             buf.append(Character.forDigit((data[i] & 240) >>> 4, 16));
31             buf.append(Character.forDigit(data[i] & 15, 16));
32         }
33         return buf.toString();
34     }
35
36     private static byte[] urlDecode(String JavaDoc encodedURL) {
37         int len = encodedURL.length();
38         ByteArrayOutputStream JavaDoc os = new ByteArrayOutputStream JavaDoc(len);
39         for (int i = 0; i < len;) {
40             switch (encodedURL.charAt(i)) {
41             case '%':
42                 if (len >= i + 3) {
43                     os.write(Integer.parseInt(encodedURL.substring(i + 1, i + 3), 16));
44                 }
45                 i += 3;
46                 break;
47             case '+': // exception from standard
48
os.write(' ');
49                 i++;
50                 break;
51             default:
52                 os.write(encodedURL.charAt(i++));
53                 break;
54             }
55
56         }
57         return os.toByteArray();
58     }
59 }
60
Popular Tags