001 /*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements. See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License. You may obtain a copy of the License at
008 *
009 * http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017 package org.apache.commons.monitoring.aop;
018
019 import org.apache.commons.monitoring.configuration.Configuration;
020 import org.apache.commons.monitoring.util.ClassLoaders;
021 import org.apache.commons.proxy.Invoker;
022 import org.apache.commons.proxy.ProxyFactory;
023
024 import java.lang.reflect.InvocationTargetException;
025 import java.lang.reflect.Method;
026
027 public final class MonitoringProxyFactory {
028 private static final ProxyFactory PROXY_FACTORY = Configuration.newInstance(ProxyFactory.class);
029
030 public static <T> T monitor(final Class<T> clazz, final Object instance) {
031 return clazz.cast(PROXY_FACTORY.createInvokerProxy(ClassLoaders.current(), new MonitoringHandler(instance), new Class<?>[]{clazz}));
032 }
033
034 private MonitoringProxyFactory() {
035 // no-op
036 }
037
038 private static class MonitoringHandler extends AbstractPerformanceInterceptor<Invocation> implements Invoker {
039 private final Object instance;
040
041 public MonitoringHandler(final Object instance) {
042 this.instance = instance;
043 }
044
045 @Override
046 public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
047 return doInvoke(new Invocation(instance, method, args));
048 }
049
050 @Override
051 protected Object proceed(final Invocation invocation) throws Throwable {
052 try {
053 return invocation.method.invoke(invocation.target, invocation.args);
054 } catch (final InvocationTargetException ite) {
055 throw ite.getCause();
056 }
057 }
058
059 @Override
060 protected String getCounterName(final Invocation invocation) {
061 return getCounterName(invocation.target, invocation.method);
062 }
063 }
064
065 private static class Invocation {
066 private final Object target;
067 private final Method method;
068 private final Object[] args;
069
070 private Invocation(final Object target, final Method method, final Object[] args) {
071 this.target = target;
072 this.method = method;
073 this.args = args;
074 }
075 }
076 }