You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

J2EEConnectionPool.java 1.9KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. /*
  2. @VaadinApache2LicenseForJavaFiles@
  3. */
  4. package com.vaadin.data.util.sqlcontainer.connection;
  5. import java.sql.Connection;
  6. import java.sql.SQLException;
  7. import java.util.logging.Level;
  8. import java.util.logging.Logger;
  9. import javax.naming.InitialContext;
  10. import javax.naming.NamingException;
  11. import javax.sql.DataSource;
  12. public class J2EEConnectionPool implements JDBCConnectionPool {
  13. private static final Logger logger = Logger
  14. .getLogger(J2EEConnectionPool.class.getName());
  15. private String dataSourceJndiName;
  16. private DataSource dataSource = null;
  17. public J2EEConnectionPool(DataSource dataSource) {
  18. this.dataSource = dataSource;
  19. }
  20. public J2EEConnectionPool(String dataSourceJndiName) {
  21. this.dataSourceJndiName = dataSourceJndiName;
  22. }
  23. public Connection reserveConnection() throws SQLException {
  24. Connection conn = getDataSource().getConnection();
  25. conn.setAutoCommit(false);
  26. return conn;
  27. }
  28. private DataSource getDataSource() throws SQLException {
  29. if (dataSource == null) {
  30. dataSource = lookupDataSource();
  31. }
  32. return dataSource;
  33. }
  34. private DataSource lookupDataSource() throws SQLException {
  35. try {
  36. InitialContext ic = new InitialContext();
  37. return (DataSource) ic.lookup(dataSourceJndiName);
  38. } catch (NamingException e) {
  39. throw new SQLException(
  40. "NamingException - Cannot connect to the database. Cause: "
  41. + e.getMessage());
  42. }
  43. }
  44. public void releaseConnection(Connection conn) {
  45. if (conn != null) {
  46. try {
  47. conn.close();
  48. } catch (SQLException e) {
  49. logger.log(Level.FINE, "Could not release SQL connection", e);
  50. }
  51. }
  52. }
  53. public void destroy() {
  54. dataSource = null;
  55. }
  56. }