001package var.mom.jms.echo; 002 003import javax.jms.Connection; 004import javax.jms.ConnectionFactory; 005import javax.jms.JMSException; 006import javax.jms.Message; 007import javax.jms.MessageConsumer; 008import javax.jms.MessageListener; 009import javax.jms.MessageProducer; 010import javax.jms.Queue; 011import javax.jms.Session; 012import javax.jms.TextMessage; 013import javax.naming.Context; 014import javax.naming.InitialContext; 015import javax.naming.NamingException; 016 017/** 018 * replier node for the echo service 019 * 020 * @author Sandro Leuchter 021 * 022 */ 023public class EchoReplierNode implements MessageListener { 024 private Connection connection; 025 private Session session; 026 private MessageConsumer consumer; 027 028 /** 029 * constructor, establishes and starts connection to JMS provider specified in 030 * JNDI (via jndi.properties), afterwards consumer is ready 031 * 032 * @throws NamingException JNDI exceptions 033 * @throws JMSException JMS exceptions 034 */ 035 public EchoReplierNode() throws NamingException, JMSException { 036 Context ctx = new InitialContext(); 037 ConnectionFactory factory = (ConnectionFactory) ctx.lookup("ConnectionFactory"); 038 Queue queue = (Queue) ctx.lookup(Conf.QUEUE); 039 this.connection = factory.createConnection(); 040 this.session = this.connection.createSession(false, Session.AUTO_ACKNOWLEDGE); 041 this.consumer = this.session.createConsumer(queue); 042 this.consumer.setMessageListener(this); 043 this.connection.start(); 044 } 045 046 /** 047 * asynchronous message consumption 048 * 049 * @see javax.jms.MessageListener 050 */ 051 @Override 052 public void onMessage(Message request) { 053 try { 054 if (request instanceof TextMessage) { 055 TextMessage requestText = (TextMessage) request; 056 System.out.println("empfangen: " + requestText.getText()); 057 MessageProducer replyProducer = this.session.createProducer(request.getJMSReplyTo()); 058 TextMessage reply = this.session.createTextMessage(); 059 reply.setText("echo: " + requestText.getText()); 060 Thread.sleep(5000); 061 replyProducer.send(reply); 062 replyProducer.close(); 063 } 064 } catch (JMSException | InterruptedException e) { 065 System.err.println(e); 066 } 067 068 } 069 070 /** 071 * main routine and starting point of program 072 * 073 * @param args not used 074 */ 075 public static void main(String[] args) { 076 EchoReplierNode node = null; 077 try { 078 node = new EchoReplierNode(); 079 while (true) { 080 Thread.sleep(1000); 081 } 082 } catch (InterruptedException | NamingException | JMSException e) { 083 System.err.println(e); 084 } finally { 085 try { 086 if ((node != null) && (node.consumer != null)) { 087 node.consumer.close(); 088 } 089 if ((node != null) && (node.session != null)) { 090 node.session.close(); 091 } 092 if ((node != null) && (node.connection != null)) { 093 node.connection.close(); 094 } 095 } catch (JMSException e) { 096 System.err.println(e); 097 } 098 } 099 } 100}