001    package org.bukkit.metadata;
002    
003    import java.lang.ref.WeakReference;
004    
005    import org.apache.commons.lang.Validate;
006    import org.bukkit.plugin.Plugin;
007    import org.bukkit.util.NumberConversions;
008    
009    /**
010     * Optional base class for facilitating MetadataValue implementations.
011     * <p>
012     * This provides all the conversion functions for MetadataValue so that
013     * writing an implementation of MetadataValue is as simple as implementing
014     * value() and invalidate().
015     */
016    public abstract class MetadataValueAdapter implements MetadataValue {
017        protected final WeakReference<Plugin> owningPlugin;
018    
019        protected MetadataValueAdapter(Plugin owningPlugin) {
020            Validate.notNull(owningPlugin, "owningPlugin cannot be null");
021            this.owningPlugin = new WeakReference<Plugin>(owningPlugin);
022        }
023    
024        public Plugin getOwningPlugin() {
025            return owningPlugin.get();
026        }
027    
028        public int asInt() {
029            return NumberConversions.toInt(value());
030        }
031    
032        public float asFloat() {
033            return NumberConversions.toFloat(value());
034        }
035    
036        public double asDouble() {
037            return NumberConversions.toDouble(value());
038        }
039    
040        public long asLong() {
041            return NumberConversions.toLong(value());
042        }
043    
044        public short asShort() {
045            return NumberConversions.toShort(value());
046        }
047    
048        public byte asByte() {
049            return NumberConversions.toByte(value());
050        }
051    
052        public boolean asBoolean() {
053            Object value = value();
054            if (value instanceof Boolean) {
055                return (Boolean) value;
056            }
057    
058            if (value instanceof Number) {
059                return ((Number) value).intValue() != 0;
060            }
061    
062            if (value instanceof String) {
063                return Boolean.parseBoolean((String) value);
064            }
065    
066            return value != null;
067        }
068    
069        public String asString() {
070            Object value = value();
071    
072            if (value == null) {
073                return "";
074            }
075            return value.toString();
076        }
077    
078    }