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.wireformat;
018
019import java.io.DataInput;
020import java.io.DataInputStream;
021import java.io.DataOutput;
022import java.io.DataOutputStream;
023import java.io.IOException;
024import java.io.InputStream;
025import java.io.ObjectOutputStream;
026import java.io.OutputStream;
027
028import org.apache.activemq.util.ByteArrayInputStream;
029import org.apache.activemq.util.ByteArrayOutputStream;
030import org.apache.activemq.util.ByteSequence;
031import org.apache.activemq.util.ClassLoadingAwareObjectInputStream;
032
033/**
034 * A simple implementation which uses Object Stream serialization.
035 * 
036 * 
037 */
038public class ObjectStreamWireFormat implements WireFormat {
039
040    public ByteSequence marshal(Object command) throws IOException {
041        ByteArrayOutputStream baos = new ByteArrayOutputStream();
042        DataOutputStream ds = new DataOutputStream(baos);
043        marshal(command, ds);
044        ds.close();
045        return baos.toByteSequence();
046    }
047
048    public Object unmarshal(ByteSequence packet) throws IOException {
049        return unmarshal(new DataInputStream(new ByteArrayInputStream(packet)));
050    }
051
052    public void marshal(Object command, DataOutput ds) throws IOException {
053        ObjectOutputStream out = new ObjectOutputStream((OutputStream)ds);
054        out.writeObject(command);
055        out.flush();
056        out.reset();
057    }
058
059    public Object unmarshal(DataInput ds) throws IOException {
060        try {
061            ClassLoadingAwareObjectInputStream in = new ClassLoadingAwareObjectInputStream((InputStream)ds);
062            Object command;
063            command = in.readObject();
064            in.close();
065            return command;
066        } catch (ClassNotFoundException e) {
067            throw (IOException)new IOException("unmarshal failed: " + e).initCause(e);
068        }
069    }
070
071    public void setVersion(int version) {
072    }
073
074    public int getVersion() {
075        return 0;
076    }
077
078}