/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You 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.apache.activeblaze;

import org.apache.activeblaze.wire.*;

import java.io.IOException;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * A <CODE>BlazeMessage</CODE> object is used to send a set of name-value pairs.
 * The names are <CODE>String</CODE> objects, and the values are primitive data
 * types in the Java programming language. The names must have a value that is
 * not null, and not an empty string. The entries can be accessed sequentially
 * or randomly by name. The order of the entries is undefined.
 * <CODE>BlazeMessage</CODE> inherits from the <CODE>Message</CODE> interface
 * and adds a message body that contains a Map.
 * <p/>
 * The primitive types can be read or written explicitly using methods for each
 * type. They may also be read or written generically as objects. For instance,
 * a call to <CODE>BlazeMessage.setInt("foo", 6)</CODE> is equivalent to
 * <CODE> BlazeMessage.setObject("foo", new Integer(6))</CODE>. Both forms are
 * provided, because the explicit form is convenient for static programming, and
 * the object form is needed when types are not known at compile time.
 * <p/>
 * <p/>
 * <CODE>BlazeMessage</CODE> objects support the following conversion table. The
 * marked cases must be supported. The unmarked cases must throw a
 * <CODE>JMSException</CODE>. The <CODE>String</CODE> -to-primitive conversions
 * may throw a runtime exception if the primitive's <CODE>valueOf()</CODE>
 * method does not accept it as a valid <CODE> String</CODE> representation of
 * the primitive.
 * <p/>
 * A value written as the row type can be read as the column type.
 * <p/>
 * <p/>
 * <PRE>
 * | | boolean byte short char int long float double String byte[] |----------------------------------------------------------------------
 * |boolean | X X |byte | X X X X X |short | X X X X |char | X X |int | X X X |long | X X |float | X X X |double | X X
 * |String | X X X X X X X X |byte[] | X |----------------------------------------------------------------------
 * &lt;p/&gt;
 * </PRE>
 * <p/>
 * <p/>
 * <p/>
 * Attempting to read a null value as a primitive type must be treated as
 * calling the primitive's corresponding <code>valueOf(String)</code> conversion
 * method with a null value. Since <code>char</code> does not support a
 * <code>String</code> conversion, attempting to read a null value as a
 * <code>char</code> must throw a <code>NullPointerException</code>.
 */
public class BlazeMessage extends Packet implements Map<String, Object> {
    private static final String DEFAULT_TEXT_PAYLOAD = "DEFAULT_TEXT_PAYLOAD";
    private static final String DEFAULT_BYTES_PAYLOAD = "DEFAULT_BYTES_PAYLOAD";
    private static final String DEFAULT_OBJECT_PAYLOAD = "DEFAULT_OBJECT_PAYLOAD";
    private Map<String, Object> map = new ConcurrentHashMap<String, Object>();
    private Destination destination;
    private Destination replyTo;
    private String messageType;
    private long timeStamp;
    private long expiration;
    private int redeliveryCounter;
    private int priority;
    private boolean persistent;
    private int type;
    private Buffer content;
    private transient boolean loaded;

    /**
     * Default Constructor
     */
    public BlazeMessage() {
    }

    /**
     * Constructor - Utility to construct a message with a text
     * <Code>String</Code> payload
     */
    public BlazeMessage(String text) {
        setStringValue(DEFAULT_TEXT_PAYLOAD, text);
    }

    /**
     * Constructor - Utility to construct a message with a byte[] array payload
     */
    public BlazeMessage(byte[] data) {
        setBytesValue(DEFAULT_BYTES_PAYLOAD, data);
    }

    /**
     * Constructor - Utility to construct a message with an object payload
     */
    public BlazeMessage(Object data) {
        setObject(data);
    }

    /**
     * Get the packetType
     *
     * @return the packetType
     */
    public int getPacketType() {
        return PacketType.MESSAGE.getNumber();
    }

    /**
     * Utility method for setting a default <Code>String</Code> payload
     */
    public void setText(String text) {
        setStringValue(DEFAULT_TEXT_PAYLOAD, text);
    }

