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.aop;
031
032import java.io.ByteArrayInputStream;
033import java.lang.instrument.ClassFileTransformer;
034import java.lang.instrument.IllegalClassFormatException;
035import java.security.ProtectionDomain;
036import java.util.ArrayList;
037import java.util.List;
038
039import javassist.CannotCompileException;
040import javassist.ClassPool;
041import javassist.CtClass;
042import javassist.NotFoundException;
043import javassist.Translator;
044
045import org.apache.log4j.Logger;
046
047/**
048 * A {@link ClassFileTransformer} that applies one or more
049 * {@link ClassTransformer}s to a class before it is loaded.
050 * 
051 * @author Jonathon Hare (jsh2@ecs.soton.ac.uk)
052 */
053public class MultiTransformClassFileTransformer implements ClassFileTransformer, Translator {
054        private static Logger logger = Logger.getLogger(MultiTransformClassFileTransformer.class);
055
056        private ClassPool classPool;
057        private List<ClassTransformer> transformers = new ArrayList<ClassTransformer>();
058
059        /**
060         * Construct with the given {@link ClassTransformer}s.
061         * 
062         * @param t1
063         *            the first transformer
064         * @param transformers
065         *            any additional transformers
066         */
067        public MultiTransformClassFileTransformer(ClassTransformer t1, ClassTransformer... transformers) {
068                this.transformers.add(t1);
069
070                for (final ClassTransformer ct : transformers)
071                        this.transformers.add(ct);
072        }
073
074        @Override
075        public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined,
076                        ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException
077        {
078                return transform(className, classfileBuffer);
079        }
080
081        /**
082         * Transform the given class.
083         * 
084         * @param className
085         *            the name of the class
086         * @param classfileBuffer
087         *            the class bytes
088         * @return the transformed bytes
089         */
090        public byte[] transform(String className, byte[] classfileBuffer) {
091                if (classPool == null)
092                        classPool = ClassPool.getDefault();
093
094                try {
095                        final CtClass ctclz = classPool.makeClass(new ByteArrayInputStream(classfileBuffer));
096
097                        transform(className, ctclz);
098
099                        return ctclz.toBytecode();
100                } catch (final Exception e) {
101                        e.printStackTrace();
102                        logger.error("Error transforming class " + className);
103                        return classfileBuffer;
104                }
105        }
106
107        private void transform(String className, CtClass ctclz) throws Exception {
108                for (final ClassTransformer ct : transformers)
109                        ct.transform(className, ctclz);
110        }
111
112        @Override
113        public void start(ClassPool pool) throws NotFoundException, CannotCompileException {
114                this.classPool = pool;
115        }
116
117        @Override
118        public void onLoad(ClassPool pool, String classname) throws NotFoundException, CannotCompileException {
119                if (classname.endsWith(".package-info"))
120                        return;
121
122                final CtClass clz = pool.get(classname);
123
124                try {
125                        transform(classname, clz);
126                } catch (final Exception e) {
127                        throw new CannotCompileException(e);
128                }
129        }
130}