| UnicodeFormatter.java |
1 /**
2 * Copyright (c) 2000-2009 Liferay, Inc. All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining a copy
5 * of this software and associated documentation files (the "Software"), to deal
6 * in the Software without restriction, including without limitation the rights
7 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 * copies of the Software, and to permit persons to whom the Software is
9 * furnished to do so, subject to the following conditions:
10 *
11 * The above copyright notice and this permission notice shall be included in
12 * all copies or substantial portions of the Software.
13 *
14 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20 * SOFTWARE.
21 */
22
23 package com.liferay.portal.kernel.util;
24
25 import com.liferay.portal.kernel.log.Log;
26 import com.liferay.portal.kernel.log.LogFactoryUtil;
27
28 /**
29 * <a href="UnicodeFormatter.java.html"><b><i>View Source</i></b></a>
30 *
31 * @author Brian Wing Shun Chan
32 *
33 */
34 public class UnicodeFormatter {
35
36 public static char HEX_DIGIT[] = {
37 '0', '1', '2', '3', '4', '5', '6', '7',
38 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
39 };
40
41 public static String byteToHex(byte b) {
42 char[] array = {HEX_DIGIT[(b >> 4) & 0x0f], HEX_DIGIT[b & 0x0f]};
43
44 return new String(array);
45 }
46
47 public static String charToHex(char c) {
48 byte hi = (byte)(c >>> 8);
49 byte lo = (byte)(c & 0xff);
50
51 return byteToHex(hi) + byteToHex(lo);
52 }
53
54 public static String parseString(String hexString) {
55 StringBuilder sb = new StringBuilder();
56
57 char[] array = hexString.toCharArray();
58
59 if ((array.length % 6) != 0) {
60 _log.error("String is not in hex format");
61
62 return hexString;
63 }
64
65 for (int i = 2; i < hexString.length(); i = i + 6) {
66 String s = hexString.substring(i, i + 4);
67
68 try {
69 char c = (char)Integer.parseInt(s, 16);
70
71 sb.append(c);
72 }
73 catch (Exception e) {
74 _log.error(e, e);
75
76 return hexString;
77 }
78 }
79
80 return sb.toString();
81 }
82
83 public static String toString(char[] array) {
84 StringBuilder sb = new StringBuilder();
85
86 for (int i = 0; i < array.length; i++) {
87 sb.append("\\u");
88 sb.append(charToHex(array[i]));
89 }
90
91 return sb.toString();
92 }
93
94 public static String toString(String s) {
95 if (s == null) {
96 return null;
97 }
98
99 return toString(s.toCharArray());
100 }
101
102 private static Log _log = LogFactoryUtil.getLog(UnicodeFormatter.class);
103
104 }