001/* 
002 * JKNIV, whinstone one contract to access your database.
003 * 
004 * Copyright (C) 2017, the original author or authors.
005 *
006 * This library is free software; you can redistribute it and/or
007 * modify it under the terms of the GNU Lesser General Public
008 * License as published by the Free Software Foundation; either
009 * version 2.1 of the License.
010 * 
011 * This library is distributed in the hope that it will be useful,
012 * but WITHOUT ANY WARRANTY; without even the implied warranty of
013 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
014 * Lesser General Public License for more details.
015 * 
016 * You should have received a copy of the GNU Lesser General Public
017 * License along with this library; if not, write to the Free Software Foundation, Inc., 
018 * 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
019 */
020package net.sf.jkniv.whinstone.types;
021
022/**
023 * A Enumeration converter value.
024 * 
025 * For save then name values of Enumeration.
026 * <pre>
027 * {@literal @}Converter(converter = TimeUnit.class, isEnum = EnumType.STRING)
028 * </pre>
029 * 
030 * For save then ordinal value of Enumeration.
031 * <pre>
032 * {@literal @}Converter(converter = TimeUnit.class, isEnum = EnumType.ORDINAL)
033 * </pre>
034 * 
035 * If any value is used for {@code isEnum} the {@code EnumType.STRING} is used per default.
036 * <pre>
037 * {@literal @}Converter(converter = TimeUnit.class)
038 * </pre>
039 * 
040 * @author Alisson Gomes
041 * @since 0.6.0
042 */
043public class EnumOrdinalType implements Convertible<Enum<?>, Integer>
044{
045    private Class<?> enumType;
046    
047    public EnumOrdinalType(Class<?> enumType)
048    {
049        this.enumType = enumType;
050    }
051    
052    @Override
053    public Integer toJdbc(Enum<?> attribute)
054    {
055        if (attribute == null)
056            return null;
057        
058        return attribute.ordinal();
059    }
060
061    @Override 
062    public Enum<?> toAttribute(Integer jdbc)
063    {
064        if (jdbc == null)
065            return null;
066        
067        return (Enum<?>) this.enumType.getEnumConstants()[jdbc.intValue()];
068    }
069
070    @Override @SuppressWarnings({ "rawtypes", "unchecked" })
071    public Class getType()
072    {
073        return enumType;
074    }
075    
076    @Override
077    public ColumnType getColumnType() 
078    {
079        return JdbcType.INTEGER;
080    }
081
082    @Override
083    public String toString()
084    {
085        return "EnumOrdinalType [enumType=" + enumType +  ", type="
086                + getType() + ", columnType=" + getColumnType() + "]";
087    }
088}