    /**
     * Utility method used for when a BlazeMessage is only carrying a byte[]
     * array
     *
     * @return text the default text
     */
    public String getText() throws Exception {
        return getStringValue(DEFAULT_TEXT_PAYLOAD);
    }

    /**
     * Utility method for setting a default <Code>byte[]</Code> payload
     */
    public void setBytes(byte[] payload) {
        setBytesValue(DEFAULT_BYTES_PAYLOAD, payload);
    }

    /**
     * Utility method used for when a BlazeMessage is only carrying an Object
     *
     * @return text the default text
     */
    public Object getObject() throws Exception {
        Buffer buffer = getBufferValue(DEFAULT_OBJECT_PAYLOAD);
        return IOUtils.getObject(buffer);
    }

    /**
     * Utility method for setting a default <Code>Object</Code> payload
     */
    public void setObject(Object payload) {
        try {
            put(DEFAULT_OBJECT_PAYLOAD, IOUtils.getBuffer(payload));
        } catch (Exception e) {
            throw new BlazeRuntimeException(e);
        }
    }

    /**
     * Utility method used for when a BlazeMessage is only carrying a String
     *
     * @return text the default text
     */
    public byte[] getBytes() throws Exception {
        return getBytesValue(DEFAULT_BYTES_PAYLOAD);
    }

    /**
     * @return the destination
     */
    public Destination getDestination() {
        initializeReading();
        return this.destination;
    }

    /**
     * @param destination the destination to set
     */
    public void setDestination(Destination destination) {
        this.destination = destination;
    }

    /**
     * The id of the channel that sent the message
     *
     * @return the fromId
     */
    public String getFromId() {
        return getProducerId();
    }

    /**
     * @return the messageId
     */
    public String getMessageId() {
        return getId();
    }

    /**
     * @return the timeStamp
     */
    public long getTimeStamp() {
        initializeReading();
        return this.timeStamp;
    }

    /**
     * @param timeStamp the timeStamp to set
     */
    public void setTimeStamp(long timeStamp) {
        this.timeStamp = timeStamp;
    }

    /**
     * @return the replyTo
     */
    public Destination getReplyTo() {
        initializeReading();
        return this.replyTo;
    }

    /**
     * @param replyTo the replyTo to set
     */
    public void setReplyTo(Destination replyTo) {
        this.replyTo = replyTo;
    }

    /**
     * @return the expiration
     */
    public long getExpiration() {
        initializeReading();
        return this.expiration;
    }

    /**
     * @param expiration the expiration to set
     */
    public void setExpiration(long expiration) {
        this.expiration = expiration;
    }

    /**
     * @return the redeliveryCounter
     */
    public int getRedeliveryCounter() {
        initializeReading();
        return this.redeliveryCounter;
    }

    /**
     * @param redeliveryCounter the redeliveryCounter to set
     */
    public void setRedeliveryCounter(int redeliveryCounter) {
        this.redeliveryCounter = redeliveryCounter;
    }

    /**
     * @return the priority
     */
    public int getPriority() {
        initializeReading();
        return this.priority;
    }

    /**
     * @param priority the priority to set
     */
    public void setPriority(int priority) {
        this.priority = priority;
    }

    /**
     * @return the persistent
     */
    public boolean isPersistent() {
        initializeReading();
        return this.persistent;
    }

    /**
     * @param persistent the persistent to set
     */
    public void setPersistent(boolean persistent) {
        this.persistent = persistent;
    }

    /**
     * @return the type
     */
    public String getMessageType() {
        initializeReading();
        return this.messageType;
    }

    /**
     * @param type the type to set
     */
    public void setMessageType(String type) {
        this.messageType = type;
    }

    /**
     * Get the type
     *
     * @return the type
     */
    public int getType() {
        return this.type;
    }

    public void setType(int type) {
        this.type = type;
    }

    /**
     * @return a copy of this message
     */
    public BlazeMessage clone() {
        BlazeMessage copy = new BlazeMessage();
        try {
            copy(copy);
        } catch (Exception e) {
            throw new BlazeRuntimeException(e);
        }
        return copy;
    }

