Using JMS %2F MDB to Log to a MySql

Using JMS %2F MDB to Log to a MySql Database Here is a fully working EJB3 tutorial for using JMS /Message Driven Beans as a logger to a MySql database. This should be everything you need in order to successfully run a working demo. This is tested with the following setup: * * * * Windows XP sp2 MySQL 5.0.13 and Connector/J 3.1.11 JBoss 4.0.3 (Oct.2005 release) Java 1.5.0_05 Explanation. Here's how the logging works. Client: 1. 2. 3. A Servlet, JSP or EJB wants to make a log entry, so they create a new par.LogEntry object The par.LogEntry object is sent to the ejb3.LoggerBean through the ejb3.Logger interface The ejb3.LoggerBean adds the par.LogEntry object to the JMS Message Driven Bean Queue Server: 1. 2. 3. The ejb3.LoggingService grabs the par.LogEntry object from the Queue The par.LogEntry object is sent to the ejb3.LogWriterBean through the ejb3.LogWriter interface The ejb3.LogWriterBean persists the par.LogEntry object in the database This is what your ear should look like when everything is set up correctly. Generated by Clearspace on 2009-05-31-04:00 1 Using JMS %2F MDB to Log to a MySql Database I'll go through the necessary portions of each file mentioned. EAR File (MyTest.ear) --------------------|-meta-inf |----application.xml |----Manifest.mf | |-MyTest.par |----meta-inf |--------Manifest.mf |--------persistence.xml |----par |--------LogEntry.class | |-MyTest.war |----meta-inf |--------Manifest.mf |----web-inf |--------jboss-web.xml |--------web.xml |--------classes |------------web |----------------TestServlet.class | |-MyTest.ejb3 |----meta-inf |--------Manifest.mf |----ejb3 |--------Logger.class |--------LoggerBean.class |--------LoggingService.class |--------LogWriter.class |--------LogWriterBean.class 1. MyTest.ear - Section 1 will go over the necessary files for MyTest.ear 1a. application.xml - I am using the context-root of MyTest, so when you test the application, your url will be similar to http://localhost:8080/MyTest. Generated by Clearspace on 2009-05-31-04:00 2 Using JMS %2F MDB to Log to a MySql Database My Logging Test MyTest.ejb3 MyTest.par MyTest.war MyTest 2. MyTest.par - Section 2 will go over the necessary files of MyTest.par 2a. persistence.xml MyTestPar java:/MyTestDS Generated by Clearspace on 2009-05-31-04:00 3 Using JMS %2F MDB to Log to a MySql Database 2b. Set up the following table in MySql CREATE TABLE `log_records` ( `id` int(10) unsigned NOT NULL auto_increment, `date` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP, `level` enum('info','warning','debug','severe') NOT NULL, `message` text NOT NULL, PRIMARY KEY (`id`) ) 2c. LogEntry.class - Since this is a basic example, we will only record the id, date, level and message package par; import javax.persistence.Entity; import javax.persistence.GeneratorType; import javax.persistence.Id; import javax.persistence.Table; import javax.servlet.http.HttpServletRequest; import java.sql.Timestamp; import java.util.GregorianCalendar; import java.util.logging.Level; import java.io.Serializable; @Entity @Table(name = "log_records") public class LogEntry implements Serializable { private int id; private Timestamp date; private String level; private String message; public LogEntry() { } public LogEntry(final Level lvl, final String msg) { date = new Timestamp(new GregorianCalendar().getTimeInMillis()); level = lvl.getName(); message = msg; } @Id(generate = GeneratorType.AUTO) public int getId() { return id; } public void setId( final int id ) { this.id = id; } Generated by Clearspace on 2009-05-31-04:00 4 Using JMS %2F MDB to Log to a MySql Database public Timestamp getDate() { return date; } public void setDate( final Timestamp date) { this.date= date; } public String getLevel() { return level; } public void setLevel( final String level ) { this.level = level; } public String getMessage() { return message; } public void setMessage( final String message ) { this.message = message; } } 2d. Make sure you make a file called MyTest-ds.xml and place it in the deploy folder of JBoss server. You will need to set the mySchemaName, myUserName and myPassword variables for your own settings. Make sure your user has enough permissions to select,insert,delete, etc... MyTestDS jdbc:mysql://localhost:3306/mySchemaName com.mysql.jdbc.Driver myUserName myPassword org.jboss.resource.adapter.jdbc.vendor.MySQLExceptionSorter mySQL Generated by Clearspace on 2009-05-31-04:00 5 Using JMS %2F MDB to Log to a MySql Database 2e. Make sure you put the Connector/J jar file (mysql-connector-java-3.1.11-bin.jar) into your JBoss servers lib directory (i.e. c:\jboss-4.0.3\server\default\lib) 3. MyTest.war - Section 3 will go over the necessary files of MyTest.war 3a. jboss-web.xml java:/jaas/MyTest jdbc/LoggerDB java:/MyTestDS 3b. web.xml TestServlet web.TestServlet TestServlet /LogTest Generated by Clearspace on 2009-05-31-04:00 6 Using JMS %2F MDB to Log to a MySql Database Log Writer Connection jdbc/LoggerDB javax.sql.DataSource Container 3c. TestServlet.class package web; import ejb3.Logger; import par.LogEntry; import javax.naming.InitialContext; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.logging.Level; public class TestServlet extends HttpServlet { protected void doPost(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOExceptio testLogger(response); } protected void doGet(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException testLogger(response); } private void testLogger(final HttpServletResponse response) throws IOException{ int numberOfLogsToCreate = 5; final ServletOutputStream out = response.getOutputStream(); try { final InitialContext ctx = new InitialContext(); final Logger logger = (Logger) ctx.lookup(Logger.class.getName()); for(int x=0; x < numberOfLogsToCreate; x++){ final LogEntry logEntry = new LogEntry(Level.WARNING, "Msg #"+x); logger.sendEntry(logEntry); } out.println("" + numberOfLogsToCreate + " Logs created"); } catch(Exception e){ System.out.println("logging attempt failed: "+e.toString()); out.println("" + e.getMessage() + ""); } finally{ out.flush(); Generated by Clearspace on 2009-05-31-04:00 7 Using JMS %2F MDB to Log to a MySql Database out.close(); } } } 4. MyTest.ejb3 - Section 4 will go over the necessary files of MyTest.ejb3 4a. Logger.class package ejb3; import par.LogEntry; public interface Logger { void sendEntry(LogEntry logEntry); } 4b. LoggerBean.class package ejb3; import par.LogEntry; import javax.ejb.Stateless; import javax.jms.*; import javax.naming.InitialContext; @Stateless public class LoggerBean implements Logger { public void sendEntry(final LogEntry logEntry) { QueueConnection cnn = null; QueueSession sess = null; QueueSender sender = null; try { final InitialContext ctx = new InitialContext(); final Queue queue = (Queue) ctx.lookup("queue/myCustomLog"); final QueueConnectionFactory factory = (QueueConnectionFactory) ctx.lookup("ConnectionFactory"); cnn = factory.createQueueConnection(); sess = cnn.createQueueSession(false, QueueSession.AUTO_ACKNOWLEDGE); final ObjectMessage objMessage = sess.createObjectMessage(logEntry); sender = sess.createSender(queue); sender.send(objMessage); } catch (Exception e) { e.printStackTrace(); } Generated by Clearspace on 2009-05-31-04:00 8 Using JMS %2F MDB to Log to a MySql Database finally { try { if (sess != null) { sess.close(); } } catch (Exception e2) { System.err.println("Could not close logger session"); } try { if (sender != null) { sender.close(); } } catch (Exception e2) { System.err.println("Could not close logger sender"); } try { if (cnn != null) { cnn.close(); } } catch (Exception e2) { System.err.println("Could not close logger queue connection"); } } } } 4c. LoggingService.class package ejb3; import par.LogEntry; import javax.ejb.ActivationConfigProperty; import javax.ejb.MessageDriven; import javax.jms.Message; import javax.jms.MessageListener; import javax.jms.ObjectMessage; import javax.naming.InitialContext; @MessageDriven(activateConfig = { @ActivationConfigProperty(propertyName="destinationType", propertyValue="javax.jms.Queue"), @ActivationConfigProperty(propertyName="destination", propertyValue="queue/myCustomLog") }) public class LoggingService implements MessageListener { Generated by Clearspace on 2009-05-31-04:00 9 Using JMS %2F MDB to Log to a MySql Database public void onMessage (Message msg) { try { final ObjectMessage objMessage = (ObjectMessage)msg; final LogEntry logEntry = (LogEntry)objMessage.getObject(); try{ final InitialContext ctx = new InitialContext(); final LogWriter logWriter = (LogWriter) ctx.lookup(LogWriter.class.getName()); logWriter.addLog(logEntry); } catch(Exception e){ // If you get an error, you probably want to insert code // in here to failover the logs to a text file System.err.println("Could not log file to database. "+e.toString()); } } catch (Exception e) { e.printStackTrace (); } } } 4d. LogWriter.class package ejb3; import par.LogEntry; public interface LogWriter { void addLog(LogEntry logEntry ); } 4e. LogWriterBean.class package ejb3; import par.LogEntry; import javax.persistence.PersistenceContext; import javax.persistence.EntityManager; import javax.ejb.Stateless; @Stateless public class LogWriterBean implements LogWriter { @PersistenceContext(unitName = "MyTestPar") EntityManager em; public void addLog( final LogEntry logEntry ) { System.out.println( "Setting Log Entry: "+logEntry.toString() ); Generated by Clearspace on 2009-05-31-04:00 10 Using JMS %2F MDB to Log to a MySql Database em.merge(logEntry); } } 5. Create and deploy the ear file from the files shown above. You may have to restart JBoss so it can pick up the MyTest-ds.xml file. 6. Test the program by calling the url (Most likely http://localhost:8080/MyTest/LogTest) Generated by Clearspace on 2009-05-31-04:00 11

