View Javadoc
1   /*
2    * Copyright (c) 2012, Dienst Landelijk Gebied - Ministerie van Economische Zaken
3    * 
4    * Gepubliceerd onder de BSD 2-clause licentie, 
5    * zie https://github.com/MinELenI/CBSviewer/blob/master/LICENSE.md voor de volledige licentie.
6    */
7   package nl.mineleni.cbsviewer.util;
8   
9   import java.io.UnsupportedEncodingException;
10  import java.net.URLDecoder;
11  import java.net.URLEncoder;
12  
13  /**
14   * Utility class for JavaScript compatible UTF-8 encoding and decoding.
15   * 
16   * @see "http://stackoverflow.com/questions/607176/java-equivalent-to-javascripts-encodeuricomponent-that-produces-identical-output"
17   * @author John Topley
18   */
19  public final class EncodingUtil {
20  	/**
21  	 * Private constructor to prevent this class from being instantiated.
22  	 */
23  	private EncodingUtil() {
24  	}
25  
26  	/**
27  	 * Decodes the passed UTF-8 String using an algorithm that's compatible with
28  	 * JavaScript's <code>decodeURIComponent</code> function. Returns
29  	 * <code>null</code> if the String is <code>null</code>.
30  	 * 
31  	 * @param s
32  	 *            The UTF-8 encoded String to be decoded
33  	 * @return the decoded String
34  	 */
35  	public static String decodeURIComponent(final String s) {
36  		if (s == null) {
37  			return null;
38  		}
39  		String result = null;
40  		try {
41  			result = URLDecoder.decode(s, "UTF-8");
42  		} catch (final UnsupportedEncodingException e) {
43  			// This exception should never occur.
44  			result = s;
45  		}
46  		return result;
47  	}
48  
49  	/**
50  	 * Encodes the passed String as UTF-8 using an algorithm that's compatible
51  	 * with JavaScript's <code>encodeURIComponent</code> function. Returns
52  	 * <code>null</code> if the String is <code>null</code>.
53  	 * 
54  	 * @param s
55  	 *            The String to be encoded
56  	 * @return the encoded String
57  	 */
58  	public static String encodeURIComponent(final String s) {
59  		String result = null;
60  		try {
61  			result = URLEncoder.encode(s, "UTF-8").replaceAll("\\+", "%20")
62  					.replaceAll("\\%21", "!").replaceAll("\\%27", "'")
63  					.replaceAll("\\%28", "(").replaceAll("\\%29", ")")
64  					.replaceAll("\\%7E", "~");
65  		} catch (final UnsupportedEncodingException e) {
66  			// This exception should never occur.
67  			result = s;
68  		}
69  		return result;
70  	}
71  
72  }