001 /**
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements. See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License. You may obtain a copy of the License at
008 *
009 * http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017 package org.apache.activemq.kaha;
018
019 import java.io.ByteArrayInputStream;
020 import java.io.ByteArrayOutputStream;
021 import java.io.DataInput;
022 import java.io.DataOutput;
023 import java.io.IOException;
024 import java.io.ObjectInputStream;
025 import java.io.ObjectOutputStream;
026
027 /**
028 * Implementation of a Marshaller for Objects
029 *
030 *
031 */
032 public class ObjectMarshaller implements Marshaller {
033
034 /**
035 * Write the payload of this entry to the RawContainer
036 *
037 * @param object
038 * @param dataOut
039 * @throws IOException
040 */
041 public void writePayload(Object object, DataOutput dataOut) throws IOException {
042 ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
043 ObjectOutputStream objectOut = new ObjectOutputStream(bytesOut);
044 objectOut.writeObject(object);
045 objectOut.close();
046 byte[] data = bytesOut.toByteArray();
047 dataOut.writeInt(data.length);
048 dataOut.write(data);
049 }
050
051 /**
052 * Read the entry from the RawContainer
053 *
054 * @param dataIn
055 * @return unmarshalled object
056 * @throws IOException
057 */
058 public Object readPayload(DataInput dataIn) throws IOException {
059 int size = dataIn.readInt();
060 byte[] data = new byte[size];
061 dataIn.readFully(data);
062 ByteArrayInputStream bytesIn = new ByteArrayInputStream(data);
063 ObjectInputStream objectIn = new ObjectInputStream(bytesIn);
064 try {
065 return objectIn.readObject();
066 } catch (ClassNotFoundException e) {
067 throw new IOException(e.getMessage());
068 }
069 }
070 }