001 /* 002 @license.text@ 003 */ 004 package biz.hammurapi.sql; 005 006 import java.sql.SQLException; 007 import java.util.ArrayList; 008 import java.util.Collection; 009 import java.util.Iterator; 010 011 import org.w3c.dom.Element; 012 import org.w3c.dom.Node; 013 import org.w3c.dom.NodeList; 014 015 import biz.hammurapi.config.Component; 016 import biz.hammurapi.config.ConfigurationException; 017 import biz.hammurapi.config.Context; 018 import biz.hammurapi.config.DomConfigurable; 019 import biz.hammurapi.config.Wrapper; 020 import biz.hammurapi.xml.dom.DOMUtils; 021 022 023 public class ConnectionPerThreadDataSourceComponent implements Wrapper, DomConfigurable, Component { 024 025 private ConnectionPerThreadDataSource master; 026 private String driverClass; 027 private String dbUrl; 028 private String user; 029 private String password; 030 031 public ConnectionPerThreadDataSourceComponent() { 032 super(); 033 } 034 035 public Object getMaster() { 036 if (master==null) { 037 throw new IllegalStateException("Not yet started"); 038 } 039 return master; 040 } 041 042 private Collection initStatements=new ArrayList(); 043 044 public void configure(Node configNode, Context context, ClassLoader classLoader) throws ConfigurationException { 045 try { 046 driverClass=DOMUtils.getSingleElementText((Element) configNode, "driver-class"); 047 dbUrl=DOMUtils.getSingleElementText((Element) configNode, "connection-url"); 048 user=DOMUtils.getSingleElementText((Element) configNode, "user"); 049 password=DOMUtils.getSingleElementText((Element) configNode, "password"); 050 NodeList nl=DOMUtils.selectNodeList(configNode, "init-connection"); 051 for (int i=0, l=nl.getLength(); i<l; ++i) { 052 Element el = (Element) nl.item(i); 053 initStatements.add(DOMUtils.getElementText(el)); 054 } 055 } catch (Exception e) { 056 throw new ConfigurationException("Cannot read parameters", e); 057 } 058 059 } 060 061 public void start() throws ConfigurationException { 062 try { 063 master=new ConnectionPerThreadDataSource( 064 driverClass, 065 dbUrl, 066 user, 067 password, 068 new Transaction() { 069 070 public boolean execute(SQLProcessor processor) throws SQLException { 071 Iterator it=initStatements.iterator(); 072 while (it.hasNext()) { 073 processor.processUpdate((String) it.next(), null); 074 } 075 return true; 076 } 077 078 }); 079 } catch (ClassNotFoundException e) { 080 throw new ConfigurationException("Driver class not found", e); 081 } 082 } 083 084 public void stop() throws ConfigurationException { 085 if (master!=null) { 086 master.shutdown(); 087 } 088 089 } 090 091 public void setOwner(Object owner) { 092 // Nothing 093 } 094 }