001    package biz.hammurapi.metrics;
002    
003    import java.lang.reflect.Method;
004    import java.util.Stack;
005    
006    import org.codehaus.aspectwerkz.joinpoint.MethodSignature;
007    import org.codehaus.aspectwerkz.joinpoint.StaticJoinPoint;
008    
009    import biz.hammurapi.metrics.MeasurementCategory;
010    import biz.hammurapi.metrics.MeasurementCategoryFactory;
011    
012    /**
013     * Metrics collecting aspect.
014     * @author Pavel
015     */
016    public class MetricsAspect {
017            private static MeasurementCategory mc = MeasurementCategoryFactory
018                            .getCategory(MetricsAspect.class);
019    
020            /**
021             * Call stack
022             */
023            private ThreadLocal calls = new ThreadLocal() {
024    
025                    protected Object initialValue() {
026                            return new Stack();
027                    }
028    
029            };
030    
031            /**
032             * This method pushes method start time to a thread local stack.
033             * @param joinPoint
034             */
035            public void before(StaticJoinPoint joinPoint) {
036                    ((Stack) calls.get()).push(new Long(System.currentTimeMillis()));
037            }
038    
039            /**
040             * This method pops method start time from the thread local stack and reports method duration measurement.
041             * @param joinPoint
042             */
043            public void after(StaticJoinPoint joinPoint) {
044                    Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
045                    Stack tlStack = (Stack) calls.get();
046                    if (!tlStack.isEmpty()) {
047                            Long start = (Long) (tlStack).pop();
048            
049                            if (start != null) {    
050                                    long now = System.currentTimeMillis();  
051                                    mc.addMeasurement(method.toString(), now - start.longValue(), now);     
052                            }
053                    }
054            }
055    
056    }