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
022import java.text.ParseException;
023import java.text.SimpleDateFormat;
024import java.util.Calendar;
025
026/**
027 * Conversion type from {@code Java Calendar} to {@code JDBC INTEGER}.
028 * 
029 * @author Alisson Gomes
030 * @since 0.6.0
031 */
032public class CalendarIntType implements Convertible<Calendar, Integer>
033{
034    private String pattern;
035    
036    public CalendarIntType(String pattern)
037    {
038        this.pattern = pattern;
039    }
040    
041    @Override
042    public Integer toJdbc(Calendar attribute)
043    {
044        if (attribute == null)
045            return null;
046        
047        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
048        return Integer.valueOf(sdf.format(attribute.getTime()));
049    }
050
051    @Override
052    public Calendar toAttribute(Integer jdbc)
053    {
054        if (jdbc == null)
055            return null;
056        
057        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
058        try
059        {
060            Calendar calendar = Calendar.getInstance();
061            calendar.setTime(sdf.parse(String.valueOf(jdbc)));
062            return calendar;
063        }
064        catch (ParseException e)
065        {
066            throw new ConverterException(e);
067        }
068    }
069
070    @Override
071    public Class<Calendar> getType()
072    {
073        return Calendar.class;
074    }
075    
076    @Override
077    public ColumnType getColumnType() 
078    {
079        return JdbcType.INTEGER;
080    }
081
082    @Override
083    public String toString()
084    {
085        return "CalendarIntType [pattern=" + pattern + ", type="
086                + getType() + ", columnType=" + getColumnType() + "]";
087    }
088}