KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > sapia > ubik > mcast > Util


1 package org.sapia.ubik.mcast;
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   public static Object JavaDoc fromDatagram(DatagramPacket JavaDoc pack)
18     throws IOException, ClassNotFoundException JavaDoc {
19     ByteArrayInputStream bis = new ByteArrayInputStream(pack.getData(),
20         pack.getOffset(), pack.getLength());
21     ObjectInputStream ois = null;
22     
23
24     try {
25       ois = new ObjectInputStream(bis);
26
27       Object JavaDoc o = ois.readObject();
28
29       return o;
30     } finally {
31       if (ois != null) {
32         ois.close();
33       }
34     }
35   }
36
37   public static byte[] toBytes(Object JavaDoc o, int bufsize) throws IOException {
38     ByteArrayOutputStream bos = new ByteArrayOutputStream(bufsize);
39     ObjectOutputStream ous = new ObjectOutputStream(bos);
40
41     ous.writeObject(o);
42     ous.flush();
43     ous.close();
44
45     return bos.toByteArray();
46   }
47
48   public static int getSizeInBytes(Object JavaDoc o) throws IOException {
49     return toBytes(o, 1000).length;
50   }
51 }
52
Popular Tags