    /**
     * clear the contents of this message
     */
    public void clear() {
        this.map.clear();
        this.content = null;
    }

    /**
     * Returns the <CODE>boolean</CODE> value with the specified name.
     *
     * @param name the name of the <CODE>boolean</CODE>
     * @return the <CODE>boolean</CODE> value with the specified name
     * @throws BlazeMessageFormatException if this type conversion is invalid.
     */
    public boolean getBooleanValue(String name) throws BlazeMessageFormatException {
        initializeReading();
        Object value = this.map.get(name);
        if (value == null) {
            return false;
        }
        if (value instanceof Boolean) {
            return ((Boolean) value).booleanValue();
        }
        if (value instanceof String) {
            return Boolean.valueOf(value.toString()).booleanValue();
        }
        throw new BlazeMessageFormatException(" cannot read a boolean from " + value.getClass().getName());
    }

    /**
     * Returns the <CODE>byte</CODE> value with the specified name.
     *
     * @param name the name of the <CODE>byte</CODE>
     * @return the <CODE>byte</CODE> value with the specified name
     * @throws BlazeMessageFormatException if this type conversion is invalid.
     */
    public byte getByteValue(String name) throws BlazeMessageFormatException {
        initializeReading();
        Object value = this.map.get(name);
        if (value == null) {
            return 0;
        }
        if (value instanceof Byte) {
            return ((Byte) value).byteValue();
        }
        if (value instanceof String) {
            return Byte.valueOf(value.toString()).byteValue();
        }
        throw new BlazeMessageFormatException(" cannot read a byte from " + value.getClass().getName());
    }

    /**
     * Returns the <CODE>short</CODE> value with the specified name.
     *
     * @param name the name of the <CODE>short</CODE>
     * @return the <CODE>short</CODE> value with the specified name
     * @throws BlazeMessageFormatException if this type conversion is invalid.
     */
    public short getShortValue(String name) throws BlazeMessageFormatException {
        initializeReading();
        Object value = this.map.get(name);
        if (value == null) {
            return 0;
        }
        if (value instanceof Short) {
            return ((Short) value).shortValue();
        }
        if (value instanceof Byte) {
            return ((Byte) value).shortValue();
        }
        if (value instanceof String) {
            return Short.valueOf(value.toString()).shortValue();
        }
        throw new BlazeMessageFormatException(" cannot read a short from " + value.getClass().getName());
    }

    /**
     * Returns the Unicode character value with the specified name.
     *
     * @param name the name of the Unicode character
     * @return the Unicode character value with the specified name
     * @throws BlazeMessageFormatException if this type conversion is invalid.
     */
    public char getCharValue(String name) throws BlazeMessageFormatException {
        initializeReading();
        Object value = this.map.get(name);
        if (value == null) {
            throw new NullPointerException();
        }
        if (value instanceof Character) {
            return ((Character) value).charValue();
        }
        throw new BlazeMessageFormatException(" cannot read a short from " + value.getClass().getName());
    }

    /**
     * Returns the <CODE>int</CODE> value with the specified name.
     *
     * @param name the name of the <CODE>int</CODE>
     * @return the <CODE>int</CODE> value with the specified name
     * @throws BlazeMessageFormatException if this type conversion is invalid.
     */
    public int getIntValue(String name) throws BlazeMessageFormatException {
        initializeReading();
        Object value = this.map.get(name);
        if (value == null) {
            return 0;
        }
        if (value instanceof Integer) {
            return ((Integer) value).intValue();
        }
        if (value instanceof Short) {
            return ((Short) value).intValue();
        }
        if (value instanceof Byte) {
            return ((Byte) value).intValue();
        }
        if (value instanceof String) {
            return Integer.valueOf(value.toString()).intValue();
        }
        throw new BlazeMessageFormatException(" cannot read an int from " + value.getClass().getName());
    }

