001/* 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache license, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the license for the specific language governing permissions and 015 * limitations under the license. 016 */ 017package org.apache.logging.log4j.util; 018 019import java.io.IOException; 020import java.lang.reflect.InvocationTargetException; 021import java.net.URL; 022import java.security.AccessController; 023import java.security.PrivilegedAction; 024import java.util.Collection; 025import java.util.Enumeration; 026import java.util.LinkedHashSet; 027import java.util.Objects; 028 029/** 030 * <em>Consider this class private.</em> Utility class for ClassLoaders. 031 * 032 * @see ClassLoader 033 * @see RuntimePermission 034 * @see Thread#getContextClassLoader() 035 * @see ClassLoader#getSystemClassLoader() 036 */ 037public final class LoaderUtil { 038 039 /** 040 * System property to set to ignore the thread context ClassLoader. 041 * 042 * @since 2.1 043 */ 044 public static final String IGNORE_TCCL_PROPERTY = "log4j.ignoreTCL"; 045 046 private static final SecurityManager SECURITY_MANAGER = System.getSecurityManager(); 047 048 // this variable must be lazily loaded; otherwise, we get a nice circular class loading problem where LoaderUtil 049 // wants to use PropertiesUtil, but then PropertiesUtil wants to use LoaderUtil. 050 private static Boolean ignoreTCCL; 051 052 private static final boolean GET_CLASS_LOADER_DISABLED; 053 054 private static final PrivilegedAction<ClassLoader> TCCL_GETTER = new ThreadContextClassLoaderGetter(); 055 056 static { 057 if (SECURITY_MANAGER != null) { 058 boolean getClassLoaderDisabled; 059 try { 060 SECURITY_MANAGER.checkPermission(new RuntimePermission("getClassLoader")); 061 getClassLoaderDisabled = false; 062 } catch (final SecurityException ignored) { 063 getClassLoaderDisabled = true; 064 } 065 GET_CLASS_LOADER_DISABLED = getClassLoaderDisabled; 066 } else { 067 GET_CLASS_LOADER_DISABLED = false; 068 } 069 } 070 071 private LoaderUtil() { 072 } 073 074 /** 075 * Gets the current Thread ClassLoader. Returns the system ClassLoader if the TCCL is {@code null}. If the system 076 * ClassLoader is {@code null} as well, then the ClassLoader for this class is returned. If running with a 077 * {@link SecurityManager} that does not allow access to the Thread ClassLoader or system ClassLoader, then the 078 * ClassLoader for this class is returned. 079 * 080 * @return the current ThreadContextClassLoader. 081 */ 082 public static ClassLoader getThreadContextClassLoader() { 083 if (GET_CLASS_LOADER_DISABLED) { 084 // we can at least get this class's ClassLoader regardless of security context 085 // however, if this is null, there's really no option left at this point 086 return LoaderUtil.class.getClassLoader(); 087 } 088 return SECURITY_MANAGER == null ? TCCL_GETTER.run() : AccessController.doPrivileged(TCCL_GETTER); 089 } 090 091 /** 092 * 093 */ 094 private static class ThreadContextClassLoaderGetter implements PrivilegedAction<ClassLoader> { 095 @Override 096 public ClassLoader run() { 097 final ClassLoader cl = Thread.currentThread().getContextClassLoader(); 098 if (cl != null) { 099 return cl; 100 } 101 final ClassLoader ccl = LoaderUtil.class.getClassLoader(); 102 return ccl == null && !GET_CLASS_LOADER_DISABLED ? ClassLoader.getSystemClassLoader() : ccl; 103 } 104 } 105 106 /** 107 * Loads a class by name. This method respects the {@link #IGNORE_TCCL_PROPERTY} Log4j property. If this property is 108 * specified and set to anything besides {@code false}, then the default ClassLoader will be used. 109 * 110 * @param className The class name. 111 * @return the Class for the given name. 112 * @throws ClassNotFoundException if the specified class name could not be found 113 * @since 2.1 114 */ 115 public static Class<?> loadClass(final String className) throws ClassNotFoundException { 116 if (isIgnoreTccl()) { 117 return Class.forName(className); 118 } 119 try { 120 return getThreadContextClassLoader().loadClass(className); 121 } catch (final Throwable ignored) { 122 return Class.forName(className); 123 } 124 } 125 126 /** 127 * Loads and instantiates a Class using the default constructor. 128 * 129 * @param className The class name. 130 * @return new instance of the class. 131 * @throws ClassNotFoundException if the class isn't available to the usual ClassLoaders 132 * @throws IllegalAccessException if the class can't be instantiated through a public constructor 133 * @throws InstantiationException if there was an exception whilst instantiating the class 134 * @throws NoSuchMethodException if there isn't a no-args constructor on the class 135 * @throws InvocationTargetException if there was an exception whilst constructing the class 136 * @since 2.1 137 */ 138 public static Object newInstanceOf(final String className) throws ClassNotFoundException, IllegalAccessException, 139 InstantiationException, NoSuchMethodException, InvocationTargetException { 140 final Class<?> clazz = loadClass(className); 141 try { 142 return clazz.getConstructor().newInstance(); 143 } catch (final NoSuchMethodException ignored) { 144 // FIXME: looking at the code for Class.newInstance(), this seems to do the same thing as above 145 return clazz.newInstance(); 146 } 147 } 148 149 /** 150 * Loads and instantiates a derived class using its default constructor. 151 * 152 * @param className The class name. 153 * @param clazz The class to cast it to. 154 * @param <T> The type of the class to check. 155 * @return new instance of the class cast to {@code T} 156 * @throws ClassNotFoundException if the class isn't available to the usual ClassLoaders 157 * @throws IllegalAccessException if the class can't be instantiated through a public constructor 158 * @throws InstantiationException if there was an exception whilst instantiating the class 159 * @throws NoSuchMethodException if there isn't a no-args constructor on the class 160 * @throws InvocationTargetException if there was an exception whilst constructing the class 161 * @throws ClassCastException if the constructed object isn't type compatible with {@code T} 162 * @since 2.1 163 */ 164 public static <T> T newCheckedInstanceOf(final String className, final Class<T> clazz) 165 throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, 166 IllegalAccessException { 167 return clazz.cast(newInstanceOf(className)); 168 } 169 170 private static boolean isIgnoreTccl() { 171 // we need to lazily initialize this, but concurrent access is not an issue 172 if (ignoreTCCL == null) { 173 final String ignoreTccl = PropertiesUtil.getProperties().getStringProperty(IGNORE_TCCL_PROPERTY, null); 174 ignoreTCCL = ignoreTccl != null && !"false".equalsIgnoreCase(ignoreTccl.trim()); 175 } 176 return ignoreTCCL; 177 } 178 179 /** 180 * Finds classpath {@linkplain URL resources}. 181 * 182 * @param resource the name of the resource to find. 183 * @return a Collection of URLs matching the resource name. If no resources could be found, then this will be empty. 184 * @since 2.1 185 */ 186 public static Collection<URL> findResources(final String resource) { 187 final Collection<UrlResource> urlResources = findUrlResources(resource); 188 final Collection<URL> resources = new LinkedHashSet<>(urlResources.size()); 189 for (final UrlResource urlResource : urlResources) { 190 resources.add(urlResource.getUrl()); 191 } 192 return resources; 193 } 194 195 static Collection<UrlResource> findUrlResources(final String resource) { 196 final ClassLoader[] candidates = {getThreadContextClassLoader(), LoaderUtil.class.getClassLoader(), 197 GET_CLASS_LOADER_DISABLED ? null : ClassLoader.getSystemClassLoader()}; 198 final Collection<UrlResource> resources = new LinkedHashSet<>(); 199 for (final ClassLoader cl : candidates) { 200 if (cl != null) { 201 try { 202 final Enumeration<URL> resourceEnum = cl.getResources(resource); 203 while (resourceEnum.hasMoreElements()) { 204 resources.add(new UrlResource(cl, resourceEnum.nextElement())); 205 } 206 } catch (final IOException e) { 207 e.printStackTrace(); 208 } 209 } 210 } 211 return resources; 212 } 213 214 /** 215 * {@link URL} and {@link ClassLoader} pair. 216 */ 217 static class UrlResource { 218 private final ClassLoader classLoader; 219 private final URL url; 220 221 public UrlResource(final ClassLoader classLoader, final URL url) { 222 this.classLoader = classLoader; 223 this.url = url; 224 } 225 226 public ClassLoader getClassLoader() { 227 return classLoader; 228 } 229 230 public URL getUrl() { 231 return url; 232 } 233 234 @Override 235 public boolean equals(final Object o) { 236 if (this == o) { 237 return true; 238 } 239 if (o == null || getClass() != o.getClass()) { 240 return false; 241 } 242 243 final UrlResource that = (UrlResource) o; 244 245 if (classLoader != null ? !classLoader.equals(that.classLoader) : that.classLoader != null) { 246 return false; 247 } 248 if (url != null ? !url.equals(that.url) : that.url != null) { 249 return false; 250 } 251 252 return true; 253 } 254 255 @Override 256 public int hashCode() { 257 return Objects.hashCode(classLoader) + Objects.hashCode(url); 258 } 259 } 260}