001package org.avaje.freemarker.util; 002 003import java.io.UnsupportedEncodingException; 004import java.net.URLDecoder; 005import java.net.URLEncoder; 006 007 008/** 009 * Utilities for encoding and decoding strings. 010 */ 011public final class EncodeUtil { 012 013 private EncodeUtil() { 014 /* no instances */ 015 } 016 017 018 /** 019 * URL-encodes the specified UTF-8 string. 020 */ 021 public static String urlEncode(String string) { 022 if (string == null) return null; 023 try { 024 return URLEncoder.encode(string, "UTF-8"); 025 } catch (UnsupportedEncodingException e) { 026 throw new IllegalStateException("Support for UTF-8 is mandated by the Java spec", e); 027 } 028 } 029 030 /** 031 * URL-decodes the specified string as a UTF-8 string. 032 */ 033 public static String urlDecode(String string) { 034 if (string == null) return null; 035 try { 036 return URLDecoder.decode(string, "UTF-8"); 037 } catch (UnsupportedEncodingException e) { 038 throw new IllegalStateException("Support for UTF-8 is mandated by the Java spec", e); 039 } 040 } 041 042 /** 043 * Returns the bytes corresponding to the specified ASCII string. 044 */ 045 public static byte[] asciiToBytes(String string) { 046 if (string == null) return null; 047 try { 048 return string.getBytes("US-ASCII"); 049 } catch (UnsupportedEncodingException e) { 050 throw new IllegalStateException("Support for US-ASCII is mandated by the Java spec", e); 051 } 052 } 053 054 /** 055 * Returns the ASCII string corresponding to the specified bytes. 056 */ 057 public static String bytesToAscii(byte[] data) { 058 try { 059 return new String(data, "US-ASCII"); 060 } catch (UnsupportedEncodingException e) { 061 throw new IllegalStateException("Support for US-ASCII is mandated by the Java spec", e); 062 } 063 } 064 065 /** 066 * Returns the bytes corresponding to the specified UTF-8 string. 067 */ 068 public static byte[] utf8ToBytes(String string) { 069 if (string == null) return null; 070 try { 071 return string.getBytes("UTF-8"); 072 } catch (UnsupportedEncodingException e) { 073 throw new IllegalStateException("Support for UTF-8 is mandated by the Java spec", e); 074 } 075 } 076 077 /** 078 * Returns the UTF-8 string corresponding to the specified bytes. 079 */ 080 public static String bytesToUtf8(byte[] data) { 081 try { 082 return new String(data, "UTF-8"); 083 } catch (UnsupportedEncodingException e) { 084 throw new IllegalStateException("Support for UTF-8 is mandated by the Java spec", e); 085 } 086 } 087 088 /** 089 * Returns the UTF-8 string corresponding to the specified bytes. 090 */ 091 public static String decodeBytes(byte[] data, String encoding) { 092 try { 093 return new String(data, encoding); 094 } catch (UnsupportedEncodingException e) { 095 throw new RuntimeException("Error decoding bytes with "+encoding, e); 096 } 097 } 098}