//
// JmsaObjectMessage.java - JMS Adapter ObjectMessage
//
// ObjectMessages can hold any Serializable java object.
// setObject(o) has to take a copy of o, not a reference to it.
// So we serialize it then and there.
// getObject() therefore has to deserialize this.
// As object (de)serialization problems can be difficult to diagnose, when
// we generate MessageFormatExceptions, we link to the underlying exception.
//

package nyangau.jmsadapter;

import java.io.*;
import javax.jms.*;

public class JmsaObjectMessage extends JmsaMessage implements ObjectMessage
  {
  protected byte[] b;

//...sgetObject:2:
public Serializable getObject()
  throws JMSException
  {
  if ( b == null )
    return null;
  ByteArrayInputStream bais = new ByteArrayInputStream(b);
  try
    {
    ObjectInputStream ois = new ObjectInputStream(bais);
    return (Serializable) ois.readObject();
    }
  catch ( IOException e )
    {
    MessageFormatException mfe = new MessageFormatException("io");
    mfe.setLinkedException(e);
    throw mfe;
    }
  catch ( ClassNotFoundException e )
    {
    MessageFormatException mfe = new MessageFormatException("class not found");
    mfe.setLinkedException(e);
    throw mfe;
    }
  }
//...e
//...ssetObject:2:
public void setObject(Serializable obj)
  throws JMSException
  {
  if ( bro )
    throw new MessageNotWriteableException("");
  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  try
    {
    ObjectOutputStream oos = new ObjectOutputStream(baos);
    oos.writeObject(obj);
    oos.flush();
    b = baos.toByteArray();
    }
  catch ( IOException e )
    {
    MessageFormatException mfe = new MessageFormatException("io");
    mfe.setLinkedException(e);
    throw mfe;
    }
  }
//...e

//...sclearBody:2:
public void clearBody()
  throws JMSException
  {
  b   = null;
  bro = false;
  }
//...e
//...sJmsaObjectMessage:2:
// Called by JmsaSession
public JmsaObjectMessage()
  {
  super();
  b = null;
  }

// Called by JmsaSession
public JmsaObjectMessage(Serializable object)
  throws JMSException
  {
  super();
  b = null;
  setObject(object); // can call this, body is not read-only
  }

// For newly received messages, or foreign outbound messages
public JmsaObjectMessage(ObjectMessage m)
  throws JMSException // caused by super(m), m.getObject()
  {
  super(m);
  Serializable obj = m.getObject();
  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  try
    {
    ObjectOutputStream oos = new ObjectOutputStream(baos);
    oos.writeObject(obj);
    oos.flush();
    b = baos.toByteArray();
    }
  catch ( IOException e )
    {
    MessageFormatException mfe = new MessageFormatException("io");
    mfe.setLinkedException(e);
    throw mfe;
    }
  }

// For converting between message formats
public JmsaObjectMessage(JmsaMessage m)
  {
  super(m);
  b = null;
  }
//...e
  }