Related docs
JMS
Views: 39  |  Downloads: 1
JMS_speakernoted
Views: 0  |  Downloads: 0
Mysql
Views: 936  |  Downloads: 112
MySQL Tutorial
Views: 128  |  Downloads: 40
PHP and MySQL
Views: 531  |  Downloads: 107
MySQL for Developers
Views: 198  |  Downloads: 47
JMS Brochure.indd
Views: 0  |  Downloads: 0
mysql
Views: 162  |  Downloads: 11
MySQL
Views: 54  |  Downloads: 4
MySQL
Views: 3115  |  Downloads: 59
MySQL Databases
Views: 121  |  Downloads: 17
mysql-tutorial
Views: 404  |  Downloads: 24
PHP-MySQL Interview Question
Views: 1255  |  Downloads: 125
SOAP Over JMS
Views: 90  |  Downloads: 2
premium docs
Other docs by derek Shouman
Transcript of Platt Amendment
Views: 198  |  Downloads: 0
Sample Executive Summary Noverus
Views: 262  |  Downloads: 1
Rent collection policies and procedures
Views: 578  |  Downloads: 15
dfsd
Views: 149  |  Downloads: 0
Scrap iron and metal business
Views: 335  |  Downloads: 6
Chapter 7 bankruptcy
Views: 563  |  Downloads: 19
Biometrics_Study
Views: 180  |  Downloads: 16
bste
Views: 152  |  Downloads: 2
Promissory Note for Business Loan Balloon Pmts
Views: 316  |  Downloads: 13
Transcript of Sherman Anti Trust Act
Views: 144  |  Downloads: 0
Sample Executive Summary Heartsoft
Views: 373  |  Downloads: 4
Transcript of Virginia Plan
Views: 239  |  Downloads: 0
25 Things You Should Have Learned by Middle Age
Views: 357  |  Downloads: 4
Oregon amendment of limited partnership
Views: 296  |  Downloads: 1