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 * Conversion type from {@code Java Boolean} to {@code JDBC VARCHAR}. 024 * 025 * <p>The {@code pattern} format is: true|false, where the values can be any string value. 026 * 027 * <pre> 028 * {@literal @}Converter(converter = BooleanVarcharType.class,pattern = "Y|N") 029 * </pre> 030 */ 031public class BooleanVarcharType implements Convertible<Boolean, String> 032{ 033 private String truePattern; 034 private String falsePattern; 035 036 public BooleanVarcharType(String pattern) 037 { 038 String[] patterns = pattern.split("\\|"); 039 if (patterns.length != 2) 040 throw new ConverterException("BooleanVarcharType expect a separator \"|\" to handle true and false values, for example \"1|0\". The value was: "+pattern); 041 this.truePattern = patterns[0]; 042 this.falsePattern = patterns[1]; 043 } 044 045 @Override 046 public String toJdbc(Boolean attribute) 047 { 048 if (attribute == null) 049 return null; 050 051 return (attribute.booleanValue() ? truePattern : falsePattern); 052 } 053 054 @Override 055 public Boolean toAttribute(String jdbc) 056 { 057 if (jdbc == null) 058 return null; 059 060 return (jdbc.equals(truePattern) ? Boolean.TRUE : Boolean.FALSE); 061 } 062 063 @Override 064 public Class<Boolean> getType() 065 { 066 return Boolean.class; 067 } 068 069 @Override 070 public ColumnType getColumnType() 071 { 072 return JdbcType.VARCHAR; 073 } 074 075 @Override 076 public String toString() 077 { 078 return "BooleanVarcharType [truePattern=" + truePattern + ", falsePattern=" + falsePattern + ", type=" 079 + getType() + ", columnType=" + getColumnType() + "]"; 080 } 081}