1 46 47 package com.coridan.sample.dbtwophase.mdb; 48 49 import java.sql.Connection ; 50 import java.sql.SQLException ; 51 import java.sql.Statement ; 52 53 import javax.ejb.EJBException ; 54 import javax.ejb.MessageDrivenBean ; 55 import javax.ejb.MessageDrivenContext ; 56 import javax.jms.JMSException ; 57 import javax.jms.Message ; 58 import javax.jms.MessageListener ; 59 import javax.jms.TextMessage ; 60 import javax.naming.InitialContext ; 61 import javax.naming.NamingException ; 62 import javax.sql.DataSource ; 63 64 import org.apache.commons.logging.Log; 65 import org.apache.commons.logging.LogFactory; 66 67 public class DB2PhaseMDB implements MessageDrivenBean , MessageListener { 68 private static final Log log = LogFactory.getLog(DB2PhaseMDB.class); 69 private transient MessageDrivenContext mdc = null; 70 71 private DataSource ds = null; 73 74 int count = 0; 76 77 78 public DB2PhaseMDB() { 79 } 80 81 82 public void setMessageDrivenContext(MessageDrivenContext arg0) throws EJBException { 83 mdc = arg0; 84 } 85 86 public void ejbCreate() { 87 try { 88 InitialContext ctx = new InitialContext (); 89 log.info("Looking up data source java:/MySQLDB"); 90 ds = (DataSource )ctx.lookup("java:/MySQLDB"); 91 } catch (NamingException e) { 92 log.error("Error during ejbCreate()", e); 93 } 94 } 95 96 public void ejbRemove() throws EJBException { 97 } 98 99 public void onMessage(Message arg0) { 100 Statement stmt = null; 101 Connection conn = null; 102 try { 103 TextMessage msg = (TextMessage )arg0; 104 String text = msg.getText(); 105 log.info("Got message: "+text); 106 log.info("Getting connection to data source"); 107 conn = ds.getConnection(); 108 stmt = conn.createStatement(); 109 log.info("Executing statement - check db"); 110 stmt.executeUpdate("insert into messages values ('"+text+"')"); 111 } catch (SQLException e) { 112 log.error("Exception during onMessage()", e); 113 } catch (JMSException e) { 114 log.error("Exception during onMessage()", e); 115 } 116 finally { 117 if (stmt != null) { 118 try { 119 stmt.close(); 120 } catch (SQLException e) { 121 e.printStackTrace(); 122 } 123 } 124 if (conn != null) { 125 log.info("Closing data source connection"); 126 try { 127 conn.close(); 128 } catch (SQLException e) { 129 e.printStackTrace(); 130 } 131 } 132 count++; 133 if (count%5 == 0) { 134 log.info("Testing rollback!"); 135 mdc.setRollbackOnly(); 136 } 137 } 138 } 139 } 140 141 142 143 | Popular Tags |