View Javadoc
1   package org.myorg.encconfig.ejb;
2   
3   import java.util.Date;
4   
5   import javax.ejb.EJBException;
6   import javax.jms.Connection;
7   import javax.jms.ConnectionFactory;
8   import javax.jms.JMSException;
9   import javax.jms.MessageProducer;
10  import javax.jms.Session;
11  import javax.jms.TextMessage;
12  import javax.jms.Topic;
13  import javax.naming.Context;
14  import javax.naming.NamingException;
15  import javax.persistence.EntityManager;
16  
17  import org.myorg.encconfig.bo.AuditRecord;
18  import org.slf4j.Logger;
19  
20  public abstract class AuditorBase {
21  	private Logger log_;
22  	private boolean publishJMS_;
23  	private EntityManager em_;
24  	private ConnectionFactory cf_;
25  	private Topic topic_;
26  
27  	public void setLog(Logger log) { this.log_ = log; }
28  	public void setEntityManager(EntityManager em) { this.em_ = em; }
29  	public void setConnectionFactory(ConnectionFactory cf) { this.cf_ = cf; }
30  	public void setTopic(Topic topic) { this.topic_ = topic; }
31  	public void setPublishJMS(boolean publishJMS) { 
32  		this.publishJMS_ = publishJMS; 
33  	}
34  	public int audit(String message) {
35  		AuditRecord rec = new AuditRecord(new Date(), message);
36  		int actions=0;
37  		if (persistRecord(rec) != null) {
38  			actions += 1;
39  		}
40  		if (publishJMS_ && cf_ != null) {
41  			publishRecord(rec);
42  			actions += 1;
43  		}
44  		return actions;
45  	}
46  	
47  	protected AuditRecord persistRecord(AuditRecord rec) {
48  		if (em_!=null) {
49  			em_.persist(rec);
50  			log_.debug("message persisted:{}", rec);
51  			return rec;		
52  		}
53  		return null;
54  	}
55  	
56  	
57  	protected void publishRecord(AuditRecord rec) {
58  		Connection connection=null;
59  		Session session = null;
60  		MessageProducer publisher = null;
61  		try {
62  			connection = cf_.createConnection();
63  			session = connection.createSession(
64  					false, Session.AUTO_ACKNOWLEDGE);
65  			TextMessage msg = session.createTextMessage(rec.getMessage());
66  			publisher = session.createProducer(topic_);
67  			publisher.send(msg);
68  			log_.debug("message sent:{}", msg);
69  		} catch (JMSException ex) {
70  			log_.error("error sending JMS message", ex);
71  			throw new EJBException("error sending JMS message:"+ex);
72  		} finally {
73  			close(connection, session);
74  		}
75  	}
76  	
77  	protected void close(Connection conn, Session session) {
78  		try { if (session != null) { session.close(); } } 
79  		catch (JMSException ex) {log_.info("error closing session", ex); }
80  		try { if (conn != null) { conn.close(); } } 
81  		catch (JMSException ex) {log_.info("error closing connection", ex); }
82  	}
83  	protected void close(Context jndi) {
84  		try { if (jndi != null) { jndi.close(); } } 
85  		catch (NamingException ex) {log_.info("error closing jndi", ex); }
86  	}
87  
88  }