1 8 package org.apache.avalon.excalibur.datasource; 9 10 import java.sql.Connection ; 11 import java.sql.SQLException ; 12 import javax.naming.Context ; 13 import javax.naming.InitialContext ; 14 import javax.naming.NamingException ; 15 import javax.sql.DataSource ; 16 import org.apache.avalon.framework.logger.AbstractLogEnabled; 17 import org.apache.avalon.framework.logger.Loggable; 18 import org.apache.avalon.framework.logger.LogKitLogger; 19 import org.apache.avalon.framework.configuration.Configuration; 20 import org.apache.avalon.framework.configuration.ConfigurationException; 21 22 31 public class J2eeDataSource 32 extends AbstractLogEnabled 33 implements DataSourceComponent, Loggable 34 { 35 public static final String JDBC_NAME = "java:comp/env/jdbc/"; 36 protected DataSource m_dataSource = null; 37 38 public void setLogger( org.apache.log.Logger logger ) 39 { 40 enableLogging( new LogKitLogger( logger ) ); 41 } 42 43 53 public void configure( final Configuration configuration ) 54 throws ConfigurationException 55 { 56 if( null == m_dataSource ) 57 { 58 final String databaseName = configuration.getChild("dbname").getValue(); 59 60 try 61 { 62 final Context initialContext = new InitialContext (); 63 m_dataSource = (DataSource )initialContext.lookup( JDBC_NAME + databaseName ); 64 } 65 catch( final NamingException ne ) 66 { 67 if (getLogger().isErrorEnabled()) 68 { 69 getLogger().error( "Problem with JNDI lookup of datasource", ne ); 70 } 71 72 throw new ConfigurationException( "Could not use JNDI to find datasource", ne ); 73 } 74 } 75 } 76 77 78 public Connection getConnection() 79 throws SQLException 80 { 81 if( null == m_dataSource ) 82 { 83 throw new SQLException ( "Can not access DataSource object" ); 84 } 85 86 return m_dataSource.getConnection(); 87 } 88 } 89 | Popular Tags |