1 18 19 package sync4j.exchange.util; 20 21 import java.sql.Connection ; 22 import java.sql.PreparedStatement ; 23 import java.sql.ResultSet ; 24 import java.sql.SQLException ; 25 26 import javax.sql.DataSource ; 27 import javax.naming.InitialContext ; 28 import javax.naming.NameNotFoundException ; 29 import javax.naming.NamingException ; 30 31 import sync4j.exchange.DataAccessException; 32 33 40 public class DataAccess { 41 42 44 private static final String JNDI_DATASOURCE_NAME_BUNDLE = "java:comp/env/jdbc/sync4j"; 45 private static final String JNDI_DATASOURCE_NAME_JBOSS = "java:/jdbc/sync4j" ; 46 47 48 50 private String jndiDataSourceName = null; 51 52 54 57 protected transient DataSource dataSource = null; 58 59 61 62 public DataAccess() 63 throws DataAccessException { 64 setJndiDataSourceName(); 65 } 66 67 69 public void setJndiDataSourceName() 70 throws DataAccessException { 71 72 try { 73 74 InitialContext ctx = new InitialContext (); 75 76 try { 77 jndiDataSourceName = JNDI_DATASOURCE_NAME_JBOSS ; 78 dataSource = (DataSource ) ctx.lookup(jndiDataSourceName ) ; 79 } catch (NameNotFoundException e) { 80 jndiDataSourceName = JNDI_DATASOURCE_NAME_BUNDLE ; 81 dataSource = (DataSource ) ctx.lookup(jndiDataSourceName ) ; 82 } 83 84 } catch (NamingException e) { 85 throw new DataAccessException ("Data source " 86 + jndiDataSourceName 87 + " not found " 88 + e.toString() 89 ); 90 } 91 } 92 93 98 public Connection getConnection () 99 throws DataAccessException { 100 101 Connection con = null; 102 103 try { 104 105 con = this.dataSource.getConnection(); 106 107 } catch (SQLException e) { 108 throw new DataAccessException 109 ("Error creating connection: " + e.getMessage()); 110 } 111 112 return con; 113 114 } 115 116 125 public void cleanUp (Connection con , 126 PreparedStatement ps , 127 ResultSet rs ) 128 throws DataAccessException { 129 130 try { 131 132 if (con != null) { 133 con.close(); 134 con = null; 135 } 136 137 if (ps != null) { 138 ps.close(); 139 ps = null; 140 } 141 142 if (rs != null) { 143 rs.close(); 144 rs = null; 145 } 146 147 } catch (SQLException e) { 148 throw new DataAccessException 149 ("Error cleaning up connection: " + e.getMessage()); 150 } 151 152 } 153 154 } | Popular Tags |