001/**
002 * Copyright (c) 2011, The University of Southampton and the individual contributors.
003 * All rights reserved.
004 *
005 * Redistribution and use in source and binary forms, with or without modification,
006 * are permitted provided that the following conditions are met:
007 *
008 *   *  Redistributions of source code must retain the above copyright notice,
009 *      this list of conditions and the following disclaimer.
010 *
011 *   *  Redistributions in binary form must reproduce the above copyright notice,
012 *      this list of conditions and the following disclaimer in the documentation
013 *      and/or other materials provided with the distribution.
014 *
015 *   *  Neither the name of the University of Southampton nor the names of its
016 *      contributors may be used to endorse or promote products derived from this
017 *      software without specific prior written permission.
018 *
019 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
020 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
021 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
022 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
023 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
024 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
025 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
026 * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
027 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
028 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
029 */
030package org.openimaj.experiment.agent;
031
032import java.lang.instrument.ClassFileTransformer;
033
034import javassist.CannotCompileException;
035import javassist.CtClass;
036import javassist.CtMethod;
037import javassist.CtNewMethod;
038import javassist.NotFoundException;
039
040import org.openimaj.aop.ClassTransformer;
041import org.openimaj.experiment.annotations.Time;
042
043/**
044 * {@link ClassFileTransformer} that dynamically augments classes and methods
045 * annotated with {@link Time} annotations in order to register and collect the
046 * method timing information.
047 *
048 * @author Jonathon Hare (jsh2@ecs.soton.ac.uk)
049 */
050public class TimeClassTransformer implements ClassTransformer {
051        @Override
052        public void transform(String className, CtClass ctclz) throws Exception {
053                final CtMethod[] methods = ctclz.getDeclaredMethods();
054
055                for (final CtMethod m : methods) {
056                        final Time ann = (Time) m.getAnnotation(Time.class);
057
058                        if (ann != null) {
059                                String timerName = ann.identifier();
060
061                                if (timerName == null || timerName.length() == 0)
062                                        timerName = String.format("%s#%s", className, m.getLongName());
063
064                                addTimingInterceptor(ctclz, m, timerName);
065                        }
066                }
067        }
068
069        /*
070         * Inspired by
071         * http://www.ibm.com/developerworks/java/library/j-dyn0916/index.html
072         */
073        private static void addTimingInterceptor(CtClass clazz, CtMethod method, String timerName)
074                        throws CannotCompileException, NotFoundException
075        {
076                final String oname = method.getName();
077                final String nname = oname + "$impl";
078                method.setName(nname);
079                final CtMethod interceptor = CtNewMethod.copy(method, oname, clazz, null);
080
081                final String type = method.getReturnType().getName();
082                final StringBuffer body = new StringBuffer();
083                body.append(
084                                "{\n" +
085                                                "org.openimaj.time.NanoTimer timer = org.openimaj.time.NanoTimer.timer();\n"
086                                );
087
088                if (!"void".equals(type)) {
089                        body.append(type + " result = ");
090                }
091                body.append(nname + "($$);\n");
092
093                body.append(
094                                "timer.stop();" +
095                                                "org.openimaj.experiment.agent.TimeTracker.accumulate(\"" + timerName
096                                                + "\", timer.duration());\n"
097                                );
098
099                if (!"void".equals(type)) {
100                        body.append("return result;\n");
101                }
102                body.append("}");
103
104                interceptor.setBody(body.toString());
105                clazz.addMethod(interceptor);
106        }
107}