Skip to main content
summaryrefslogtreecommitdiffstats
blob: 03a505ee202d6e6181c1ba2d3d16c0c61967f7b3 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
/*******************************************************************************
 * Copyright (c) 2000, 2015 IBM Corporation and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     IBM Corporation - initial API and implementation
 *******************************************************************************/
package org.eclipse.help.internal.util;

import java.io.ByteArrayOutputStream;
import java.io.UnsupportedEncodingException;

public class URLCoder {

	public static String encode(String s) {
		try {
			return urlEncode(s.getBytes("UTF8"), true); //$NON-NLS-1$
		} catch (UnsupportedEncodingException uee) {
			return null;
		}
	}

	public static String compactEncode(String s) {
		try {
			return urlEncode(s.getBytes("UTF8"), false); //$NON-NLS-1$
		} catch (UnsupportedEncodingException uee) {
			return null;
		}
	}

	public static String decode(String s) {
		try {
			return new String(urlDecode(s), "UTF8"); //$NON-NLS-1$
		} catch (UnsupportedEncodingException uee) {
			return null;
		}
	}

	private static String urlEncode(byte[] data, boolean encodeAllCharacters) {
		StringBuffer buf = new StringBuffer(data.length);
		for (int i = 0; i < data.length; i++) {
			byte nextByte = data[i];
			if (!encodeAllCharacters && isAlphaNumericOrDot(nextByte)) {
				buf.append((char)nextByte);
			} else {
				buf.append('%');
				buf.append(Character.forDigit((nextByte & 240) >>> 4, 16));
				buf.append(Character.forDigit(nextByte & 15, 16));
			}
		}
		return buf.toString();
	}

	private static boolean isAlphaNumericOrDot(byte b) {
		return (b >= '0' && b <= '9') || (b >= 'a' && b <= 'z') || ( b >= 'A' && b <= 'Z')
		   || b == '.';
	}

	private static byte[] urlDecode(String encodedURL) {
		int len = encodedURL.length();
		ByteArrayOutputStream os = new ByteArrayOutputStream(len);
		for (int i = 0; i < len;) {
			switch (encodedURL.charAt(i)) {
			case '%':
				if (len >= i + 3) {
					os.write(Integer.parseInt(encodedURL.substring(i + 1, i + 3), 16));
				}
				i += 3;
				break;
			case '+': // exception from standard
				os.write(' ');
				i++;
				break;
			default:
				os.write(encodedURL.charAt(i++));
				break;
			}

		}
		return os.toByteArray();
	}
}

Back to the top