KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > cayenne > enhancer > Enhancer


1 /*****************************************************************
2  * Licensed to the Apache Software Foundation (ASF) under one
3  * or more contributor license agreements. See the NOTICE file
4  * distributed with this work for additional information
5  * regarding copyright ownership. The ASF licenses this file
6  * to you under the Apache License, Version 2.0 (the
7  * "License"); you may not use this file except in compliance
8  * with the License. You may obtain a copy of the License at
9  *
10  * http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing,
13  * software distributed under the License is distributed on an
14  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15  * KIND, either express or implied. See the License for the
16  * specific language governing permissions and limitations
17  * under the License.
18  ****************************************************************/

19 package org.apache.cayenne.enhancer;
20
21 import java.lang.instrument.ClassFileTransformer JavaDoc;
22 import java.lang.instrument.IllegalClassFormatException JavaDoc;
23 import java.security.ProtectionDomain JavaDoc;
24
25 import org.apache.commons.logging.Log;
26 import org.apache.commons.logging.LogFactory;
27 import org.objectweb.asm.ClassReader;
28 import org.objectweb.asm.ClassVisitor;
29 import org.objectweb.asm.ClassWriter;
30
31 /**
32  * A ClassFileTransformer that delegates class enhancement to a chain of ASM transformers
33  * provided by the {@link EnhancerVisitorFactory}.
34  *
35  * @since 3.0
36  * @author Andrus Adamchik
37  */

38 public class Enhancer implements ClassFileTransformer JavaDoc {
39
40     protected Log logger;
41     protected EnhancerVisitorFactory visitorFactory;
42
43     public Enhancer(EnhancerVisitorFactory visitorFactory) {
44         logger = LogFactory.getLog(getClass());
45         this.visitorFactory = visitorFactory;
46     }
47
48     public byte[] transform(
49             ClassLoader JavaDoc loader,
50             String JavaDoc className,
51             Class JavaDoc<?> classBeingRedefined,
52             ProtectionDomain JavaDoc protectionDomain,
53             byte[] classfileBuffer) throws IllegalClassFormatException JavaDoc {
54
55         ClassReader reader = new ClassReader(classfileBuffer);
56         ClassWriter writer = new ClassWriter(reader, true);
57
58         ClassVisitor visitor = visitorFactory.createVisitor(className, writer);
59         if (visitor == null) {
60             // per instrumentation docs, if no transformation occured, we must return null
61
return null;
62         }
63
64         logger.info("enhancing class " + className);
65         reader.accept(visitor, true);
66         return writer.toByteArray();
67     }
68 }
69
Popular Tags