KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jboss > cache > marshall > MarshallUtil


1 /*
2  * JBoss, the OpenSource J2EE webOS
3  *
4  * Distributable under LGPL license.
5  * See terms of license at gnu.org.
6  */

7
8 package org.jboss.cache.marshall;
9
10 import org.jboss.util.stream.MarshalledValueInputStream;
11 import org.jboss.util.stream.MarshalledValueOutputStream;
12
13 import java.io.ByteArrayInputStream JavaDoc;
14 import java.io.ByteArrayOutputStream JavaDoc;
15 import java.io.InputStream JavaDoc;
16
17 /**
18  * Utility methods related to marshalling and unmarshalling objects.
19  *
20  * @author <a HREF="mailto://brian.stansberry@jboss.com">Brian Stansberry</a>
21  * @version $Revision$
22  */

23 public class MarshallUtil
24 {
25
26     /**
27      * Creates an object from a byte buffer using
28      * {@link MarshalledValueInputStream}.
29      *
30      * @param bytes serialized form of an object
31      * @return the object, or <code>null</code> if <code>bytes</code>
32      * is <code>null</code>
33      */

34     public static Object JavaDoc objectFromByteBuffer(byte[] bytes) throws Exception JavaDoc
35     {
36         if (bytes == null)
37         {
38             return null;
39         }
40
41         ByteArrayInputStream JavaDoc bais = new ByteArrayInputStream JavaDoc(bytes);
42         MarshalledValueInputStream input = new MarshalledValueInputStream(bais);
43         Object JavaDoc result = input.readObject();
44         input.close();
45         return result;
46     }
47
48     /**
49      * Creates an object from a byte buffer using
50      * {@link MarshalledValueInputStream}.
51      *
52      * @param bytes serialized form of an object
53      * @return the object, or <code>null</code> if <code>bytes</code>
54      * is <code>null</code>
55      */

56     public static Object JavaDoc objectFromByteBuffer(InputStream bytes) throws Exception JavaDoc
57     {
58         if (bytes == null)
59         {
60             return null;
61         }
62
63         MarshalledValueInputStream input = new MarshalledValueInputStream(bytes);
64         Object JavaDoc result = input.readObject();
65         input.close();
66         return result;
67     }
68
69     /**
70      * Serializes an object into a byte buffer using
71      * {@link org.jboss.util.stream.MarshalledValueOutputStream}.
72      *
73      * @param obj an object that implements Serializable or Externalizable
74      * @return serialized form of the object
75      */

76     public static byte[] objectToByteBuffer(Object JavaDoc obj) throws Exception JavaDoc
77     {
78         ByteArrayOutputStream JavaDoc baos = new ByteArrayOutputStream JavaDoc();
79         MarshalledValueOutputStream out = new MarshalledValueOutputStream(baos);
80         out.writeObject(obj);
81         out.close();
82         return baos.toByteArray();
83     }
84
85 }
86
Popular Tags