001 package com.mockrunner.mock.jms;
002
003 import java.io.ByteArrayInputStream;
004 import java.io.ByteArrayOutputStream;
005 import java.io.ObjectInputStream;
006 import java.io.ObjectOutputStream;
007 import java.io.Serializable;
008
009 import javax.jms.JMSException;
010 import javax.jms.MessageNotWriteableException;
011 import javax.jms.ObjectMessage;
012
013 import com.mockrunner.base.NestedApplicationException;
014
015 /**
016 * Mock implementation of JMS <code>ObjectMessage</code>.
017 */
018 public class MockObjectMessage extends MockMessage implements ObjectMessage
019 {
020 private Serializable object;
021
022 public MockObjectMessage()
023 {
024 this(null);
025 }
026
027 public MockObjectMessage(Serializable object)
028 {
029 this.object = object;
030 }
031
032 public void setObject(Serializable object) throws JMSException
033 {
034 if(!isInWriteMode())
035 {
036 throw new MessageNotWriteableException("Message is in read mode");
037 }
038 this.object = object;
039 }
040
041 public Serializable getObject() throws JMSException
042 {
043 return object;
044 }
045
046 public void clearBody() throws JMSException
047 {
048 super.clearBody();
049 object = null;
050 }
051
052 /**
053 * Calls the <code>equals</code> method of the underlying
054 * object. If both objects are <code>null</code>, this
055 * method returns <code>true</code>.
056 */
057 public boolean equals(Object otherObject)
058 {
059 if(null == otherObject) return false;
060 if(!(otherObject instanceof MockObjectMessage)) return false;
061 MockObjectMessage otherMessage = (MockObjectMessage)otherObject;
062 if(null == object && null == otherMessage.object) return true;
063 return object.equals(otherMessage.object);
064 }
065
066 public int hashCode()
067 {
068 if(null == object) return 0;
069 return object.hashCode();
070 }
071
072 public Object clone()
073 {
074 MockObjectMessage message = (MockObjectMessage)super.clone();
075 try
076 {
077 ByteArrayOutputStream byteOutStream = new ByteArrayOutputStream();
078 ObjectOutputStream objectOutStream = new ObjectOutputStream(byteOutStream);
079 objectOutStream.writeObject(object);
080 objectOutStream.flush();
081 ByteArrayInputStream byteInStream = new ByteArrayInputStream(byteOutStream.toByteArray());
082 ObjectInputStream objectInStream = new ObjectInputStream(byteInStream);
083 message.object = (Serializable)objectInStream.readObject();
084 return message;
085 }
086 catch(Exception exc)
087 {
088 throw new NestedApplicationException(exc);
089 }
090 }
091
092 public String toString()
093 {
094 return this.getClass().getName() + ": " + object;
095 }
096 }