KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > sapia > ubik > net > udp > Util


1 package org.sapia.ubik.net.udp;
2
3 import java.io.*;
4
5 import java.net.DatagramPacket JavaDoc;
6
7
8 /**
9  * @author Yanick Duchesne
10  * <dl>
11  * <dt><b>Copyright:</b><dd>Copyright &#169; 2002-2003 <a HREF="http://www.sapia-oss.org">Sapia Open Source Software</a>. All Rights Reserved.</dd></dt>
12  * <dt><b>License:</b><dd>Read the license.txt file of the jar or visit the
13  * <a HREF="http://www.sapia-oss.org/license.html">license page</a> at the Sapia OSS web site</dd></dt>
14  * </dl>
15  */

16 public class Util {
17   /**
18    * Constructor for Util.
19    */

20   public Util() {
21     super();
22   }
23
24   public static Object JavaDoc fromDatagram(DatagramPacket JavaDoc pack)
25     throws IOException, ClassNotFoundException JavaDoc {
26     ByteArrayInputStream bis = new ByteArrayInputStream(pack.getData(),
27         pack.getOffset(), pack.getLength());
28     ObjectInputStream ois = null;
29
30     try {
31       ois = new ObjectInputStream(bis);
32
33       Object JavaDoc o = ois.readObject();
34
35       return o;
36     } finally {
37       if (ois != null) {
38         ois.close();
39       }
40     }
41   }
42
43   public static byte[] toBytes(Object JavaDoc o, int bufsize, ObjectStreamFactory fac)
44     throws IOException {
45     ByteArrayOutputStream bos = new ByteArrayOutputStream(bufsize);
46     ObjectOutputStream ous = fac.toOutput(bos);
47
48     ous.writeObject(o);
49     ous.flush();
50     ous.close();
51
52     return bos.toByteArray();
53   }
54
55   public static int getSizeInBytes(Object JavaDoc o) throws IOException {
56     return toBytes(o, 1000, ObjectStreamFactory.DEFAULT_FACTORY).length;
57   }
58 }
59
Popular Tags