001    package biz.hammurapi.jdbc;
002    
003    import java.sql.Connection;
004    import java.sql.SQLException;
005    import java.sql.Statement;
006    
007    import org.apache.commons.dbcp.BasicDataSource;
008    
009    import biz.hammurapi.config.Component;
010    import biz.hammurapi.config.ConfigurationException;
011    import biz.hammurapi.jms.adapter.JmsAdapter;
012    
013    /**
014     * Invokes close() in stop() method.
015     * @author Pavel
016     *
017     */
018    public class BasicDataSourceComponent extends BasicDataSource implements Component {
019    
020            public void setOwner(Object owner) {
021                    // Nothing to do                
022            }
023    
024            public void start() throws ConfigurationException {
025                    // Nothing to do                
026            }
027    
028            public void stop() throws ConfigurationException {
029                    try {
030                            super.close();
031                    } catch (SQLException e) {
032                            throw new ConfigurationException("Failed to close data source: "+e, e);
033                    }               
034            }
035            
036            private String initConnectionStatement;
037            
038            /**
039             * Statement which is invoked every time connection is obtained from the data source.
040             * @param initConnectionStatement
041             */
042            public void setInitConnectionStatement(String initConnectionStatement) {
043                    this.initConnectionStatement = initConnectionStatement;
044            }
045            
046            public Connection getConnection() throws SQLException {
047                    Connection ret = super.getConnection();
048                    if (!JmsAdapter.isBlank(initConnectionStatement)) {
049                            Statement stmt = ret.createStatement();
050                            try {
051                                    stmt.execute(initConnectionStatement);
052                            } finally {
053                                    stmt.close();
054                            }
055                    }
056                    return ret;
057            }
058                    
059    }