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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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 String dataSourceJndiName;
  14. private DataSource dataSource = null;
  15. public J2EEConnectionPool(DataSource dataSource) {
  16. this.dataSource = dataSource;
  17. }
  18. public J2EEConnectionPool(String dataSourceJndiName) {
  19. this.dataSourceJndiName = dataSourceJndiName;
  20. }
  21. @Override
  22. public Connection reserveConnection() throws SQLException {
  23. Connection conn = getDataSource().getConnection();
  24. conn.setAutoCommit(false);
  25. return conn;
  26. }
  27. private DataSource getDataSource() throws SQLException {
  28. if (dataSource == null) {
  29. dataSource = lookupDataSource();
  30. }
  31. return dataSource;
  32. }
  33. private DataSource lookupDataSource() throws SQLException {
  34. try {
  35. InitialContext ic = new InitialContext();
  36. return (DataSource) ic.lookup(dataSourceJndiName);
  37. } catch (NamingException e) {
  38. throw new SQLException(
  39. "NamingException - Cannot connect to the database. Cause: "
  40. + e.getMessage());
  41. }
  42. }
  43. @Override
  44. public void releaseConnection(Connection conn) {
  45. if (conn != null) {
  46. try {
  47. conn.close();
  48. } catch (SQLException e) {
  49. Logger.getLogger(J2EEConnectionPool.class.getName()).log(
  50. Level.FINE, "Could not release SQL connection", e);
  51. }
  52. }
  53. }
  54. @Override
  55. public void destroy() {
  56. dataSource = null;
  57. }
  58. }