001 /* 002 @license.text@ 003 */ 004 package biz.hammurapi.jms; 005 006 import java.io.IOException; 007 import java.util.Timer; 008 import java.util.TimerTask; 009 010 import javax.jms.JMSException; 011 import javax.jms.Session; 012 import javax.jms.TextMessage; 013 import javax.jms.Topic; 014 import javax.jms.TopicConnection; 015 import javax.jms.TopicPublisher; 016 import javax.jms.TopicSession; 017 import javax.xml.parsers.ParserConfigurationException; 018 import javax.xml.transform.TransformerException; 019 020 import biz.hammurapi.config.ConfigurationException; 021 022 /** 023 * Sends collected metrics to JMS topic. 024 * @author Pavel Vlasov 025 * @revision $Revision$ 026 */ 027 public class JmsTopicSliceConsumer extends JmsSliceConsumer { 028 029 private Topic topic; 030 private TopicConnection connection; 031 032 /** 033 * @param timer Shared timer to schedule send. If null then internal timer is used. 034 * @param interval Send interval. 035 * @param connection JMS connection. 036 * @param topic JMS topic. 037 */ 038 public JmsTopicSliceConsumer(Timer timer, long interval, TopicConnection connection, Topic topic) { 039 super(timer, interval); 040 this.connection=connection; 041 this.topic=topic; 042 } 043 044 private TimerTask sendTask=new TimerTask() { 045 046 public void run() { 047 try { 048 TopicSession session=connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); 049 try { 050 TextMessage msg = session.createTextMessage(); 051 msg.setText(getSlicesXml()); 052 TopicPublisher publisher = session.createPublisher(topic); 053 try { 054 publisher.publish(msg); 055 } finally { 056 publisher.close(); 057 } 058 } finally { 059 session.close(); 060 } 061 } catch (JMSException e) { 062 System.err.println("[WARNING] Could not send metrics to topic: "+e); 063 e.printStackTrace(); 064 } catch (IOException e) { 065 System.err.println("[WARNING] Could not write slices to message: "+e); 066 e.printStackTrace(); 067 } catch (TransformerException e) { 068 System.err.println("[WARNING] Could not write slices to XML: "+e); 069 e.printStackTrace(); 070 } catch (ParserConfigurationException e) { 071 System.err.println("[WARNING] Could not write slices to XML: "+e); 072 e.printStackTrace(); 073 } 074 075 } 076 077 }; 078 079 public void start() throws ConfigurationException { 080 super.start(); 081 timer.schedule(sendTask, interval, interval); 082 } 083 084 public void stop() throws ConfigurationException { 085 sendTask.cancel(); 086 // Send remaining metrics. 087 sendTask.run(); 088 super.stop(); 089 } 090 091 }