001/* 002 * Copyright 2002-2017 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 * https://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 017package org.springframework.instrument.classloading; 018 019import java.io.IOException; 020import java.io.InputStream; 021import java.lang.instrument.ClassFileTransformer; 022import java.lang.instrument.IllegalClassFormatException; 023import java.net.URL; 024import java.util.Enumeration; 025import java.util.HashMap; 026import java.util.LinkedList; 027import java.util.List; 028import java.util.Map; 029 030import org.springframework.core.DecoratingClassLoader; 031import org.springframework.util.Assert; 032import org.springframework.util.FileCopyUtils; 033import org.springframework.util.StringUtils; 034 035/** 036 * ClassLoader decorator that shadows an enclosing ClassLoader, 037 * applying registered transformers to all affected classes. 038 * 039 * @author Rob Harrop 040 * @author Juergen Hoeller 041 * @author Costin Leau 042 * @since 2.0 043 * @see #addTransformer 044 * @see org.springframework.core.OverridingClassLoader 045 */ 046public class ShadowingClassLoader extends DecoratingClassLoader { 047 048 /** Packages that are excluded by default */ 049 public static final String[] DEFAULT_EXCLUDED_PACKAGES = 050 new String[] {"java.", "javax.", "sun.", "oracle.", "com.sun.", "com.ibm.", "COM.ibm.", 051 "org.w3c.", "org.xml.", "org.dom4j.", "org.eclipse", "org.aspectj.", "net.sf.cglib", 052 "org.springframework.cglib", "org.apache.xerces.", "org.apache.commons.logging."}; 053 054 055 private final ClassLoader enclosingClassLoader; 056 057 private final List<ClassFileTransformer> classFileTransformers = new LinkedList<ClassFileTransformer>(); 058 059 private final Map<String, Class<?>> classCache = new HashMap<String, Class<?>>(); 060 061 062 /** 063 * Create a new ShadowingClassLoader, decorating the given ClassLoader, 064 * applying {@link #DEFAULT_EXCLUDED_PACKAGES}. 065 * @param enclosingClassLoader the ClassLoader to decorate 066 * @see #ShadowingClassLoader(ClassLoader, boolean) 067 */ 068 public ShadowingClassLoader(ClassLoader enclosingClassLoader) { 069 this(enclosingClassLoader, true); 070 } 071 072 /** 073 * Create a new ShadowingClassLoader, decorating the given ClassLoader. 074 * @param enclosingClassLoader the ClassLoader to decorate 075 * @param defaultExcludes whether to apply {@link #DEFAULT_EXCLUDED_PACKAGES} 076 * @since 4.3.8 077 */ 078 public ShadowingClassLoader(ClassLoader enclosingClassLoader, boolean defaultExcludes) { 079 Assert.notNull(enclosingClassLoader, "Enclosing ClassLoader must not be null"); 080 this.enclosingClassLoader = enclosingClassLoader; 081 if (defaultExcludes) { 082 for (String excludedPackage : DEFAULT_EXCLUDED_PACKAGES) { 083 excludePackage(excludedPackage); 084 } 085 } 086 } 087 088 089 /** 090 * Add the given ClassFileTransformer to the list of transformers that this 091 * ClassLoader will apply. 092 * @param transformer the ClassFileTransformer 093 */ 094 public void addTransformer(ClassFileTransformer transformer) { 095 Assert.notNull(transformer, "Transformer must not be null"); 096 this.classFileTransformers.add(transformer); 097 } 098 099 /** 100 * Copy all ClassFileTransformers from the given ClassLoader to the list of 101 * transformers that this ClassLoader will apply. 102 * @param other the ClassLoader to copy from 103 */ 104 public void copyTransformers(ShadowingClassLoader other) { 105 Assert.notNull(other, "Other ClassLoader must not be null"); 106 this.classFileTransformers.addAll(other.classFileTransformers); 107 } 108 109 110 @Override 111 public Class<?> loadClass(String name) throws ClassNotFoundException { 112 if (shouldShadow(name)) { 113 Class<?> cls = this.classCache.get(name); 114 if (cls != null) { 115 return cls; 116 } 117 return doLoadClass(name); 118 } 119 else { 120 return this.enclosingClassLoader.loadClass(name); 121 } 122 } 123 124 /** 125 * Determine whether the given class should be excluded from shadowing. 126 * @param className the name of the class 127 * @return whether the specified class should be shadowed 128 */ 129 private boolean shouldShadow(String className) { 130 return (!className.equals(getClass().getName()) && !className.endsWith("ShadowingClassLoader") && 131 isEligibleForShadowing(className)); 132 } 133 134 /** 135 * Determine whether the specified class is eligible for shadowing 136 * by this class loader. 137 * @param className the class name to check 138 * @return whether the specified class is eligible 139 * @see #isExcluded 140 */ 141 protected boolean isEligibleForShadowing(String className) { 142 return !isExcluded(className); 143 } 144 145 146 private Class<?> doLoadClass(String name) throws ClassNotFoundException { 147 String internalName = StringUtils.replace(name, ".", "/") + ".class"; 148 InputStream is = this.enclosingClassLoader.getResourceAsStream(internalName); 149 if (is == null) { 150 throw new ClassNotFoundException(name); 151 } 152 try { 153 byte[] bytes = FileCopyUtils.copyToByteArray(is); 154 bytes = applyTransformers(name, bytes); 155 Class<?> cls = defineClass(name, bytes, 0, bytes.length); 156 // Additional check for defining the package, if not defined yet. 157 if (cls.getPackage() == null) { 158 int packageSeparator = name.lastIndexOf('.'); 159 if (packageSeparator != -1) { 160 String packageName = name.substring(0, packageSeparator); 161 definePackage(packageName, null, null, null, null, null, null, null); 162 } 163 } 164 this.classCache.put(name, cls); 165 return cls; 166 } 167 catch (IOException ex) { 168 throw new ClassNotFoundException("Cannot load resource for class [" + name + "]", ex); 169 } 170 } 171 172 private byte[] applyTransformers(String name, byte[] bytes) { 173 String internalName = StringUtils.replace(name, ".", "/"); 174 try { 175 for (ClassFileTransformer transformer : this.classFileTransformers) { 176 byte[] transformed = transformer.transform(this, internalName, null, null, bytes); 177 bytes = (transformed != null ? transformed : bytes); 178 } 179 return bytes; 180 } 181 catch (IllegalClassFormatException ex) { 182 throw new IllegalStateException(ex); 183 } 184 } 185 186 187 @Override 188 public URL getResource(String name) { 189 return this.enclosingClassLoader.getResource(name); 190 } 191 192 @Override 193 public InputStream getResourceAsStream(String name) { 194 return this.enclosingClassLoader.getResourceAsStream(name); 195 } 196 197 @Override 198 public Enumeration<URL> getResources(String name) throws IOException { 199 return this.enclosingClassLoader.getResources(name); 200 } 201 202}