001/*
002 *  Copyright 2018 Anyware Services
003 *
004 *  Licensed under the Apache License, Version 2.0 (the "License");
005 *  you may not use this file except in compliance with the License.
006 *  You may obtain a copy of the License at
007 *
008 *      http://www.apache.org/licenses/LICENSE-2.0
009 *
010 *  Unless required by applicable law or agreed to in writing, software
011 *  distributed under the License is distributed on an "AS IS" BASIS,
012 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 *  See the License for the specific language governing permissions and
014 *  limitations under the License.
015 */
016package org.ametys.plugins.contentio.synchronize.impl.typehandler;
017
018import java.sql.CallableStatement;
019import java.sql.PreparedStatement;
020import java.sql.ResultSet;
021import java.sql.SQLException;
022import java.util.Optional;
023
024import org.apache.ibatis.type.BaseTypeHandler;
025import org.apache.ibatis.type.JdbcType;
026
027/**
028 * Handle Float SQL types to return Double value
029 */
030public class SQLDoubleTypeHandler extends BaseTypeHandler<Double>
031{
032    @Override
033    public void setNonNullParameter(PreparedStatement ps, int i, Double parameter, JdbcType jdbcType) throws SQLException
034    {
035        ps.setObject(i, parameter);
036    }
037
038    @Override
039    public Double getNullableResult(ResultSet rs, String columnName) throws SQLException
040    {
041        return _transformNullableObjectToDouble(rs.getObject(columnName));
042    }
043
044    @Override
045    public Double getNullableResult(ResultSet rs, int columnIndex) throws SQLException
046    {
047        return _transformNullableObjectToDouble(rs.getObject(columnIndex));
048        
049    }
050
051    @Override
052    public Double getNullableResult(CallableStatement cs, int columnIndex) throws SQLException
053    {
054        return _transformNullableObjectToDouble(cs.getObject(columnIndex));
055    }
056    
057    private Double _transformNullableObjectToDouble(Object obj)
058    {
059        return Optional.ofNullable(obj)
060                .map(Object::toString)
061                .map(Double::valueOf)
062                .orElse(null);
063    }
064}