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.aspectj;
018    
019    import org.apache.commons.monitoring.aop.AbstractPerformanceInterceptor;
020    import org.aspectj.lang.ProceedingJoinPoint;
021    import org.aspectj.lang.Signature;
022    import org.aspectj.lang.annotation.Around;
023    import org.aspectj.lang.annotation.Aspect;
024    import org.aspectj.lang.annotation.Pointcut;
025    
026    import java.lang.reflect.Method;
027    
028    @Aspect
029    public abstract class CommonsMonitoringAspect extends AbstractPerformanceInterceptor<ProceedingJoinPoint> {
030        @Pointcut
031        protected abstract void pointcut();
032    
033        @Around("pointcut()")
034        public Object monitor(final ProceedingJoinPoint pjp) throws Throwable {
035            return doInvoke(pjp);
036        }
037    
038        @Override
039        protected Object proceed(final ProceedingJoinPoint invocation) throws Throwable {
040            return invocation.proceed();
041        }
042    
043        @Override
044        protected String getCounterName(final ProceedingJoinPoint invocation) {
045            final String monitorName = getCounterName(invocation.getTarget(), findMethod(invocation.getSignature()));
046            if (monitorName != null) {
047                return monitorName;
048            }
049            return invocation.getSignature().toLongString();
050        }
051    
052        private static Method findMethod(final Signature signature) {
053            if ("org.aspectj.runtime.reflect.MethodSignatureImpl".equals(signature.getClass().getName())) {
054                try {
055                    final Method mtd = signature.getClass().getMethod("getMethod");
056                    if (!mtd.isAccessible()) {
057                        mtd.setAccessible(true);
058                    }
059                    return Method.class.cast(mtd.invoke(signature));
060                } catch (final Exception e) {
061                    // no-op
062                }
063            }
064            return null;
065        }
066    }