1 package example; 2 3 import java.io.*; 4 import java.util.*; 5 import java.util.logging.*; 6 import javax.jms.*; 7 import javax.ejb.*; 8 import javax.naming.*; 9 10 public class AdProducer 11 implements MessageDrivenBean, MessageListener { 12 13 private static final Logger log = 14 Logger.getLogger(AdProducer.class.getName()); 15 16 private MessageDrivenContext _messageDrivenContext; 17 private Random _random = new Random(); 18 private Session _jmsSession; 19 private Connection _connection; 20 private ConnectionFactory _connectionFactory; 21 private SessionContext _sessionContext; 22 private MessageProducer _producer; 23 24 private static final String [] _ads = { 25 "Buy widgets", 26 "Watch this movie", 27 "Eat at Joe's", 28 "Learn a new trade", 29 "Find your mate" 30 }; 31 32 public void setMessageDrivenContext(MessageDrivenContext messageDrivenContext) 33 throws EJBException 34 { 35 _messageDrivenContext = messageDrivenContext; 36 } 37 38 public void ejbCreate() 39 { 40 try { 41 Context context = (Context) new InitialContext().lookup("java:comp/env"); 42 43 ConnectionFactory connectionFactory = 44 (ConnectionFactory) context.lookup("jms/ConnectionFactory"); 45 46 Destination destination = (Destination) context.lookup("jms/AdQueue"); 47 48 _connection = connectionFactory.createConnection(); 49 _jmsSession = _connection.createSession(false, Session.AUTO_ACKNOWLEDGE); 50 _producer = _jmsSession.createProducer(destination); 51 52 TextMessage outgoingMessage = _jmsSession.createTextMessage(); 54 55 String ad = _ads[_random.nextInt(_ads.length)]; 56 57 outgoingMessage.setText(ad); 58 59 _producer.send(outgoingMessage); 60 } catch (Exception e) { 61 log.fine(e.toString()); 62 } 63 } 64 65 public void onMessage(Message incomingMessage) 66 { 67 try { 68 TextMessage outgoingMessage = _jmsSession.createTextMessage(); 69 70 String ad = _ads[_random.nextInt(_ads.length)]; 71 72 outgoingMessage.setText(ad); 73 74 _producer.send(outgoingMessage); 75 } catch (JMSException e) { 76 _messageDrivenContext.setRollbackOnly(); 77 } 78 } 79 80 public void ejbRemove() 81 { 82 try { 83 _connection.close(); 84 } catch (JMSException e) { 85 log.fine(e.toString()); 86 } 87 } 88 } 89 90 | Popular Tags |