    /**
     * Returns the <CODE>long</CODE> value with the specified name.
     *
     * @param name the name of the <CODE>long</CODE>
     * @return the <CODE>long</CODE> value with the specified name
     * @throws BlazeMessageFormatException if this type conversion is invalid.
     */
    public long getLongValue(String name) throws BlazeMessageFormatException {
        initializeReading();
        Object value = this.map.get(name);
        if (value == null) {
            return 0;
        }
        if (value instanceof Long) {
            return ((Long) value).longValue();
        }
        if (value instanceof Integer) {
            return ((Integer) value).longValue();
        }
        if (value instanceof Short) {
            return ((Short) value).longValue();
        }
        if (value instanceof Byte) {
            return ((Byte) value).longValue();
        }
        if (value instanceof String) {
            return Long.valueOf(value.toString()).longValue();
        }
        throw new BlazeMessageFormatException(" cannot read a long from " + value.getClass().getName());
    }

    /**
     * Returns the <CODE>float</CODE> value with the specified name.
     *
     * @param name the name of the <CODE>float</CODE>
     * @return the <CODE>float</CODE> value with the specified name
     * @throws BlazeMessageFormatException if this type conversion is invalid.
     */
    public float getFloatValue(String name) throws BlazeMessageFormatException {
        initializeReading();
        Object value = this.map.get(name);
        if (value == null) {
            return 0;
        }
        if (value instanceof Float) {
            return ((Float) value).floatValue();
        }
        if (value instanceof String) {
            return Float.valueOf(value.toString()).floatValue();
        }
        throw new BlazeMessageFormatException(" cannot read a float from " + value.getClass().getName());
    }

    /**
     * Returns the <CODE>double</CODE> value with the specified name.
     *
     * @param name the name of the <CODE>double</CODE>
     * @return the <CODE>double</CODE> value with the specified name
     * @throws BlazeMessageFormatException if this type conversion is invalid.
     */
    public double getDoubleValue(String name) throws BlazeMessageFormatException {
        initializeReading();
        Object value = this.map.get(name);
        if (value == null) {
            return 0;
        }
        if (value instanceof Double) {
            return ((Double) value).doubleValue();
        }
        if (value instanceof Float) {
            return ((Float) value).floatValue();
        }
        if (value instanceof String) {
            return Float.valueOf(value.toString()).floatValue();
        }
        throw new BlazeMessageFormatException(" cannot read a double from " + value.getClass().getName());
    }

    /**
     * Returns the <CODE>String</CODE> value with the specified name.
     *
     * @param name the name of the <CODE>String</CODE>
     * @return the <CODE>String</CODE> value with the specified name; if there
     *         is no item by this name, a null value is returned
     * @throws BlazeMessageFormatException if this type conversion is invalid.
     */
    public String getStringValue(String name) throws BlazeMessageFormatException {
        initializeReading();
        Object value = this.map.get(name);
        if (value == null) {
            return null;
        }
        if (value instanceof byte[]) {
            throw new BlazeMessageFormatException("Use getBytes to read a byte array");
        }
        return value.toString();
    }

    /**
     * Returns the byte array value with the specified name.
     *
     * @param name the name of the byte array
     * @return the byte array value with the specified name; if there is no item
     *         by this name, a null value is returned.
     * @throws BlazeMessageFormatException if this type conversion is invalid.
     */
    public byte[] getBytesValue(String name) throws BlazeMessageFormatException {
        initializeReading();
        Object value = this.map.get(name);
        if (value instanceof byte[]) {
            return (byte[]) value;
        }
        throw new BlazeMessageFormatException(" cannot read a byte[] from " + value.getClass().getName());
    }

    /**
     * Returns a Buffer with the specified name.
     *
     * @param name the name of the byte array
     * @return the byte array value with the specified name; if there is no item
     *         by this name, a null value is returned.
     * @throws BlazeMessageFormatException if this type conversion is invalid.
     */
    public Buffer getBufferValue(String name) throws BlazeMessageFormatException {
        initializeReading();
        Object value = this.map.get(name);
        if (value instanceof Buffer) {
            return (Buffer) value;
        }
        throw new BlazeMessageFormatException(" cannot read a Buffer from " + value.getClass().getName());
    }

