001    package org.shiftone.jrat.jvmti;
002    
003    
004    import org.shiftone.jrat.core.criteria.MethodCriteria;
005    import org.shiftone.jrat.util.Assert;
006    import org.shiftone.jrat.util.log.Logger;
007    
008    import java.lang.instrument.ClassFileTransformer;
009    import java.lang.instrument.IllegalClassFormatException;
010    import java.security.ProtectionDomain;
011    
012    
013    /**
014     * @author jeff@shiftone.org (Jeff Drost)
015     */
016    public class FilterClassFileTransformer implements ClassFileTransformer {
017    
018        private static final Logger LOG = Logger.getLogger(FilterClassFileTransformer.class);
019        private final MethodCriteria methodCriteria;
020        private final ClassFileTransformer transformer;
021    
022        public FilterClassFileTransformer(MethodCriteria methodCriteria, ClassFileTransformer transformer) {
023            Assert.assertNotNull("methodCriteria", methodCriteria);
024            Assert.assertNotNull("transformer", transformer);
025            this.methodCriteria = methodCriteria;
026            this.transformer = transformer;
027        }
028    
029    
030        public byte[] transform(
031                ClassLoader loader,
032                String className,
033                Class /* <?> */ classBeingRedefined,
034                ProtectionDomain protectionDomain,
035                byte[] classfileBuffer)
036                throws IllegalClassFormatException {
037    
038    
039            String fixedClassName = className.replace('/', '.');
040    
041            int modifiers = 0;
042    
043            if (classBeingRedefined != null) {
044                modifiers = classBeingRedefined.getModifiers();
045            }
046    
047            if (methodCriteria.isMatch(fixedClassName, modifiers)) {
048    
049                return transformer.transform(
050                        loader,
051                        className,
052                        classBeingRedefined,
053                        protectionDomain,
054                        classfileBuffer);
055    
056            } else {
057    
058                return classfileBuffer;
059    
060            }
061    
062        }
063    
064        public String toString() {
065            return "FilterClassFileTransformer[" + methodCriteria + " : " + transformer + "]";
066        }
067    }