001/* 002 * (C) Copyright 2010 Nuxeo SA (http://nuxeo.com/) and others. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 * 016 * Contributors: 017 * Nuxeo - initial API and implementation 018 */ 019 020package org.nuxeo.runtime.management.metrics; 021 022import java.lang.reflect.InvocationHandler; 023import java.lang.reflect.InvocationTargetException; 024import java.lang.reflect.Method; 025import java.lang.reflect.Proxy; 026 027import org.javasimon.SimonManager; 028import org.javasimon.Split; 029import org.javasimon.Stopwatch; 030 031public class MetricInvocationHandler<T> implements InvocationHandler { 032 033 protected final T proxied; 034 035 protected MetricInvocationHandler(T proxied) { 036 this.proxied = proxied; 037 } 038 039 @SuppressWarnings("unchecked") 040 public static <T> T newProxy(T proxied, Class<?>... classes) { 041 MetricInvocationHandler<T> handler = new MetricInvocationHandler<T>(proxied); 042 return (T) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), classes, handler); 043 } 044 045 protected String formatParms(Object... parms) { 046 if (parms == null) { 047 return ""; 048 } 049 StringBuffer buffer = new StringBuffer(); 050 for (Object parm : parms) { 051 buffer.append(".").append(parm); 052 } 053 return buffer.toString(); 054 } 055 056 protected String formatName(Method m, Object[] parms) { 057 Class<?> declaringClass = m.getDeclaringClass(); 058 return String.format("%s.%s", declaringClass.getSimpleName(), m.getName()); 059 } 060 061 protected String formatNote(Method m, Object[] parms) { 062 return String.format("%s#%s(%s)", m.getDeclaringClass().getSimpleName(), m.getName(), formatParms(parms)); 063 } 064 065 protected Stopwatch getStopwatch(Method m, Object[] parms) { 066 String name = formatName(m, parms); 067 Stopwatch stopwatch = SimonManager.getStopwatch(name); 068 stopwatch.setNote(formatNote(m, parms)); 069 return stopwatch; 070 } 071 072 @Override 073 public Object invoke(Object proxy, Method m, Object[] parms) throws Throwable { 074 Split split = getStopwatch(m, parms).start(); 075 try { 076 return m.invoke(proxied, parms); 077 } catch (InvocationTargetException e) { 078 throw e.getTargetException(); 079 } finally { 080 split.stop(); 081 } 082 } 083 084}