    /**
     * Returns the value of the object with the specified name.
     * <p/>
     * This method can be used to return, in objectified format, an object in
     * the Java programming language ("Java object") that had been stored in the
     * Map with the equivalent <CODE>setObject</CODE> method call, or its
     * equivalent primitive <CODE>set <I>type </I></CODE> method.
     * <p/>
     * Note that byte values are returned as <CODE>byte[]</CODE>, not
     * <CODE>Byte[]</CODE>.
     *
     * @param name the name of the Java object
     * @return a copy of the Java object value with the specified name, in
     *         objectified format (for example, if the object was set as an
     *         <CODE>int</CODE>, an <CODE>Integer</CODE> is returned); if there
     *         is no item by this name, a null value is returned
     */
    public Object getObjectValue(String name) {
        initializeReading();
        return this.map.get(name);
    }

    /**
     * Returns an <CODE>Enumeration</CODE> of all the names in the
     * <CODE>BlazeMessage</CODE> object.
     *
     * @return an enumeration of all the names in this <CODE>BlazeMessage</CODE>
     */
    public Enumeration<String> getNames() {
        initializeReading();
        return Collections.enumeration(this.map.keySet());
    }

    /**
     * put a key,value pair into the message
     *
     * @param value must be a supported primitive, or map of supported primitives
     * @return the previous value associated with the key
     */
    public Object put(String name, Object value) {
        initializeWriting();
        if (name == null) {
            throw new IllegalArgumentException("The name of the property cannot be null.");
        }
        if (name.length() == 0) {
            throw new IllegalArgumentException("The name of the property cannot be an emprty string.");
        }
        checkValidObject(value);
        return this.map.put(name, value);
    }

    /**
     * Sets a <CODE>boolean</CODE> value with the specified name into the Map.
     *
     * @param name  the name of the <CODE>boolean</CODE>
     * @param value the <CODE>boolean</CODE> value to set in the Map
     */
    public void setBooleanValue(String name, boolean value) {
        initializeWriting();
        put(name, value ? Boolean.TRUE : Boolean.FALSE);
    }

    /**
     * Sets a <CODE>byte</CODE> value with the specified name into the Map.
     *
     * @param name  the name of the <CODE>byte</CODE>
     * @param value the <CODE>byte</CODE> value to set in the Map
     */
    public void setByteValue(String name, byte value) {
        initializeWriting();
        put(name, Byte.valueOf(value));
    }

    /**
     * Sets a <CODE>short</CODE> value with the specified name into the Map.
     *
     * @param name  the name of the <CODE>short</CODE>
     * @param value the <CODE>short</CODE> value to set in the Map
     */
    public void setShortValue(String name, short value) {
        initializeWriting();
        put(name, Short.valueOf(value));
    }

    /**
     * Sets a Unicode character value with the specified name into the Map.
     *
     * @param name  the name of the Unicode character
     * @param value the Unicode character value to set in the Map
     */
    public void setCharValue(String name, char value) {
        initializeWriting();
        put(name, Character.valueOf(value));
    }

    /**
     * Sets an <CODE>int</CODE> value with the specified name into the Map.
     *
     * @param name  the name of the <CODE>int</CODE>
     * @param value the <CODE>int</CODE> value to set in the Map
     */
    public void setIntValue(String name, int value) {
        initializeWriting();
        put(name, Integer.valueOf(value));
    }

    /**
     * Sets a <CODE>long</CODE> value with the specified name into the Map.
     *
     * @param name  the name of the <CODE>long</CODE>
     * @param value the <CODE>long</CODE> value to set in the Map
     */
    public void setLongValue(String name, long value) {
        initializeWriting();
        put(name, Long.valueOf(value));
    }

    /**
     * Sets a <CODE>float</CODE> value with the specified name into the Map.
     *
     * @param name  the name of the <CODE>float</CODE>
     * @param value the <CODE>float</CODE> value to set in the Map
     */
    public void setFloatValue(String name, float value) {
        initializeWriting();
        put(name, new Float(value));
    }

