1 22 package org.jboss.varia.counter; 23 24 import java.text.DecimalFormat ; 25 import java.util.HashMap ; 26 import java.util.Iterator ; 27 import java.util.Vector ; 28 import javax.naming.InitialContext ; 29 import javax.naming.NamingException ; 30 import javax.naming.Reference ; 31 import javax.naming.StringRefAddr ; 32 import org.jboss.system.ServiceMBeanSupport; 33 import org.jboss.naming.NonSerializableFactory; 34 35 44 public class CounterService 45 extends ServiceMBeanSupport 46 implements CounterServiceMBean 47 { 48 public static final String JNDI_NAME = "java:/CounterService"; 49 50 private HashMap counterMap = new HashMap (); 51 52 56 public void accumulate(String counterName, long add) 57 { 58 Counter counter = null; 59 synchronized (counterMap) 60 { 61 counter = (Counter)counterMap.get(counterName); 62 if (counter == null) 63 { 64 counter = new Counter(counterName); 65 counterMap.put(counterName, counter); 66 } 67 } 68 counter.addToCount(add); 69 } 70 71 protected void startService() throws Exception 72 { 73 InitialContext ctx = new InitialContext (); 74 75 NonSerializableFactory.bind(JNDI_NAME, this); 77 StringRefAddr addr = new StringRefAddr ("nns", JNDI_NAME); 78 Reference ref = new Reference (this.getClass().getName(), addr, NonSerializableFactory.class.getName(), null); 79 ctx.bind(JNDI_NAME, ref); 80 } 81 82 protected void stopService() throws Exception 83 { 84 InitialContext ctx = new InitialContext (); 85 ctx.unbind(JNDI_NAME); 86 NonSerializableFactory.unbind(JNDI_NAME); 87 } 88 89 92 public String list() 93 { 94 DecimalFormat format = new DecimalFormat ("####0.0000"); 95 String retVal = ""; 96 Iterator keys = counterMap.keySet().iterator(); 97 while (keys.hasNext()) 98 { 99 String key = (String )keys.next(); 100 Counter counter = (Counter)counterMap.get(key); 101 long total = 0; 102 int entries = 0; 103 synchronized (counter) 104 { total = counter.getCount(); 106 entries = counter.getEntries(); 107 } 108 double avg = ((double)total)/((double)entries); 109 String descrip = key+": total="+total+" on "+entries+"entries for "+ 110 "an average of "+format.format(avg)+"<br>\n"; 111 retVal += descrip; 112 } 113 return retVal; 114 } 115 116 private static class Counter 117 { 118 private String name; 119 private long count=0; 120 private int entries=0; 121 122 public Counter(String n) 123 { 124 name = n; 125 } 126 127 public String getName() 128 { 129 return name; 130 } 131 132 public synchronized long getCount() 133 { 134 return count; 135 } 136 137 public synchronized int getEntries() 138 { 139 return entries; 140 } 141 142 public synchronized void addToCount(long add) 143 { 144 count += add; 145 entries++; 146 } 147 } 148 } 149 | Popular Tags |