1 2 import java.sql.Connection ; 3 import java.sql.SQLException ; 4 import java.util.Properties ; 5 6 import javax.naming.InitialContext ; 7 import javax.sql.XAConnection ; 8 import javax.sql.XADataSource ; 9 import org.objectweb.jotm.Jotm; 10 import org.objectweb.transaction.jta.TMService; 11 12 import org.enhydra.jdbc.standard.StandardXADataSource; 13 14 15 public class DatabaseHelper { 16 17 private String password; 18 private TMService jotm; 19 private XADataSource xads; 20 private String login; 21 private static final String USER_TRANSACTION_JNDI_NAME = "UserTransaction"; 22 23 26 public DatabaseHelper() { 27 Properties props = new Properties (); 28 try { 29 props.load(ClassLoader.getSystemResourceAsStream("spy.properties")); 30 } catch (Exception e) { 31 System.err.println("no properties file found to init the database"); 32 System.exit(1); 33 } 34 35 System.out.println("\n database configuration:"); 36 props.list(System.out); 37 System.out.println("------------------------\n"); 38 39 login = props.getProperty("login"); 40 password = props.getProperty("password"); 41 42 try { 44 jotm = new Jotm(true, false); 46 InitialContext ictx = new InitialContext (); 47 ictx.rebind(USER_TRANSACTION_JNDI_NAME, jotm.getUserTransaction()); 48 } catch (Exception e) { 49 e.printStackTrace(); 50 System.exit(1); 51 } 52 53 xads = new StandardXADataSource(); 54 try { 55 ((StandardXADataSource) xads).setDriverName(props.getProperty("driver")); 56 ((StandardXADataSource) xads).setUrl(props.getProperty("url")); 57 ((StandardXADataSource) xads).setTransactionManager(jotm.getTransactionManager()); 58 } catch (Exception e) { 59 e.printStackTrace(); 60 System.exit(1); 61 } 62 } 63 64 public Connection getConnection() throws SQLException { 65 XAConnection xaconn = xads.getXAConnection(login, password); 66 return xaconn.getConnection(); 67 } 68 71 public void stop() { 72 try { 73 InitialContext ictx = new InitialContext (); 74 ictx.unbind(USER_TRANSACTION_JNDI_NAME); 75 } catch (Exception e) { 76 e.printStackTrace(); 77 } 78 jotm.stop(); 79 jotm = null; 80 } 81 82 } 83 84 | Popular Tags |