    /**
     * Sets a <CODE>double</CODE> value with the specified name into the Map.
     *
     * @param name  the name of the <CODE>double</CODE>
     * @param value the <CODE>double</CODE> value to set in the Map
     */
    public void setDoubleValue(String name, double value) {
        initializeWriting();
        put(name, new Double(value));
    }

    /**
     * Sets a <CODE>String</CODE> value with the specified name into the Map.
     *
     * @param name  the name of the <CODE>String</CODE>
     * @param value the <CODE>String</CODE> value to set in the Map
     */
    public void setStringValue(String name, String value) {
        initializeWriting();
        put(name, value);
    }

    /**
     * Sets a byte array value with the specified name into the Map.
     *
     * @param name  the name of the byte array
     * @param value the byte array value to set in the Map; the array is copied so
     *              that the value for <CODE>name </CODE> will not be altered by
     *              future modifications
     * @throws NullPointerException if the name is null, or if the name is an empty string.
     */
    public void setBytesValue(String name, byte[] value) {
        initializeWriting();
        if (value != null) {
            put(name, value);
        } else {
            this.map.remove(name);
        }
    }

    /**
     * Sets a Buffer value with the specified name into the Map.
     *
     * @param name  the name of the byte array
     * @param value the Buffer value to set in the Map
     * @throws NullPointerException if the name is null, or if the name is an empty string.
     */
    public void setBufferValue(String name, Buffer value) {
        initializeWriting();
        if (value != null) {
            put(name, value);
        } else {
            this.map.remove(name);
        }
    }

    /**
     * Sets a portion of the byte array value with the specified name into the
     * Map.
     *
     * @param name   the name of the byte array
     * @param value  the byte array value to set in the Map
     * @param offset the initial offset within the byte array
     * @param length the number of bytes to use
     */
    public void setBytesValue(String name, byte[] value, int offset, int length) {
        initializeWriting();
        byte[] data = new byte[length];
        System.arraycopy(value, offset, data, 0, length);
        put(name, data);
    }

    /**
     * Find out if the message contains a key This isn't recursive
     *
     * @return true if the message contains the key
     */
    public boolean containsKey(Object key) {
        initializeReading();
        return this.map.containsKey(key.toString());
    }

    /**
     * Find out if the message contains a value
     *
     * @return true if the value exists
     */
    public boolean containsValue(Object value) {
        initializeReading();
        return this.map.containsValue(value);
    }

    /**
     * @return a set of Map.Entry values
     */
    public Set<java.util.Map.Entry<String, Object>> entrySet() {
        initializeReading();
        return this.map.entrySet();
    }

    /**
     * Retrieve the object associated with the key
     *
     * @return the object
     */
    public Object get(Object key) {
        initializeReading();
        return getObjectValue(key.toString());
    }

    /**
     * @return true if the message is empty
     */
    public boolean isEmpty() {
        initializeReading();
        return this.map.isEmpty();
    }

    /**
     * @return a Set of all the keys
     */
    public Set<String> keySet() {
        initializeReading();
        return this.map.keySet();
    }

    /**
     * Add all entries in a Map to the message
     *
     * @param t the map
     */
    public void putAll(Map<? extends String, ? extends Object> t) {
        for (Map.Entry<? extends String, ? extends Object> entry : t.entrySet()) {
            put(entry.getKey(), entry.getValue());
        }
    }

    /**
     * Remove a key/value pair from the message
     *
     * @return the value removed or null
     */
    public Object remove(Object key) {
        setContent(null);
        return this.map.remove(key.toString());
    }

    /**
     * @return the number of entries in the message
     */
    public int size() {
        initializeReading();
        return this.map.size();
    }

    /**
     * @return a Collection of the values in the message
     */
    public Collection<Object> values() {
        initializeReading();
        return this.map.values();
    }

    /**
     * check if a named value exists in the message
     *
     * @return true if value exits
     */
    public boolean valueExists(String name) {
        return this.map.containsKey(name);
    }

