1 /*2 * JBoss, the OpenSource J2EE webOS3 *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 ;14 import java.io.ByteArrayOutputStream ;15 import java.io.InputStream ;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 MarshallUtil24 {25 26 /**27 * Creates an object from a byte buffer using28 * {@link MarshalledValueInputStream}.29 *30 * @param bytes serialized form of an object31 * @return the object, or <code>null</code> if <code>bytes</code>32 * is <code>null</code>33 */34 public static Object objectFromByteBuffer(byte[] bytes) throws Exception 35 {36 if (bytes == null)37 {38 return null;39 }40 41 ByteArrayInputStream bais = new ByteArrayInputStream (bytes);42 MarshalledValueInputStream input = new MarshalledValueInputStream(bais);43 Object result = input.readObject();44 input.close();45 return result;46 }47 48 /**49 * Creates an object from a byte buffer using50 * {@link MarshalledValueInputStream}.51 *52 * @param bytes serialized form of an object53 * @return the object, or <code>null</code> if <code>bytes</code>54 * is <code>null</code>55 */56 public static Object objectFromByteBuffer(InputStream bytes) throws Exception 57 {58 if (bytes == null)59 {60 return null;61 }62 63 MarshalledValueInputStream input = new MarshalledValueInputStream(bytes);64 Object result = input.readObject();65 input.close();66 return result;67 }68 69 /**70 * Serializes an object into a byte buffer using71 * {@link org.jboss.util.stream.MarshalledValueOutputStream}.72 *73 * @param obj an object that implements Serializable or Externalizable74 * @return serialized form of the object75 */76 public static byte[] objectToByteBuffer(Object obj) throws Exception 77 {78 ByteArrayOutputStream baos = new ByteArrayOutputStream ();79 MarshalledValueOutputStream out = new MarshalledValueOutputStream(baos);80 out.writeObject(obj);81 out.close();82 return baos.toByteArray();83 }84 85 }86