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.fusesource.hawtbuf.codec;
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    public class ObjectCodec<T> extends VariableCodec<T> {
032    
033        public void encode(Object object, DataOutput dataOut) throws IOException {
034            ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
035            ObjectOutputStream objectOut = new ObjectOutputStream(bytesOut);
036            objectOut.writeObject(object);
037            objectOut.close();
038            byte[] data = bytesOut.toByteArray();
039            dataOut.writeInt(data.length);
040            dataOut.write(data);
041        }
042    
043        public T decode(DataInput dataIn) throws IOException {
044            int size = dataIn.readInt();
045            byte[] data = new byte[size];
046            dataIn.readFully(data);
047            ByteArrayInputStream bytesIn = new ByteArrayInputStream(data);
048            ObjectInputStream objectIn = new ObjectInputStream(bytesIn);
049            try {
050                return (T) objectIn.readObject();
051            } catch (ClassNotFoundException e) {
052                throw createIOException(e.getMessage(), e);
053            }
054        }
055    
056        private static IOException createIOException(String message, Throwable cause) {
057            IOException answer = new IOException(message);
058            answer.initCause(cause);
059            return answer;
060        }
061        
062    }