001package var.mom.jms.log; 002 003import javax.jms.Connection; 004import javax.jms.ConnectionFactory; 005import javax.jms.Destination; 006import javax.jms.JMSException; 007import javax.jms.Message; 008import javax.jms.MessageConsumer; 009import javax.jms.Session; 010import javax.jms.TextMessage; 011import javax.naming.Context; 012import javax.naming.InitialContext; 013import javax.naming.NamingException; 014 015/** 016 * synchronous provider for the log service 017 * 018 * @author Sandro Leuchter 019 * 020 */ 021 022public class ConsumerPullNode { 023 private Connection connection; 024 private Session session; 025 private MessageConsumer consumer; 026 027 /** 028 * constructor, establishes and starts connection to JMS provider specified in 029 * JNDI (via jndi.properties), afterwards consumer is ready 030 * 031 * @throws NamingException JNDI exceptions 032 * @throws JMSException JMS exceptions 033 */ 034 public ConsumerPullNode() throws NamingException, JMSException { 035 Context ctx = new InitialContext(); 036 ConnectionFactory factory = (ConnectionFactory) ctx.lookup("ConnectionFactory"); 037 Destination queue = (Destination) ctx.lookup(Conf.QUEUE); 038 this.connection = factory.createConnection(); 039 this.session = this.connection.createSession(false, Session.AUTO_ACKNOWLEDGE); 040 this.consumer = this.session.createConsumer(queue); 041 this.connection.start(); 042 } 043 044 /** 045 * synchronously receives the TextMessages in an infinite loop and prints 046 * payload text to StdOut 047 * 048 * @param timeout timeout in ms 049 * @see javax.jms.TextMessage 050 * @throws JMSException JMS exceptions 051 */ 052 public void receiveAndPrintMessages(long timeout) throws JMSException { 053 Message message; 054 while ((message = this.consumer.receive(timeout)) != null) { 055 if (message instanceof TextMessage) { 056 TextMessage textMessage = (TextMessage) message; 057 String messageText = textMessage.getText(); 058 System.out.println(messageText); 059 } 060 } 061 } 062 063 /** 064 * main routine and starting point of program 065 * 066 * @param args[0] time to wait in ms 067 */ 068 public static void main(String[] args) { 069 long timeout = Long.parseLong(args[0]); 070 ConsumerPullNode node = null; 071 try { 072 node = new ConsumerPullNode(); 073 node.receiveAndPrintMessages(timeout); 074 } catch (NamingException | JMSException e) { 075 System.err.println(e); 076 } finally { 077 try { 078 if ((node != null) && (node.consumer != null)) { 079 node.consumer.close(); 080 } 081 if ((node != null) && (node.session != null)) { 082 node.session.close(); 083 } 084 if ((node != null) && (node.connection != null)) { 085 node.connection.close(); 086 } 087 } catch (JMSException e) { 088 System.err.println(e); 089 } 090 } 091 } 092}