Skip to main content
summaryrefslogtreecommitdiffstats
blob: 05cd5d041e5cd0ed80e0c88b1571e12f321f5944 (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
/*******************************************************************************
 * Copyright (c) 2004, 2008 Tasktop Technologies 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:
 *     Tasktop Technologies - initial API and implementation
 *******************************************************************************/

package org.eclipse.mylyn.internal.provisional.tasks.core;

/**
 * @author Steffen Pingel
 */
public class TasksUtil {

	public static String decode(String text) {
		boolean escaped = false;
		StringBuffer sb = new StringBuffer(text.length());
		StringBuffer escapedText = new StringBuffer(4);
		char[] chars = text.toCharArray();
		for (char c : chars) {
			if (c >= '0' && c <= '9' || c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c == '.') {
				if (escaped) {
					escapedText.append(c);
				} else {
					sb.append(c);
				}
			} else if (c == '%') {
				if (escaped) {
					throw new IllegalArgumentException("Unexpected '%' sign in '" + text + "'");
				}
				escaped = !escaped;
			} else if (c == '_') {
				if (!escaped) {
					throw new IllegalArgumentException("Unexpected '_' sign in '" + text + "'");
				}
				try {
					sb.append((char) Integer.parseInt(escapedText.toString(), 16));
					escapedText.setLength(0);
				} catch (NumberFormatException e) {
					throw new IllegalArgumentException("Invalid escape code in '" + text + "'");
				}
				escaped = !escaped;
			} else {
				throw new IllegalArgumentException("Unexpected character '" + c + "' in '" + text + "'");
			}
		}
		return sb.toString();
	}

	public static String encode(String text) {
		StringBuffer sb = new StringBuffer(text.length());
		char[] chars = text.toCharArray();
		for (char c : chars) {
			if (c >= '0' && c <= '9' || c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c == '.') {
				sb.append(c);
			} else {
				sb.append("%" + Integer.toHexString(c).toUpperCase() + "_");
			}
		}
		return sb.toString();
	}

}

Back to the top