/** * DataCleaner (community edition) * Copyright (C) 2014 Neopost - Customer Information Management * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.datacleaner.beans.writers; import java.util.Date; import org.apache.metamodel.schema.Column; import org.apache.metamodel.schema.ColumnType; import org.datacleaner.components.convert.ConvertToBooleanTransformer; import org.datacleaner.components.convert.ConvertToNumberTransformer; /** * Static utility class to convert a value from class Object to the type of a {@link Column} if possible. * */ class TypeConverter { static Object convertType(final Object value, final Column targetColumn) throws IllegalArgumentException { if (value == null) { return null; } Object result = value; final ColumnType type = targetColumn.getType(); if (type.isLiteral()) { // for strings, only convert some simple cases, since JDBC drivers // typically also do a decent job here (with eg. Clob types, char[] // types etc.) if (value instanceof Number || value instanceof Date) { result = value.toString(); } } else if (type.isNumber()) { final Number numberValue = ConvertToNumberTransformer.transformValue(value); if (numberValue == null && !"".equals(value)) { throw new IllegalArgumentException("Could not convert " + value + " to number"); } result = numberValue; } else if (type == ColumnType.BOOLEAN) { final Boolean booleanValue = ConvertToBooleanTransformer.transformValue(value); if (booleanValue == null && !"".equals(value)) { throw new IllegalArgumentException("Could not convert " + value + " to boolean"); } result = booleanValue; } return result; } }