001 /* 002 @license.text@ 003 */ 004 package biz.hammurapi.sql; 005 006 import java.sql.ResultSet; 007 import java.sql.SQLException; 008 import java.util.Map; 009 import java.util.StringTokenizer; 010 011 /** 012 * Base class for reflection projectors. 013 * @author Pavel Vlasov 014 * @version $Revision: 1.2 $ 015 */ 016 public class BaseReflectionProjector { 017 018 private Map typeMap; 019 020 /** 021 * @param typeMap type map to be used in java.sql.ResultSet.getField(String/int, Map) method 022 */ 023 protected BaseReflectionProjector(Map typeMap) { 024 this.typeMap=typeMap; 025 } 026 027 /** 028 * This implmentation uses ResultSet.getObject() method to obtain field value. 029 * Override this method if needed to provide custom type conversion. 030 * @param rs ResultSet 031 * @param columnName Field name 032 * @return Column value 033 * @throws SQLException 034 */ 035 protected Object getColumn(ResultSet rs, String columnName) throws SQLException { 036 return typeMap==null ? rs.getObject(columnName) : rs.getObject(columnName, typeMap); 037 } 038 039 /** 040 * This implmentation uses ResultSet.getObject() method to obtain field value. 041 * Override this method if needed to provide custom type conversion. 042 * @param rs ResultSet 043 * @param columnNo Column number 044 * @return Field value 045 * @throws SQLException 046 */ 047 protected Object getColumn(ResultSet rs, int columnNo) throws SQLException { 048 return typeMap==null ? rs.getObject(columnNo) : rs.getObject(columnNo, typeMap); 049 } 050 051 /** 052 * Converts column name such as "MY_COLUMN" to java property name such as myColumn 053 * @param columnName 054 * @return 055 */ 056 public static String propertyName(String columnName) { 057 StringTokenizer st=new StringTokenizer(columnName,"_"); 058 StringBuffer ret=new StringBuffer(); 059 boolean capitalize=false; 060 while (st.hasMoreTokens()) { 061 String token=st.nextToken(); 062 if (capitalize) { 063 ret.append(Character.toUpperCase(token.charAt(0))); 064 if (token.length()>1) { 065 ret.append(token.substring(1).toLowerCase()); 066 } 067 } else { 068 ret.append(token.toLowerCase()); 069 capitalize=true; 070 } 071 } 072 return ret.toString(); 073 } 074 075 /** 076 * MY_COLUMN -> getMyColumn 077 * @param columnName 078 * @return 079 */ 080 public static String accessorName(String columnName) { 081 String propertyName=propertyName(columnName); 082 return "get"+ (propertyName.length()<2 ? propertyName.toUpperCase() : propertyName.substring(0, 1).toUpperCase() + propertyName.substring(1)); 083 } 084 085 /** 086 * MY_COLUMN -> setMyColumn 087 * @param columnName 088 * @return 089 */ 090 public static String mutatorName(String columnName) { 091 String propertyName=propertyName(columnName); 092 return "set"+ (propertyName.length()<2 ? propertyName.toUpperCase() : propertyName.substring(0, 1).toUpperCase() + propertyName.substring(1)); 093 } 094 }