001 /* 002 @license.text@ 003 */ 004 package biz.hammurapi.jms; 005 006 import java.io.IOException; 007 import java.util.ArrayList; 008 import java.util.Collection; 009 import java.util.HashMap; 010 import java.util.Map; 011 import java.util.Timer; 012 013 import javax.xml.parsers.ParserConfigurationException; 014 import javax.xml.transform.TransformerException; 015 016 import biz.hammurapi.config.Component; 017 import biz.hammurapi.config.ConfigurationException; 018 import biz.hammurapi.metrics.Slice; 019 import biz.hammurapi.metrics.SliceConsumer; 020 import biz.hammurapi.xml.dom.DOMUtils; 021 022 023 /** 024 * Collects slices for a period of time and send them 025 * as JMS text message with XML payload. 026 * @author Pavel Vlasov 027 * @revision $Revision$ 028 */ 029 public abstract class JmsSliceConsumer implements SliceConsumer, Component { 030 protected Timer timer; 031 private boolean isOwnTimer; 032 protected long interval; 033 034 /** 035 * @param timer Timer to use for scheduling. If null than internal timer 036 * is created. 037 * @param interval Send interval. 038 */ 039 public JmsSliceConsumer(Timer timer, long interval) { 040 super(); 041 this.timer=timer; 042 this.interval=interval; 043 } 044 045 private Map slices=new HashMap(); 046 047 public boolean consumeSlice(String category, Slice slice) { 048 synchronized (slices) { 049 Collection bucket=(Collection) slices.get(category); 050 if (bucket==null) { 051 bucket=new ArrayList(); 052 slices.put(category, bucket); 053 } 054 bucket.add(slice); 055 return true; 056 } 057 } 058 059 /** 060 * Converts accumulated slices to XML. Clears internal slices map. 061 * @throws ParserConfigurationException 062 * @throws TransformerException 063 * @throws IOException 064 * @return Slices in XML format. 065 */ 066 protected String getSlicesXml() throws IOException, TransformerException, ParserConfigurationException { 067 synchronized (slices) { 068 try { 069 return DOMUtils.toXmlString(slices, "slices"); 070 } finally { 071 slices.clear(); 072 } 073 } 074 } 075 076 public void start() throws ConfigurationException { 077 if (timer==null) { 078 timer=new Timer(); 079 isOwnTimer=true; 080 } 081 082 } 083 084 public void stop() throws ConfigurationException { 085 if (isOwnTimer) { 086 timer.cancel(); 087 } 088 } 089 090 public void setOwner(Object owner) { 091 // Nothing 092 } 093 094 }