001: /*
002: * Copyright 2002-2007 the original author or authors.
003: *
004: * Licensed under the Apache License, Version 2.0 (the "License");
005: * you may not use this file except in compliance with the License.
006: * You may obtain a copy of the License at
007: *
008: * http://www.apache.org/licenses/LICENSE-2.0
009: *
010: * Unless required by applicable law or agreed to in writing, software
011: * distributed under the License is distributed on an "AS IS" BASIS,
012: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013: * See the License for the specific language governing permissions and
014: * limitations under the License.
015: */
016:
017: package org.springframework.instrument.classloading;
018:
019: import java.io.IOException;
020: import java.io.InputStream;
021: import java.lang.instrument.ClassFileTransformer;
022: import java.lang.instrument.IllegalClassFormatException;
023: import java.net.URL;
024: import java.util.Enumeration;
025: import java.util.HashMap;
026: import java.util.LinkedList;
027: import java.util.List;
028: import java.util.Map;
029:
030: import org.springframework.util.Assert;
031: import org.springframework.util.FileCopyUtils;
032: import org.springframework.util.StringUtils;
033:
034: /**
035: * ClassLoader decorator that shadows an enclosing ClassLoader, applying
036: * registered transformers to all affected classes.
037: *
038: * @author Rob Harrop
039: * @author Rod Johnson
040: * @author Costin Leau
041: * @author Juergen Hoeller
042: * @since 2.0
043: * @see #addTransformer
044: * @see #isClassNameExcludedFromShadowing(String)
045: */
046: public class ShadowingClassLoader extends ClassLoader {
047:
048: /** Packages that are excluded by default */
049: public static final String[] DEFAULT_EXCLUDED_PACKAGES = new String[] {
050: "java.", "javax.", "sun.", "com.sun.", "org.w3c.",
051: "org.xml.", "org.dom4j.", "org.aspectj.",
052: "org.apache.xerces.", "org.apache.commons.logging." };
053:
054: private final ClassLoader enclosingClassLoader;
055:
056: private final List<ClassFileTransformer> classFileTransformers = new LinkedList<ClassFileTransformer>();
057:
058: private final Map<String, Class> classCache = new HashMap<String, Class>();
059:
060: /**
061: * Create a new ShadowingClassLoader, decorating the given ClassLoader.
062: * @param enclosingClassLoader the ClassLoader to decorate
063: */
064: public ShadowingClassLoader(ClassLoader enclosingClassLoader) {
065: Assert.notNull(enclosingClassLoader,
066: "Enclosing ClassLoader must not be null");
067: this .enclosingClassLoader = enclosingClassLoader;
068: }
069:
070: /**
071: * Add the given ClassFileTransformer to the list of transformers that this
072: * ClassLoader will apply.
073: * @param transformer the ClassFileTransformer
074: */
075: public void addTransformer(ClassFileTransformer transformer) {
076: Assert.notNull(transformer, "Transformer must not be null");
077: this .classFileTransformers.add(transformer);
078: }
079:
080: /**
081: * Copy all ClassFileTransformers from the given ClassLoader to the list of
082: * transformers that this ClassLoader will apply.
083: * @param other the ClassLoader to copy from
084: */
085: public void copyTransformers(ShadowingClassLoader other) {
086: Assert.notNull(other, "Other ClassLoader must not be null");
087: this .classFileTransformers.addAll(other.classFileTransformers);
088: }
089:
090: public Class<?> loadClass(String name)
091: throws ClassNotFoundException {
092: if (shouldShadow(name)) {
093: Class cls = this .classCache.get(name);
094: if (cls != null) {
095: return cls;
096: }
097: return doLoadClass(name);
098: } else {
099: return this .enclosingClassLoader.loadClass(name);
100: }
101: }
102:
103: /**
104: * Determine whether the given class should be excluded from shadowing.
105: * @param className the name of the class
106: * @return whether the specified class should be shadowed
107: */
108: private boolean shouldShadow(String className) {
109: return (!className.equals(getClass().getName())
110: && !className.endsWith("ShadowingClassLoader")
111: && !isExcludedPackage(className) && !isClassNameExcludedFromShadowing(className));
112: }
113:
114: /**
115: * Determine whether the given class is defined in an excluded package.
116: * @param className the name of the class
117: * @return whether the specified package is excluded
118: */
119: private boolean isExcludedPackage(String className) {
120: for (int i = 0; i < DEFAULT_EXCLUDED_PACKAGES.length; i++) {
121: if (className.startsWith(DEFAULT_EXCLUDED_PACKAGES[i])) {
122: return true;
123: }
124: }
125: return false;
126: }
127:
128: /**
129: * Subclasses can override this method to specify whether or not a
130: * particular class should be excluded from shadowing.
131: * @param className the class name to test
132: * @return whether the specified class is excluded
133: */
134: protected boolean isClassNameExcludedFromShadowing(String className) {
135: return false;
136: }
137:
138: private Class doLoadClass(String name)
139: throws ClassNotFoundException {
140: String internalName = StringUtils.replace(name, ".", "/")
141: + ".class";
142: InputStream is = this .enclosingClassLoader
143: .getResourceAsStream(internalName);
144: if (is == null) {
145: throw new ClassNotFoundException(name);
146: }
147: try {
148: byte[] bytes = FileCopyUtils.copyToByteArray(is);
149: bytes = applyTransformers(name, bytes);
150: Class cls = defineClass(name, bytes, 0, bytes.length);
151: // Additional check for defining the package, if not defined yet.
152: if (cls.getPackage() == null) {
153: String packageName = name.substring(0, name
154: .lastIndexOf('.'));
155: definePackage(packageName, null, null, null, null,
156: null, null, null);
157: }
158: this .classCache.put(name, cls);
159: return cls;
160: } catch (IOException ex) {
161: throw new ClassNotFoundException(
162: "Cannot load resource for class [" + name + "]", ex);
163: }
164: }
165:
166: private byte[] applyTransformers(String name, byte[] bytes) {
167: String internalName = StringUtils.replace(name, ".", "/");
168: try {
169: for (ClassFileTransformer transformer : this .classFileTransformers) {
170: byte[] transformed = transformer.transform(this ,
171: internalName, null, null, bytes);
172: bytes = (transformed != null ? transformed : bytes);
173: }
174: return bytes;
175: } catch (IllegalClassFormatException ex) {
176: throw new IllegalStateException(ex);
177: }
178: }
179:
180: public URL getResource(String name) {
181: return this .enclosingClassLoader.getResource(name);
182: }
183:
184: public InputStream getResourceAsStream(String name) {
185: return this .enclosingClassLoader.getResourceAsStream(name);
186: }
187:
188: public Enumeration<URL> getResources(String name)
189: throws IOException {
190: return this.enclosingClassLoader.getResources(name);
191: }
192:
193: }
|