    protected void checkValidObject(Object value) throws IllegalArgumentException {
        boolean valid = value instanceof Boolean || value instanceof Byte || value instanceof Short
                || value instanceof Integer || value instanceof Long;
        valid = valid || value instanceof Float || value instanceof Double || value instanceof Character
                || value instanceof String || value == null || value instanceof byte[];
        if (value instanceof Map) {
            Map<?, ?> map = (Map<?, ?>) value;
            for (Object v : map.values()) {
                checkValidObject(v);
            }
            valid = true;
        }
        if (!valid) {
            throw new IllegalArgumentException("Not a valid message value: " + value);
        }
    }

    /**
     * @return pretty print
     * @see java.lang.Object#toString()
     */
    public String toString() {
        return super.toString() + "MQBlazeMessage{ " + "map = " + this.map + " }";
    }

    protected void copy(BlazeMessage copy) throws IOException {
        super.copy(copy);
        storeContent();
        copy.persistent = this.persistent;
        copy.destination = this.destination;
        copy.replyTo = this.replyTo;
        copy.messageType = this.messageType;
        copy.timeStamp = this.timeStamp;
        copy.expiration = this.expiration;
        copy.redeliveryCounter = this.redeliveryCounter;
        copy.priority = this.priority;
        copy.type = this.type;
        copy.content = this.content;
    }

    /**
     * @return the content data
     */
    public Buffer getContent() {
        return this.content;
    }

    /**
     * Set the content data
     */
    public void setContent(Buffer content) {
        this.content = content;
    }

    /**
     * Initialize from a Buffer
     */
    public void read(BufferInputStream in) throws IOException {
        super.read(in);
        this.persistent = this.byteBool.readBoolean();
        if (this.byteBool.readBoolean()) {
            this.destination = new Destination();
            this.destination.read(in);
        }
        if (this.byteBool.readBoolean()) {
            this.replyTo = new Destination();
            this.replyTo.read(in);
        }
        this.messageType = in.readString();
        this.timeStamp = in.readLong();
        this.expiration = in.readLong();
        this.redeliveryCounter = in.readByte();
        this.priority = in.readByte();
        this.type = in.readByte();
        this.content = in.readBuffer();
    }

    protected void preWrite() {
        super.preWrite();
        this.byteBool.writeBoolean(this.persistent);
        this.byteBool.writeBoolean(this.destination != null);
        this.byteBool.writeBoolean(this.replyTo != null);
    }

    /**
     * Write state to a Buffer
     */
    public void write(BufferOutputStream out) throws IOException {
        super.write(out);
        if (this.destination != null) {
            this.destination.write(out);
        } else {
        }
        if (this.replyTo != null) {
            this.replyTo.write(out);
        }
        out.writeString(this.messageType);
        out.writeLong(this.timeStamp);
        out.writeLong(this.expiration);
        out.writeByte(this.redeliveryCounter);
        out.writeByte(this.priority);
        out.writeByte(this.type);
        storeContent();
        out.write(this.content);
    }

    protected void initializeReading() {
        try {
            loadContent();
        } catch (IOException e) {
            BlazeRuntimeException ex = new BlazeRuntimeException(e);
            ex.initCause(e);
            throw ex;
        }
    }

    protected void initializeWriting() {
        setContent(null);
    }

    /**
     * Store content into a BlazeData object for serialization
     */
    protected void storeContent() throws IOException {
        if (getContent() == null) {
            int streamSize = Math.max(16, this.map.size() * 16);
            BufferOutputStream out = new BufferOutputStream(streamSize);
            MarshallingSupport.marshalPrimitiveMap(this.map, out);
            out.flush();
            this.content = out.toBuffer();
        }
    }

    /**
     * Builds the message body from data
     */
    protected void loadContent() throws IOException {
        if (!this.loaded) {
            this.loaded = true;
            Buffer buffer = getContent();
            if (buffer != null && (this.map == null || this.map.isEmpty())) {
                BufferInputStream in = new BufferInputStream(buffer);
                this.map = MarshallingSupport.unmarshalPrimitiveMap(in);
            }
        }
    }
}