1 17 18 21 package org.quartz.utils; 22 23 import java.sql.Connection ; 24 import java.sql.SQLException ; 25 import java.util.Properties ; 26 27 import javax.naming.Context ; 28 import javax.naming.InitialContext ; 29 import javax.sql.DataSource ; 30 import javax.sql.XADataSource ; 31 32 import org.apache.commons.logging.Log; 33 import org.apache.commons.logging.LogFactory; 34 35 51 public class JNDIConnectionProvider implements ConnectionProvider { 52 53 60 61 private String url; 62 63 private Properties props; 64 65 private Object datasource; 66 67 private boolean alwaysLookup = false; 68 69 private final Log log = LogFactory.getLog(getClass()); 70 71 78 79 85 public JNDIConnectionProvider(String jndiUrl, boolean alwaysLookup) { 86 this.url = jndiUrl; 87 this.alwaysLookup = alwaysLookup; 88 init(); 89 } 90 91 100 public JNDIConnectionProvider(String jndiUrl, Properties jndiProps, 101 boolean alwaysLookup) { 102 this.url = jndiUrl; 103 this.props = jndiProps; 104 this.alwaysLookup = alwaysLookup; 105 init(); 106 } 107 108 115 116 protected Log getLog() { 117 return log; 118 } 119 120 private void init() { 121 122 if (!isAlwaysLookup()) { 123 Context ctx = null; 124 try { 125 ctx = (props != null) ? new InitialContext (props) : new InitialContext (); 126 127 datasource = (DataSource ) ctx.lookup(url); 128 } catch (Exception e) { 129 getLog().error( 130 "Error looking up datasource: " + e.getMessage(), e); 131 } finally { 132 if (ctx != null) { 133 try { ctx.close(); } catch(Exception ignore) {} 134 } 135 } 136 } 137 } 138 139 public Connection getConnection() throws SQLException { 140 Context ctx = null; 141 try { 142 Object ds = this.datasource; 143 144 if (ds == null || isAlwaysLookup()) { 145 ctx = (props != null) ? new InitialContext (props): new InitialContext (); 146 147 ds = ctx.lookup(url); 148 if (!isAlwaysLookup()) { 149 this.datasource = ds; 150 } 151 } 152 153 if (ds == null) { 154 throw new SQLException ( "There is no object at the JNDI URL '" + url + "'"); 155 } 156 157 if (ds instanceof XADataSource ) { 158 return (((XADataSource ) ds).getXAConnection().getConnection()); 159 } else if (ds instanceof DataSource ) { 160 return ((DataSource ) ds).getConnection(); 161 } else { 162 throw new SQLException ("Object at JNDI URL '" + url + "' is not a DataSource."); 163 } 164 } catch (Exception e) { 165 this.datasource = null; 166 throw new SQLException ( 167 "Could not retrieve datasource via JNDI url '" + url + "' " 168 + e.getClass().getName() + ": " + e.getMessage()); 169 } finally { 170 if (ctx != null) { 171 try { ctx.close(); } catch(Exception ignore) {} 172 } 173 } 174 } 175 176 public boolean isAlwaysLookup() { 177 return alwaysLookup; 178 } 179 180 public void setAlwaysLookup(boolean b) { 181 alwaysLookup = b; 182 } 183 184 187 public void shutdown() throws SQLException { 188 } 190 191 } 192 | Popular Tags |