KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > xsocket > DataConverter


1 // $Id: DataConverter.java 1546 2007-07-23 06:07:56Z grro $
2

3 /*
4  * Copyright (c) xsocket.org, 2006 - 2007. All rights reserved.
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19  *
20  * Please refer to the LGPL license at: http://www.gnu.org/copyleft/lesser.txt
21  * The latest copy of this software may be found on http://www.xsocket.org/
22  */

23 package org.xsocket;
24
25
26 import java.io.UnsupportedEncodingException JavaDoc;
27 import java.nio.ByteBuffer JavaDoc;
28 import java.nio.CharBuffer JavaDoc;
29 import java.nio.charset.CharacterCodingException JavaDoc;
30 import java.nio.charset.Charset JavaDoc;
31 import java.nio.charset.CharsetDecoder JavaDoc;
32 import java.nio.charset.CharsetEncoder JavaDoc;
33 import java.text.SimpleDateFormat JavaDoc;
34 import java.util.ArrayList JavaDoc;
35 import java.util.Date JavaDoc;
36 import java.util.HashMap JavaDoc;
37 import java.util.List JavaDoc;
38 import java.util.Map JavaDoc;
39
40
41
42 /**
43  * a data converter utilities class
44  *
45  * @author grro@xsocket.org
46  */

