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 */
017package org.apache.activemq.store.kahadb.disk.util;
018
019import java.io.ByteArrayInputStream;
020import java.io.ByteArrayOutputStream;
021import java.io.DataInput;
022import java.io.DataOutput;
023import java.io.IOException;
024import java.io.ObjectInputStream;
025import java.io.ObjectOutputStream;
026
027/**
028 * Implementation of a Marshaller for Objects
029 * 
030 * 
031 */
032public class ObjectMarshaller extends VariableMarshaller<Object> {
033
034    public void writePayload(Object object, DataOutput dataOut) throws IOException {
035        ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
036        ObjectOutputStream objectOut = new ObjectOutputStream(bytesOut);
037        objectOut.writeObject(object);
038        objectOut.close();
039        byte[] data = bytesOut.toByteArray();
040        dataOut.writeInt(data.length);
041        dataOut.write(data);
042    }
043
044    public Object readPayload(DataInput dataIn) throws IOException {
045        int size = dataIn.readInt();
046        byte[] data = new byte[size];
047        dataIn.readFully(data);
048        ByteArrayInputStream bytesIn = new ByteArrayInputStream(data);
049        ObjectInputStream objectIn = new ObjectInputStream(bytesIn);
050        try {
051            return objectIn.readObject();
052        } catch (ClassNotFoundException e) {
053            throw new IOException(e.getMessage());
054        }
055    }
056    
057}