001 /* 002 @license.text@ 003 */ 004 package biz.hammurapi.ant; 005 006 import java.io.IOException; 007 import java.sql.Connection; 008 import java.sql.DriverManager; 009 import java.sql.SQLException; 010 import java.util.ArrayList; 011 import java.util.Collection; 012 import java.util.Iterator; 013 014 import org.apache.tools.ant.BuildException; 015 016 import biz.hammurapi.config.Context; 017 import biz.hammurapi.sql.ConnectionPerThreadDataSource; 018 import biz.hammurapi.sql.SQLProcessor; 019 020 021 /** 022 * Defines database connection. 023 * @ant.element name="Database connection" 024 * @author Pavel Vlasov 025 * @version $Revision: 1.8 $ 026 */ 027 public class ConnectionEntry { 028 private String driverClass; 029 private String url; 030 private String user; 031 private String password; 032 private Collection onConnects=new ArrayList(); 033 034 /** 035 * Driver class. 036 * @ant.required 037 */ 038 public void setDriverClass(String driverClass) { 039 this.driverClass = driverClass; 040 } 041 042 /** 043 * Database password. 044 * @ant.non-required 045 * @param password 046 */ 047 public void setPassword(String password) { 048 this.password = password; 049 } 050 051 /** 052 * Connection url 053 * @ant.required 054 * @param url 055 */ 056 public void setUrl(String url) { 057 this.url = url; 058 } 059 060 /** 061 * Database user 062 * @ant.non-required 063 * @param user 064 */ 065 public void setUser(String user) { 066 this.user = user; 067 } 068 069 public SQLProcessor getProcessor(Context nameMap) { 070 SQLProcessor ret = new SQLProcessor(getDataSource(), nameMap); 071 processOnConnects(ret); 072 return ret; 073 } 074 075 /** 076 * @param ret 077 */ 078 private void processOnConnects(SQLProcessor ret) { 079 Iterator it=onConnects.iterator(); 080 while (it.hasNext()) { 081 try { 082 ((Script) it.next()).execute(ret); 083 } catch (IOException e) { 084 throw new BuildException(e); 085 } catch (SQLException e) { 086 throw new BuildException(e); 087 } 088 } 089 } 090 091 private Collection dataSources=new ArrayList(); 092 093 /** 094 * @return 095 * @throws ClassNotFoundException 096 */ 097 public ConnectionPerThreadDataSource getDataSource() { 098 try { 099 ConnectionPerThreadDataSource ds = new ConnectionPerThreadDataSource(driverClass, url, user, password, null); 100 dataSources.add(ds); 101 return ds; 102 } catch (ClassNotFoundException e) { 103 throw new BuildException("Cannot load driver class", e); 104 } 105 } 106 107 public Connection getConnection() throws SQLException, ClassNotFoundException { 108 Class.forName(driverClass); 109 return DriverManager.getConnection(url, user, password); 110 111 } 112 113 public Script createOnConnect() { 114 Script ret = new Script(); 115 onConnects.add(ret); 116 return ret; 117 } 118 119 public void shutdown() { 120 Iterator it=dataSources.iterator(); 121 while (it.hasNext()) { 122 ((ConnectionPerThreadDataSource) it.next()).shutdown(); 123 } 124 } 125 }