/** 
 * 
 * Copyright 2004 Hiram Chirino
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); 
 * you may not use this file except in compliance with the License. 
 * You may obtain a copy of the License at 
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, 
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
 * See the License for the specific language governing permissions and 
 * limitations under the License. 
 * 
 **/
package org.codehaus.activemq.message;

import javax.jms.JMSException;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

/**
 * A receipt that also carries a reponse object.
 */
public class ResponseReceipt extends Receipt {

    private Serializable result;
    private byte[] resultBytes;

    /**
     * @see org.codehaus.activemq.message.Receipt#getPacketType()
     */
    public int getPacketType() {
        return RESPONSE_RECEIPT_INFO;
    }

    /**
     * @return Returns the result.
     */
    public Serializable getResult() throws JMSException {
        if (result == null) {
            if (resultBytes == null) {
                return null;
            }
            try {
                result = (Serializable) new ObjectInputStream(new ByteArrayInputStream(resultBytes)).readObject();
            }
            catch (Exception e) {
                throw ((JMSException) new JMSException("Invalid network mesage received.").initCause(e));
            }
        }
        return result;
    }

    /**
     * @param result The result to set.
     */
    public void setResult(Serializable result) {
        this.result = result;
        this.resultBytes = null;
    }

    /**
     * @param data
     */
    public void setResultBytes(byte[] resultBytes) {
        this.resultBytes = resultBytes;
        this.result = null;
    }

    /**
     * @return Returns the resultBytes.
     */
    public byte[] getResultBytes() throws IOException {
        if (resultBytes == null) {
            if (result == null) {
                return null;
            }
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ObjectOutputStream os = new ObjectOutputStream(baos);
            os.writeObject(result);
            os.close();
            resultBytes = baos.toByteArray();
        }
        return resultBytes;
    }

    public String toString() {
        return super.toString() + " ResponseReceipt{ " +
                "result = " + result +
                ", resultBytes = " + resultBytes +
                " }";
    }
}
