001 /*
002 GRANITE DATA SERVICES
003 Copyright (C) 2011 GRANITE DATA SERVICES S.A.S.
004
005 This file is part of Granite Data Services.
006
007 Granite Data Services is free software; you can redistribute it and/or modify
008 it under the terms of the GNU Library General Public License as published by
009 the Free Software Foundation; either version 2 of the License, or (at your
010 option) any later version.
011
012 Granite Data Services is distributed in the hope that it will be useful, but
013 WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
014 FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License
015 for more details.
016
017 You should have received a copy of the GNU Library General Public License
018 along with this library; if not, see <http://www.gnu.org/licenses/>.
019 */
020
021 package org.granite.util;
022
023 import java.io.BufferedReader;
024 import java.io.IOException;
025 import java.io.StringReader;
026 import java.lang.reflect.Array;
027 import java.nio.ByteBuffer;
028 import java.nio.LongBuffer;
029 import java.util.ArrayList;
030 import java.util.Arrays;
031 import java.util.Collection;
032 import java.util.HashMap;
033 import java.util.List;
034 import java.util.Map;
035
036 /**
037 * @author Franck WOLFF
038 */
039 public class StringUtil {
040
041 private static final char[] HEX_CHARS = "0123456789ABCDEF".toCharArray();
042
043 public static char[] bytesToHexChars(byte[] bytes) {
044 return bytesToHexChars(bytes, new char[bytes.length * 2], 0);
045 }
046
047 public static char[] bytesToHexChars(byte[] bytes, char[] chars, int off) {
048 if (chars.length - off < bytes.length * 2)
049 throw new IllegalArgumentException("Unsufficient capacity in 'chars' parameter");
050
051 for (int i = off, j = 0; i < bytes.length; ) {
052 int b = bytes[i++] & 0xFF;
053 chars[j++] = HEX_CHARS[b >> 4];
054 chars[j++] = HEX_CHARS[b & 0x0F];
055 }
056
057 return chars;
058 }
059
060 public static byte[] hexCharsToBytes(char[] chars) {
061 return hexCharsToBytes(chars, 0);
062 }
063
064 public static byte[] hexCharsToBytes(char[] chars, int off) {
065 final int len = chars.length;
066 if (((len - off) % 2) != 0)
067 throw new IllegalArgumentException("(chars.length - off) must be even");
068
069 byte[] bytes = new byte[(len - off) / 2];
070 for (int i = off, j = 0; i < len; ) {
071 int b = 0;
072 char c = chars[i++];
073 b |= ((c - (c < 'A' ? '0' : ('A' - 10))) << 4);
074 c = chars[i++];
075 b |= (c - (c < 'A' ? '0' : ('A' - 10)));
076 bytes[j++] = (byte)b;
077 }
078 return bytes;
079 }
080
081 public static byte[] hexStringToBytes(String s) {
082 return hexStringToBytes(s, 0);
083 }
084
085 public static byte[] hexStringToBytes(String s, int off) {
086 final int len = s.length();
087 if (((len - off) % 2) != 0)
088 throw new IllegalArgumentException("(s.length() - off) must be even");
089
090 byte[] bytes = new byte[(len - off) / 2];
091 for (int i = off, j = 0; i < len; ) {
092 int b = 0;
093 char c = s.charAt(i++);
094 b |= ((c - (c < 'A' ? '0' : ('A' - 10))) << 4);
095 c = s.charAt(i++);
096 b |= (c - (c < 'A' ? '0' : ('A' - 10)));
097 bytes[j++] = (byte)b;
098 }
099 return bytes;
100 }
101
102 public static String toHexString(Number n) {
103 if (n == null)
104 return "null";
105
106 byte[] bytes = new byte[8];
107 ByteBuffer bytesBuffer = ByteBuffer.wrap(bytes);
108 LongBuffer longBuffer = bytesBuffer.asLongBuffer();
109 longBuffer.put(0, n.longValue());
110
111 StringBuilder sb = new StringBuilder(16);
112 for (int i = 0; i < bytes.length; i++) {
113 int b = bytes[i] & 0xFF;
114 if (b != 0 || sb.length() > 0 || i == (bytes.length - 1))
115 sb.append(HEX_CHARS[b >> 4]).append(HEX_CHARS[b & 0x0F]);
116 }
117 return sb.toString();
118 }
119
120 public static String removeSpaces(String s) {
121 if (s == null)
122 return null;
123 String[] tokens = s.split("\\s", -1);
124 if (tokens.length == 0)
125 return "";
126 if (tokens.length == 1)
127 return tokens[0];
128 StringBuilder sb = new StringBuilder();
129 for (String token : tokens)
130 sb.append(token);
131 return sb.toString();
132 }
133
134 public static String[] toStringArray(String s) {
135 if (s == null)
136 return new String[0];
137
138 List<String> lines = new ArrayList<String>();
139 try {
140 BufferedReader reader = new BufferedReader(new StringReader(s));
141 String line = null;
142 while ((line = reader.readLine()) != null)
143 lines.add(line);
144 }
145 catch (IOException e) {
146 // can't happen...
147 }
148 return lines.toArray(new String[lines.size()]);
149 }
150
151 public static String toString(Object o) {
152 return toString(o, -1);
153 }
154
155 public static String toString(Object o, int maxItems) {
156 if (o == null)
157 return "null";
158
159 if (o instanceof String)
160 return ("\"" + o + "\"");
161
162 if (o instanceof Character || o.getClass() == Character.TYPE)
163 return ("'" + o + "'");
164
165 if (o instanceof Number) {
166 if (o instanceof Byte || o instanceof Short || o instanceof Integer || o instanceof Long)
167 return o + " <0x" + toHexString((Number)o) + ">";
168 return String.valueOf(o);
169 }
170
171 // Enclose code in try catch block for uninitialized proxy exceptions (and the like).
172 try {
173 if (o.getClass().isArray()) {
174 Class<?> type = o.getClass().getComponentType();
175
176 if (maxItems < 0) {
177 if (type.isPrimitive()) {
178 if (type == Byte.TYPE)
179 return Arrays.toString((byte[])o);
180 if (type == Character.TYPE)
181 return Arrays.toString((char[])o);
182 if (type == Integer.TYPE)
183 return Arrays.toString((int[])o);
184 if (type == Double.TYPE)
185 return Arrays.toString((double[])o);
186 if (type == Long.TYPE)
187 return Arrays.toString((long[])o);
188 if (type == Float.TYPE)
189 return Arrays.toString((float[])o);
190 if (type == Short.TYPE)
191 return Arrays.toString((short[])o);
192 if (type == Boolean.TYPE)
193 return Arrays.toString((boolean[])o);
194 return "[Array of unknown primitive type: " + type + "]"; // Should never append...
195 }
196 return Arrays.toString((Object[])o);
197 }
198
199 final int max = Math.min(maxItems, Array.getLength(o));
200 List<Object> list = new ArrayList<Object>(max);
201
202 for (int i = 0; i < max; i++)
203 list.add(Array.get(o, i));
204 if (max < Array.getLength(o))
205 list.add("(first " + max + '/' + Array.getLength(o) + " elements only...)");
206
207 o = list;
208 }
209 else if (o instanceof Collection<?> && maxItems >= 0) {
210
211 Collection<?> coll = (Collection<?>)o;
212 final int max = Math.min(maxItems, coll.size());
213 List<Object> list = new ArrayList<Object>(max);
214
215 int i = 0;
216 for (Object item : coll) {
217 if (i >= max) {
218 list.add("(first " + max + '/' + coll.size() + " elements only...)");
219 break;
220 }
221 list.add(item);
222 i++;
223 }
224
225 o = list;
226 }
227 else if (o instanceof Map<?, ?> && maxItems >= 0) {
228 Map<?, ?> map = (Map<?, ?>)o;
229 final int max = Math.min(maxItems, map.size());
230 Map<Object, Object> copy = new HashMap<Object, Object>(max);
231
232 int i = 0;
233 for (Map.Entry<?, ?> item : map.entrySet()) {
234 if (i >= max) {
235 copy.put("(first " + max + '/' + map.size() + " elements only...)", "...");
236 break;
237 }
238 copy.put(item.getKey(), item.getValue());
239 i++;
240 }
241
242 o = copy;
243 }
244
245 return String.valueOf(o);
246 } catch (Exception e) {
247 return o.getClass().getName() + " (exception: " + e.toString() + ")";
248 }
249 }
250 }