47 public final class DataConverter {
48
49     private static final Map JavaDoc<String JavaDoc, CharsetEncoder JavaDoc> encoders = new HashMap JavaDoc<String JavaDoc, CharsetEncoder JavaDoc>();
50     private static final Map JavaDoc<String JavaDoc, CharsetDecoder JavaDoc> decoders = new HashMap JavaDoc<String JavaDoc, CharsetDecoder JavaDoc>();
51     
52     
53     /**
54      * converts the given byte size in a textual representation
55      *
56      * @param bytes the bytes to convert
57      * @return the formated String representation of the bytes
58      */

59     public static String JavaDoc toFormatedBytesSize(long bytes) {
60         if (bytes > (5 * 1000 * 1000)) {
61             return (bytes/1000000) + " mb";
62             
63         } else if (bytes > (10 * 1000)) {
64             return (bytes/1000) + " kb";
65             
66         } else {
67             return bytes + " bytes";
68         }
69     }
70     
71     
72     /**
73      * converts the given time in a textual representation
74      *
75      * @param time the time to convert
76      * @return the formated String representation of the date
77      */

78     public static String JavaDoc toFormatedDate(long time) {
79         return new SimpleDateFormat JavaDoc("MMM.dd HH:mm").format(new Date JavaDoc(time));
80     }
81
82     /**
83      * converts the given duration in a textual representation
84      *
85      * @param duration the duration to convert
86      * @return the formated String representation of the duration
87      */

88     public static String JavaDoc toFormatedDuration(long duration) {
89
90         if (duration < 5 * 1000) {
91             return duration + " millis";
92             
93         } else if (duration < (60 * 1000)) {
94             return ((int) (duration / 1000)) + " sec";
95
96         } else if (duration < (60 * 60 * 1000)) {
97             return ((int) (duration / (60* 1000))) + " min";
98         } else {
99             return ((int) (duration / (60 * 60* 1000))) + " h";
100         }
101     }
102     
103     
104     /**
105      * converts the given String into a ByteBuffer
106      *
107      * @param s the String to convert
108      * @param encoding the encoding to use
109      * @return the String as ByteBuffer
110      */

111     public static ByteBuffer JavaDoc toByteBuffer(String JavaDoc s, String JavaDoc encoding) {
112         CharsetEncoder JavaDoc encoder = encoders.get(encoding);
113         if (encoder == null) {
114             Charset JavaDoc charset = Charset.forName(encoding);
115             if (charset != null) {
116                 encoder = charset.newEncoder();
117                 encoders.put(encoding, encoder);
118                 decoders.put(encoding, charset.newDecoder());
119             } else {
120                 return null;
121             }
122         }
123         
124         try {
125             return encoder.encode(CharBuffer.wrap(s));
126         } catch (CharacterCodingException JavaDoc cce) {
127             throw new RuntimeException JavaDoc(cce);
128         }
129     }
130     
131     
132     /**
133      * converts the given ByteBuffer into String by using
134      * UTF-8 encoding
135      *
136      * @param buffer the ByteBuffer to convert
137      * @return the ByteByuffer as String
138      */

139     public static String JavaDoc toString(ByteBuffer JavaDoc buffer) throws UnsupportedEncodingException JavaDoc {
140         return toString(buffer, "UTF-8");
141     }
142
143     
144     /**
145      * converts the given ByteBuffer array into String by using
146      * UTF-8 encoding
147      *
148      * @param buffer the ByteBuffer arrayto convert
149      * @return the ByteByuffer as String
150      */

151     public static String JavaDoc toString(ByteBuffer JavaDoc[] buffer) throws UnsupportedEncodingException JavaDoc {
152         return toString(buffer, "UTF-8");
153     }
154
155
156     /**
157      * converts the given ByteBuffer into String repesentation
158      *
159      * @param buffer the ByteBuffer to convert
160      * @param encoding the encoding to use
161      * @return the ByteByuffer as String
162      */

163     public static String JavaDoc toString(ByteBuffer JavaDoc buffer, String JavaDoc encoding) throws UnsupportedEncodingException JavaDoc {
164         try {
165             CharsetDecoder JavaDoc decoder = decoders.get(encoding);
166             if (decoder == null) {
167                 Charset JavaDoc charset = Charset.forName(encoding);
168                 if (charset != null) {
169                     decoder = charset.newDecoder();
170                     decoders.put(encoding, decoder);
171                     encoders.put(encoding, charset.newEncoder());
172                 } else {
173                     throw new UnsupportedEncodingException JavaDoc("charset '" + encoding + "' has not been found");
174                 }
175             }
176             
177             return decoder.decode(buffer).toString();
178             
179         } catch (CharacterCodingException JavaDoc cce) {
180             RuntimeException JavaDoc re = new RuntimeException JavaDoc("coding exception for '" + encoding + "' occured: " + cce.toString(), cce);
181             throw re;
182         }
183     }
184     
185     
186     
187     /**
188      * converts the given ByteBuffer into a hex string
189      *
190      * @param buffer the ByteBuffer to convert
191      * @return the hex string
192      */

193     public static String JavaDoc toByteString(ByteBuffer JavaDoc buffer) {
194         StringBuilder JavaDoc sb = new StringBuilder JavaDoc();
195         
196         while (buffer.hasRemaining()) {
197             String JavaDoc hex = Integer.toHexString(0x0100 + (buffer.get() & 0x00FF)).substring(1);
198             sb.append((hex.length() < 2 ? "0" : "") + hex + " ");
199         }
200         
201         return sb.toString();
202     }
203
204
205     
206     /**
207      * converts the given list of ByteBuffers into a String
208      *
209      * @param buffers the list of ByteBuffer to convert
210      * @param encoding the encoding to use
211      * @return the ByteByuffer as String
212      */

213     public static String JavaDoc toString(List JavaDoc<ByteBuffer JavaDoc> buffers, String JavaDoc encoding) throws UnsupportedEncodingException JavaDoc {
214         return toString(buffers.toArray(new ByteBuffer JavaDoc[buffers.size()]), encoding);
215     }
216     
217
218     /**
219      * converts the given array of ByteBuffers into String
220      *
221      * @param buffers the array of ByteBuffer to convert
222      * @param encoding the encoding to use
223      * @return the ByteByuffer as String
224      */

225     public static String JavaDoc toString(ByteBuffer JavaDoc[] buffers, String JavaDoc encoding) throws UnsupportedEncodingException JavaDoc {
226         byte[] bytes = toBytes(buffers);
227         if (bytes != null) {
228             return new String JavaDoc(bytes, encoding);
229         } else {
230             return "";
231         }
232     }
233     
234
235
236     /**
237      * print the bytebuffer as limited string
238      *
239      * @param buffers the buffers to print
240      * @param encoding the encoding to use
241      * @param maxOutSize the max size to print
242      *
243      * @return the ByteBuffers as string representation
244      */

245     public static String JavaDoc toString(ByteBuffer JavaDoc[] buffers, String JavaDoc encoding, int maxOutSize) throws UnsupportedEncodingException JavaDoc {
246         String JavaDoc s = toString(buffers, encoding);
247         if (s.length() > maxOutSize) {
248             s = s.substring(0, maxOutSize) + " [output has been cut]";
249         }
250         return s;
251     }
252
253     
254     /**
255      * merges a ByteBuffer array into a (direct) ByteBuffer
256      *
257      * @param buffers the ByteBuffer array to merge
258      * @return the single ByteBuffer
259      */

260     public static ByteBuffer JavaDoc toByteBuffer(ByteBuffer JavaDoc[] buffers) {
261         byte[] bytes = toBytes(buffers);
262         return ByteBuffer.wrap(bytes);
263     }
264
265     
266     /**
267      * converts a list of ByteBuffer to a byte array
268      *
269      * @param buffers the ByteBuffer list to convert
270      * @return the byte array
271      */

272     public static byte[] toBytes(List JavaDoc<ByteBuffer JavaDoc> buffers) {
273         return toBytes(buffers.toArray(new ByteBuffer JavaDoc[buffers.size()]));
274     }
275
276     
277     
278     /**
279      * converts a ByteBuffer array to a byte array
280      *
281      * @param buffers the ByteBuffer array to convert
282      * @return the byte array
283      */

284     public static byte[] toBytes(ByteBuffer JavaDoc[] buffers) {
285         byte[] result = null;
286
287         if (buffers == null) {
288             return null;
289         }
290
291         int size = 0;
292         for (ByteBuffer JavaDoc buffer : buffers) {
293             size += buffer.remaining();
294             if (result == null) {
295                 byte[] bytes = toBytes(buffer);
296                 if (bytes.length > 0) {
297                     result = bytes;
298                 }
299             } else {
300                 byte[] additionalBytes = toBytes(buffer);
301                 byte[] newResult = new byte[result.length + additionalBytes.length];
302                 System.arraycopy(result, 0, newResult, 0, result.length);
303                 System.arraycopy(additionalBytes, 0, newResult, result.length, additionalBytes.length);
304                 result = newResult;
305             }
306         }
307                 
308         return result;
309     }
310
311     
312     /**
313      * converts a ByteBuffer into a byte array
314      *
315      * @param buffer the ByteBuffer to convert
316      * @return the byte array
317      */

318     public static byte[] toBytes(ByteBuffer JavaDoc buffer) {
319         
320         int savedPos = buffer.position();
321         int savedLimit = buffer.limit();
322
323         try {
324             
325             byte[] array = new byte[buffer.limit() - buffer.position()];
326     
327             if (buffer.hasArray()) {
328                 int offset = buffer.arrayOffset();
329                 byte[] bufferArray = buffer.array();
330                 System.arraycopy(bufferArray, offset, array, 0, array.length);
331     
332                 return array;
333             } else {
334                 buffer.get(array);
335                 return array;
336             }
337             
338         } finally {
339             buffer.position(savedPos);
340             buffer.limit(savedLimit);
341         }
342     }
343     
344     
345
346     /**
347      * print the byte array as a hex string
348      *
349      * @param buffers the buffers to print
350      * @param maxOutSize the max size to print
351      *
352      * @return the ByteBuffers as hex representation
353      */

354     public static String JavaDoc toHexString(byte[] buffers, int maxOutSize) {
355         return toHexString(new ByteBuffer JavaDoc[] { ByteBuffer.wrap(buffers) }, maxOutSize);
356     }
357
358
359
360     /**
361      * print the bytebuffer as a hex string
362      *
363      * @param buffers the buffers to print
364      * @param maxOutSize the max size to print
365      *
366      * @return the ByteBuffers as hex representation
367      */

368     public static String JavaDoc toHexString(ByteBuffer JavaDoc[] buffers, int maxOutSize) {
369
370         // first cut output if longer than max limit
371
String JavaDoc postfix = "";
372         int size = 0;
373         List JavaDoc<ByteBuffer JavaDoc> copies = new ArrayList JavaDoc<ByteBuffer JavaDoc>();
374         for (ByteBuffer JavaDoc buffer : buffers) {
375             ByteBuffer JavaDoc copy = buffer.duplicate();
376             if ((size + copy.limit()) > maxOutSize) {
377                 copy.limit(maxOutSize - size);
378                 copies.add(copy);
379                 postfix = " [...output has been cut]";
380                 break;
381             } else {
382                 copies.add(copy);
383             }
384         }
385     
386         StringBuilder JavaDoc result = new StringBuilder JavaDoc();
387     
388     
389         for (ByteBuffer JavaDoc buffer : copies) {
390             result.append(toByteString(buffer));
391         }
392     
393         result.append(postfix);
394     
395         return result.toString();
396     }
397
398
399     /**
400      * convert the ByteBuffer into a hex or text string (deping on content)
401      *
402      * @param buffer the buffers to print
403      * @param maxOutSize the max size to print
404      * @param encoding the encoding to use
405      * @return the converted ByteBuffer
406      */

407     public static String JavaDoc toTextOrHexString(ByteBuffer JavaDoc buffer, String JavaDoc encoding, int maxOutSize) {
408         return toTextOrHexString(new ByteBuffer JavaDoc[] { buffer }, encoding, maxOutSize);
409     }
410     
411     
412     /**
413      * convert the ByteBuffer array into a hex or text string (deping on content)
414      *
415      * @param buffers the buffers to print
416      * @param maxOutSize the max size to print
417      * @param encoding the encoding to use
418      * @return the converted ByteBuffer
419      */

420     public static String JavaDoc toTextOrHexString(ByteBuffer JavaDoc[] buffers, String JavaDoc encoding, int maxOutSize) {
421         boolean hasNonPrintableChars = false;
422         
423         for (ByteBuffer JavaDoc buffer : buffers) {
424             ByteBuffer JavaDoc copy = buffer.duplicate();
425             while (copy.hasRemaining()) {
426                 int i = copy.get();
427                 if (i < 10) {
428                     hasNonPrintableChars = true;
429                 }
430             }
431         }
432         
433         if (hasNonPrintableChars) {
434             return toHexString(buffers, maxOutSize);
435         } else {
436             try {
437                 return toString(buffers, encoding, maxOutSize);
438             } catch (UnsupportedEncodingException JavaDoc use) {
439                 return toHexString(buffers, maxOutSize);
440             }
441         }
442     }
443     
444     
445     
446     public static String JavaDoc toTextAndHexString(ByteBuffer JavaDoc[] buffers, String JavaDoc encoding, int maxOutSize) {
447         StringBuilder JavaDoc sb = new StringBuilder JavaDoc();
448         sb.append(DataConverter.toHexString(buffers, 500));
449         sb.append("\n");
450         try {
451             sb.append("[txt:] " + toString(buffers, "US-ASCII", 500));
452         } catch (Exception JavaDoc ignore) {
453             sb.append("[txt:] ... content not printable ...");
454         }
455         return sb.toString();
456     }
457 }
458
Popular Tags