svnno****@sourc*****
svnno****@sourc*****
2008年 12月 28日 (日) 07:22:08 JST
Revision: 1634 http://svn.sourceforge.jp/view?root=pal&view=rev&rev=1634 Author: shinsuke Date: 2008-12-28 07:22:08 +0900 (Sun, 28 Dec 2008) Log Message: ----------- added status column to userinfo table. replaced with dbflute 0.8.7. Removed Paths: ------------- todolist/trunk/src/main/java/jp/sf/pal/todolist/db/allcommon/BFinder.java todolist/trunk/src/main/java/jp/sf/pal/todolist/db/allcommon/CacheDaoSelector.java todolist/trunk/src/main/java/jp/sf/pal/todolist/db/allcommon/DaoReadable.java todolist/trunk/src/main/java/jp/sf/pal/todolist/db/allcommon/DaoSelector.java todolist/trunk/src/main/java/jp/sf/pal/todolist/db/allcommon/DaoWritable.java todolist/trunk/src/main/java/jp/sf/pal/todolist/db/allcommon/GenMetaData.java todolist/trunk/src/main/java/jp/sf/pal/todolist/db/allcommon/annotation/OutsideSql.java todolist/trunk/src/main/java/jp/sf/pal/todolist/db/allcommon/cbean/SimpleOrderByBean.java todolist/trunk/src/main/java/jp/sf/pal/todolist/db/allcommon/cbean/outsidesql/OutsideSqlDao.java todolist/trunk/src/main/java/jp/sf/pal/todolist/db/allcommon/s2dao/FetchNarrowingResultSetFactory.java todolist/trunk/src/main/java/jp/sf/pal/todolist/db/allcommon/s2dao/S2BeanMetaDataFactoryImpl.java todolist/trunk/src/main/java/jp/sf/pal/todolist/db/allcommon/s2dao/S2DaoInterceptor.java todolist/trunk/src/main/java/jp/sf/pal/todolist/db/allcommon/s2dao/S2DaoLatestSqlProvider.java todolist/trunk/src/main/java/jp/sf/pal/todolist/db/allcommon/s2dao/S2DaoMetaDataExtension.java todolist/trunk/src/main/java/jp/sf/pal/todolist/db/allcommon/s2dao/S2DaoMetaDataFactoryImpl.java todolist/trunk/src/main/java/jp/sf/pal/todolist/db/allcommon/s2dao/S2DaoPropertyTypeFactoryBuilderExtension.java todolist/trunk/src/main/java/jp/sf/pal/todolist/db/allcommon/s2dao/S2DaoSelectDynamicCommand.java -------------- next part -------------- Deleted: todolist/trunk/src/main/java/jp/sf/pal/todolist/db/allcommon/BFinder.java =================================================================== --- todolist/trunk/src/main/java/jp/sf/pal/todolist/db/allcommon/BFinder.java 2008-12-27 22:21:53 UTC (rev 1633) +++ todolist/trunk/src/main/java/jp/sf/pal/todolist/db/allcommon/BFinder.java 2008-12-27 22:22:08 UTC (rev 1634) @@ -1,110 +0,0 @@ -package jp.sf.pal.todolist.db.allcommon; - -import jp.sf.pal.todolist.db.allcommon.bhv.BehaviorReadable; - -/** - * The entry of DBFlute. - * - * @author DBFlute(AutoGenerator) - */ - @ SuppressWarnings("unchecked") -public class BFinder { - - //========================================================================== - // ========= - // Definition - // ========== - protected static String _dbfluteDiconName = "dbflute.dicon"; - - //========================================================================== - // ========= - // Constructor - // =========== - private BFinder() { - } - - //========================================================================== - // ========= - // Finder - // ====== - public static <BEHAVIOR_TYPE extends BehaviorReadable> BEHAVIOR_TYPE find( - Class<BEHAVIOR_TYPE> behaviorType) { - assertObjectNotNull("behaviorType", behaviorType); - if (!org.seasar.framework.container.factory.SingletonS2ContainerFactory - .hasContainer()) { - synchronized (BFinder.class) { - if (!org.seasar.framework.container.factory.SingletonS2ContainerFactory - .hasContainer()) { - final String configFile = _dbfluteDiconName; - if (org.seasar.framework.util.ResourceUtil - .isExist(configFile)) { - org.seasar.framework.container.factory.SingletonS2ContainerFactory - .setConfigPath(configFile); - org.seasar.framework.container.factory.SingletonS2ContainerFactory - .init(); - } else { - String msg = "S2Container is not initialized! Confirm your initializer and your dicon files."; - throw new IllegalStateException(msg); - } - } - } - } - final org.seasar.framework.container.S2Container container = org.seasar.framework.container.factory.SingletonS2ContainerFactory - .getContainer(); - final BEHAVIOR_TYPE behavior = (BEHAVIOR_TYPE) container - .getComponent(behaviorType); - return behavior; - } - - //========================================================================== - // ========= - // Accessor - // ======== - public static void setDBFluteDiconName(String dbfluteDiconName) { - _dbfluteDiconName = dbfluteDiconName; - } - - //========================================================================== - // ========= - // General Helper - // ============== - /** - * Assert that the object is not null. - * - * @param variableName Variable name. (NotNull) - * @param value Value. (NotNull) - * @exception IllegalArgumentException - */ - protected static void assertObjectNotNull(String variableName, Object value) { - if (variableName == null) { - String msg = "The value should not be null: variableName=" - + variableName + " value=" + value; - throw new IllegalArgumentException(msg); - } - if (value == null) { - String msg = "The value should not be null: variableName=" - + variableName; - throw new IllegalArgumentException(msg); - } - } - - // ---------------------------------------------------------------- - // Assert String - // ------------- - /** - * Assert that the entity is not null and not trimmed empty. - * - * @param variableName Variable name. (NotNull) - * @param value Value. (NotNull) - */ - protected void assertStringNotNullAndNotTrimmedEmpty(String variableName, - String value) { - assertObjectNotNull("variableName", variableName); - assertObjectNotNull("value", value); - if (value.trim().length() == 0) { - String msg = "The value should not be empty: variableName=" - + variableName + " value=" + value; - throw new IllegalArgumentException(msg); - } - } -} Deleted: todolist/trunk/src/main/java/jp/sf/pal/todolist/db/allcommon/CacheDaoSelector.java =================================================================== --- todolist/trunk/src/main/java/jp/sf/pal/todolist/db/allcommon/CacheDaoSelector.java 2008-12-27 22:21:53 UTC (rev 1633) +++ todolist/trunk/src/main/java/jp/sf/pal/todolist/db/allcommon/CacheDaoSelector.java 2008-12-27 22:22:08 UTC (rev 1634) @@ -1,66 +0,0 @@ -package jp.sf.pal.todolist.db.allcommon; - -import jp.sf.pal.todolist.db.allcommon.dbmeta.DBMeta; -import jp.sf.pal.todolist.db.allcommon.dbmeta.DBMetaInstanceHandler; - -/** - * The implementation of DAO-selector. - * - * <pre> - * Long long ago this object have cache of DAO and behavior. - * But the cache cause wrong performance when this is initialized. - * So now this object don't have cache. - * </pre> - * - * @author DBFlute(AutoGenerator) - */ - @ SuppressWarnings("unchecked") -public class CacheDaoSelector extends CacheAbstractSelector implements - DaoSelector { - - //========================================================================== - // ========= - // Selector - // ======== - /** - * Select DAO. - * - * @param <DAO> The type of DAO. - * @param daoType DAO type. (NotNull) - * @return DAO. (NotNull) - */ - public <DAO extends DaoReadable> DAO select(Class<DAO> daoType) { - return (DAO) getComponent(daoType); - } - - /** - * Select DAO-readable by name. - * - * @param tableFlexibleName Table flexible name. (NotNull) - * @return DAO-readable. (NotNull) - */ - public DaoReadable byName(String tableFlexibleName) { - assertStringNotNullAndNotTrimmedEmpty("tableFlexibleName", - tableFlexibleName); - final DBMeta dbmeta = DBMetaInstanceHandler - .findDBMeta(tableFlexibleName); - return select(getDaoType(dbmeta)); - } - - protected Class<DaoReadable> getDaoType(DBMeta dbmeta) { - final String daoTypeName = dbmeta.getDaoTypeName(); - if (daoTypeName == null) { - String msg = "The dbmeta.getDaoTypeName() should not return null: dbmeta=" - + dbmeta; - throw new IllegalStateException(msg); - } - final Class<DaoReadable> daoType; - try { - daoType = (Class<DaoReadable>) Class.forName(daoTypeName); - } catch (ClassNotFoundException e) { - throw new RuntimeException("The class does not exist: " - + daoTypeName, e); - } - return daoType; - } -} Deleted: todolist/trunk/src/main/java/jp/sf/pal/todolist/db/allcommon/DaoReadable.java =================================================================== --- todolist/trunk/src/main/java/jp/sf/pal/todolist/db/allcommon/DaoReadable.java 2008-12-27 22:21:53 UTC (rev 1633) +++ todolist/trunk/src/main/java/jp/sf/pal/todolist/db/allcommon/DaoReadable.java 2008-12-27 22:22:08 UTC (rev 1634) @@ -1,11 +0,0 @@ -package jp.sf.pal.todolist.db.allcommon; - -/** - * The interface of dao-readable. - * - * @author DBFlute(AutoGenerator) - */ -public interface DaoReadable { - public void initializeDaoMetaData(String methodName);// Very Internal - // Method! -} Deleted: todolist/trunk/src/main/java/jp/sf/pal/todolist/db/allcommon/DaoSelector.java =================================================================== --- todolist/trunk/src/main/java/jp/sf/pal/todolist/db/allcommon/DaoSelector.java 2008-12-27 22:21:53 UTC (rev 1633) +++ todolist/trunk/src/main/java/jp/sf/pal/todolist/db/allcommon/DaoSelector.java 2008-12-27 22:22:08 UTC (rev 1634) @@ -1,26 +0,0 @@ -package jp.sf.pal.todolist.db.allcommon; - -/** - * The interface of DAO-selector. - * - * @author DBFlute(AutoGenerator) - */ -public interface DaoSelector { - - /** - * Select DAO. - * - * @param <DAO> The type of DAO. - * @param daoType DAO type. (NotNull) - * @return Dao. (NotNull) - */ - public <DAO extends DaoReadable> DAO select(Class<DAO> daoType); - - /** - * Select DAO-readable by name. - * - * @param tableFlexibleName Table flexible name. (NotNull) - * @return DAO-readable. (NotNull) - */ - public DaoReadable byName(String tableFlexibleName); -} Deleted: todolist/trunk/src/main/java/jp/sf/pal/todolist/db/allcommon/DaoWritable.java =================================================================== --- todolist/trunk/src/main/java/jp/sf/pal/todolist/db/allcommon/DaoWritable.java 2008-12-27 22:21:53 UTC (rev 1633) +++ todolist/trunk/src/main/java/jp/sf/pal/todolist/db/allcommon/DaoWritable.java 2008-12-27 22:22:08 UTC (rev 1634) @@ -1,70 +0,0 @@ -package jp.sf.pal.todolist.db.allcommon; - -import java.util.List; - -/** - * The interface of dao-writable. - * - * @author DBFlute(AutoGenerator) - */ -public interface DaoWritable extends DaoReadable { - - /** - * Insert one entity that the type is entity-interface. - * - * @param entity Entity that the type is entity-interface. (NotNull) - * @return Inserted count. - */ - public int create(Entity entity); - - /** - * Update one entity that the type is entity-interface. - * - * @param entity Entity that the type is entity-interface. (NotNull) - * @return Updated count. - */ - public int modify(Entity entity); - - /** - * Update one entity that the type is entity-interface. (modified only) - * - * @param entity Entity that the type is entity-interface. (NotNull) - * @return Updated count. - */ - public int modifyModifiedOnly(Entity entity); - - /** - * Delete one entity that the type is entity-interface. - * - * @param entity Entity that the type is entity-interface. (NotNull) - * @return Deleted count. - */ - public int remove(Entity entity); - - /** - * Insert several entities that the type is entity-interface. - * - * @param entityList Entity-list that the type is entity-interface. - * (NotNull) - * @return The array of inserted count. - */ - public int[] createList(List<Entity> entityList); - - /** - * Update several entities that the type is entity-interface. - * - * @param entityList Entity-list that the type is entity-interface. - * (NotNull) - * @return The array of updated count. - */ - public int[] modifyList(List<Entity> entityList); - - /** - * Delete several entities that the type is entity-interface. - * - * @param entityList Entity-list that the type is entity-interface. - * (NotNull) - * @return The array of deleted count. - */ - public int[] removeList(List<Entity> entityList); -} Deleted: todolist/trunk/src/main/java/jp/sf/pal/todolist/db/allcommon/GenMetaData.java =================================================================== --- todolist/trunk/src/main/java/jp/sf/pal/todolist/db/allcommon/GenMetaData.java 2008-12-27 22:21:53 UTC (rev 1633) +++ todolist/trunk/src/main/java/jp/sf/pal/todolist/db/allcommon/GenMetaData.java 2008-12-27 22:22:08 UTC (rev 1634) @@ -1,258 +0,0 @@ -package jp.sf.pal.todolist.db.allcommon; - -/** - * The sigleton class that has generate-meta-data(GenMetaData). - * - * @author DBFlute(AutoGenerator) - */ -public class GenMetaData { - - /** Singleton instance. */ - private static final GenMetaData _instance = new GenMetaData(); - - /** - * Constructor. - */ - private GenMetaData() { - } - - /** - * Get instance. - * - * @return Singleton instance. - */ - public static GenMetaData getInstance() { - return _instance; - } - - //========================================================================== - // ========= - // Basic - // ===== - /** - * Get the property-value of targetLanguage. - * - * @return The property-value. - */ - public String getTargetLanguage() { - return "java"; - } - - /** - * Get the property-value of templateFileExtension. - * - * @return The property-value. - */ - public String getTemplateFileExtension() { - return "vm"; - } - - /** - * Get the property-value of classFileExtension. - * - * @return The property-value. - */ - public String getClassFileExtension() { - return "java"; - } - - /** - * Get the property-value of templateFileEncoding. - * - * @return The property-value. - */ - public String getTemplateEncoding() { - return "UTF-8"; - } - - /** - * Get the property-value of classAuthor. - * - * @return The property-value. - */ - public String getClassAuthor() { - return "DBFlute(AutoGenerator)"; - } - - //========================================================================== - // ========= - // Naming - // ====== - /** - * Is java name of table same as db name? Answer is false! - * - * @return The property-value. - */ - public boolean isJavaNameOfTableSameAsDbName() { - return false; - } - - /** - * Is java name of column same as db name? Answer is false! - * - * @return The property-value. - */ - public boolean isJavaNameOfColumnSameAsDbName() { - return false; - } - - //========================================================================== - // ========= - // Prefix - // ====== - /** - * Get the property-value of projectPrefix. - * - * @return The property-value. - */ - public String getProjectPrefix() { - return ""; - } - - /** - * Get the property-value of basePrefix. - * - * @return The property-value. - */ - public String getBasePrefix() { - return "Bs"; - } - - //========================================================================== - // ========= - // Package - // ======= - /** - * Get the property-value of baseCommonPackage. - * - * @return The property-value. - */ - public String getBaseCommonPackage() { - return "jp.sf.pal.todolist.db.allcommon"; - } - - /** - * Get the property-value of baseBehaviorPackage. - * - * @return The property-value. - */ - public String getBaseBehaviorPackage() { - return "jp.sf.pal.todolist.db.bsbhv"; - } - - /** - * Get the property-value of baseDaoPackage. - * - * @return The property-value. - */ - public String getBaseDaoPackage() { - return "jp.sf.pal.todolist.db.bsdao"; - } - - /** - * Get the property-value of baseEntityPackage. - * - * @return The property-value. - */ - public String getBaseEntityPackage() { - return "jp.sf.pal.todolist.db.bsentity"; - } - - /** - * Get the property-value of conditionBeanPackage. - * - * @return The property-value. - */ - public String getConditionBeanPackage() { - return "jp.sf.pal.todolist.db.cbean"; - } - - /** - * Get the property-value of extendedDaoPackage. - * - * @return The property-value. - */ - public String getExtendedDaoPackage() { - return "jp.sf.pal.todolist.db.exdao"; - } - - /** - * Get the property-value of extendedBehaviorPackage. - * - * @return The property-value. - */ - public String getExtendedBehaviorPackage() { - return "jp.sf.pal.todolist.db.exbhv"; - } - - /** - * Get the property-value of extendedEntityPackage. - * - * @return The property-value. - */ - public String getExtendedEntityPackage() { - return "jp.sf.pal.todolist.db.exentity"; - } - - //========================================================================== - // ========= - // Optimistic Lock - // =============== - /** - * Get the property-value of updateDateFieldName. - * - * @return The property-value. - */ - public String getUpdateDateFieldName() { - return ""; - } - - /** - * Get the property-value of versionNoFieldName. - * - * @return The property-value. - */ - public String getVersionNoFieldName() { - return ""; - } - - //========================================================================== - // ========= - // Extract - // ======= - /** - * Get the value of 'extractAcceptStartBrace'. - * - * @return The property-value. (NotNull) - */ - public String getExtractAcceptStartBrace() { - return "@{"; - } - - /** - * Get the value of 'extractAcceptEndBrace'. - * - * @return The property-value. (NotNull) - */ - public String getExtractAcceptEndBrace() { - return "@}"; - } - - /** - * Get the value of 'extractAcceptDelimiter'. - * - * @return The property-value. (NotNull) - */ - public String getExtractAcceptDelimiter() { - return "@;"; - } - - /** - * Get the value of 'extractAcceptEqual'. - * - * @return The property-value. (NotNull) - */ - public String getExtractAcceptEqual() { - return "@="; - } -} Deleted: todolist/trunk/src/main/java/jp/sf/pal/todolist/db/allcommon/annotation/OutsideSql.java =================================================================== --- todolist/trunk/src/main/java/jp/sf/pal/todolist/db/allcommon/annotation/OutsideSql.java 2008-12-27 22:21:53 UTC (rev 1633) +++ todolist/trunk/src/main/java/jp/sf/pal/todolist/db/allcommon/annotation/OutsideSql.java 2008-12-27 22:22:08 UTC (rev 1634) @@ -1,18 +0,0 @@ -package jp.sf.pal.todolist.db.allcommon.annotation; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Inherited; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - - @ Inherited - @ Retention(RetentionPolicy.RUNTIME) - @ Target(ElementType.METHOD) -public @interface OutsideSql { - boolean dynamicBinding() default false; - - boolean offsetByCursor() default false; - - boolean limitByCursor() default false; -} Deleted: todolist/trunk/src/main/java/jp/sf/pal/todolist/db/allcommon/cbean/SimpleOrderByBean.java =================================================================== --- todolist/trunk/src/main/java/jp/sf/pal/todolist/db/allcommon/cbean/SimpleOrderByBean.java 2008-12-27 22:21:53 UTC (rev 1633) +++ todolist/trunk/src/main/java/jp/sf/pal/todolist/db/allcommon/cbean/SimpleOrderByBean.java 2008-12-27 22:22:08 UTC (rev 1634) @@ -1,165 +0,0 @@ -package jp.sf.pal.todolist.db.allcommon.cbean; - -import jp.sf.pal.todolist.db.allcommon.cbean.sqlclause.OrderByClause; -import jp.sf.pal.todolist.db.allcommon.cbean.sqlclause.SqlClause; - -/** - * @deprecated - */ -public class SimpleOrderByBean implements OrderByBean { - - //========================================================================== - // ========= - // Attribute - // ========= - /** SQL clause instance. */ - protected final SqlClause _sqlClause; - { - _sqlClause = ConditionBeanContext.createSqlClause("Dummy"); - } - - //========================================================================== - // ========= - // Constructor - // =========== - /** - * Constructor. - */ - public SimpleOrderByBean() { - } - - //========================================================================== - // ========= - // SqlClause - // ========= - /** - * Get sql-clause. - * - * @return Sql clause. (NotNull) - */ - protected SqlClause getSqlClause() { - return _sqlClause; - } - - //========================================================================== - // ========= - // Select Resource - // =============== - /** - * Check safety result. - * - * @param safetyMaxResultSize Safety max result size. (If zero or minus, - * ignore checking) - */ - public void checkSafetyResult(int safetyMaxResultSize) { - throw new UnsupportedOperationException(); - } - - //========================================================================== - // ========= - // OrderBy - // ======= - /** - * The implementation. - * - * @return Sql component of order-by clause. (NotNull) - */ - public OrderByClause getSqlComponentOfOrderByClause() { - return getSqlClause().getSqlComponentOfOrderByClause(); - } - - /** - * The implementation. - * - * @return Order-by clause. (NotNull) - */ - public String getOrderByClause() { - return getSqlClause().getOrderByClause(); - } - - /** - * The implementation. - * - * @return this. (NotNull) - */ - public OrderByBean clearOrderBy() { - getSqlClause().clearOrderBy(); - return this; - } - - /** - * The implementation. - * - * @return this. (NotNull) - */ - public OrderByBean ignoreOrderBy() { - getSqlClause().ignoreOrderBy(); - return this; - } - - /** - * The implementation. - * - * @return this. (NotNull) - */ - public OrderByBean makeOrderByEffective() { - getSqlClause().makeOrderByEffective(); - return this; - } - - /** - * Register order-by-asc. - * - * @param orderByProperty Order-by-property. - * 'aliasName.columnName/aliasName.columnName/...' (NotNull) - * @return this. (NotNull) - * @deprecated - */ - public OrderByBean registerOrderByAsc(String orderByProperty) { - getSqlClause().registerOrderBy(orderByProperty, orderByProperty, true); - return this; - } - - /** - * Register order-by-desc. - * - * @param orderByProperty Order-by-property. - * 'aliasName.columnName/aliasName.columnName/...' (NotNull) - * @return this. (NotNull) - * @deprecated - */ - public OrderByBean registerOrderByDesc(String orderByProperty) { - getSqlClause().registerOrderBy(orderByProperty, orderByProperty, false); - return this; - } - - /** - * Reverse order-by or Override order-by asc. - * - * @param orderByProperty Order-by-property. - * 'aliasName.columnName/aliasName.columnName/...' (NotNull) - * @return this. (NotNull) - * @deprecated - */ - public OrderByBean reverseOrderBy_Or_OverrideOrderByAsc( - String orderByProperty) { - getSqlClause().reverseOrderBy_Or_OverrideOrderBy(orderByProperty, - orderByProperty, true); - return this; - } - - /** - * Reverse order-by or Override order-by desc. - * - * @param orderByProperty Order-by-property. - * 'aliasName.columnName/aliasName.columnName/...' (NotNull) - * @return this. (NotNull) - * @deprecated - */ - public OrderByBean reverseOrderBy_Or_OverrideOrderByDesc( - String orderByProperty) { - getSqlClause().reverseOrderBy_Or_OverrideOrderBy(orderByProperty, - orderByProperty, false); - return this; - } -} Deleted: todolist/trunk/src/main/java/jp/sf/pal/todolist/db/allcommon/cbean/outsidesql/OutsideSqlDao.java =================================================================== --- todolist/trunk/src/main/java/jp/sf/pal/todolist/db/allcommon/cbean/outsidesql/OutsideSqlDao.java 2008-12-27 22:21:53 UTC (rev 1633) +++ todolist/trunk/src/main/java/jp/sf/pal/todolist/db/allcommon/cbean/outsidesql/OutsideSqlDao.java 2008-12-27 22:22:08 UTC (rev 1634) @@ -1,37 +0,0 @@ -package jp.sf.pal.todolist.db.allcommon.cbean.outsidesql; - -import java.util.List; - -import jp.sf.pal.todolist.db.allcommon.DaoReadable; -import jp.sf.pal.todolist.db.allcommon.jdbc.CursorHandler; - -/** - * The dao of outside-sql. - * - * @author DBFlute(AutoGenerator) - */ -public interface OutsideSqlDao extends DaoReadable { - - //========================================================================== - // ========= - // Select - // ====== - <ENTITY> List<ENTITY> selectList(String path, Object pmb, - OutsideSqlOption option, Class<ENTITY> entityType); - - <ENTITY> Object selectCursor(String path, Object pmb, - OutsideSqlOption option, CursorHandler handler); - - //========================================================================== - // ========= - // Execute - // ======= - int execute(String path, Object pmb, OutsideSqlOption option); - - // [DBFlute-0.7.5] - //========================================================================== - // ========= - // Call - // ==== - void call(String path, Object pmb, OutsideSqlOption option); -} Deleted: todolist/trunk/src/main/java/jp/sf/pal/todolist/db/allcommon/s2dao/FetchNarrowingResultSetFactory.java =================================================================== --- todolist/trunk/src/main/java/jp/sf/pal/todolist/db/allcommon/s2dao/FetchNarrowingResultSetFactory.java 2008-12-27 22:21:53 UTC (rev 1633) +++ todolist/trunk/src/main/java/jp/sf/pal/todolist/db/allcommon/s2dao/FetchNarrowingResultSetFactory.java 2008-12-27 22:22:08 UTC (rev 1634) @@ -1,125 +0,0 @@ -package jp.sf.pal.todolist.db.allcommon.s2dao; - -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; - -import jp.sf.pal.todolist.db.allcommon.s2dao.internal.sqlhandler.InternalBasicHandler.SQLExceptionHandler; - -import org.seasar.extension.jdbc.ResultSetFactory; - -/** - * This is unused in DBFlute so this is very NORMAL result-set-factory for - * S2Dao. - * - * @author DBFlute(AutoGenerator) - */ -public class FetchNarrowingResultSetFactory implements ResultSetFactory { - - //========================================================================== - // ========= - // Constructor - // =========== - /** - * Constructor. - */ - public FetchNarrowingResultSetFactory() { - } - - //========================================================================== - // ========= - // Main - // ==== - /** - * Get result set. - * - * @param statement Statement. (NotNull) - * @return Result set for procedure executing of s2dao. (NotNull) - */ - public ResultSet getResultSet(Statement statement) { // Unused in DBFlute - return doGetResultSet(statement); - } - - /** - * Create result set. - * - * @param ps Prepared statement. (NotNull) - * @return Result set. (NotNull) - */ - public ResultSet createResultSet(PreparedStatement ps) { // Unused in - // DBFlute - return executeQuery(ps); - - // *Move to InternalBasicSelectHandler - // if (!FetchNarrowingBeanContext.isExistFetchNarrowingBeanOnThread()) { - // return resultSet; - // } - // final FetchNarrowingBean cb = - // FetchNarrowingBeanContext.getFetchNarrowingBeanOnThread(); - // if (!isUseFetchNarrowingResultSetWrapper(cb)) { - // return resultSet; - // } - // final FetchNarrowingResultSetWrapper wrapper; - // if (OutsideSqlContext.isExistOutsideSqlContextOnThread()) { - // final OutsideSqlContext outsideSqlContext = - // OutsideSqlContext.getOutsideSqlContextOnThread(); - // wrapper = new FetchNarrowingResultSetWrapper(resultSet, cb, - // outsideSqlContext.isOffsetByCursorForcedly(), - // outsideSqlContext.isLimitByCursorForcedly()); - // } else { - // wrapper = new FetchNarrowingResultSetWrapper(resultSet, cb, false, - // false); - // } - // return wrapper; - } - - // protected boolean isUseFetchNarrowingResultSetWrapper(FetchNarrowingBean - // cb) { - // if (cb.getSafetyMaxResultSize() > 0) { - // return true; - // } - // if (!cb.isFetchNarrowingEffective()) { - // return false;// It is not necessary to control. - // } - // if (OutsideSqlContext.isExistOutsideSqlContextOnThread()) { - // final OutsideSqlContext outsideSqlContext = - // OutsideSqlContext.getOutsideSqlContextOnThread(); - // if (outsideSqlContext.isOffsetByCursorForcedly() || - // outsideSqlContext.isLimitByCursorForcedly()) { - // return true; - // } - // } - // if (cb.isFetchNarrowingSkipStartIndexEffective() || - // cb.isFetchNarrowingLoopCountEffective()) { - // return true; - // } - // return false; - // } - - //========================================================================== - // ========= - // JDBC Delegator - // ============== - protected ResultSet doGetResultSet(Statement statement) { - try { - return statement.getResultSet(); - } catch (SQLException e) { - handleSQLException(e, statement); - return null;// Unreachable! - } - } - - protected ResultSet executeQuery(PreparedStatement ps) { - try { - return ps.executeQuery(); - } catch (SQLException e) { - handleSQLException(e, ps); - return null;// Unreachable! - } - } - - protected void handleSQLException(SQLException e, Statement statement) { - new SQLExceptionHandler().handleSQLException(e, statement); - } -} Deleted: todolist/trunk/src/main/java/jp/sf/pal/todolist/db/allcommon/s2dao/S2BeanMetaDataFactoryImpl.java =================================================================== --- todolist/trunk/src/main/java/jp/sf/pal/todolist/db/allcommon/s2dao/S2BeanMetaDataFactoryImpl.java 2008-12-27 22:21:53 UTC (rev 1633) +++ todolist/trunk/src/main/java/jp/sf/pal/todolist/db/allcommon/s2dao/S2BeanMetaDataFactoryImpl.java 2008-12-27 22:22:08 UTC (rev 1634) @@ -1,116 +0,0 @@ -package jp.sf.pal.todolist.db.allcommon.s2dao; - -import java.sql.DatabaseMetaData; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; - -import jp.sf.pal.todolist.db.allcommon.Entity; - -import org.seasar.dao.BeanMetaData; -import org.seasar.dao.impl.BeanMetaDataFactoryImpl; -import org.seasar.dao.impl.BeanMetaDataImpl; - -/** - * BeanMetaDataFactoryImpl for DBFlute. - * - * @author DBFlute(AutoGenerator) - */ - @ SuppressWarnings("unchecked") -public class S2BeanMetaDataFactoryImpl extends BeanMetaDataFactoryImpl { - - protected Map<Class<? extends Entity>, BeanMetaData> _metaMap = Collections - .synchronizedMap(new HashMap<Class<? extends Entity>, BeanMetaData>()); - - @Override - public BeanMetaData createBeanMetaData(Class beanClass) { - final BeanMetaData cachedMeta = findCachedMeta(beanClass); - if (cachedMeta != null) { - return cachedMeta; - } else { - return super.createBeanMetaData(beanClass); - } - } - - @Override - public BeanMetaData createBeanMetaData(Class beanClass, - int relationNestLevel) { - final BeanMetaData cachedMeta = findCachedMeta(beanClass); - if (cachedMeta != null) { - return cachedMeta; - } else { - return super.createBeanMetaData(beanClass, relationNestLevel); - } - } - - @Override - public BeanMetaData createBeanMetaData(DatabaseMetaData dbMetaData, - Class beanClass, int relationNestLevel) { - final BeanMetaData cachedMeta = findOrCreateCachedMetaIfNeeds( - dbMetaData, beanClass, relationNestLevel); - if (cachedMeta != null) { - return cachedMeta; - } else { - return super.createBeanMetaData(dbMetaData, beanClass, - relationNestLevel); - } - } - - protected BeanMetaData findCachedMeta(Class beanClass) { - if (isDBFluteEntity(beanClass)) { - final BeanMetaData cachedMeta = getMetaFromCache(beanClass); - if (cachedMeta != null) { - return cachedMeta; - } - } - return null; - } - - protected BeanMetaData findOrCreateCachedMetaIfNeeds( - DatabaseMetaData dbMetaData, Class beanClass, int relationNestLevel) { - if (isDBFluteEntity(beanClass)) { - final BeanMetaData cachedMeta = getMetaFromCache(beanClass); - if (cachedMeta != null) { - return cachedMeta; - } else { - return super.createBeanMetaData(dbMetaData, beanClass, 0); - } - } - return null; - } - - @Override - protected BeanMetaDataImpl createBeanMetaDataImpl() { - return new BeanMetaDataImpl() { - @Override - public void initialize() { - final Class myBeanClass = getBeanClass(); - if (isDBFluteEntity(myBeanClass)) { - final BeanMetaData cachedMeta = getMetaFromCache(myBeanClass); - if (cachedMeta == null) { - _metaMap.put(myBeanClass, this); - } - } - super.initialize(); - } - }; - } - - protected boolean isDBFluteEntity(Class beanClass) { - return Entity.class.isAssignableFrom(beanClass); - } - - protected BeanMetaData getMetaFromCache(Class beanClass) { - return _metaMap.get(beanClass); - } - - /** - * Get the limit nest level of relation. - * - * @return The limit nest level of relation. - */ - @Override - protected int getLimitRelationNestLevel() { - return 2;// for Compatible to old version DBFlute - } -} \ No newline at end of file Deleted: todolist/trunk/src/main/java/jp/sf/pal/todolist/db/allcommon/s2dao/S2DaoInterceptor.java =================================================================== --- todolist/trunk/src/main/java/jp/sf/pal/todolist/db/allcommon/s2dao/S2DaoInterceptor.java 2008-12-27 22:21:53 UTC (rev 1633) +++ todolist/trunk/src/main/java/jp/sf/pal/todolist/db/allcommon/s2dao/S2DaoInterceptor.java 2008-12-27 22:22:08 UTC (rev 1634) @@ -1,1027 +0,0 @@ -package jp.sf.pal.todolist.db.allcommon.s2dao; - -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.util.Arrays; -import java.util.List; - -import jp.sf.pal.todolist.db.allcommon.Entity; -import jp.sf.pal.todolist.db.allcommon.InternalMapContext; -import jp.sf.pal.todolist.db.allcommon.XLog; -import jp.sf.pal.todolist.db.allcommon.cbean.ConditionBean; -import jp.sf.pal.todolist.db.allcommon.cbean.ConditionBeanContext; -import jp.sf.pal.todolist.db.allcommon.cbean.FetchNarrowingBean; -import jp.sf.pal.todolist.db.allcommon.cbean.FetchNarrowingBeanContext; -import jp.sf.pal.todolist.db.allcommon.cbean.outsidesql.OutsideSqlContext; -import jp.sf.pal.todolist.db.allcommon.cbean.outsidesql.OutsideSqlDao; -import jp.sf.pal.todolist.db.allcommon.cbean.outsidesql.OutsideSqlOption; -import jp.sf.pal.todolist.db.allcommon.dbmeta.DBMeta; -import jp.sf.pal.todolist.db.allcommon.dbmeta.DBMetaInstanceHandler; -import jp.sf.pal.todolist.db.allcommon.exception.EntityAlreadyUpdatedException; -import jp.sf.pal.todolist.db.allcommon.helper.stacktrace.InvokeNameExtractingResource; -import jp.sf.pal.todolist.db.allcommon.helper.stacktrace.InvokeNameResult; -import jp.sf.pal.todolist.db.allcommon.helper.stacktrace.impl.InvokeNameExtractorImpl; -import jp.sf.pal.todolist.db.allcommon.util.TraceViewUtil; - -import org.aopalliance.intercept.MethodInvocation; -import org.seasar.dao.DaoMetaData; -import org.seasar.dao.DaoMetaDataFactory; -import org.seasar.dao.NotSingleRowUpdatedRuntimeException; -import org.seasar.dao.SqlCommand; -import org.seasar.framework.beans.MethodNotFoundRuntimeException; - -/** - * The interceptor of S2Dao for DBFlute. - * - * @author DBFlute(AutoGenerator) - */ -public class S2DaoInterceptor extends - org.seasar.framework.aop.interceptors.AbstractInterceptor { - - //========================================================================== - // ========= - // Definition - // ========== - /** Serial version UID. (Default) */ - private static final long serialVersionUID = 1L; - - /** Log instance. */ - private static final org.apache.commons.logging.Log _log = org.apache.commons.logging.LogFactory - .getLog(S2DaoInterceptor.class); - - //========================================================================== - // ========= - // Attribute - // ========= - /** The factory of DAO meta data. */ - protected DaoMetaDataFactory _daoMetaDataFactory; - - //========================================================================== - // ========= - // Constructor - // =========== - /** - * Constructor. - * - * @param daoMetaDataFactory The factory of DAO meta data. (NotNull) - */ - public S2DaoInterceptor(DaoMetaDataFactory daoMetaDataFactory) { - _daoMetaDataFactory = daoMetaDataFactory; - } - - //========================================================================== - // ========= - // Execute Status Log - // ================== - protected void log(String msg) { - XLog.log(msg); - } - - protected boolean isLogEnabled() { - return XLog.isLogEnabled(); - } - - //========================================================================== - // ========= - // Invoke - // ====== - /** - * Invoke the method. - * - * @param invocation The method invocation. (NotNull) - * @return The result of the method. (Nullable) - * @throws Throwable - */ - public Object invoke(MethodInvocation invocation) throws Throwable { - clearThreadLocal(); - try { - return dispatchInvoking(invocation); - } finally { - clearThreadLocal(); - } - } - - /** - * Dispatch invoking the method. - * - * @param invocation The method invocation. (NotNull) - * @return The result of the method. (Nullable) - * @throws Throwable - */ - protected Object dispatchInvoking(MethodInvocation invocation) - throws Throwable { - final Method method = invocation.getMethod(); - if (!isAbstract(method)) { - return invocation.proceed(); - } - - // - - - - - - - - - - - - - - // Initialize DAO meta data - // - - - - - - - - - - - - - - if (method.getName().equals("initializeDaoMetaData")) { - initializeSqlCommand(invocation); - return null;// The end! (Initilization Only) - } - - // - - - - - - - - - - - - - // Preprocess outside-SQL - // - - - - - - - - - - - - - preprocessOutsideSql(invocation); - - // - - - - - - - - - - - - - - // Preprocess condition-bean - // - - - - - - - - - - - - - - final ConditionBean cb = preprocessConditionBean(invocation); - - // - - - - - - - - - - - // Set up SQL-command - // - - - - - - - - - - - final SqlCommand cmd; - try { - long beforeCmd = 0; - if (isLogEnabled()) { - beforeCmd = System.currentTimeMillis(); - } - cmd = findSqlCommand(invocation); - if (isLogEnabled()) { - final long afterCmd = System.currentTimeMillis(); - if (beforeCmd != afterCmd) { - logSqlCommand(invocation, cmd, beforeCmd, afterCmd); - } - } - } finally { - if (isLogEnabled()) { - logInvocation(invocation); - } - } - - long before = 0; - if (isLogEnabled()) { - before = System.currentTimeMillis(); - } - - // - - - - - - - - - - - // Execute SQL-command - // - - - - - - - - - - - Object ret = null; - try { - ret = cmd.execute(invocation.getArguments()); - } catch (Exception e) { - if (e.getClass().equals(NotSingleRowUpdatedRuntimeException.class)) { - throw new EntityAlreadyUpdatedException( - (NotSingleRowUpdatedRuntimeException) e); - } - throw e; - } finally { - postprocessConditionBean(invocation, cb); - } - final Class<?> retType = method.getReturnType(); - assertRetType(retType, ret); - - if (isLogEnabled()) { - final long after = System.currentTimeMillis(); - logReturn(invocation, retType, ret, before, after); - } - - // - - - - - - - - - - - // Convert and Return! - // - - - - - - - - - - - if (retType.isPrimitive()) { - return org.seasar.framework.util.NumberConversionUtil - .convertPrimitiveWrapper(retType, ret); - } else if (Number.class.isAssignableFrom(retType)) { - return org.seasar.framework.util.NumberConversionUtil - .convertNumber(retType, ret); - } else { - return ret; - } - } - - //========================================================================== - // ========= - // SqlCommand - // ========== - protected void initializeSqlCommand(MethodInvocation invocation) { - final Class<?> targetType = getTargetClass(invocation); - final DaoMetaData dmd = _daoMetaDataFactory.getDaoMetaData(targetType); - if (OutsideSqlDao.class.isAssignableFrom(targetType)) { - return;// Do nothing! - } else { - final Object[] arguments = invocation.getArguments(); - if (arguments != null && arguments.length > 0 - && arguments[0] instanceof String) { - final String methodName = (String) arguments[0]; - try { - dmd.getSqlCommand(methodName); - } catch (MethodNotFoundRuntimeException ignored) { - // Do nothing! - if (isLogEnabled()) { - log("Not Found the method: " + methodName + " msg=" - + ignored.getMessage()); - } - } - return; - } else { - String msg = "The method should have one string argument as method name: " - + invocation; - throw new IllegalStateException(msg); - } - } - } - - protected SqlCommand findSqlCommand(MethodInvocation invocation) { - final SqlCommand cmd; - final Class<?> targetType = getTargetClass(invocation); - final DaoMetaData dmd = _daoMetaDataFactory.getDaoMetaData(targetType); - if (OutsideSqlDao.class.isAssignableFrom(targetType)) { - cmd = dmd - .getSqlCommand(generateSpecifiedOutsideSqlUniqueKey(invocation)); - } else { - cmd = dmd.getSqlCommand(invocation.getMethod().getName()); - } - return cmd; - } - - protected String generateSpecifiedOutsideSqlUniqueKey( - MethodInvocation invocation) { - final Object[] args = invocation.getArguments(); - final String path = (String) args[0]; - final Object pmb = args[1]; - final OutsideSqlOption option = (OutsideSqlOption) args[2]; - Object resultTypeSpecification = null; - if (args.length > 3) { - resultTypeSpecification = args[3]; - } - return OutsideSqlContext.generateSpecifiedOutsideSqlUniqueKey( - invocation.getMethod().getName(), path, pmb, option, - resultTypeSpecification); - } - - //========================================================================== - // ========= - // Log Invocation - // ============== - protected void logInvocation(MethodInvocation invocation) { - final StackTraceElement[] stackTrace = new Exception().getStackTrace(); - final InvokeNameResult behaviorResult = extractBehaviorInvokeName(stackTrace); - - final String invokeClassName; - final String invokeMethodName; - if (!behaviorResult.isEmptyResult()) { - invokeClassName = behaviorResult.getSimpleClassName(); - invokeMethodName = behaviorResult.getMethodName(); - } else { - final Method method = invocation.getMethod(); - invokeClassName = extractInvocationExpression(method); - invokeMethodName = method.getName(); - } - final String expWithoutKakko = buildInvocationExpressionWithoutKakko( - invocation, invokeClassName, invokeMethodName); - - // Save behavior invoke name for error message. - putObjectToMapContext("df:BehaviorInvokeName", expWithoutKakko + "()"); - - final String equalBorder = buildFitBorder("", "=", expWithoutKakko, - false); - final String invocationExpression = expWithoutKakko + "()"; - - log("/=====================================================" - + equalBorder + "=="); - log(" " - + invocationExpression); - log(" " - + equalBorder + "=/"); - - logPath(invocation, stackTrace, behaviorResult); - - // Specified OutsideSql - if (isSpecifiedOutsideSql(invocation)) { - final OutsideSqlContext outsideSqlContext = getOutsideSqlContext(); - if (!outsideSqlContext.isProcedure()) {// [DBFlute-0.7.5] - Object[] args = invocation.getArguments(); - if (outsideSqlContext != null) { - log("path: " + outsideSqlContext.getOutsideSqlPath()); - } else { - log("path: " + getOutsideSqlPath(args)); - } - log("option: " + getOutsideSqlOption(args)); - } - } - } - - protected String buildInvocationExpressionWithoutKakko( - MethodInvocation invocation, String invokeClassName, - String invokeMethodName) { - if (invokeClassName.contains("OutsideSql") - && invokeClassName.endsWith("Executor")) { // OutsideSql - // Executor Handling - try { - final String originalName = invokeClassName; - if (isSpecifiedOutsideSql()) { - final OutsideSqlContext outsideSqlContext = getOutsideSqlContext(); - final String tableDbName = outsideSqlContext - .getTableDbName(); - final DBMeta dbmeta = DBMetaInstanceHandler - .findDBMeta(tableDbName); - final String behaviorTypeName = dbmeta - .getBehaviorTypeName(); - final String behaviorClassName = behaviorTypeName - .substring(behaviorTypeName.lastIndexOf(".") - + ".".length()); - invokeClassName = behaviorClassName + ".outsideSql()"; - if (originalName.endsWith("OutsideSqlEntityExecutor")) { - invokeClassName = invokeClassName + ".entityHandling()"; - } else if (originalName - .endsWith("OutsideSqlPagingExecutor")) { - if (outsideSqlContext.isOffsetByCursorForcedly() - || outsideSqlContext.isLimitByCursorForcedly()) { - invokeClassName = invokeClassName + ".autoPaging()"; - } else { - invokeClassName = invokeClassName - + ".manualPaging()"; - } - } else if (originalName - .endsWith("OutsideSqlCursorExecutor")) { - invokeClassName = invokeClassName + ".cursorHandling()"; - } - } else { - invokeClassName = "OutsideSql"; - } - } catch (RuntimeException ignored) { - log("Ignored exception occurred: msg=" + ignored.getMessage()); - } - } - String invocationExpressionWithoutKakko = invokeClassName + "." - + invokeMethodName; - if ("selectPage".equals(invokeMethodName)) { // Special Handling! - boolean resultTypeInteger = false; - if (isSpecifiedOutsideSql()) { - final OutsideSqlContext outsideSqlContext = getOutsideSqlContext(); - final Object resultTypeSpecification = outsideSqlContext - .getResultTypeSpecification(); - if (resultTypeSpecification != null - && resultTypeSpecification instanceof Class<?>) { - final Class<?> resultType = (Class<?>) resultTypeSpecification; - if (Integer.class.isAssignableFrom(resultType)) { - resultTypeInteger = true; - } - } - } - if (resultTypeInteger - || "selectCount".equals(invocation.getMethod().getName())) { - invocationExpressionWithoutKakko = invocationExpressionWithoutKakko - + "():count"; - } else { - invocationExpressionWithoutKakko = invocationExpressionWithoutKakko - + "():paging"; - } - } - return invocationExpressionWithoutKakko; - } - - protected void logPath(MethodInvocation invocation, - StackTraceElement[] stackTrace, InvokeNameResult behaviorResult) { - final int bhvNextIndex = behaviorResult.getNextStartIndex(); - final InvokeNameResult clientResult = extractClientInvokeName( - stackTrace, bhvNextIndex); - final int clientFirstIndex = clientResult.getFoundFirstIndex(); - final InvokeNameResult byPassResult = extractByPassInvokeName( - stackTrace, bhvNextIndex, clientFirstIndex - bhvNextIndex); - - final String clientInvokeName = clientResult.getInvokeName(); - final String byPassInvokeName = byPassResult.getInvokeName(); - final String behaviorInvokeName = behaviorResult.getInvokeName(); - if (clientInvokeName.trim().length() == 0 - && byPassInvokeName.trim().length() == 0) { - return; - } - - // Save client invoke name for error message. - if (!clientResult.isEmptyResult()) { - putObjectToMapContext("df:ClientInvokeName", clientInvokeName); - } - // Save by-pass invoke name for error message. - if (!byPassResult.isEmptyResult()) { - putObjectToMapContext("df:ByPassInvokeName", byPassInvokeName); - } - - log(clientInvokeName + byPassInvokeName + behaviorInvokeName + "..."); - } - - protected String buildFitBorder(String prefix, String element, - String lengthTargetString, boolean space) { - final int length = space ? lengthTargetString.length() / 2 - : lengthTargetString.length(); - final StringBuffer sb = new StringBuffer(); - sb.append(prefix); - for (int i = 0; i < length; i++) { - sb.append(element); - if (space) { - sb.append(" "); - } - } - if (space) { - sb.append(element); - } - return sb.toString(); - } - - protected InvokeNameResult extractClientInvokeName( - StackTraceElement[] stackTrace, final int startIndex) { - final List<String> suffixList = Arrays.asList(new String[] { "Page", - "Action" }); - final InvokeNameExtractingResource resource = new InvokeNameExtractingResource() { - public boolean isTargetElement(String className, String methodName) { - return isClassNameEndsWith(className, suffixList); - } - - public String filterSimpleClassName(String simpleClassName) { - return simpleClassName; - } - - public boolean isUseAdditionalInfo() { - return true; - } - - public int getStartIndex() { - return startIndex; - } - - public int getLoopSize() { - return 25; - } - }; - return extractInvokeName(resource, stackTrace); - } - - protected InvokeNameResult extractByPassInvokeName( - StackTraceElement[] stackTrace, final int startIndex, - final int loopSize) { - final List<String> suffixList = Arrays.asList(new String[] { "Service", - "ServiceImpl", "Facade", "FacadeImpl" }); - final InvokeNameExtractingResource resource = new InvokeNameExtractingResource() { - public boolean isTargetElement(String className, String methodName) { - return isClassNameEndsWith(className, suffixList); - } - - public String filterSimpleClassName(String simpleClassName) { - return simpleClassName; - } - - public boolean isUseAdditionalInfo() { - return true; - } - - public int getStartIndex() { - return startIndex; - } - - public int getLoopSize() { - return loopSize >= 0 ? loopSize : 25; - } - }; - return extractInvokeName(resource, stackTrace); - } - - protected InvokeNameResult extractBehaviorInvokeName( - StackTraceElement[] stackTrace) { - final List<String> suffixList = Arrays.asList(new String[] { "Bhv", - "BehaviorReadable", "BehaviorWritable", "PagingInvoker" }); - final List<String> keywordList = Arrays.asList(new String[] { "Bhv$", - "BehaviorReadable$", "BehaviorWritable$" }); - final List<String> ousideSql1List = Arrays - .asList(new String[] { "OutsideSql" }); - final List<String> ousideSql2List = Arrays - .asList(new String[] { "Executor" }); - final List<String> ousideSql3List = Arrays - .asList(new String[] { "Executor$" }); - final InvokeNameExtractingResource resource = new InvokeNameExtractingResource() { - public boolean isTargetElement(String className, String methodName) { - if (isClassNameEndsWith(className, suffixList)) { - return true; - } - if (isClassNameContains(className, keywordList)) { - return true; - } - if (isClassNameContains(className, ousideSql1List) - && (isClassNameEndsWith(className, ousideSql2List) || isClassNameContains( - className, ousideSql3List))) { - return true; - } - return false; - } - - public String filterSimpleClassName(String simpleClassName) { - return removeBasePrefixFromSimpleClassName(simpleClassName); - } - - public boolean isUseAdditionalInfo() { - return false; - } - - public int getStartIndex() { - return 0; - } - - public int getLoopSize() { - return 25; - } - }; - return extractInvokeName(resource, stackTrace); - } - - protected boolean isClassNameEndsWith(String className, - List<String> suffixList) { - for (String suffix : suffixList) { - if (className.endsWith(suffix)) { - return true; - } - } - return false; - } - - protected boolean isClassNameContains(String className, - List<String> keywordList) { - for (String keyword : keywordList) { - if (className.contains(keyword)) { - return true; - } - } - return false; - } - - /** - * @param resource the call-back resource for invoke-name-extracting. - * (NotNull) - * @param stackTrace Stack log. (NotNull) - * @return The result of invoke name. (NotNull: If not found, returns empty - * string.) - */ - protected InvokeNameResult extractInvokeName( - InvokeNameExtractingResource resource, - StackTraceElement[] stackTrace) { - final InvokeNameExtractorImpl extractor = new InvokeNameExtractorImpl(); - extractor.setStackTrace(stackTrace); - return extractor.extractInvokeName(resource); - } - - /** - * @param method The invoked method. (NotNull) - * @return The expression of invocation. (NotNull) - */ - protected String extractInvocationExpression(Method method) { - final Class<?> declaringClass = method.getDeclaringClass(); - return removeBasePrefixFromSimpleClassName(declaringClass - .getSimpleName()); - } - - /** - * @param simpleClassName The simple class name. (NotNull) - * @return The simple class name removed the base prefix. (NotNull) - */ - protected String removeBasePrefixFromSimpleClassName(String simpleClassName) { - if (!simpleClassName.startsWith("Bs")) { - return simpleClassName; - } - final int prefixLength = "Bs".length(); - if (!Character.isUpperCase(simpleClassName.substring(prefixLength) - .charAt(0))) { - return simpleClassName; - } - if (simpleClassName.length() <= prefixLength) { - return simpleClassName; - } - return "" + simpleClassName.substring(prefixLength); - } - - //========================================================================== - // ========= - // Log SqlCommand - // ============== - protected void logSqlCommand(MethodInvocation invocation, SqlCommand cmd, - long beforeCmd, long afterCmd) { - log("SqlCommand Initialization Cost: [" - + TraceViewUtil.convertToPerformanceView(afterCmd - beforeCmd) - + "]"); - } - - protected void assertRetType(Class<?> retType, Object ret) { - if (java.util.List.class.isAssignableFrom(retType)) { - if (ret != null && !(ret instanceof java.util.List)) { - String msg = "The retType is difference from actual return: "; - msg = msg + "retType=" + retType + " ret.getClass()=" - + ret.getClass() + " ref=" + ret; - throw new IllegalStateException(msg); - } - } else if (Entity.class.isAssignableFrom(retType)) { - if (ret != null && !(ret instanceof Entity)) { - String msg = "The retType is difference from actual return: "; - msg = msg + "retType=" + retType + " ret.getClass()=" - + ret.getClass() + " ref=" + ret; - throw new IllegalStateException(msg); - } - } - } - - //========================================================================== - // ========= - // Log Return - // ========== - protected void logReturn( - org.aopalliance.intercept.MethodInvocation invocation, - Class<?> retType, Object ret, long before, long after) - throws Throwable { - try { - final String daoResultPrefix = "===========/ [" - + TraceViewUtil.convertToPerformanceView(after - before) - + " - "; - if (java.util.List.class.isAssignableFrom(retType)) { - if (ret == null) { - log(daoResultPrefix + "Selected list: null]"); - } else { - final java.util.List<?> ls = (java.util.List<?>) ret; - if (ls.isEmpty()) { - log(daoResultPrefix + "Selected list: 0]"); - } else if (ls.size() == 1 && ls.get(0) instanceof Number) { - log(daoResultPrefix + "Selected count: " + ls.get(0) - + "]"); - } else { - log(daoResultPrefix + "Selected list: " + ls.size() - + " first=" + ls.get(0) + "]"); - } - } - } else if (Entity.class.isAssignableFrom(retType)) { - if (ret == null) { - log(daoResultPrefix + "Selected entity: null" + "]"); - } else { - final Entity entity = (Entity) ret; - log(daoResultPrefix + "Selected entity: " + entity + "]"); - } - } else if (Entity.class.isAssignableFrom(retType)) { - if (ret == null) { - log(daoResultPrefix + "Selected entity: null" + "]"); - } else { - final Entity entity = (Entity) ret; - log(daoResultPrefix + "Selected entity: " + entity + "]"); - } - } else if (int[].class.isAssignableFrom(retType)) { - if (ret == null) { - log(daoResultPrefix + "Selected entity: null" + "]"); - } else { - final int[] resultArray = (int[]) ret; - if (resultArray.length == 0) { - log(daoResultPrefix + "All updated count: 0]"); - } else { - final StringBuilder sb = new StringBuilder(); - boolean resultExpressionScope = true; - int resultCount = 0; - int loopCount = 0; - for (int element : resultArray) { - resultCount = resultCount + element; - if (resultExpressionScope) { - if (loopCount <= 10) { - if (sb.length() == 0) { - sb.append(element); - } else { - sb.append(",").append(element); - } - } else { - sb.append(",").append("..."); - resultExpressionScope = false; - } - } - ++loopCount; - } - sb.insert(0, "{").append("}"); - log(daoResultPrefix + "All updated count: " - + resultCount + " result=" + sb + "]"); - } - } - } else { - if (isSelectCountIgnoreFetchScopeMethod(invocation)) { - log(daoResultPrefix + "Selected count: " + ret + "]"); - } else { - log(daoResultPrefix + "Result: " + ret + "]"); - } - } - log(" "); - } catch (Exception e) { - String msg = "Result object debug threw the exception: methodName="; - msg = msg + invocation.getMethod().getName() + " retType=" - + retType; - msg = msg + " ret=" + ret; - _log.warn(msg, e); - throw e; - } - } - - //========================================================================== - // ========= - // Pre Post Process - // ================ - // ----------------------------------------------------- - // OutsideSql - // ---------- - protected void preprocessOutsideSql(MethodInvocation invocation) { - final Class<jp.sf.pal.todolist.db.allcommon.annotation.OutsideSql> outsideSqlType = jp.sf.pal.todolist.db.allcommon.annotation.OutsideSql.class; - final jp.sf.pal.todolist.db.allcommon.annotation.OutsideSql outsideSql = invocation - .getMethod().getAnnotation(outsideSqlType); - - // Traditional OutsideSql - if (outsideSql != null - && (outsideSql.dynamicBinding() || outsideSql.offsetByCursor() - || outsideSql.offsetByCursor() || outsideSql - .limitByCursor())) { - final OutsideSqlContext outsideSqlContext = new OutsideSqlContext(); - outsideSqlContext.setDynamicBinding(outsideSql.dynamicBinding()); - outsideSqlContext.setOffsetByCursorForcedly(outsideSql - .offsetByCursor()); - outsideSqlContext.setLimitByCursorForcedly(outsideSql - .limitByCursor()); - OutsideSqlContext.setOutsideSqlContextOnThread(outsideSqlContext); - - // Set up fetchNarrowingBean. - final Object[] args = invocation.getArguments(); - if (args == null || args.length == 0) { - return; - } - if (FetchNarrowingBeanContext.isTheTypeFetchNarrowingBean(args[0] - .getClass())) { - FetchNarrowingBeanContext - .setFetchNarrowingBeanOnThread((FetchNarrowingBean) args[0]); - } - return; - } - - // Specified OutsideSql - if (isSpecifiedOutsideSql(invocation)) { - if (isOutsideSqlDaoMethodSelect(invocation)) { - setupOutsideSqlContextSelect(invocation); - } else { - setupOutsideSqlContextExecute(invocation); - } - return; - } - } - - protected boolean isSpecifiedOutsideSql(MethodInvocation invocation) { - return OutsideSqlDao.class.isAssignableFrom(getTargetClass(invocation)); - } - - // - - - - - - - - - - - - - // Select - // - - - - protected boolean isOutsideSqlDaoMethodSelect(MethodInvocation invocation) { - return invocation.getMethod().getName().startsWith("select"); - } - - protected void setupOutsideSqlContextSelect(MethodInvocation invocation) { - final Object[] args = invocation.getArguments(); - if (args.length != 4) { - String msg = "Internal Error! OutsideSqlDao.selectXxx() should have 4 arguements: args.length=" - + args.length; - throw new IllegalStateException(msg); - } - final String path = getOutsideSqlPath(args); - final Object pmb = getOutsideSqlParameterBean(args); - final OutsideSqlOption option = getOutsideSqlOption(args); - final Object resultTypeSpecification = args[3]; - final OutsideSqlContext outsideSqlContext = new OutsideSqlContext(); - outsideSqlContext.setDynamicBinding(option.isDynamicBinding()); - outsideSqlContext.setOffsetByCursorForcedly(option.isAutoPaging()); - outsideSqlContext.setLimitByCursorForcedly(option.isAutoPaging()); - outsideSqlContext.setOutsideSqlPath(path); - outsideSqlContext.setParameterBean(pmb); - outsideSqlContext.setResultTypeSpecification(resultTypeSpecification); - outsideSqlContext.setMethodName(invocation.getMethod().getName()); - outsideSqlContext.setStatementConfig(option.getStatementConfig()); - outsideSqlContext.setTableDbName(option.getTableDbName()); - outsideSqlContext.setupBehaviorQueryPathIfNeeds(); - OutsideSqlContext.setOutsideSqlContextOnThread(outsideSqlContext); - - // Set up fetchNarrowingBean. - setupOutsideSqlFetchNarrowingBean(pmb, option); - } - - // - - - - - - - - - - - - - // Execute - // - - - - - protected void setupOutsideSqlContextExecute(MethodInvocation invocation) { - final Object[] args = invocation.getArguments(); - if (args.length != 3) { - String msg = "Internal Error! OutsideSqlDao.execute() should have 3 arguements: args.length=" - + args.length; - throw new IllegalStateException(msg); - } - final String path = getOutsideSqlPath(args); - final Object pmb = getOutsideSqlParameterBean(args); - final OutsideSqlOption option = getOutsideSqlOption(args); - final OutsideSqlContext outsideSqlContext = new OutsideSqlContext(); - outsideSqlContext.setDynamicBinding(option.isDynamicBinding()); - outsideSqlContext.setOffsetByCursorForcedly(option.isAutoPaging()); - outsideSqlContext.setLimitByCursorForcedly(option.isAutoPaging()); - outsideSqlContext.setOutsideSqlPath(path); - outsideSqlContext.setParameterBean(pmb); - outsideSqlContext.setMethodName(invocation.getMethod().getName()); - outsideSqlContext.setStatementConfig(option.getStatementConfig()); - outsideSqlContext.setTableDbName(option.getTableDbName()); - outsideSqlContext.setupBehaviorQueryPathIfNeeds(); - OutsideSqlContext.setOutsideSqlContextOnThread(outsideSqlContext); - - // Set up fetchNarrowingBean. - setupOutsideSqlFetchNarrowingBean(pmb, option); - } - - // - - - - - - - - - - - - - // Common - // - - - - protected String getOutsideSqlPath(Object[] args) { - return (String) args[0]; - } - - protected Object getOutsideSqlParameterBean(Object[] args) { - return args[1]; - } - - protected OutsideSqlOption getOutsideSqlOption(Object[] args) { - return (OutsideSqlOption) args[2]; - } - - protected void setupOutsideSqlFetchNarrowingBean(Object pmb, - OutsideSqlOption option) { - if (pmb == null - || !FetchNarrowingBeanContext.isTheTypeFetchNarrowingBean(pmb - .getClass())) { - return; - } - final FetchNarrowingBean fetchNarrowingBean = (FetchNarrowingBean) pmb; - if (option.isManualPaging()) { - fetchNarrowingBean.ignoreFetchNarrowing(); - } - FetchNarrowingBeanContext - .setFetchNarrowingBeanOnThread(fetchNarrowingBean); - } - - // ----------------------------------------------------- - // ConditionBean - // ------------- - /** - * Pre-process conditionBean. - * <p> - * If this method is condition bean select target, make dynamic SQL. Else - * nothing. - * - * @param invocation Method invocation. (NotNull) - * @return ConditionBean. (Nullable) - */ - protected ConditionBean preprocessConditionBean(MethodInvocation invocation) { - final OutsideSqlContext outsideSqlContext = getOutsideSqlContext(); - if (outsideSqlContext != null) { - return null; // Because it has already finished setting up - // fetchNarrowingBean for outsideSql here. - } - - final ConditionBean cb; - { - final Object[] args = invocation.getArguments(); - if (args == null || args.length == 0) { - return null; - } - final Object arg0 = args[0]; - if (arg0 == null) { - return null; - } - if (!ConditionBeanContext.isTheTypeConditionBean(arg0.getClass())) {// The - // argument - // is - // not - // condition - // - - // bean - // ... - if (FetchNarrowingBeanContext.isTheTypeFetchNarrowingBean(arg0 - .getClass()) - && !isSelectCountIgnoreFetchScopeMethod(invocation)) { - // Fetch-narrowing-bean and Not select count! - FetchNarrowingBeanContext - .setFetchNarrowingBeanOnThread((FetchNarrowingBean) arg0); - } - return null; - } - cb = (ConditionBean) arg0; - } - - if (isSelectCountIgnoreFetchScopeMethod(invocation)) { - cb.xsetupSelectCountIgnoreFetchScope(); - } else { - FetchNarrowingBeanContext.setFetchNarrowingBeanOnThread(cb); - } - - ConditionBeanContext.setConditionBeanOnThread(cb); - return cb; - } - - /** - * Post-process condition-bean. - * - * @param invocation Method invocation. (NotNull) - * @param cb Condition-bean. (Nullable) - */ - protected void postprocessConditionBean(MethodInvocation invocation, - ConditionBean cb) { - if (cb == null) { - return; - } - if (isSelectCountIgnoreFetchScopeMethod(invocation)) { - cb.xafterCareSelectCountIgnoreFetchScope(); - } - } - - // ----------------------------------------------------- - // Clear Thread Local - // ------------------ - protected void clearThreadLocal() { - if (OutsideSqlContext.isExistOutsideSqlContextOnThread()) { - OutsideSqlContext.clearOutsideSqlContextOnThread(); - } - if (FetchNarrowingBeanContext.isExistFetchNarrowingBeanOnThread()) { - // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // - - - - - - - - - - - - - - - - // Because there is possible that fetch narrowing has been ignored - // for manualPaging of outsideSql. - // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // - - - - - - - - - - - - - - - - FetchNarrowingBeanContext.getFetchNarrowingBeanOnThread() - .restoreIgnoredFetchNarrowing(); - - FetchNarrowingBeanContext.clearFetchNarrowingBeanOnThread(); - } - if (ConditionBeanContext.isExistConditionBeanOnThread()) { - ConditionBeanContext.clearConditionBeanOnThread(); - } - if (InternalMapContext.isExistInternalMapContextOnThread()) { - InternalMapContext.clearInternalMapContextOnThread(); - } - } - - //========================================================================== - // ========= - // Context Helper - // ============== - protected OutsideSqlContext getOutsideSqlContext() { - if (!OutsideSqlContext.isExistOutsideSqlContextOnThread()) { - return null; - } - return OutsideSqlContext.getOutsideSqlContextOnThread(); - } - - protected boolean isSpecifiedOutsideSql() { - final OutsideSqlContext outsideSqlContext = getOutsideSqlContext(); - return outsideSqlContext != null - && outsideSqlContext.isSpecifiedOutsideSql(); - } - - protected void putObjectToMapContext(String key, Object value) { - InternalMapContext.setObject(key, value); - } - - //========================================================================== - // ========= - // Determination - // ============= - /** - * Is select count ignore-fetch-scope method? - * - * @param invocation Method invocation. (NotNull) - * @return Determination. - */ - protected boolean isSelectCountIgnoreFetchScopeMethod( - MethodInvocation invocation) { - final String name = invocation.getMethod().getName(); - return name.startsWith("readCount") || name.startsWith("selectCount"); - } - - //========================================================================== - // ========= - // General Helper - // ============== - /** - * Is the method abstract? - * - * @param method Method. (NotNull) - * @return Determination. (NotNull) - */ - public boolean isAbstract(Method method) { - final int mod = method.getModifiers(); - return Modifier.isAbstract(mod); - } - - /** - * Get the value of line separator. - * - * @return The value of line separator. (NotNull) - */ - protected String getLineSeparator() { - return System.getProperty("line.separator"); - } -} \ No newline at end of file Deleted: todolist/trunk/src/main/java/jp/sf/pal/todolist/db/allcommon/s2dao/S2DaoLatestSqlProvider.java =================================================================== --- todolist/trunk/src/main/java/jp/sf/pal/todolist/db/allcommon/s2dao/S2DaoLatestSqlProvider.java 2008-12-27 22:21:53 UTC (rev 1633) +++ todolist/trunk/src/main/java/jp/sf/pal/todolist/db/allcommon/s2dao/S2DaoLatestSqlProvider.java 2008-12-27 22:22:08 UTC (rev 1634) @@ -1,20 +0,0 @@ -package jp.sf.pal.todolist.db.allcommon.s2dao; - -import jp.sf.pal.todolist.db.allcommon.jdbc.LatestSqlProvider; -import jp.sf.pal.todolist.db.allcommon.s2dao.internal.sqllog.InternalSqlLogRegistry; - -/** - * The provider of latest SQL as S2Dao. This instance should be singleton. - * - * @author DBFlute(AutoGenerator) - */ -public class S2DaoLatestSqlProvider implements LatestSqlProvider { - - public String getDisplaySql() { - return InternalSqlLogRegistry.peekCompleteSql(); - } - - public void clearSqlCache() { - InternalSqlLogRegistry.clearSqlLogRegistry(); - } -} Deleted: todolist/trunk/src/main/java/jp/sf/pal/todolist/db/allcommon/s2dao/S2DaoMetaDataExtension.java =================================================================== --- todolist/trunk/src/main/java/jp/sf/pal/todolist/db/allcommon/s2dao/S2DaoMetaDataExtension.java 2008-12-27 22:21:53 UTC (rev 1633) +++ todolist/trunk/src/main/java/jp/sf/pal/todolist/db/allcommon/s2dao/S2DaoMetaDataExtension.java 2008-12-27 22:22:08 UTC (rev 1634) @@ -1,1460 +0,0 @@ -package jp.sf.pal.todolist.db.allcommon.s2dao; - -import java.lang.reflect.Method; -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.Type; -import java.sql.Connection; -import java.sql.DatabaseMetaData; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.ArrayList; -import java.util.List; - -import javax.sql.DataSource; - -import jp.sf.pal.todolist.db.allcommon.BehaviorSelector; -import jp.sf.pal.todolist.db.allcommon.Entity; -import jp.sf.pal.todolist.db.allcommon.annotation.OutsideSql; -import jp.sf.pal.todolist.db.allcommon.cbean.ConditionBean; -import jp.sf.pal.todolist.db.allcommon.cbean.ConditionBeanContext; -import jp.sf.pal.todolist.db.allcommon.cbean.outsidesql.OutsideSqlContext; -import jp.sf.pal.todolist.db.allcommon.dbmeta.DBMeta; -import jp.sf.pal.todolist.db.allcommon.exception.BatchEntityAlreadyUpdatedException; -import jp.sf.pal.todolist.db.allcommon.exception.EntityAlreadyDeletedException; -import jp.sf.pal.todolist.db.allcommon.exception.EntityDuplicatedException; -import jp.sf.pal.todolist.db.allcommon.jdbc.CursorHandler; -import jp.sf.pal.todolist.db.allcommon.s2dao.internal.rshandler.InternalBeanArrayMetaDataResultSetHandler; -import jp.sf.pal.todolist.db.allcommon.s2dao.internal.rshandler.InternalBeanListMetaDataResultSetHandler; -import jp.sf.pal.todolist.db.allcommon.s2dao.internal.sqlcommand.InternalDeleteAutoStaticCommand; -import jp.sf.pal.todolist.db.allcommon.s2dao.internal.sqlcommand.InternalDeleteBatchAutoStaticCommand; -import jp.sf.pal.todolist.db.allcommon.s2dao.internal.sqlcommand.InternalDeleteQueryAutoDynamicCommand; -import jp.sf.pal.todolist.db.allcommon.s2dao.internal.sqlcommand.InternalInsertAutoDynamicCommand; -import jp.sf.pal.todolist.db.allcommon.s2dao.internal.sqlcommand.InternalInsertBatchAutoStaticCommand; -import jp.sf.pal.todolist.db.allcommon.s2dao.internal.sqlcommand.InternalProcedureCommand; -import jp.sf.pal.todolist.db.allcommon.s2dao.internal.sqlcommand.InternalUpdateAutoDynamicCommand; -import jp.sf.pal.todolist.db.allcommon.s2dao.internal.sqlcommand.InternalUpdateBatchAutoStaticCommand; -import jp.sf.pal.todolist.db.allcommon.s2dao.internal.sqlcommand.InternalUpdateDynamicCommand; -import jp.sf.pal.todolist.db.allcommon.s2dao.internal.sqlcommand.InternalUpdateModifiedOnlyCommand; -import jp.sf.pal.todolist.db.allcommon.s2dao.internal.sqlcommand.InternalUpdateQueryAutoDynamicCommand; -import jp.sf.pal.todolist.db.allcommon.s2dao.internal.sqlhandler.InternalDeleteBatchAutoHandler; -import jp.sf.pal.todolist.db.allcommon.s2dao.internal.sqlhandler.InternalUpdateBatchAutoHandler; -import jp.sf.pal.todolist.db.allcommon.s2dao.internal.sqlhandler.InternalBasicHandler.SQLExceptionHandler; -import jp.sf.pal.todolist.db.allcommon.s2dao.internal.various.InternalProcedureMetaData; -import jp.sf.pal.todolist.db.allcommon.s2dao.internal.various.InternalProcedureMetaDataFactory; -import jp.sf.pal.todolist.db.allcommon.s2dao.internal.various.InternalRelationRowCreator; -import jp.sf.pal.todolist.db.allcommon.s2dao.internal.various.InternalRowCreator; -import jp.sf.pal.todolist.db.allcommon.util.SimpleSystemUtil; - -import org.seasar.dao.BeanEnhancer; -import org.seasar.dao.BeanMetaData; -import org.seasar.dao.BeanMetaDataFactory; -import org.seasar.dao.ColumnNaming; -import org.seasar.dao.PropertyTypeFactoryBuilder; -import org.seasar.dao.RelationPropertyTypeFactoryBuilder; -import org.seasar.dao.RelationRowCreator; -import org.seasar.dao.RowCreator; -import org.seasar.dao.SqlCommand; -import org.seasar.dao.TableNaming; -import org.seasar.dao.dbms.DbmsManager; -import org.seasar.dao.impl.BeanMetaDataImpl; -import org.seasar.dao.impl.DaoMetaDataImpl; -import org.seasar.dao.impl.ResultSetHandlerFactoryImpl; -import org.seasar.dao.impl.SelectDynamicCommand; -import org.seasar.dao.impl.UpdateAutoStaticCommand; -import org.seasar.extension.jdbc.ResultSetHandler; -import org.seasar.extension.jdbc.StatementFactory; -import org.seasar.extension.jdbc.ValueType; -import org.seasar.extension.jdbc.types.ValueTypes; -import org.seasar.framework.beans.MethodNotFoundRuntimeException; -import org.seasar.framework.beans.factory.BeanDescFactory; -import org.seasar.framework.util.MethodUtil; - -/** - * The extension of DaoMetaDataImpl for DBFlute. - * - * @author DBFlute(AutoGenerator) - */ - @ SuppressWarnings("unchecked") -public class S2DaoMetaDataExtension extends DaoMetaDataImpl { - - //========================================================================== - // ========= - // Definition - // ========== - /** Log instance. */ - private static final org.apache.commons.logging.Log _log = org.apache.commons.logging.LogFactory - .getLog(S2DaoMetaDataExtension.class); - - //========================================================================== - // ========= - // Attribute - // ========= - /** Bean enhancer. */ - protected BeanEnhancer beanEnhancer; - - /** The factory of annotation reader. */ - protected org.seasar.dao.AnnotationReaderFactory annotationReaderFactory; - - /** The naming of column. {After S2Dao-1.0.47} */ - protected ColumnNaming columnNaming; - - /** The builder of property type factory. {After S2Dao-1.0.47} */ - protected PropertyTypeFactoryBuilder propertyTypeFactoryBuilder; - - /** The builder of relation property type factory. {After S2Dao-1.0.47} */ - protected RelationPropertyTypeFactoryBuilder relationPropertyTypeFactoryBuilder; - - /** The builder of table naming. {After S2Dao-1.0.47} */ - protected TableNaming tableNaming; - - // ----------------------------------------------------- - // DBFlute Extension - // ----------------- - /** The selector of behavior. {Since DBFlute-0.7.1} */ - protected BehaviorSelector _behaviorSelector; - - /** The lock monitor of method initialization. */ - protected Object _methodInitializationLockMonitor = new Object(); - - /** The determination of internal debug. {Since DBFlute-0.6.2} */ - protected boolean _internalDebug; - - //========================================================================== - // ========= - // Constructor - // =========== - public S2DaoMetaDataExtension() { - } - - //========================================================================== - // ========= - // Initialize Override - // =================== - @Override - public void initialize() { - beanClass = daoAnnotationReader.getBeanClass(); - daoInterface = getDaoInterface(daoClass); - daoBeanDesc = BeanDescFactory.getBeanDesc(daoClass); - final Connection conn = getConnection();// It is first impact to - // Database! - try { - final DatabaseMetaData dbMetaData = getMetaData(conn); - dbms = DbmsManager.getDbms(getDatabaseProductName(dbMetaData)); - } finally { - close(conn); - } - this.beanMetaData = beanMetaDataFactory.createBeanMetaData( - daoInterface, beanClass); - checkSingleRowUpdateForAll = daoAnnotationReader - .isCheckSingleRowUpdate(); - - // Comment out for lazy-load! - // setupSqlCommand(); - } - - //========================================================================== - // ========= - // SqlCommand Setup Override - // ========================= - @Override - public SqlCommand getSqlCommand(String methodName) - throws MethodNotFoundRuntimeException { - SqlCommand cmd = (SqlCommand) sqlCommands.get(methodName); - if (cmd != null) { - return cmd; - } - synchronized (_methodInitializationLockMonitor) { - cmd = (SqlCommand) sqlCommands.get(methodName); - if (cmd != null) { - if (_log.isDebugEnabled()) { - _log - .debug("...Getting sqlCommand as cache because the previous thread have already initilized."); - } - return cmd; - } - if (_log.isDebugEnabled()) { - _log.debug("...Initializing sqlCommand for " + methodName - + "()."); - } - cmd = initializeSqlCommand(methodName); - } - return cmd; - } - - protected SqlCommand initializeSqlCommand(String methodName) - throws MethodNotFoundRuntimeException { - if (OutsideSqlContext.isExistOutsideSqlContextOnThread()) { - final OutsideSqlContext outsideSqlContext = OutsideSqlContext - .getOutsideSqlContextOnThread(); - if (outsideSqlContext != null - && outsideSqlContext.isSpecifiedOutsideSql()) { - return initializeSpecifiedOutsideSqlCommand(methodName, - outsideSqlContext); - } - } - final Method[] methods = daoBeanDesc.getMethods(methodName); - if (methods.length == 1 && MethodUtil.isAbstract(methods[0])) { - setupMethod(methods[0]); - } - final SqlCommand cmd = (SqlCommand) sqlCommands.get(methodName); - if (cmd != null) { - return cmd; - } - throw new MethodNotFoundRuntimeException(daoClass, methodName, null); - } - - protected SqlCommand initializeSpecifiedOutsideSqlCommand( - String sqlCommandKey, OutsideSqlContext outsideSqlContext) - throws MethodNotFoundRuntimeException { - final Method[] methods = daoBeanDesc.getMethods(outsideSqlContext - .getMethodName());// By real method name. - if (methods.length == 1 - && org.seasar.framework.util.MethodUtil.isAbstract(methods[0])) { - final Method method = methods[0]; - if (isOutsideSqlDaoMethodSelect(method)) { - setupSpecifiedOutsideSqlSelectCommand(sqlCommandKey, method, - outsideSqlContext); - } else if (isOutsideSqlDaoMethodCall(method)) { - setupSpecifiedOutsideSqlCallCommand(sqlCommandKey, method, - outsideSqlContext); - } else { - setupSpecifiedOutsideSqlExecuteCommand(sqlCommandKey, method, - outsideSqlContext); - } - } - final SqlCommand cmd = (SqlCommand) sqlCommands.get(sqlCommandKey); - if (cmd != null) { - return cmd; - } - String msg = "Internal Error! The sql-command is not found:"; - msg = msg + " sqlCommandKey=" + sqlCommandKey; - msg = msg + " sqlCommands=" + sqlCommands; - throw new IllegalStateException(msg); - } - - protected boolean isOutsideSqlDaoMethodSelect(Method method) { - return method.getName().startsWith("select"); - } - - protected boolean isOutsideSqlDaoMethodCall(Method method) { - return method.getName().startsWith("call"); - } - - //========================================================================== - // ========= - // Assert Override - // =============== - @Override - protected void setupMethodByAnnotation(Class daoInterface, Method method) { - final String sql = daoAnnotationReader.getSQL(method, dbms.getSuffix()); - assertSQLAnnotationUnsupported(method, sql); - super.setupMethodByAnnotation(daoInterface, method); - } - - protected void assertSQLAnnotationUnsupported(final Method method, - String sql) { - if (sql != null) { - throwS2DaoSQLAnnotationUnsupportedException(method, sql); - } - } - - protected void throwS2DaoSQLAnnotationUnsupportedException( - final Method method, String sql) { - String msg = "Look! Read the message below." + getLineSeparator(); - msg = msg - + "/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *" - + getLineSeparator(); - msg = msg - + "Sorry, the SQL annotation of S2Dao is unsupported on DBFlute!" - + getLineSeparator(); - msg = msg + getLineSeparator(); - msg = msg + "[Advice]" + getLineSeparator(); - msg = msg + "Please use outside-sql of behavior." + getLineSeparator(); - msg = msg + " For example:" + getLineSeparator(); - msg = msg + " memberBhv.outsideSql().selectList(...)" - + getLineSeparator(); - msg = msg + getLineSeparator(); - msg = msg + "If you've got to use it, you can set the property:" - + getLineSeparator(); - msg = msg + "{torque.isCompatibleS2DaoSQLAnnotationValid = true}" - + getLineSeparator(); - msg = msg + "But pay attention to version up of DBFlute" - + getLineSeparator(); - msg = msg - + " because the property will not always supported at the future." - + getLineSeparator(); - msg = msg + getLineSeparator(); - msg = msg + "[Method]" + getLineSeparator() + method - + getLineSeparator(); - msg = msg + getLineSeparator(); - msg = msg + "[SQL]" + getLineSeparator() + sql + getLineSeparator(); - msg = msg + "* * * * * * * * * */"; - throw new UnsupportedOperationException(msg); - } - - @Override - protected void setupMethodByAuto(Method method) { - final OutsideSql outsideSql = method.getAnnotation(OutsideSql.class); - if (outsideSql != null) { - String msg = "This method '" + method.getName() - + "()' should use Outside Sql but the file was not found!"; - msg = msg + " Expected sql file name is '" - + method.getDeclaringClass().getSimpleName() + "_" - + method.getName() + ".sql'"; - throw new IllegalStateException(msg); - } - super.setupMethodByAuto(method); - } - - //========================================================================== - // ========= - // ConditionBean Override - // ====================== - @Override - protected void setupSelectMethodByAuto(final Method method) { - if (setupInternalSelectMethodSequenceNextVal(method)) { // For sequence - return; - } - if (setupInternalSelectMethodEntityByIdsForBuri(method)) { // For Buri - return; - } - - // Assert unsupported - final String query = daoAnnotationReader.getQuery(method); - assertQueryAnnotationUnsupported(method, query); - final String[] argNames = daoAnnotationReader.getArgNames(method); - assertAutoQueryByArgsAnnotationUnsupported(method, argNames); - - // Here it is the only method that the argument is DTO. - final ResultSetHandler handler = createResultSetHandler(method); - final SqlCommand cmd = setupInternalNonQuerySelectMethodByDto(method, - handler); - - putSqlCommand(method.getName(), cmd); - } - - protected boolean setupInternalSelectMethodSequenceNextVal( - final Method method) { // For sequence - if (!"selectNextVal".equals(method.getName())) { - return false; - } - final DBMeta dbmeta = findDBMeta(); - if (!dbmeta.hasSequence()) { - String msg = "If the method 'selectNextVal()' exists, DBMeta.hasSequence() should return true:"; - msg = msg + " dbmeta.hasSequence()=" + dbmeta.hasSequence() - + " method=" + method; - throw new IllegalStateException(msg); - } - final String nextValSql = dbmeta.getSequenceNextValSql(); - if (nextValSql == null) { - String msg = "If the method 'selectNextVal()' exists, DBMeta.getSequenceNextValSql() should not return null:"; - msg = msg + " dbmeta.getSequenceNextValSql()=" - + dbmeta.getSequenceNextValSql() + " method=" + method; - throw new IllegalStateException(msg); - } - setupSelectMethodByManual(method, nextValSql); - return true; - } - - protected boolean setupInternalSelectMethodEntityByIdsForBuri( - final Method method) { // For Buri - if (!"getEntityByIds".equals(method.getName())) { - return false; - } - final ResultSetHandler handler = createResultSetHandler(method); - final String[] argNames = daoAnnotationReader.getArgNames(method); - final String query = daoAnnotationReader.getQuery(method); - if (query == null) { - String msg = "The method 'getEntityByIds()' should have QUERY annotation:"; - msg = msg + " method=" + method; - throw new IllegalStateException(msg); - } - final Class[] types = method.getParameterTypes(); - final SelectDynamicCommand cmd = createSelectDynamicCommand(handler, - query); - cmd.setArgNames(argNames); - cmd.setArgTypes(types); - putSqlCommand(method.getName(), cmd); - return true; - } - - protected void assertQueryAnnotationUnsupported(final Method method, - String query) { - if (query != null) { - String msg = "Sorry! The QUERY annotation of S2Dao is unsupported on DBFlute:"; - msg = msg + " query=" + query + " method=" + method; - throw new UnsupportedOperationException(msg); - } - } - - protected void assertAutoQueryByArgsAnnotationUnsupported( - final Method method, String[] argNames) { - if (!isAutoSelectSqlByDto(method, argNames)) { - String msg = "Sorry! The auto query by ARGS annotation of S2Dao is unsupported on DBFlute:"; - msg = msg + " argNames=" + argNames + " method=" + method; - throw new UnsupportedOperationException(msg); - } - } - - // For condition-bean! - protected SqlCommand setupInternalNonQuerySelectMethodByDto(Method method, - ResultSetHandler handler) { - final Class[] argTypes = method.getParameterTypes(); - assertAutoQueryByDtoUnsupported(method, argTypes); - final S2DaoSelectDynamicCommand cmd = createCustomizeSelectDynamicCommand(handler); - cmd.setArgNames(new String[] { "dto" }); - cmd.setArgTypes(argTypes); - return cmd; - } - - protected void assertAutoQueryByDtoUnsupported(final Method method, - Class[] argTypes) { - final Class firstArgType = argTypes[0]; - if (!ConditionBeanContext.isTheTypeConditionBean(firstArgType)) { - String msg = "Sorry! The auto query by DTO of S2Dao is unsupported on DBFlute:"; - msg = msg + " dto=" + firstArgType + " method=" + method; - throw new UnsupportedOperationException(msg); - } - } - - //========================================================================== - // ========= - // Insert and Update and Delete By Auto Override - // ============================================= - // ----------------------------------------------------- - // Insert - // ------ - @Override - protected void setupInsertMethodByAuto(final Method method) { - checkAutoUpdateMethod(method); - final String[] propertyNames = getPersistentPropertyNames(method); - final SqlCommand command; - if (isUpdateSignatureForBean(method)) { - final InternalInsertAutoDynamicCommand cmd = new InternalInsertAutoDynamicCommand(); - cmd.setBeanMetaData(getBeanMetaData()); - cmd.setDataSource(dataSource); - - // It is unnecessary for DBFlute! - // cmd.setNotSingleRowUpdatedExceptionClass( - // getNotSingleRowUpdatedExceptionClass(method)); - - cmd.setPropertyNames(propertyNames); - cmd.setStatementFactory(statementFactory); - cmd.setCheckSingleRowUpdate(isCheckSingleRowUpdate(method)); - command = cmd; - } else { - boolean returningRows = false; - if (int[].class.isAssignableFrom(method.getReturnType())) { - returningRows = true; - } - final InternalInsertBatchAutoStaticCommand cmd = new InternalInsertBatchAutoStaticCommand( - dataSource, statementFactory, getBeanMetaData(), - propertyNames, returningRows); - command = cmd; - } - putSqlCommand(method.getName(), command); - } - - // ----------------------------------------------------- - // Update - // ------ - @Override - protected void setupUpdateMethodByAuto(final Method method) { - if (isFirstArgumentConditionBean(method)) { - final SqlCommand cmd = new InternalUpdateQueryAutoDynamicCommand( - dataSource, statementFactory); - putSqlCommand(method.getName(), cmd); - return; - } - checkAutoUpdateMethod(method); - final String[] propertyNames = getPersistentPropertyNames(method); - SqlCommand cmd; - if (isUpdateSignatureForBean(method)) { - if (isUnlessNull(method.getName())) { - cmd = createInternalUpdateAutoDynamicCommand(method, - propertyNames); - } else if (isModifiedOnly(method.getName())) { - cmd = createInternalUpdateModifiedOnlyCommand(method, - propertyNames); - } else { - cmd = createInternalUpdateAutoStaticCommand(method, - propertyNames); - } - } else { - boolean returningRows = false; - if (int[].class.isAssignableFrom(method.getReturnType())) { - returningRows = true; - } - cmd = createInternalUpdateBatchAutoStaticCommand(method, - propertyNames, returningRows); - } - putSqlCommand(method.getName(), cmd); - } - - protected UpdateAutoStaticCommand createInternalUpdateAutoStaticCommand( - final Method method, final String[] propertyNames) { - final UpdateAutoStaticCommand cmd = new UpdateAutoStaticCommand( - dataSource, statementFactory, beanMetaData, propertyNames); - cmd.setCheckSingleRowUpdate(isCheckSingleRowUpdate(method)); - return cmd; - } - - protected InternalUpdateAutoDynamicCommand createInternalUpdateAutoDynamicCommand( - Method method, String[] propertyNames) { - final InternalUpdateAutoDynamicCommand cmd = newUpdateAutoDynamicCommand( - method, dataSource, statementFactory); - cmd.setBeanMetaData(createBeanMetaData4UpdateDeleteByAuto(method));// Extension - // Point - // ! - cmd.setPropertyNames(propertyNames); - cmd.setCheckSingleRowUpdate(!isNonstrictMethod(method)); - - // It is unnecessary for DBFlute! - // cmd.setNotSingleRowUpdatedExceptionClass( - // getNotSingleRowUpdatedExceptionClass(method)); - - cmd - .setVersionNoAutoIncrementOnMemory(isUpdateVersionNoAutoIncrementOnMemory(method)); - return cmd; - } - - protected InternalUpdateAutoDynamicCommand newUpdateAutoDynamicCommand( - Method method, DataSource ds, StatementFactory sf) { - return new InternalUpdateAutoDynamicCommand(ds, sf); - } - - protected InternalUpdateModifiedOnlyCommand createInternalUpdateModifiedOnlyCommand( - final Method method, final String[] propertyNames) { - final InternalUpdateModifiedOnlyCommand cmd = newInternalUpdateModifiedOnlyCommand( - method, dataSource, statementFactory); - cmd.setBeanMetaData(createBeanMetaData4UpdateDeleteByAuto(method));// Extension - // Point - // ! - cmd.setPropertyNames(propertyNames); - cmd.setCheckSingleRowUpdate(!isNonstrictMethod(method)); - - // It is unnecessary for DBFlute! - // cmd.setNotSingleRowUpdatedExceptionClass( - // getNotSingleRowUpdatedExceptionClass(method)); - - cmd - .setVersionNoAutoIncrementOnMemory(isUpdateVersionNoAutoIncrementOnMemory(method)); - return cmd; - } - - protected InternalUpdateModifiedOnlyCommand newInternalUpdateModifiedOnlyCommand( - Method method, DataSource ds, StatementFactory sf) { - return new InternalUpdateModifiedOnlyCommand(ds, sf); - } - - protected InternalUpdateBatchAutoStaticCommand createInternalUpdateBatchAutoStaticCommand( - final Method method, final String[] propertyNames, - boolean returningRows) { - return new InternalUpdateBatchAutoStaticCommand(dataSource, - statementFactory, - createBeanMetaData4UpdateDeleteByAuto(method), propertyNames, - returningRows, isUpdateVersionNoAutoIncrementOnMemory(method)) { - @Override - protected InternalUpdateBatchAutoHandler newInternalBatchAutoHandler() { - return new InternalUpdateBatchAutoHandler(getDataSource(), - getStatementFactory(), getBeanMetaData(), - getPropertyTypes()) { - @Override - protected int[] executeBatch(PreparedStatement ps, - List<?> list) { - final int[] result = super.executeBatch(ps, list); - try { - handleBatchUpdateResultWithOptimisticLock(ps, list, - result, method); - } catch (SQLException e) { - handleSQLException(e, ps, false); - return null;// Unreachable! - } - return result; - } - }; - } - }; - } - - // ----------------------------------------------------- - // Delete - // ------ - @Override - protected void setupDeleteMethodByAuto(final Method method) { - if (isFirstArgumentConditionBean(method)) { - final SqlCommand cmd = new InternalDeleteQueryAutoDynamicCommand( - dataSource, statementFactory); - putSqlCommand(method.getName(), cmd); - return; - } - checkAutoUpdateMethod(method); - final String[] propertyNames = getPersistentPropertyNames(method); - final SqlCommand cmd; - if (isUpdateSignatureForBean(method)) { - cmd = createInternalDeleteAutoStaticCommand(method, propertyNames); - } else { - boolean returningRows = false; - if (int[].class.isAssignableFrom(method.getReturnType())) { - returningRows = true; - } - cmd = createInternalDeleteBatchAutoStaticCommand(method, - propertyNames, returningRows); - } - putSqlCommand(method.getName(), cmd); - } - - protected InternalDeleteAutoStaticCommand createInternalDeleteAutoStaticCommand( - final Method method, final String[] propertyNames) { - final InternalDeleteAutoStaticCommand cmd = new InternalDeleteAutoStaticCommand( - dataSource, statementFactory, - createBeanMetaData4UpdateDeleteByAuto(method), propertyNames); - cmd.setCheckSingleRowUpdate(!isNonstrictMethod(method)); - return cmd; - } - - protected InternalDeleteBatchAutoStaticCommand createInternalDeleteBatchAutoStaticCommand( - final Method method, final String[] propertyNames, - boolean returningRows) { - return new InternalDeleteBatchAutoStaticCommand(dataSource, - statementFactory, - createBeanMetaData4UpdateDeleteByAuto(method), propertyNames, - returningRows) { - @Override - protected InternalDeleteBatchAutoHandler newInternalBatchAutoHandler() { - return new InternalDeleteBatchAutoHandler(getDataSource(), - getStatementFactory(), getBeanMetaData(), - getPropertyTypes()) { - @Override - protected int[] executeBatch(PreparedStatement ps, - List<?> list) { - final int[] result = super.executeBatch(ps, list); - try { - handleBatchUpdateResultWithOptimisticLock(ps, list, - result, method); - } catch (SQLException e) { - handleSQLException(e, ps, false); - return null;// Unreachable! - } - return result; - } - }; - } - }; - } - - // ----------------------------------------------------- - // Common Helper - // ------------- - protected BeanMetaData createBeanMetaData4UpdateDeleteByAuto(Method method) { - if (isNonstrictMethod(method)) { - return createNonConcurrencyBmdFactory().createBeanMetaData( - getBeanClass()); - } else { - return getBeanMetaData(); - } - } - - protected boolean isUpdateVersionNoAutoIncrementOnMemory(Method method) { - return !isNonstrictMethod(method); - } - - protected boolean isNonstrictMethod(Method method) { - return method.getName().contains("Nonstrict"); - } - - protected BeanMetaDataFactory createNonConcurrencyBmdFactory() { - final S2BeanMetaDataFactoryImpl nonConcurrencyBmdFactory = new S2BeanMetaDataFactoryImpl() { - protected BeanMetaDataImpl createBeanMetaDataImpl() { - return new BeanMetaDataImpl() { - public boolean hasVersionNoPropertyType() { - return false; - } - - public boolean hasTimestampPropertyType() { - return false; - } - }; - } - }; - nonConcurrencyBmdFactory - .setAnnotationReaderFactory(this.annotationReaderFactory); - nonConcurrencyBmdFactory - .setPropertyTypeFactoryBuilder(this.propertyTypeFactoryBuilder); - nonConcurrencyBmdFactory - .setRelationPropertyTypeFactoryBuilder(this.relationPropertyTypeFactoryBuilder); - nonConcurrencyBmdFactory.setTableNaming(this.tableNaming); - nonConcurrencyBmdFactory.setDataSource(this.dataSource); - nonConcurrencyBmdFactory - .setDaoNamingConvention(this.daoNamingConvention); - nonConcurrencyBmdFactory.setBeanEnhancer(this.beanEnhancer); - return nonConcurrencyBmdFactory; - } - - protected boolean isFirstArgumentConditionBean(final Method method) { - final Class<?>[] pmbTypes = method.getParameterTypes(); - return pmbTypes.length > 0 - && ConditionBean.class.isAssignableFrom(pmbTypes[0]); - } - - protected void handleBatchUpdateResultWithOptimisticLock( - PreparedStatement ps, List<?> list, int[] result, Method method) - throws SQLException { - if (ConditionBeanContext.isOracle()) { - final int updateCount = ps.getUpdateCount(); - handleBatchUpdateResultWithOptimisticLockByUpdateCount(list, - updateCount, method); - } else { - handleBatchUpdateResultWithOptimisticLockByResult(list, result, - method); - } - } - - protected void handleBatchUpdateResultWithOptimisticLockByUpdateCount( - List<?> list, int updateCount, Method method) { - if (list.isEmpty()) { - return;// for Safety! - } - if (updateCount < 0) { - return;// for Safety! - } - final int entityCount = list.size(); - if (updateCount < entityCount) { - if (isNonstrictMethod(method)) { - String msg = "The entity have already deleted:"; - msg = msg + " updateCount=" + updateCount; - msg = msg + " entityCount=" + entityCount; - msg = msg + " allEntities=" + list; - throw new EntityAlreadyDeletedException(msg); - } else { - throw new BatchEntityAlreadyUpdatedException(list.get(0), 0, - updateCount); - } - } - } - - protected void handleBatchUpdateResultWithOptimisticLockByResult( - List<?> list, Object result, Method method) { - if (list.isEmpty()) { - return;// for Safety! - } - if (!(result instanceof int[])) { - return;// for Safety! - } - final int[] updatedCountArray = (int[]) result; - final int entityCount = list.size(); - int index = 0; - boolean alreadyUpdated = false; - for (int oneUpdateCount : updatedCountArray) { - if (entityCount <= index) { - break;// for Safety! - } - if (oneUpdateCount == 0) { - alreadyUpdated = true; - break; - } else if (oneUpdateCount > 1) { - String msg = "The entity updated two or more records in batch update:"; - msg = msg + " entity=" + list.get(index); - msg = msg + " updatedCount=" + oneUpdateCount; - msg = msg + " allEntities=" + list; - throw new EntityDuplicatedException(msg); - } - ++index; - } - if (alreadyUpdated) { - int updateCount = 0; - for (int oneUpdateCount : updatedCountArray) { - updateCount = updateCount + oneUpdateCount; - } - if (isNonstrictMethod(method)) { - String msg = "The entity have already deleted:"; - msg = msg + " entity=" + list.get(index); - msg = msg + " updateCount=" + updateCount; - msg = msg + " allEntities=" + list; - throw new EntityAlreadyDeletedException(msg); - } else { - throw new BatchEntityAlreadyUpdatedException(list.get(index), - 0, updateCount); - } - } - } - - //========================================================================== - // ========= - // OutsideSql Override - // =================== - // ----------------------------------------------------- - // Normal OutsideSql - // ----------------- - @Override - protected void setupSelectMethodByManual(Method method, String sql) { - final Class<?>[] pmbTypes = method.getParameterTypes(); - final String[] argNames = this.daoAnnotationReader.getArgNames(method); - final Class<?>[] argTypes; - if (pmbTypes != null - && pmbTypes.length > 0 - && CursorHandler.class - .isAssignableFrom(pmbTypes[pmbTypes.length - 1])) { - argTypes = new Class<?>[pmbTypes.length - 1]; - for (int i = 0; i < pmbTypes.length - 1; i++) { - argTypes[i] = pmbTypes[i]; - } - } else { - argTypes = pmbTypes; - } - final BeanMetaData myBeanMetaData = getOutsideSqlBeanMetaData(method); - registerSqlCommand(method.getName(), method, sql, argNames, argTypes, - myBeanMetaData); - } - - protected BeanMetaData getOutsideSqlBeanMetaData(Method method) { - final Class beanClass4SelectMethodByManual = getOutsideSqlDefaultBeanClass(method); - if (beanClass4SelectMethodByManual.equals(getBeanClass())) { - return getBeanMetaData(); - } - return createOutsideSqlCustomizeBeanMetaDataFactory() - .createBeanMetaData(getOutsideSqlDefaultBeanClass(method)); - } - - @Override - protected void setupUpdateMethodByManual(Method method, final String sql) { - // DBFlute Extesion does not exist. Because DBFlute methods don't use - // this! - // The insert/update/delete methods on DAO interface as outside SQL are - // target. - // And especially NonPrimaryInsertMethod uses this for using S2Dao's - // BindVariableNode. - super.setupUpdateMethodByManual(method, sql); - } - - // ----------------------------------------------------- - // Specified OutsideSql - // -------------------- - // - - - - - - - - - - - - - // Select - // - - - - protected void setupSpecifiedOutsideSqlSelectCommand(String sqlCommandKey, - Method method, OutsideSqlContext outsideSqlContext) { - // - - - - - - - - - - - - - - - - - - - - - - - - // The attribute of Specified-OutsideSqlContext. - // - - - - - - - - - - - - - - - - - - - - - - - - final String sql = outsideSqlContext.readFilteredOutsideSql( - getSqlFileEncoding(), dbms.getSuffix()); - final Object pmb = outsideSqlContext.getParameterBean(); - final Object resultTypeSpecification = outsideSqlContext - .getResultTypeSpecification(); - - // - - - - - - - - - - - - - - - - // The attribute of SqlCommand. - // - - - - - - - - - - - - - - - - final String[] argNames = (pmb != null ? new String[] { "pmb" } - : new String[] {}); - final Class<?>[] argTypes = (pmb != null ? new Class<?>[] { pmb - .getClass() } : new Class<?>[] {}); - - // - - - - - - - - - - - - - - - - - // Create customized BeanMetaData. - // - - - - - - - - - - - - - - - - - final Class<?> lastestArguementType = method.getParameterTypes()[method - .getParameterTypes().length - 1]; - final ResultSetHandler myResultSetHandler; - if (Class.class.isAssignableFrom(lastestArguementType)) { - // - - - - - - - - - // EntityHandling - // - - - - - - - - - final Class<?> customizeEntityType = (Class<?>) resultTypeSpecification; - final BeanMetaData myBeanMetaData = createSpecifiedOutsideSqlCustomizeBeanMetaData(customizeEntityType); - if (List.class.isAssignableFrom(method.getReturnType())) { - myResultSetHandler = createSpecifiedOutsideSqlCustomizeBeanListResultSetHandler( - myBeanMetaData, customizeEntityType); - } else { - throw new UnsupportedOperationException( - "The return type of method is unsupported: method.getReturnType()=" - + method.getReturnType()); - // myResultSetHandler = - // createSpecifiedOutsideSqlCustomizeBeanResultSetHandler - // (myBeanMetaData, customizeEntityType); - } - } else if (CursorHandler.class.isAssignableFrom(lastestArguementType)) { - // - - - - - - - - - // CursorHandling - // - - - - - - - - - final BeanMetaData myBeanMetaData = createSpecifiedOutsideSqlCursorBeanMetaData(method); - myResultSetHandler = createSpecifiedOutsideSqlCursorResultSetHandler(myBeanMetaData); - } else { - String msg = "The lastestArguementType is unsupported:"; - msg = msg + " lastestArguementType=" + lastestArguementType; - msg = msg + " method=" + method; - throw new IllegalStateException(msg); - } - - // - - - - - - - - - - - - // Register Sql-Command. - // - - - - - - - - - - - - registerSqlCommand(sqlCommandKey, method, sql, argNames, argTypes, - myResultSetHandler); - } - - protected BeanMetaData createSpecifiedOutsideSqlCustomizeBeanMetaData( - Class clazz) { - return createOutsideSqlCustomizeBeanMetaDataFactory() - .createBeanMetaData(clazz); - } - - /** - * Create the handler of result set of specified outside-sql for the list of - * customize bean. - * - * @param specifiedBeanMetaData Specified bean meta data. (NotNull) - * @param customizeEntityType The type of customize entity. (NotNull) - * @return The handler of result set. (NotNull) - */ - protected ResultSetHandler createSpecifiedOutsideSqlCustomizeBeanListResultSetHandler( - BeanMetaData specifiedBeanMetaData, Class<?> customizeEntityType) { - final ValueType valueType = ValueTypes - .getValueType(customizeEntityType); - if (valueType == null || !valueType.equals(ValueTypes.OBJECT)) { - return new InternalObjectListResultSetHandler(valueType); - } - final InternalRowCreator rowCreator = createSpecifiedOutsideSqlInternalRowCreator(specifiedBeanMetaData); - final InternalRelationRowCreator relationRowCreator = createSpecifiedOutsideSqlInternalRelationRowCreator(specifiedBeanMetaData); - return new InternalBeanListMetaDataResultSetHandler( - specifiedBeanMetaData, rowCreator, relationRowCreator); - } - - protected InternalRowCreator createSpecifiedOutsideSqlInternalRowCreator( - BeanMetaData bmd) { - final Class clazz = bmd.getBeanClass(); - return InternalRowCreator.createInternalRowCreator(clazz); - } - - protected InternalRelationRowCreator createSpecifiedOutsideSqlInternalRelationRowCreator( - BeanMetaData bmd) { - return new InternalRelationRowCreator(); - } - - protected class InternalObjectListResultSetHandler implements - ResultSetHandler { - private ValueType valueType; - - public InternalObjectListResultSetHandler(ValueType valueType) { - this.valueType = valueType; - } - - public Object handle(ResultSet rs) throws SQLException { - final List<Object> ret = new ArrayList<Object>(); - while (rs.next()) { - ret.add(valueType.getValue(rs, 1)); - } - return ret; - } - } - - protected BeanMetaData createSpecifiedOutsideSqlCursorBeanMetaData( - Method method) { - return createOutsideSqlCustomizeBeanMetaDataFactory() - .createBeanMetaData(getOutsideSqlDefaultBeanClass(method)); - } - - protected ResultSetHandler createSpecifiedOutsideSqlCursorResultSetHandler( - BeanMetaData specifiedBeanMetaData) { - return new org.seasar.extension.jdbc.impl.ObjectResultSetHandler();// This - // is - // dummy - // for - // cursor - // handling - // ! - } - - // - - - - - - - - - - - - - // Execute - // - - - - - protected void setupSpecifiedOutsideSqlExecuteCommand(String sqlCommandKey, - Method method, OutsideSqlContext outsideSqlContext) { - // - - - - - - - - - - - - - - - - - - - - - - - - // The attribute of Specified-OutsideSqlContext. - // - - - - - - - - - - - - - - - - - - - - - - - - final String sql = outsideSqlContext.readFilteredOutsideSql( - getSqlFileEncoding(), dbms.getSuffix()); - final Object pmb = outsideSqlContext.getParameterBean(); - - // - - - - - - - - - - - - - - - - // The attribute of SqlCommand. - // - - - - - - - - - - - - - - - - final String[] argNames = (pmb != null ? new String[] { "pmb" } - : new String[] {}); - final Class<?>[] argTypes = (pmb != null ? new Class<?>[] { pmb - .getClass() } : new Class<?>[] {}); - - final InternalUpdateDynamicCommand cmd = new InternalUpdateDynamicCommand( - dataSource, statementFactory) { - @Override - public Object execute(Object[] args) { - if (args.length != 3) { - String msg = "Internal Error! OutsideSqlDao.execute() should have 3 arguements: args.length=" - + args.length; - throw new IllegalStateException(msg); - } - Object arg = args[1]; - return super.execute(new Object[] { arg }); - } - }; - - // It is unnecessary for DBFlute! - // cmd.setNotSingleRowUpdatedExceptionClass( - // getNotSingleRowUpdatedExceptionClass(method)); - - registerSqlCommand(sqlCommandKey, method, sql, argNames, argTypes, cmd); - } - - // - - - - - - - - - - - - - // Call Procedure - // - - - - - - - - protected void setupSpecifiedOutsideSqlCallCommand(String sqlCommandKey, - Method method, OutsideSqlContext outsideSqlContext) { - // - - - - - - - - - - - - - - - - - - - - - - - - // The attribute of Specified-OutsideSqlContext. - // - - - - - - - - - - - - - - - - - - - - - - - - final Object pmb = outsideSqlContext.getParameterBean(); - final String procedureName = outsideSqlContext.getOutsideSqlPath(); - - // - - - - - - - - - - - - - - - - // The attribute of SqlCommand. - // - - - - - - - - - - - - - - - - final InternalProcedureMetaDataFactory factory = createInternalProcedureMetaDataFactory(); - factory.setValueTypeFactory(valueTypeFactory); - final Class<?> pmbType = pmb != null ? pmb.getClass() : null; - final InternalProcedureMetaData metaData = factory - .createProcedureMetaData(procedureName, pmbType); - final InternalProcedureCommand cmd = createInternalProcedureCommand( - method, metaData); - putSqlCommand(sqlCommandKey, cmd); - } - - protected InternalProcedureMetaDataFactory createInternalProcedureMetaDataFactory() { - return new InternalProcedureMetaDataFactory(); - } - - protected InternalProcedureCommand createInternalProcedureCommand( - Method method, InternalProcedureMetaData metaData) { - final ResultSetHandler resultSetHandler = createResultSetHandler(method); - return new InternalProcedureCommand(dataSource, resultSetHandler, - statementFactory, metaData); - } - - // ----------------------------------------------------- - // Common of OutsideSql - // -------------------- - protected BeanMetaDataFactory createOutsideSqlCustomizeBeanMetaDataFactory() { - final S2BeanMetaDataFactoryImpl originalBmdFactory = new S2BeanMetaDataFactoryImpl() { - protected BeanMetaDataImpl createBeanMetaDataImpl() { - return newOutsideSqlCustomizeBeanMetaDataImpl(); - } - }; - originalBmdFactory - .setAnnotationReaderFactory(this.annotationReaderFactory); - originalBmdFactory - .setPropertyTypeFactoryBuilder(createOutsideSqlPropertyTypeFactoryBuilder()); - originalBmdFactory - .setRelationPropertyTypeFactoryBuilder(this.relationPropertyTypeFactoryBuilder); - originalBmdFactory.setTableNaming(this.tableNaming); - originalBmdFactory.setDataSource(this.dataSource); - originalBmdFactory.setDaoNamingConvention(this.daoNamingConvention); - originalBmdFactory.setBeanEnhancer(this.beanEnhancer); - return originalBmdFactory; - } - - protected BeanMetaDataImpl newOutsideSqlCustomizeBeanMetaDataImpl() { - return new OutsideSqlCustomizeBeanMetaDataImpl(); - } - - protected static class OutsideSqlCustomizeBeanMetaDataImpl extends - BeanMetaDataImpl { - // Though nothing to override, it uses original class just in case. - } - - protected S2DaoPropertyTypeFactoryBuilderExtension createOutsideSqlPropertyTypeFactoryBuilder() { - final S2DaoPropertyTypeFactoryBuilderExtension impl = new S2DaoPropertyTypeFactoryBuilderExtension(); - if (columnNaming == null) { - String msg = "Internal Error! The columnNaming should not be null! {Failed to Injection!}"; - throw new IllegalStateException(msg); - } - impl.setColumnNaming(columnNaming); - impl.setValueTypeFactory(valueTypeFactory); - return impl; - } - - protected Class getOutsideSqlDefaultBeanClass(Method method) { - final Class retType = method.getReturnType(); - if (java.util.List.class.isAssignableFrom(retType)) { - final Class elementType = InternalMethodUtil - .getElementTypeOfListFromReturnMethod(method); - if (elementType != null) { - return elementType; - } else { - return getBeanClass(); - } - } else if (retType.isArray()) { - return retType.getComponentType(); - } else if (retType.isPrimitive() - || !ValueTypes.getValueType(retType).equals(ValueTypes.OBJECT)) { - return getBeanClass(); - } else { - return retType; - } - } - - protected void registerSqlCommand(String sqlCommandKey, Method method, - String sql, String[] argNames, Class[] argTypes, - BeanMetaData myBeanMetaData) { - registerSqlCommand(sqlCommandKey, method, sql, argNames, argTypes, - createResultSetHandler(myBeanMetaData, method)); - } - - protected void registerSqlCommand(String sqlCommandKey, Method method, - String sql, String[] argNames, Class[] argTypes, - ResultSetHandler myResultSetHandler) { - final S2DaoSelectDynamicCommand cmd = createCustomizeSelectDynamicCommand(myResultSetHandler); - registerSqlCommand(sqlCommandKey, method, sql, argNames, argTypes, cmd); - } - - protected void registerSqlCommand(String sqlCommandKey, Method method, - String sql, String[] argNames, Class[] argTypes, - S2DaoSelectDynamicCommand cmd) { - cmd.setSql(sql); - cmd.setArgNames(argNames); - cmd.setArgTypes(argTypes); - this.sqlCommands.put(sqlCommandKey, cmd); - } - - protected void registerSqlCommand(String sqlCommandKey, Method method, - String sql, String[] argNames, Class[] argTypes, - InternalUpdateDynamicCommand cmd) { - cmd.setSql(sql); - cmd.setArgNames(argNames); - cmd.setArgTypes(argTypes); - this.sqlCommands.put(sqlCommandKey, cmd); - } - - //========================================================================== - // ========= - // Common Handlnig - // =============== - @Override - protected void putSqlCommand(String methodName, SqlCommand cmd) { - sqlCommands.put(methodName, cmd); - } - - protected boolean isCheckSingleRowUpdate(Method method) { - return checkSingleRowUpdateForAll - & daoAnnotationReader.isCheckSingleRowUpdate(method); - } - - //========================================================================== - // ========= - // Customize SelectDynamicCommand Creation - // ======================================= - /** - * Create the customize select dynamic command that is for all select SQL on - * DBFlute. - * - * @param handler The handler of result set. (NotNull) - * @return The customize select dynamic command. (NotNull) - */ - protected S2DaoSelectDynamicCommand createCustomizeSelectDynamicCommand( - ResultSetHandler handler) { - return new S2DaoSelectDynamicCommand(dataSource, statementFactory, - handler); - } - - //========================================================================== - // ========= - // ResultSetHandler Override - // ========================= - @Override - protected ResultSetHandler createResultSetHandler(Method method) { - return this.resultSetHandlerFactory.getResultSetHandler( - daoAnnotationReader, beanMetaData, method); - } - - protected ResultSetHandler createResultSetHandler( - BeanMetaData specifiedBeanMetaData, Method method) {// For specified - // BeanMetaData - return this.resultSetHandlerFactory.getResultSetHandler( - daoAnnotationReader, specifiedBeanMetaData, method); - } - - //========================================================================== - // ========= - // JDBC Delegator - // ============== - protected Connection getConnection() { - if (dataSource == null) { - throw new IllegalStateException( - "The dataSource should not be null!"); - } - try { - return dataSource.getConnection(); - } catch (SQLException e) { - handleSQLException(e, null); - return null;// Unreachable! - } - } - - protected DatabaseMetaData getMetaData(Connection conn) { - try { - return conn.getMetaData(); - } catch (SQLException e) { - handleSQLException(e, null); - return null;// Unreachable! - } - } - - protected String getDatabaseProductName(DatabaseMetaData dbMetaData) { - try { - return dbMetaData.getDatabaseProductName(); - } catch (SQLException e) { - handleSQLException(e, null); - return null;// Unreachable! - } - } - - protected void close(Connection conn) { - if (conn == null) { - return; - } - try { - conn.close(); - } catch (SQLException e) { - handleSQLException(e, null); - } - } - - //========================================================================== - // ========= - // Exception Handlnig - // ================== - protected void handleSQLException(SQLException e, Statement statement) { - new SQLExceptionHandler().handleSQLException(e, statement); - } - - //========================================================================== - // ========= - // ResultSetHandlerFactoryImpl Extension - // ===================================== - public static class ResultSetHandlerFactoryExtension extends - ResultSetHandlerFactoryImpl { - public ResultSetHandlerFactoryExtension() { - super(); - } - - @Override - protected RowCreator createRowCreator() { // [DAO-118] (2007/08/25) - return createInternalRowCreator(null); - } - - @Override - protected RelationRowCreator createRelationRowCreator() { - return createInternalRelationRowCreator(null); - } - - @Override - protected ResultSetHandler createBeanListMetaDataResultSetHandler( - BeanMetaData bmd) { // DBFlute Target - final InternalRowCreator rowCreator = createInternalRowCreator(bmd); - final InternalRelationRowCreator relationRowCreator = createInternalRelationRowCreator(bmd); - return new InternalBeanListMetaDataResultSetHandler(bmd, - rowCreator, relationRowCreator); - } - - @Override - protected ResultSetHandler createBeanArrayMetaDataResultSetHandler( - BeanMetaData bmd) { // DBFlute Target - final InternalRowCreator rowCreator = createInternalRowCreator(bmd); - final InternalRelationRowCreator relationRowCreator = createInternalRelationRowCreator(bmd); - return new InternalBeanArrayMetaDataResultSetHandler(bmd, - rowCreator, relationRowCreator); - } - - protected InternalRowCreator createInternalRowCreator(BeanMetaData bmd) { - final Class<?> clazz = bmd != null ? bmd.getBeanClass() : null; - return InternalRowCreator.createInternalRowCreator(clazz); - } - - protected InternalRelationRowCreator createInternalRelationRowCreator( - BeanMetaData bmd) { - return new InternalRelationRowCreator(); // Not yet implemented - // about performance - // tuning! - } - } - - //========================================================================== - // ========= - // Vert Internal - // ============= - protected static class InternalMethodUtil { - public static Class getElementTypeOfListFromReturnMethod(Method method) { - return InternalReflectionUtil - .getElementTypeOfListFromReturnType(method); - } - } - - protected static class InternalReflectionUtil { - public static Class<?> getElementTypeOfList(final Type parameterizedList) { - if (!(parameterizedList instanceof ParameterizedType)) { - return null; - } - final ParameterizedType parameterizedType = ParameterizedType.class - .cast(parameterizedList); - final Type rawType = parameterizedType.getRawType(); - if (!(rawType instanceof Class)) { - return null; - } - final Class<?> rawClass = Class.class.cast(rawType); - if (!rawClass.isAssignableFrom(List.class)) { - return null; - } - final Type[] actualTypeArgument = parameterizedType - .getActualTypeArguments(); - if (actualTypeArgument == null || actualTypeArgument.length != 1) { - return null; - } - if (!(actualTypeArgument[0] instanceof Class)) { - return null; - } - return Class.class.cast(actualTypeArgument[0]); - } - - public static Class<?> getElementTypeOfListFromParameterType( - final Method method, final int parameterPosition) { - final Type[] pmbTypes = method.getGenericParameterTypes(); - return getElementTypeOfList(pmbTypes[parameterPosition]); - } - - public static Class<?> getElementTypeOfListFromReturnType( - final Method method) { - return getElementTypeOfList(method.getGenericReturnType()); - } - } - - //========================================================================== - // ========= - // Assist Helper - // ============= - protected DBMeta findDBMeta() { - final Class<?> beanType = getBeanClass(); - if (beanType == null) { - return null; - } - if (!Entity.class.isAssignableFrom(beanType)) { - return null; - } - final Entity entity; - try { - entity = (Entity) beanType.newInstance(); - } catch (InstantiationException e) { - throw new IllegalStateException(e); - } catch (IllegalAccessException e) { - throw new IllegalStateException(e); - } - return entity.getDBMeta(); - } - - //========================================================================== - // ========= - // General Helper - // ============== - protected String getLineSeparator() { - return SimpleSystemUtil.getLineSeparator(); - } - - //========================================================================== - // ========= - // Accessor - // ======== - // ----------------------------------------------------- - // Sql File Encoding - // ----------------- - public String getSqlFileEncoding() { - return sqlFileEncoding; - } - - // ----------------------------------------------------- - // Bean Enhancer - // ------------- - public BeanEnhancer getBeanEnhancer() { - return beanEnhancer; - } - - public void setBeanEnhancer(final BeanEnhancer beanEnhancer) { - this.beanEnhancer = beanEnhancer; - } - - // ----------------------------------------------------- - // Annotation Reader Factory - // ------------------------- - public void setAnnotationReaderFactory( - org.seasar.dao.AnnotationReaderFactory annotationReaderFactory) { - this.annotationReaderFactory = annotationReaderFactory; - } - - // ----------------------------------------------------- - // Version After 1.0.47 - // -------------------- - public ColumnNaming getColumnNaming() { - return columnNaming; - } - - public void setColumnNaming(final ColumnNaming columnNaming) { - this.columnNaming = columnNaming; - } - - public PropertyTypeFactoryBuilder getPropertyTypeFactoryBuilder() { - return propertyTypeFactoryBuilder; - } - - public void setPropertyTypeFactoryBuilder( - final PropertyTypeFactoryBuilder propertyTypeFactoryBuilder) { - this.propertyTypeFactoryBuilder = propertyTypeFactoryBuilder; - } - - public RelationPropertyTypeFactoryBuilder getRelationPropertyTypeFactoryBuilder() { - return relationPropertyTypeFactoryBuilder; - } - - public void setRelationPropertyTypeFactoryBuilder( - final RelationPropertyTypeFactoryBuilder relationPropertyTypeFactoryBuilder) { - this.relationPropertyTypeFactoryBuilder = relationPropertyTypeFactoryBuilder; - } - - public TableNaming getTableNaming() { - return tableNaming; - } - - public void setTableNaming(final TableNaming tableNaming) { - this.tableNaming = tableNaming; - } - - // ----------------------------------------------------- - // DBFlute Extension - // ----------------- - public BehaviorSelector getBehaviorSelector() { - return _behaviorSelector; - } - - public void setBehaviorSelector(final BehaviorSelector behaviorSelector) { - this._behaviorSelector = behaviorSelector; - } - - public boolean isInternalDebug() { - return _internalDebug; - } - - public void setInternalDebug(final boolean internalDebug) { - this._internalDebug = internalDebug; - } -} Deleted: todolist/trunk/src/main/java/jp/sf/pal/todolist/db/allcommon/s2dao/S2DaoMetaDataFactoryImpl.java =================================================================== --- todolist/trunk/src/main/java/jp/sf/pal/todolist/db/allcommon/s2dao/S2DaoMetaDataFactoryImpl.java 2008-12-27 22:21:53 UTC (rev 1633) +++ todolist/trunk/src/main/java/jp/sf/pal/todolist/db/allcommon/s2dao/S2DaoMetaDataFactoryImpl.java 2008-12-27 22:22:08 UTC (rev 1634) @@ -1,655 +0,0 @@ -package jp.sf.pal.todolist.db.allcommon.s2dao; - -import java.sql.CallableStatement; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.HashMap; -import java.util.Map; - -import javax.sql.DataSource; -import javax.sql.XADataSource; - -import jp.sf.pal.todolist.db.allcommon.DBFluteConfig; -import jp.sf.pal.todolist.db.allcommon.cbean.ConditionBean; -import jp.sf.pal.todolist.db.allcommon.cbean.ConditionBeanContext; -import jp.sf.pal.todolist.db.allcommon.cbean.outsidesql.OutsideSqlContext; -import jp.sf.pal.todolist.db.allcommon.jdbc.StatementConfig; -import jp.sf.pal.todolist.db.allcommon.s2dao.internal.sqlhandler.InternalBasicHandler.SQLExceptionHandler; -import jp.sf.pal.todolist.db.allcommon.s2dao.internal.sqllog.InternalSqlLogRegistry; - -import org.seasar.dao.AnnotationReaderFactory; -import org.seasar.dao.BeanEnhancer; -import org.seasar.dao.BeanMetaDataFactory; -import org.seasar.dao.ColumnNaming; -import org.seasar.dao.DaoAnnotationReader; -import org.seasar.dao.DaoMetaData; -import org.seasar.dao.DaoMetaDataFactory; -import org.seasar.dao.DaoNamingConvention; -import org.seasar.dao.DtoMetaDataFactory; -import org.seasar.dao.ProcedureMetaDataFactory; -import org.seasar.dao.PropertyTypeFactoryBuilder; -import org.seasar.dao.RelationPropertyTypeFactoryBuilder; -import org.seasar.dao.ResultSetHandlerFactory; -import org.seasar.dao.TableNaming; -import org.seasar.dao.ValueTypeFactory; -import org.seasar.dao.impl.DaoMetaDataImpl; -import org.seasar.dao.pager.PagingSqlRewriter; -import org.seasar.extension.jdbc.ResultSetFactory; -import org.seasar.extension.jdbc.StatementFactory; -import org.seasar.framework.beans.BeanDesc; -import org.seasar.framework.beans.factory.BeanDescFactory; -import org.seasar.framework.util.Disposable; -import org.seasar.framework.util.DisposableUtil; - -/** - * The implementation of DaoMetaDataFactory for DBFlute. - * - * @author DBFlute(AutoGenerator) - */ -public class S2DaoMetaDataFactoryImpl implements DaoMetaDataFactory, Disposable { - - //========================================================================== - // ========= - // Definition - // ========== - /** Log-instance. */ - private static final org.apache.commons.logging.Log _log = org.apache.commons.logging.LogFactory - .getLog(S2DaoMetaDataFactoryImpl.class); - - // ----------------------------------------------------- - // For Logging - // ----------- - /** The binding annotation for xaDataSource. {bindingType=may} */ - public static final String xaDataSource_BINDING = "bindingType=may"; - - // ----------------------------------------------------- - // Factory Basic - // ------------- - public static final String dataSource_BINDING = "bindingType=must"; - - public static final String annotationReaderFactory_BINDING = "bindingType=must"; - - public static final String valueTypeFactory_BINDING = "bindingType=must"; - - public static final String beanMetaDataFactory_BINDING = "bindingType=must"; - - public static final String daoNamingConvention_BINDING = "bindingType=must"; - - public static final String resultSetHandlerFactory_BINDING = "bindingType=must"; - - public static final String dtoMetaDataFactory_BINDING = "bindingType=must"; - - public static final String procedureMetaDataFactory_BINDING = "bindingType=must"; - - public static final String pagingSQLRewriter_BINDING = "bindingType=may"; - - //========================================================================== - // ========= - // Attribute - // ========= - // ----------------------------------------------------- - // Factory Basic - // ------------- - protected DataSource dataSource; - - protected AnnotationReaderFactory annotationReaderFactory; - - protected ValueTypeFactory valueTypeFactory; - - protected BeanMetaDataFactory beanMetaDataFactory; - - protected DaoNamingConvention daoNamingConvention; - - protected ResultSetHandlerFactory resultSetHandlerFactory; - - protected DtoMetaDataFactory dtoMetaDataFactory; - - protected ProcedureMetaDataFactory procedureMetaDataFactory; - - protected PagingSqlRewriter pagingSqlRewriter; - - protected Map<String, DaoMetaData> daoMetaDataCache = new HashMap<String, DaoMetaData>(); - - protected boolean initialized; - - protected boolean useDaoClassForLog; - - protected String sqlFileEncoding; - - protected BeanEnhancer beanEnhancer; - - // ----------------------------------------------------- - // Version After 1.0.47 - // -------------------- - /** The naming of column. {After S2Dao-1.0.47} */ - protected ColumnNaming columnNaming; - - /** The builder of property type factory. {After S2Dao-1.0.47} */ - protected PropertyTypeFactoryBuilder propertyTypeFactoryBuilder; - - /** The builder of relation property type factory. {After S2Dao-1.0.47} */ - protected RelationPropertyTypeFactoryBuilder relationPropertyTypeFactoryBuilder; - - /** The builder of table naming. {After S2Dao-1.0.47} */ - protected TableNaming tableNaming; - - // ----------------------------------------------------- - // DBFlute Extension - // ----------------- - /** The lock monitor of DAO meta data initialization. */ - protected Object _daoMetaDataInitializationLockMonitor = new Object(); - - //========================================================================== - // ========= - // Constructor - // =========== - public S2DaoMetaDataFactoryImpl(DataSource dataSource, - AnnotationReaderFactory annotationReaderFactory, - XADataSource xaDataSource) { - this.dataSource = dataSource; - this.annotationReaderFactory = annotationReaderFactory; - - _log - .info("/* * * * * * * * * * * * * * * * * * * * * * * * * * * * {DBFlute}"); - showInformation(dataSource, xaDataSource); - - // Stop the LinkageError! - ConditionBeanContext.initialize(); - - initializeDatabaseProductNameOfContext(xaDataSource); - - handleSqlLogRegistry(); - - DBFluteConfig.getInstance().lock(); - _log.info("* * * * */"); - } - - protected void showInformation(javax.sql.DataSource dataSource, - javax.sql.XADataSource xaDataSource) { - final StringBuilder sb = new StringBuilder(); - if (xaDataSource != null - && xaDataSource instanceof org.seasar.extension.dbcp.impl.XADataSourceImpl) { - final org.seasar.extension.dbcp.impl.XADataSourceImpl xaDataSourceImpl = (org.seasar.extension.dbcp.impl.XADataSourceImpl) xaDataSource; - final String driverClassName = xaDataSourceImpl - .getDriverClassName(); - final String url = xaDataSourceImpl.getURL(); - final String user = xaDataSourceImpl.getUser(); - sb.append(" [XADataSource]:").append(getLineSeparator()); - sb.append(" driver = " + driverClassName).append( - getLineSeparator()); - sb.append(" url = " + url).append(getLineSeparator()); - sb.append(" user = " + user); - } - _log.info("{Injection Information}" + getLineSeparator() + sb); - } - - protected void handleSqlLogRegistry() { - final StringBuilder sb = new StringBuilder(); - sb.append("{SqlLog Information}").append(getLineSeparator()); - sb.append(" [SqlLogRegistry]").append(getLineSeparator()); - if (DBFluteConfig.getInstance().isUseSqlLogRegistry()) { - if (InternalSqlLogRegistry.setupSqlLogRegistry()) { - sb - .append( - " ...Setting up SqlLogRegistry(org.seasar.extension.jdbc)!") - .append(getLineSeparator()); - sb - .append(" Because the property 'useSqlLogRegistry' of the config of DBFlute is true."); - } else { - sb - .append(" SqlLogRegistry(org.seasar.extension.jdbc) is not supported at the version!"); - } - } else { - final Object sqlLogRegistry = InternalSqlLogRegistry - .findContainerSqlLogRegistry(); - if (sqlLogRegistry != null) { - InternalSqlLogRegistry.closeRegistration(); - sb - .append( - " SqlLogRegistry(org.seasar.extension.jdbc) is close! It's default for DBFlute.") - .append(getLineSeparator()); - sb - .append(" If you want to use this, set SqlLogRegistry to SqlLogRegistryLocator at yourself."); - } else { - sb - .append(" SqlLogRegistry(org.seasar.extension.jdbc) is not available!"); - } - } - _log.info(sb); - } - - // ----------------------------------------------------- - // Database Product Name - // --------------------- - protected void initializeDatabaseProductNameOfContext( - javax.sql.XADataSource xaDataSource) { - if (getDatabaseProductNameFromContext() != null) { - return; - } - - // From JDBC Driver! - if (xaDataSource != null - && xaDataSource instanceof org.seasar.extension.dbcp.impl.XADataSourceImpl) { - final org.seasar.extension.dbcp.impl.XADataSourceImpl xaDataSourceImpl = (org.seasar.extension.dbcp.impl.XADataSourceImpl) xaDataSource; - final String driverClassName = xaDataSourceImpl - .getDriverClassName(); - if (driverClassName != null) { - if (setupDatabaseProductNameByDriverClassName(driverClassName)) { - _log - .info("...Initializing database product name from driverClassName: " - + getDatabaseProductNameFromContext()); - return; - } - } - } - - _log.info("...Initializing database product name as default: H2"); - setDatabaseProductNameToContext("H2"); - } - - protected String getDatabaseProductNameFromContext() { - return ConditionBeanContext.getDatabaseProductName(); - } - - protected void setDatabaseProductNameToContext(String name) { - ConditionBeanContext.setDatabaseProductName(name); - } - - protected boolean setupDatabaseProductNameByDriverClassName( - String driverClassName) { - return ConditionBeanContext - .setupDatabaseProductNameByDriverClassName(driverClassName); - } - - //========================================================================== - // ========= - // Implementation - // ============== - @SuppressWarnings("unchecked") - public DaoMetaData getDaoMetaData(final Class daoClass) { - if (!initialized) { - DisposableUtil.add(this); - initialized = true; - } - final String key = daoClass.getName(); - - // [A] - DaoMetaData dmd = getSynchronizedDaoMetaDataCache(key); - - // [B] - if (dmd != null) { - return dmd; - } - - // [C] - synchronized (_daoMetaDataInitializationLockMonitor) {// One Thread Only - // Entered - // [D] - dmd = getSynchronizedDaoMetaDataCache(key); - // [E] - if (dmd != null) { - // The second thread that stops at [C] can find - // because the first thread have already initialized. - if (_log.isDebugEnabled()) { - _log - .debug("...Getting daoMetaData as cache because the previous thread have already initilized."); - } - return dmd; - } - // [F] - if (_log.isDebugEnabled()) { - _log.debug("...Creating daoMetaData for " - + daoClass.getSimpleName() + "."); - } - final DaoMetaData dmdi = createDaoMetaData(daoClass); - putSynchronizedDaoMetaDataCache(key, dmdi); - } - // [G] - dmd = getSynchronizedDaoMetaDataCache(key); - if (dmd != null) { - return dmd; - } - String msg = "The cache should have data meta data here: key=" + key - + " cache=" + daoMetaDataCache; - throw new IllegalStateException(msg); - } - - @SuppressWarnings("unchecked") - protected void putSynchronizedDaoMetaDataCache(String key, DaoMetaData dmd) { - synchronized (daoMetaDataCache) { - daoMetaDataCache.put(key, dmd); - } - } - - protected DaoMetaData getSynchronizedDaoMetaDataCache(String key) { - DaoMetaData dmd = null; - synchronized (daoMetaDataCache) { - dmd = (DaoMetaData) daoMetaDataCache.get(key); - } - return dmd; - } - - //========================================================================== - // ========= - // DataMetaData Creation - // ===================== - protected DaoMetaData createDaoMetaData(final Class<?> daoClass) { - final BeanDesc daoBeanDesc = BeanDescFactory.getBeanDesc(daoClass); - final DaoAnnotationReader daoAnnotationReader = annotationReaderFactory - .createDaoAnnotationReader(daoBeanDesc); - - final DaoMetaDataImpl daoMetaData = createDaoMetaDataExtension(); - daoMetaData.setDaoClass(daoClass); - daoMetaData.setDataSource(dataSource); - daoMetaData.setStatementFactory(createCustomizeStatememtFactory()); - daoMetaData.setResultSetFactory(createCustomizeResultSetFactory()); - daoMetaData.setValueTypeFactory(valueTypeFactory); - daoMetaData.setBeanMetaDataFactory(getBeanMetaDataFactory()); - daoMetaData.setDaoNamingConvention(getDaoNamingConvention()); - daoMetaData.setUseDaoClassForLog(useDaoClassForLog); - daoMetaData.setDaoAnnotationReader(daoAnnotationReader); - daoMetaData.setProcedureMetaDataFactory(procedureMetaDataFactory); - daoMetaData.setDtoMetaDataFactory(dtoMetaDataFactory); - daoMetaData.setResultSetHandlerFactory(resultSetHandlerFactory); - if (sqlFileEncoding != null) { - daoMetaData.setSqlFileEncoding(sqlFileEncoding); - } - if (pagingSqlRewriter != null) { - daoMetaData.setPagingSQLRewriter(pagingSqlRewriter); - } - daoMetaData.initialize(); - return daoMetaData; - } - - protected S2DaoMetaDataExtension createDaoMetaDataExtension() { - final S2DaoMetaDataExtension dmdExtension = newDaoMetaDataExtension(); - dmdExtension.setBeanEnhancer(beanEnhancer); - dmdExtension.setAnnotationReaderFactory(this.annotationReaderFactory); - dmdExtension.setColumnNaming(this.columnNaming); - dmdExtension - .setPropertyTypeFactoryBuilder(this.propertyTypeFactoryBuilder); - dmdExtension - .setRelationPropertyTypeFactoryBuilder(this.relationPropertyTypeFactoryBuilder); - dmdExtension.setTableNaming(tableNaming); - dmdExtension.setInternalDebug(DBFluteConfig.getInstance() - .isInternalDebug()); - return dmdExtension; - } - - protected S2DaoMetaDataExtension newDaoMetaDataExtension() { - return new S2DaoMetaDataExtension(); - } - - //========================================================================== - // ========= - // Result Set Factory - // ================== - /** - * Create the customize result set factory that is for all SQL on DBFlute. - * - * @return The customize statement factory. (NotNull) - */ - protected ResultSetFactory createCustomizeResultSetFactory() { - return new FetchNarrowingResultSetFactory(); - } - - //========================================================================== - // ========= - // Statement Factory - // ================= - /** - * Create the customize statement factory that is for all SQL on DBFlute. - * - * @return The customize statement factory. (NotNull) - */ - protected StatementFactory createCustomizeStatememtFactory() { - final StatementConfig defaultStatementConfig = DBFluteConfig - .getInstance().getDefaultStatementConfig(); - final boolean internalDebug = DBFluteConfig.getInstance() - .isInternalDebug(); - return new StatementFactory() { - public PreparedStatement createPreparedStatement(Connection con, - String sql) { - try { - final StatementConfig config = findStatementConfigOnThread(); - ; - final int resultSetType; - if (config != null && config.hasResultSetType()) { - resultSetType = config.getResultSetType(); - } else if (defaultStatementConfig != null - && defaultStatementConfig.hasResultSetType()) { - resultSetType = defaultStatementConfig - .getResultSetType(); - } else { - resultSetType = java.sql.ResultSet.TYPE_FORWARD_ONLY; - } - final int resultSetConcurrency = java.sql.ResultSet.CONCUR_READ_ONLY; - if (internalDebug) { - _log.debug("...Creating prepareStatement(sql, " - + resultSetType + ", " + resultSetConcurrency - + ")"); - } - final PreparedStatement ps = con.prepareStatement(sql, - resultSetType, resultSetConcurrency); - if (config != null && config.hasStatementOptions()) { - if (internalDebug) { - _log - .debug("...Setting statement config as request: " - + config); - } - reflectStatementOptions(config, ps); - } else { - reflectDefaultOptionsToStatementIfNeeds(ps); - } - return ps; - } catch (SQLException e) { - handleSQLException(e, null); - return null;// Unreachable! - } - } - - public CallableStatement createCallableStatement(Connection conn, - String sql) { - return prepareCall(conn, sql); - } - - protected StatementConfig findStatementConfigOnThread() { - final StatementConfig config; - if (ConditionBeanContext.isExistConditionBeanOnThread()) { - final ConditionBean cb = ConditionBeanContext - .getConditionBeanOnThread(); - config = cb.getStatementConfig(); - } else if (OutsideSqlContext.isExistOutsideSqlContextOnThread()) { - final OutsideSqlContext context = OutsideSqlContext - .getOutsideSqlContextOnThread(); - config = context.getStatementConfig(); - } else { - config = null; - } - return config; - } - - protected void reflectDefaultOptionsToStatementIfNeeds( - PreparedStatement ps) { - if (defaultStatementConfig != null - && defaultStatementConfig.hasStatementOptions()) { - if (internalDebug) { - _log.debug("...Setting statement config as default: " - + defaultStatementConfig); - } - reflectStatementOptions(defaultStatementConfig, ps); - return; - } - } - - protected void reflectStatementOptions(StatementConfig config, - PreparedStatement ps) { - try { - if (config.hasQueryTimeout()) { - ps.setQueryTimeout(config.getQueryTimeout()); - } - if (config.hasFetchSize()) { - ps.setFetchSize(config.getFetchSize()); - } - if (config.hasMaxRows()) { - ps.setMaxRows(config.getMaxRows()); - } - } catch (SQLException e) { - handleSQLException(e, ps); - } - } - - protected CallableStatement prepareCall(Connection conn, String sql) { - try { - return conn.prepareCall(sql); - } catch (SQLException e) { - handleSQLException(e, null); - return null;// Unreachable! - } - } - - protected void handleSQLException(SQLException e, - Statement statement) { - new SQLExceptionHandler().handleSQLException(e, statement); - } - }; - } - - //========================================================================== - // ========= - // Dispose - // ======= - public synchronized void dispose() { - daoMetaDataCache.clear(); - initialized = false; - } - - //========================================================================== - // ========= - // Helper - // ====== - /** - * Get the value of line separator. - * - * @return The value of line separator. (NotNull) - */ - protected static String getLineSeparator() { - return System.getProperty("line.separator"); - } - - //========================================================================== - // ========= - // Accessor - // ======== - // ----------------------------------------------------- - // Factory Basic - // ------------- - public void setValueTypeFactory(final ValueTypeFactory valueTypeFactory) { - this.valueTypeFactory = valueTypeFactory; - } - - protected BeanMetaDataFactory getBeanMetaDataFactory() { - return beanMetaDataFactory; - } - - public void setBeanMetaDataFactory( - final BeanMetaDataFactory beanMetaDataFactory) { - this.beanMetaDataFactory = beanMetaDataFactory; - } - - public DaoNamingConvention getDaoNamingConvention() { - return daoNamingConvention; - } - - public void setDaoNamingConvention( - final DaoNamingConvention daoNamingConvention) { - this.daoNamingConvention = daoNamingConvention; - } - - public void setAnnotationReaderFactory( - final AnnotationReaderFactory annotationReaderFactory) { - this.annotationReaderFactory = annotationReaderFactory; - } - - public void setDataSource(final DataSource dataSource) { - this.dataSource = dataSource; - } - - public void setUseDaoClassForLog(final boolean userDaoClassForLog) { - useDaoClassForLog = userDaoClassForLog; - } - - public void setResultSetHandlerFactory( - final ResultSetHandlerFactory resultSetHandlerFactory) { - this.resultSetHandlerFactory = resultSetHandlerFactory; - } - - public void setDtoMetaDataFactory( - final DtoMetaDataFactory dtoMetaDataFactory) { - this.dtoMetaDataFactory = dtoMetaDataFactory; - } - - public void setProcedureMetaDataFactory( - ProcedureMetaDataFactory procedureMetaDataFactory) { - this.procedureMetaDataFactory = procedureMetaDataFactory; - } - - public void setPagingSQLRewriter(final PagingSqlRewriter pagingSqlRewriter) { - this.pagingSqlRewriter = pagingSqlRewriter; - } - - public String getSqlFileEncoding() { - return sqlFileEncoding; - } - - public void setSqlFileEncoding(final String encoding) { - sqlFileEncoding = encoding; - } - - public BeanEnhancer getBeanEnhancer() { - return beanEnhancer; - } - - public void setBeanEnhancer(final BeanEnhancer beanEnhancer) { - this.beanEnhancer = beanEnhancer; - } - - // ----------------------------------------------------- - // Version After 1.0.47 - // -------------------- - public ColumnNaming getColumnNaming() { - return columnNaming; - } - - public void setColumnNaming(final ColumnNaming columnNaming) { - this.columnNaming = columnNaming; - } - - public PropertyTypeFactoryBuilder getPropertyTypeFactoryBuilder() { - return propertyTypeFactoryBuilder; - } - - public void setPropertyTypeFactoryBuilder( - final PropertyTypeFactoryBuilder propertyTypeFactoryBuilder) { - this.propertyTypeFactoryBuilder = propertyTypeFactoryBuilder; - } - - public RelationPropertyTypeFactoryBuilder getRelationPropertyTypeFactoryBuilder() { - return relationPropertyTypeFactoryBuilder; - } - - public void setRelationPropertyTypeFactoryBuilder( - final RelationPropertyTypeFactoryBuilder relationPropertyTypeFactoryBuilder) { - this.relationPropertyTypeFactoryBuilder = relationPropertyTypeFactoryBuilder; - } - - public TableNaming getTableNaming() { - return tableNaming; - } - - public void setTableNaming(final TableNaming tableNaming) { - this.tableNaming = tableNaming; - } -} \ No newline at end of file Deleted: todolist/trunk/src/main/java/jp/sf/pal/todolist/db/allcommon/s2dao/S2DaoPropertyTypeFactoryBuilderExtension.java =================================================================== --- todolist/trunk/src/main/java/jp/sf/pal/todolist/db/allcommon/s2dao/S2DaoPropertyTypeFactoryBuilderExtension.java 2008-12-27 22:21:53 UTC (rev 1633) +++ todolist/trunk/src/main/java/jp/sf/pal/todolist/db/allcommon/s2dao/S2DaoPropertyTypeFactoryBuilderExtension.java 2008-12-27 22:22:08 UTC (rev 1634) @@ -1,215 +0,0 @@ -package jp.sf.pal.todolist.db.allcommon.s2dao; - -import java.sql.DatabaseMetaData; -import java.util.ArrayList; -import java.util.List; - -import jp.sf.pal.todolist.db.allcommon.Entity; -import jp.sf.pal.todolist.db.allcommon.dbmeta.DBMeta; - -import org.seasar.dao.BeanAnnotationReader; -import org.seasar.dao.ColumnNaming; -import org.seasar.dao.Dbms; -import org.seasar.dao.PropertyTypeFactory; -import org.seasar.dao.PropertyTypeFactoryBuilder; -import org.seasar.dao.ValueTypeFactory; -import org.seasar.dao.impl.AbstractPropertyTypeFactory; -import org.seasar.extension.jdbc.PropertyType; -import org.seasar.framework.beans.BeanDesc; -import org.seasar.framework.beans.PropertyDesc; - -/** - * The factory builder of property type for S2Dao. {Since S2Dao-1.0.47} - * - * @author DBFlute(AutoGenerator) - */ - @ SuppressWarnings("unchecked") -public class S2DaoPropertyTypeFactoryBuilderExtension implements - PropertyTypeFactoryBuilder { - - //========================================================================== - // ========= - // Attribute - // ========= - protected ValueTypeFactory valueTypeFactory; - - protected ColumnNaming columnNaming; - - //========================================================================== - // ========= - // Build - // ===== - public PropertyTypeFactory build(Class beanClass, - BeanAnnotationReader beanAnnotationReader) { - return new FastPropertyTypeFactoryExtension(beanClass, - beanAnnotationReader, valueTypeFactory, columnNaming); - } - - public PropertyTypeFactory build(Class beanClass, - BeanAnnotationReader beanAnnotationReader, Dbms dbms, - DatabaseMetaData databaseMetaData) { - return new FastPropertyTypeFactoryExtension(beanClass, - beanAnnotationReader, valueTypeFactory, columnNaming, dbms); - } - - //========================================================================== - // ========= - // Extension Class - // =============== - protected static class FastPropertyTypeFactoryExtension extends - AbstractPropertyTypeFactory { - - protected DBMeta _dbmeta; - - protected String[] _noPersisteneProps; - - public FastPropertyTypeFactoryExtension(Class beanClass, - BeanAnnotationReader beanAnnotationReader, - ValueTypeFactory valueTypeFactory, ColumnNaming columnNaming) { - super(beanClass, beanAnnotationReader, valueTypeFactory, - columnNaming); - initializeResources(); - } - - public FastPropertyTypeFactoryExtension(Class beanClass, - BeanAnnotationReader beanAnnotationReader, - ValueTypeFactory valueTypeFactory, ColumnNaming columnNaming, - Dbms dbms) { - super(beanClass, beanAnnotationReader, valueTypeFactory, - columnNaming, dbms); - initializeResources(); - } - - protected void initializeResources() { - if (isEntity()) { - _dbmeta = findDBMeta(); - } - _noPersisteneProps = beanAnnotationReader.getNoPersisteneProps(); - } - - protected boolean isEntity() { - return Entity.class.isAssignableFrom(beanClass); - } - - protected boolean hasDBMeta() { - return _dbmeta != null; - } - - protected DBMeta findDBMeta() { - try { - final Entity entity = (Entity) beanClass.newInstance(); - return entity.getDBMeta(); - } catch (Exception e) { - String msg = "beanClass.newInstance() threw the exception: beanClass=" - + beanClass; - throw new RuntimeException(msg, e); - } - } - - public PropertyType[] createBeanPropertyTypes(String tableName) { - final List<PropertyType> list = new ArrayList<PropertyType>(); - final BeanDesc beanDesc = getBeanDesc(); - for (int i = 0; i < beanDesc.getPropertyDescSize(); ++i) { - final PropertyDesc pd = beanDesc.getPropertyDesc(i); - - // Read-only property is unnecessary! - if (!pd.hasWriteMethod()) { - continue; - } - - // Relation property is unnecessary! - if (isRelation(pd)) { - continue; - } - - final PropertyType pt = createPropertyType(pd); - pt.setPrimaryKey(isPrimaryKey(pd)); - pt.setPersistent(isPersistent(pt)); - list.add(pt); - } - return list.toArray(new PropertyType[list.size()]); - } - - @Override - protected boolean isRelation(PropertyDesc propertyDesc) { - final String propertyName = propertyDesc.getPropertyName(); - if (hasDBMeta() - && (_dbmeta.hasForeign(propertyName) || _dbmeta - .hasReferrer(propertyName))) { - return true; - } - return hasRelationNoAnnotation(propertyDesc); - } - - protected boolean hasRelationNoAnnotation(PropertyDesc propertyDesc) { - return beanAnnotationReader.hasRelationNo(propertyDesc); - } - - @Override - protected boolean isPrimaryKey(PropertyDesc propertyDesc) { - final String propertyName = propertyDesc.getPropertyName(); - if (hasDBMeta() && _dbmeta.hasPrimaryKey() - && _dbmeta.hasColumn(propertyName)) { - if (_dbmeta.findColumnInfo(propertyName).isPrimary()) { - return true; - } - } - return hasIdAnnotation(propertyDesc); - } - - protected boolean hasIdAnnotation(PropertyDesc propertyDesc) { - final Dbms dbms = getDbms(); - return beanAnnotationReader.getId(propertyDesc, dbms) != null; - } - - @Override - protected boolean isPersistent(PropertyType propertyType) { - final String propertyName = propertyType.getPropertyName(); - final PropertyDesc propertyDesc = propertyType.getPropertyDesc(); - if ((hasDBMeta() && _dbmeta.hasColumn(propertyName)) - || hasColumnAnnotation(propertyDesc)) { - if (!isElementOfNoPersistentProps(propertyDesc)) { - return true; - } - } - return false; - } - - protected boolean hasColumnAnnotation(PropertyDesc propertyDesc) { - return beanAnnotationReader.getColumnAnnotation(propertyDesc) != null; - } - - protected boolean isElementOfNoPersistentProps(PropertyDesc propertyDesc) { - final String propertyName = propertyDesc.getPropertyName(); - final String[] props = _noPersisteneProps; - if (props != null && props.length >= 0) { - for (int i = 0; i < props.length; ++i) { - if (props[i].equals(propertyName)) { - return true; - } - } - } - return false; - } - } - - //========================================================================== - // ========= - // Accessor - // ======== - public ValueTypeFactory getValueTypeFactory() { - return valueTypeFactory; - } - - public void setValueTypeFactory(ValueTypeFactory valueTypeFactory) { - this.valueTypeFactory = valueTypeFactory; - } - - public ColumnNaming getColumnNaming() { - return columnNaming; - } - - public void setColumnNaming(ColumnNaming columnNaming) { - this.columnNaming = columnNaming; - } -} Deleted: todolist/trunk/src/main/java/jp/sf/pal/todolist/db/allcommon/s2dao/S2DaoSelectDynamicCommand.java =================================================================== --- todolist/trunk/src/main/java/jp/sf/pal/todolist/db/allcommon/s2dao/S2DaoSelectDynamicCommand.java 2008-12-27 22:21:53 UTC (rev 1633) +++ todolist/trunk/src/main/java/jp/sf/pal/todolist/db/allcommon/s2dao/S2DaoSelectDynamicCommand.java 2008-12-27 22:22:08 UTC (rev 1634) @@ -1,491 +0,0 @@ -package jp.sf.pal.todolist.db.allcommon.s2dao; - -import java.util.ArrayList; -import java.util.List; - -import javax.sql.DataSource; - -import jp.sf.pal.todolist.db.allcommon.cbean.ConditionBean; -import jp.sf.pal.todolist.db.allcommon.cbean.ConditionBeanContext; -import jp.sf.pal.todolist.db.allcommon.cbean.outsidesql.OutsideSqlContext; -import jp.sf.pal.todolist.db.allcommon.s2dao.internal.sqlcommand.InternalAbstractDynamicCommand; -import jp.sf.pal.todolist.db.allcommon.s2dao.internal.sqlhandler.InternalBasicSelectHandler; -import jp.sf.pal.todolist.db.allcommon.util.SimpleStringUtil; -import jp.sf.pal.todolist.db.allcommon.util.SimpleSystemUtil; - -import org.seasar.dao.CommandContext; -import org.seasar.extension.jdbc.ResultSetHandler; -import org.seasar.extension.jdbc.StatementFactory; -import org.seasar.extension.jdbc.ValueType; -import org.seasar.extension.jdbc.types.ValueTypes; -import org.seasar.framework.beans.BeanDesc; -import org.seasar.framework.beans.PropertyDesc; -import org.seasar.framework.beans.factory.BeanDescFactory; - -/** - * SelectDynamicCommand for DBFlute. - * - * @author DBFlute(AutoGenerator) - */ - @ SuppressWarnings("unchecked") -public class S2DaoSelectDynamicCommand extends InternalAbstractDynamicCommand { - - //========================================================================== - // ========= - // Attribute - // ========= - /** The handler of resultSet. */ - protected ResultSetHandler resultSetHandler; - - //========================================================================== - // ========= - // Constructor - // =========== - /** - * Constructor. - * - * @param dataSource Data source. - * @param statementFactory The factory of statement. - * @param resultSetHandler The handler of resultSet. - */ - public S2DaoSelectDynamicCommand(DataSource dataSource, - StatementFactory statementFactory, ResultSetHandler resultSetHandler) { - super(dataSource, statementFactory); - this.resultSetHandler = resultSetHandler; - } - - //========================================================================== - // ========= - // Very Important Extension - // ======================== - // ----------------------------------------------------- - // SelectDynamicCommand Creation - // ----------------------------- - protected S2DaoSelectDynamicCommand createMySelectDynamicCommand() { - return new S2DaoSelectDynamicCommand(getDataSource(), - getStatementFactory(), resultSetHandler); - } - - //========================================================================== - // ========= - // Execute - // ======= - // ----------------------------------------------------- - // Top Execute - // ----------- - /** - * @param args The array of argument. (Nullable) - * @return The object of execution result. (Nullable) - */ - public Object execute(Object[] args) { - // - - - - - - - - - - - - - // This is top execution. - // - - - - - - - - - - - - - - if (!ConditionBeanContext.isExistConditionBeanOnThread()) { - // - - - - - - - - - - - // Execute outsideSql. - // - - - - - - - - - - - if (OutsideSqlContext.isExistOutsideSqlContextOnThread()) { - final OutsideSqlContext outsideSqlContext = OutsideSqlContext - .getOutsideSqlContextOnThread(); - if (outsideSqlContext.isDynamicBinding()) { - return executeOutsideSqlAsDynamic(args, outsideSqlContext); - } else { - return executeOutsideSqlAsStatic(args, outsideSqlContext); - } - } - - // - - - - - - - - - - // Execute default. - // - - - - - - - - - - return executeDefault(args); - } - - // - - - - - - - - - - - - - // Execute conditionBean. - // - - - - - - - - - - - - - final List<Object> bindVariableList = new ArrayList<Object>(4); - final List<Class> bindVariableTypeList = new ArrayList<Class>(4); - - final ConditionBean cb = ConditionBeanContext - .getConditionBeanOnThread(); - final String finalClause; - if (cb.hasUnionQueryOrUnionAllQuery()) { - final String realClause = setupRealClause(args, bindVariableList, - bindVariableTypeList); - if (cb.isSelectCountIgnoreFetchScope()) { - // If the query uses union and it selects count, the way of - // select-count is as follows. - finalClause = "select count(*) from (" + realClause - + ") dfmain"; - } else { - finalClause = realClause; - } - } else { - if (cb.isSelectCountIgnoreFetchScope()) { - finalClause = setupRealSelectCountClause(args, - bindVariableList, bindVariableTypeList); - } else { - finalClause = setupRealClause(args, bindVariableList, - bindVariableTypeList); - } - } - - final InternalBasicSelectHandler selectHandler = createBasicSelectHandler( - finalClause, this.resultSetHandler); - final Object[] bindVariableArray = bindVariableList.toArray(); - selectHandler.setLoggingMessageSqlArgs(bindVariableArray); - return selectHandler.execute(bindVariableArray, - toClassArray(bindVariableTypeList)); - } - - // ----------------------------------------------------- - // Default Execute - // --------------- - /** - * Execute default. - * - * @param args The array of argument. (Nullable) - * @return Result. (Nullable) - */ - protected Object executeDefault(Object args[]) { - // - - - - - - - - - - - - - - - - - - // Find specified resultSetHandler. - // - - - - - - - - - - - - - - - - - - final ResultSetHandler specifiedResultSetHandler = findSpecifiedResultSetHandler(args); - - // - - - - - - - - - - // Filter arguments. - // - - - - - - - - - - final Object[] filteredArgs = filterArgumentsForResultSetHandler(args); - - final org.seasar.dao.CommandContext ctx = apply(filteredArgs); - final InternalBasicSelectHandler selectHandler = createBasicSelectHandler( - ctx.getSql(), specifiedResultSetHandler); - final Object[] bindVariableArray = ctx.getBindVariables(); - selectHandler.setLoggingMessageSqlArgs(bindVariableArray); - return selectHandler.execute(bindVariableArray, ctx - .getBindVariableTypes()); - } - - // ----------------------------------------------------- - // OutsideSql Execute - // ------------------ - /** - * Execute outsideSql as static. - * - * @param args The array of argument. (Nullable) - * @param outsideSqlContext The context of outsideSql. (NotNull) - * @return Result. (Nullable) - */ - protected Object executeOutsideSqlAsStatic(Object[] args, - OutsideSqlContext outsideSqlContext) { - // - - - - - - - - - - - - - - - - - - // Find specified resultSetHandler. - // - - - - - - - - - - - - - - - - - - final ResultSetHandler specifiedResultSetHandler = findSpecifiedResultSetHandler(args); - - // - - - - - - - - - - // Filter arguments. - // - - - - - - - - - - final Object[] filteredArgs; - if (outsideSqlContext.isSpecifiedOutsideSql()) { - final Object parameterBean = outsideSqlContext.getParameterBean(); - filteredArgs = new Object[] { parameterBean }; - } else { - filteredArgs = filterArgumentsForResultSetHandler(args); - } - - final org.seasar.dao.CommandContext ctx = apply(filteredArgs); - final InternalBasicSelectHandler selectHandler = createBasicSelectHandler( - ctx.getSql(), specifiedResultSetHandler); - final Object[] bindVariableArray = ctx.getBindVariables(); - selectHandler.setLoggingMessageSqlArgs(bindVariableArray); - return selectHandler.execute(bindVariableArray, ctx - .getBindVariableTypes()); - } - - /** - * Execute outsideSql as Dynamic. - * - * @param args The array of argument. (Nullable) - * @param outsideSqlContext The context of outsideSql. (NotNull) - * @return Result. (Nullable) - */ - protected Object executeOutsideSqlAsDynamic(Object[] args, - OutsideSqlContext outsideSqlContext) { - final Object firstArg; - if (outsideSqlContext.isSpecifiedOutsideSql()) { - final Object parameterBean = outsideSqlContext.getParameterBean(); - firstArg = parameterBean; - } else { - firstArg = args[0]; - } - String filteredSql = getSql(); - if (firstArg != null) { - final BeanDesc beanDesc = BeanDescFactory.getBeanDesc(firstArg - .getClass()); - - // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // - - - - - - - - // Resolve embedded comment for parsing bind variable comment in - // embedded comment. - // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // - - - - - - - - for (int i = 0; i < beanDesc.getPropertyDescSize(); i++) { - final PropertyDesc propertyDesc = beanDesc.getPropertyDesc(i); - final Class propertyType = propertyDesc.getPropertyType(); - if (!propertyType.equals(String.class)) { - continue; - } - final String outsideSqlPiece = (String) propertyDesc - .getValue(firstArg); - if (outsideSqlPiece == null) { - continue; - } - final String embeddedComment = "/*$pmb." - + propertyDesc.getPropertyName() + "*/"; - filteredSql = replaceString(filteredSql, embeddedComment, - outsideSqlPiece); - } - } - final S2DaoSelectDynamicCommand outsideSqlCommand = createMySelectDynamicCommand(); - if (outsideSqlContext.isSpecifiedOutsideSql()) { - outsideSqlCommand.setArgNames(new String[] { "pmb" }); - outsideSqlCommand - .setArgTypes(new Class<?>[] { firstArg != null ? firstArg - .getClass() : Object.class }); - } else { - outsideSqlCommand.setArgNames(getArgNames()); - outsideSqlCommand.setArgTypes(getArgTypes()); - } - outsideSqlCommand.setSql(filteredSql); - - // - - - - - - - - - - - - - - - - - - // Find specified resultSetHandler. - // - - - - - - - - - - - - - - - - - - final ResultSetHandler specifiedResultSetHandler = findSpecifiedResultSetHandler(args); - - // - - - - - - - - - - // Filter arguments. - // - - - - - - - - - - final Object[] filteredArgs; - if (outsideSqlContext.isSpecifiedOutsideSql()) { - final Object parameterBean = outsideSqlContext.getParameterBean(); - filteredArgs = new Object[] { parameterBean }; - } else { - filteredArgs = filterArgumentsForResultSetHandler(args); - } - - final org.seasar.dao.CommandContext ctx = outsideSqlCommand - .apply(filteredArgs); - final java.util.List<Object> bindVariableList = new java.util.ArrayList<Object>(); - final java.util.List<Class> bindVariableTypeList = new java.util.ArrayList<Class>(); - addBindVariableInfo(ctx, bindVariableList, bindVariableTypeList); - final InternalBasicSelectHandler selectHandler = createBasicSelectHandler( - ctx.getSql(), specifiedResultSetHandler); - final Object[] bindVariableArray = bindVariableList.toArray(); - selectHandler.setLoggingMessageSqlArgs(bindVariableArray); - return selectHandler.execute(bindVariableArray, - toClassArray(bindVariableTypeList)); - } - - protected Object[] filterArgumentsForResultSetHandler(Object[] args) { - if (args == null || args.length == 0) { - return args; - } - final Object[] filteredArgs; - if (args[args.length - 1] instanceof jp.sf.pal.todolist.db.allcommon.jdbc.CursorHandler) { - filteredArgs = new Object[args.length - 1]; - for (int i = 0; i < args.length - 1; i++) { - filteredArgs[i] = args[i]; - } - } else { - filteredArgs = args; - } - return filteredArgs; - } - - protected ResultSetHandler findSpecifiedResultSetHandler(Object[] args) { - if (args == null || args.length == 0) { - return this.resultSetHandler; - } - if (args[args.length - 1] instanceof jp.sf.pal.todolist.db.allcommon.jdbc.CursorHandler) { - final jp.sf.pal.todolist.db.allcommon.jdbc.CursorHandler cursorHandler = (jp.sf.pal.todolist.db.allcommon.jdbc.CursorHandler) args[args.length - 1]; - return new ResultSetHandler() { - public Object handle(java.sql.ResultSet rs) - throws java.sql.SQLException { - return cursorHandler.handle(rs); - } - }; - } - if (getArgTypes().length + 1 == args.length - && args[args.length - 1] == null) { - String msg = "System Level Exception!" + getLineSeparator(); - msg = msg - + "/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *" - + getLineSeparator(); - msg = msg - + "The size of arg types have not been same as the size of arg objects:"; - msg = msg + " argTypes=" + getArgTypes().length + " args=" - + args.length + getLineSeparator(); - msg = msg - + "If the arguments contain ResultSetHandler, the argument value should not be null!" - + getLineSeparator(); - for (int i = 0; i < args.length - 1; i++) { - msg = msg + " args[" + i + "] -- " + args[i] - + getLineSeparator(); - } - msg = msg + "* * * * * * * * * */" + getLineSeparator(); - throw new IllegalStateException(msg); - } - return this.resultSetHandler; - } - - // ----------------------------------------------------- - // Setup Clause - // ------------ - protected String setupRealClause(Object[] args, - List<Object> bindVariableList, List<Class> bindVariableTypeList) { - final ConditionBean cb = ConditionBeanContext - .getConditionBeanOnThread(); - final String realClause; - { - final S2DaoSelectDynamicCommand dynamicCommand = createMySelectDynamicCommand(); - dynamicCommand.setArgNames(getArgNames()); - dynamicCommand.setArgTypes(getArgTypes()); - if (cb.isLimitSelect_PKOnly()) { - dynamicCommand.setSql(cb.getSqlClause().getClausePKOnly()); - } else { - dynamicCommand.setSql(cb.getSqlClause().getClause()); - } - final CommandContext ctx = dynamicCommand.apply(args); - realClause = ctx.getSql(); - addBindVariableInfo(ctx, bindVariableList, bindVariableTypeList); - } - return realClause; - } - - protected String setupRealSelectCountClause(Object[] args, - List<Object> bindVariableList, List<Class> bindVariableTypeList) { - final ConditionBean cb = ConditionBeanContext - .getConditionBeanOnThread(); - final String realSelectCountClause; - { - final S2DaoSelectDynamicCommand selectCountCommand = createMySelectDynamicCommand(); - selectCountCommand.setArgNames(getArgNames()); - selectCountCommand.setArgTypes(getArgTypes()); - final String selectClause = "select count(*)"; - String fromWhereClause = cb.getSqlClause() - .getClauseFromWhereWithUnionTemplate(); - - // Replace template marks. These are very important! - fromWhereClause = replaceString(fromWhereClause, cb.getSqlClause() - .getUnionSelectClauseMark(), selectClause); - fromWhereClause = replaceString(fromWhereClause, cb.getSqlClause() - .getUnionWhereClauseMark(), ""); - fromWhereClause = replaceString(fromWhereClause, cb.getSqlClause() - .getUnionWhereFirstConditionMark(), ""); - - final String sql = cb.getSqlClause().filterSubQueryIndent( - selectClause + " " + fromWhereClause); - selectCountCommand.setSql(sql); - - final CommandContext ctx = selectCountCommand.apply(args); - realSelectCountClause = ctx.getSql(); - addBindVariableInfo(ctx, bindVariableList, bindVariableTypeList); - } - return realSelectCountClause; - } - - protected InternalBasicSelectHandler createBasicSelectHandler( - String realSql, ResultSetHandler specifiedResultSetHandler) { - return newBasicSelectHandler(realSql, specifiedResultSetHandler, - getStatementFactory()); - } - - protected InternalBasicSelectHandler newBasicSelectHandler(String sql, - ResultSetHandler resultSetHandler, StatementFactory statementFactory) { - return new InternalBasicSelectHandler(getDataSource(), sql, - resultSetHandler, statementFactory) { - @Override - protected void bindArgs(java.sql.PreparedStatement ps, - Object[] args, Class[] argTypes) { - if (args == null) { - return; - } - for (int i = 0; i < args.length; ++i) { - final ValueType valueType = findValueType(argTypes[i], - args[i]); - try { - valueType.bindValue(ps, i + 1, args[i]); - } catch (java.sql.SQLException e) { - handleSQLException(e, ps); - } - } - } - - protected ValueType findValueType(Class argType, Object arg) { - ValueType valueType = ValueTypes.getValueType(arg); - if (valueType != null) { - return valueType; - } - valueType = ValueTypes.getValueType(argType); - if (valueType != null) { - return valueType; - } - String msg = "Unknown type:argType=" + argType + " args=" + arg; - throw new IllegalStateException(msg); - } - }; - } - - // ----------------------------------------------------- - // Setup Helper - // ------------ - protected Class[] toClassArray(List<Class> bindVariableTypeList) { - final Class[] bindVariableTypesArray = new Class[bindVariableTypeList - .size()]; - for (int i = 0; i < bindVariableTypeList.size(); i++) { - final Class bindVariableType = (Class) bindVariableTypeList.get(i); - bindVariableTypesArray[i] = bindVariableType; - } - return bindVariableTypesArray; - } - - protected void addBindVariableInfo(CommandContext ctx, - List<Object> bindVariableList, List<Class> bindVariableTypeList) { - final Object[] bindVariables = ctx.getBindVariables(); - addBindVariableList(bindVariableList, bindVariables); - final Class[] bindVariableTypes = ctx.getBindVariableTypes(); - addBindVariableTypeList(bindVariableTypeList, bindVariableTypes); - } - - protected void addBindVariableList(List<Object> bindVariableList, - Object[] bindVariables) { - for (int i = 0; i < bindVariables.length; i++) { - bindVariableList.add(bindVariables[i]); - } - } - - protected void addBindVariableTypeList(List<Class> bindVariableTypeList, - Class[] bindVariableTypes) { - for (int i = 0; i < bindVariableTypes.length; i++) { - bindVariableTypeList.add(bindVariableTypes[i]); - } - } - - //========================================================================== - // ========= - // General Helper - // ============== - protected final String replaceString(String text, String fromText, - String toText) { - return SimpleStringUtil.replace(text, fromText, toText); - } - - protected String getLineSeparator() { - return SimpleSystemUtil.getLineSeparator(); - } -} \ No newline at end of file