package com.anwrt.tools.xbeans;

/**
 * A runtime exception that indicates that a JavaBean property is immutable, i.e. can be set only once.
 * This exception is typically thrown by a property setter if the property already has a value.
 *
 * @author <a href="mailto:sylvain@apache.org">Sylvain Wallez</a>
 */

public class ImmutablePropertyException extends IllegalStateException
{

    public ImmutablePropertyException()
    {
        super();
    }

    public ImmutablePropertyException(String msg)
    {
        super(msg);
    }

    /**
     * Convenience method that checks if the current value of a property is null 
     * or already set to <code>newValue</code> and throws an
     * <code>ImmutablePropertyException</code> if not.
     * <p>
     * Usage example : <pre>
     *   public void setMyProp(Object value)
     *   {
     *       ImmutablePropertyException.check(this.myProp, value);
     *       this.myProp = value;
     *   }
     * </pre>
     * 
     * @param oldValue the current value for the property
     * @param newValue the new value for the property
     * @throws ImmutablePropertyException if <code>oldValue != null && oldValue != newValue</code>
     */
    public static void check(Object oldValue, Object newValue)
      throws ImmutablePropertyException
    {
        if (oldValue != null && newValue != oldValue)
        {
            throw new ImmutablePropertyException();
        }
    }

    /**
     * Same as @{link #check(Object, Object)} whith an additional message.
     */
    public static void check(Object oldValue, Object newValue, String message)
      throws ImmutablePropertyException
    {
        if (oldValue != null && newValue != oldValue)
        {
            throw new ImmutablePropertyException(message);
        }
    }
}
