1 22 package org.jboss.varia.stats; 23 24 import org.jboss.tm.TransactionLocal; 25 26 import javax.transaction.Transaction ; 27 import javax.transaction.Synchronization ; 28 import javax.transaction.Status ; 29 import java.util.Map ; 30 import java.util.HashMap ; 31 import java.util.Iterator ; 32 import java.util.Set ; 33 import java.util.HashSet ; 34 35 39 public class TxStatistics 40 { 41 private final Map reports = new HashMap (); 42 private final Set collectedItemNames = new HashSet (); 43 44 private final TransactionLocal txReport = new TransactionLocal() 45 { 46 protected Object initialValue() 47 { 48 Transaction tx = getTransaction(); 49 TxReport report; 50 if(tx != null) 51 { 52 report = new TxReport(); 53 try 54 { 55 tx.registerSynchronization(new TxSynchronization(report)); 56 } 57 catch(Exception e) 58 { 59 e.printStackTrace(); 60 throw new IllegalStateException ("Failed to register tx synchronization: " + e.getMessage()); 61 } 62 } 63 else 64 { 65 report = null; 66 } 67 return report; 68 } 69 }; 70 71 public String [] getCollectedItemNames() 72 { 73 return (String [])collectedItemNames.toArray(new String [collectedItemNames.size()]); 74 } 75 76 public Iterator getReports() 77 { 78 return reports.values().iterator(); 79 } 80 81 public synchronized void clear() 82 { 83 reports.clear(); 84 collectedItemNames.clear(); 85 } 86 87 public synchronized void addStatisticalItem(StatisticalItem item) 88 { 89 TxReport report = (TxReport) txReport.get(); 90 if(report != null) 91 { 92 boolean addedNew = report.addItem(item); 93 if(addedNew) 94 { 95 collectedItemNames.add(item.getName()); 96 } 97 } 98 } 99 100 private synchronized void addReport(TxReport report) 101 { 102 TxReport oldReport = (TxReport)reports.get(report.getName()); 103 if(oldReport == null) 104 { 105 reports.put(report.getName(), report); 106 } 107 else 108 { 109 oldReport.merge(report); 110 } 111 } 112 113 public TxReport getReports(String reportName) 114 { 115 return (TxReport)reports.get(reportName); 116 } 117 118 120 private class TxSynchronization implements Synchronization 121 { 122 private final TxReport report; 123 124 public TxSynchronization(TxReport report) 125 { 126 this.report = report; 127 } 128 129 public void beforeCompletion() 130 { 131 } 132 133 public void afterCompletion(int status) 134 { 135 if(status != Status.STATUS_ROLLEDBACK) 136 { 137 try 138 { 139 addReport(report); 140 } 141 catch(Exception e) 142 { 143 e.printStackTrace(); 144 } 145 } 146 } 147 } 148 } 149 | Popular Tags |