KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > help > internal > util > URLCoder


1 /*******************************************************************************
2  * Copyright (c) 2000, 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.help.internal.util;
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) {
19         try {
20             return urlEncode(s.getBytes("UTF8")); //$NON-NLS-1$
21
} catch (UnsupportedEncodingException JavaDoc uee) {
22             return null;
23         }
24     }
25
26     public static String JavaDoc decode(String JavaDoc s) {
27         try {
28             return new String JavaDoc(urlDecode(s), "UTF8"); //$NON-NLS-1$
29
} catch (UnsupportedEncodingException JavaDoc uee) {
30             return null;
31         }
32     }
33
34     private static String JavaDoc urlEncode(byte[] data) {
35         StringBuffer JavaDoc buf = new StringBuffer JavaDoc(data.length);
36         for (int i = 0; i < data.length; i++) {
37             buf.append('%');
38             buf.append(Character.forDigit((data[i] & 240) >>> 4, 16));
39             buf.append(Character.forDigit(data[i] & 15, 16));
40         }
41         return buf.toString();
42     }
43
44     private static byte[] urlDecode(String JavaDoc encodedURL) {
45         int len = encodedURL.length();
46         ByteArrayOutputStream JavaDoc os = new ByteArrayOutputStream JavaDoc(len);
47         for (int i = 0; i < len;) {
48             switch (encodedURL.charAt(i)) {
49             case '%':
50                 if (len >= i + 3) {
51                     os.write(Integer.parseInt(encodedURL.substring(i + 1, i + 3), 16));
52                 }
53                 i += 3;
54                 break;
55             case '+': // exception from standard
56
os.write(' ');
57                 i++;
58                 break;
59             default:
60                 os.write(encodedURL.charAt(i++));
61                 break;
62             }
63
64         }
65         return os.toByteArray();
66     }
67 }
68
Popular Tags