1 /*
2 * Licensed to the Apache Software Foundation (ASF) under one or more
3 * contributor license agreements. See the NOTICE file distributed with
4 * this work for additional information regarding copyright ownership.
5 * The ASF licenses this file to You under the Apache license, Version 2.0
6 * (the "License"); you may not use this file except in compliance with
7 * the License. You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the license for the specific language governing permissions and
15 * limitations under the license.
16 */
17 package org.apache.logging.log4j.util;
18
19 import java.io.IOException;
20 import java.lang.reflect.InvocationTargetException;
21 import java.net.URL;
22 import java.security.AccessController;
23 import java.security.PrivilegedAction;
24 import java.util.Collection;
25 import java.util.Enumeration;
26 import java.util.LinkedHashSet;
27 import java.util.Objects;
28
29 /**
30 * <em>Consider this class private.</em> Utility class for ClassLoaders.
31 *
32 * @see ClassLoader
33 * @see RuntimePermission
34 * @see Thread#getContextClassLoader()
35 * @see ClassLoader#getSystemClassLoader()
36 */
37 public final class LoaderUtil {
38
39 /**
40 * System property to set to ignore the thread context ClassLoader.
41 *
42 * @since 2.1
43 */
44 public static final String IGNORE_TCCL_PROPERTY = "log4j.ignoreTCL";
45
46 private static final SecurityManager SECURITY_MANAGER = System.getSecurityManager();
47
48 // this variable must be lazily loaded; otherwise, we get a nice circular class loading problem where LoaderUtil
49 // wants to use PropertiesUtil, but then PropertiesUtil wants to use LoaderUtil.
50 private static Boolean ignoreTCCL;
51
52 private static final boolean GET_CLASS_LOADER_DISABLED;
53
54 private static final PrivilegedAction<ClassLoader> TCCL_GETTER = new ThreadContextClassLoaderGetter();
55
56 static {
57 if (SECURITY_MANAGER != null) {
58 boolean getClassLoaderDisabled;
59 try {
60 SECURITY_MANAGER.checkPermission(new RuntimePermission("getClassLoader"));
61 getClassLoaderDisabled = false;
62 } catch (final SecurityException ignored) {
63 getClassLoaderDisabled = true;
64 }
65 GET_CLASS_LOADER_DISABLED = getClassLoaderDisabled;
66 } else {
67 GET_CLASS_LOADER_DISABLED = false;
68 }
69 }
70
71 private LoaderUtil() {
72 }
73
74 /**
75 * Gets the current Thread ClassLoader. Returns the system ClassLoader if the TCCL is {@code null}. If the system
76 * ClassLoader is {@code null} as well, then the ClassLoader for this class is returned. If running with a
77 * {@link SecurityManager} that does not allow access to the Thread ClassLoader or system ClassLoader, then the
78 * ClassLoader for this class is returned.
79 *
80 * @return the current ThreadContextClassLoader.
81 */
82 public static ClassLoader getThreadContextClassLoader() {
83 if (GET_CLASS_LOADER_DISABLED) {
84 // we can at least get this class's ClassLoader regardless of security context
85 // however, if this is null, there's really no option left at this point
86 return LoaderUtil.class.getClassLoader();
87 }
88 return SECURITY_MANAGER == null ? TCCL_GETTER.run() : AccessController.doPrivileged(TCCL_GETTER);
89 }
90
91 /**
92 *
93 */
94 private static class ThreadContextClassLoaderGetter implements PrivilegedAction<ClassLoader> {
95 @Override
96 public ClassLoader run() {
97 final ClassLoader cl = Thread.currentThread().getContextClassLoader();
98 if (cl != null) {
99 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 public static ClassLoader[] getClassLoaders() {
107 final Collection<ClassLoader> classLoaders = new LinkedHashSet<>();
108 final ClassLoader tcl = getThreadContextClassLoader();
109 if (tcl != null) {
110 classLoaders.add(tcl);
111 }
112 accumulateClassLoaders(LoaderUtil.class.getClassLoader(), classLoaders);
113 accumulateClassLoaders(tcl == null ? null : tcl.getParent(), classLoaders);
114 final ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader();
115 if (systemClassLoader != null) {
116 classLoaders.add(systemClassLoader);
117 }
118 return classLoaders.toArray(new ClassLoader[classLoaders.size()]);
119 }
120
121 /**
122 * Adds the provided loader to the loaders collection, and traverses up the tree until either a null
123 * value or a classloader which has already been added is encountered.
124 */
125 private static void accumulateClassLoaders(ClassLoader loader, Collection<ClassLoader> loaders) {
126 // Some implementations may use null to represent the bootstrap class loader.
127 if (loader != null && loaders.add(loader)) {
128 accumulateClassLoaders(loader.getParent(), loaders);
129 }
130 }
131
132 /**
133 * Determines if a named Class can be loaded or not.
134 *
135 * @param className The class name.
136 * @return {@code true} if the class could be found or {@code false} otherwise.
137 * @since 2.7
138 */
139 public static boolean isClassAvailable(final String className) {
140 try {
141 final Class<?> clazz = loadClass(className);
142 return clazz != null;
143 } catch (final ClassNotFoundException | LinkageError e) {
144 return false;
145 } catch (final Throwable e) {
146 LowLevelLogUtil.logException("Unknown error checking for existence of class: " + className, e);
147 return false;
148 }
149 }
150
151 /**
152 * Loads a class by name. This method respects the {@link #IGNORE_TCCL_PROPERTY} Log4j property. If this property is
153 * specified and set to anything besides {@code false}, then the default ClassLoader will be used.
154 *
155 * @param className The class name.
156 * @return the Class for the given name.
157 * @throws ClassNotFoundException if the specified class name could not be found
158 * @since 2.1
159 */
160 public static Class<?> loadClass(final String className) throws ClassNotFoundException {
161 if (isIgnoreTccl()) {
162 return Class.forName(className);
163 }
164 try {
165 ClassLoader tccl = getThreadContextClassLoader();
166 if (tccl != null) {
167 return tccl.loadClass(className);
168 }
169 } catch (final Throwable ignored) {
170 }
171 return Class.forName(className);
172 }
173
174 /**
175 * Loads and instantiates a Class using the default constructor.
176 *
177 * @param clazz The class.
178 * @return new instance of the class.
179 * @throws IllegalAccessException if the class can't be instantiated through a public constructor
180 * @throws InstantiationException if there was an exception whilst instantiating the class
181 * @throws InvocationTargetException if there was an exception whilst constructing the class
182 * @since 2.7
183 */
184 public static <T> T newInstanceOf(final Class<T> clazz)
185 throws InstantiationException, IllegalAccessException, InvocationTargetException {
186 try {
187 return clazz.getConstructor().newInstance();
188 } catch (final NoSuchMethodException ignored) {
189 // FIXME: looking at the code for Class.newInstance(), this seems to do the same thing as above
190 return clazz.newInstance();
191 }
192 }
193
194 /**
195 * Loads and instantiates a Class using the default constructor.
196 *
197 * @param className The class name.
198 * @return new instance of the class.
199 * @throws ClassNotFoundException if the class isn't available to the usual ClassLoaders
200 * @throws IllegalAccessException if the class can't be instantiated through a public constructor
201 * @throws InstantiationException if there was an exception whilst instantiating the class
202 * @throws NoSuchMethodException if there isn't a no-args constructor on the class
203 * @throws InvocationTargetException if there was an exception whilst constructing the class
204 * @since 2.1
205 */
206 @SuppressWarnings("unchecked")
207 public static <T> T newInstanceOf(final String className) throws ClassNotFoundException, IllegalAccessException,
208 InstantiationException, NoSuchMethodException, InvocationTargetException {
209 return newInstanceOf((Class<T>) loadClass(className));
210 }
211
212 /**
213 * Loads and instantiates a derived class using its default constructor.
214 *
215 * @param className The class name.
216 * @param clazz The class to cast it to.
217 * @param <T> The type of the class to check.
218 * @return new instance of the class cast to {@code T}
219 * @throws ClassNotFoundException if the class isn't available to the usual ClassLoaders
220 * @throws IllegalAccessException if the class can't be instantiated through a public constructor
221 * @throws InstantiationException if there was an exception whilst instantiating the class
222 * @throws NoSuchMethodException if there isn't a no-args constructor on the class
223 * @throws InvocationTargetException if there was an exception whilst constructing the class
224 * @throws ClassCastException if the constructed object isn't type compatible with {@code T}
225 * @since 2.1
226 */
227 public static <T> T newCheckedInstanceOf(final String className, final Class<T> clazz)
228 throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException,
229 IllegalAccessException {
230 return clazz.cast(newInstanceOf(className));
231 }
232
233 /**
234 * Loads and instantiates a class given by a property name.
235 *
236 * @param propertyName The property name to look up a class name for.
237 * @param clazz The class to cast it to.
238 * @param <T> The type to cast it to.
239 * @return new instance of the class given in the property or {@code null} if the property was unset.
240 * @throws ClassNotFoundException if the class isn't available to the usual ClassLoaders
241 * @throws IllegalAccessException if the class can't be instantiated through a public constructor
242 * @throws InstantiationException if there was an exception whilst instantiating the class
243 * @throws NoSuchMethodException if there isn't a no-args constructor on the class
244 * @throws InvocationTargetException if there was an exception whilst constructing the class
245 * @throws ClassCastException if the constructed object isn't type compatible with {@code T}
246 * @since 2.5
247 */
248 public static <T> T newCheckedInstanceOfProperty(final String propertyName, final Class<T> clazz)
249 throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException,
250 IllegalAccessException {
251 final String className = PropertiesUtil.getProperties().getStringProperty(propertyName);
252 if (className == null) {
253 return null;
254 }
255 return newCheckedInstanceOf(className, clazz);
256 }
257
258 private static boolean isIgnoreTccl() {
259 // we need to lazily initialize this, but concurrent access is not an issue
260 if (ignoreTCCL == null) {
261 final String ignoreTccl = PropertiesUtil.getProperties().getStringProperty(IGNORE_TCCL_PROPERTY, null);
262 ignoreTCCL = ignoreTccl != null && !"false".equalsIgnoreCase(ignoreTccl.trim());
263 }
264 return ignoreTCCL;
265 }
266
267 /**
268 * Finds classpath {@linkplain URL resources}.
269 *
270 * @param resource the name of the resource to find.
271 * @return a Collection of URLs matching the resource name. If no resources could be found, then this will be empty.
272 * @since 2.1
273 */
274 public static Collection<URL> findResources(final String resource) {
275 final Collection<UrlResource> urlResources = findUrlResources(resource);
276 final Collection<URL> resources = new LinkedHashSet<>(urlResources.size());
277 for (final UrlResource urlResource : urlResources) {
278 resources.add(urlResource.getUrl());
279 }
280 return resources;
281 }
282
283 static Collection<UrlResource> findUrlResources(final String resource) {
284 // @formatter:off
285 final ClassLoader[] candidates = {
286 getThreadContextClassLoader(),
287 LoaderUtil.class.getClassLoader(),
288 GET_CLASS_LOADER_DISABLED ? null : ClassLoader.getSystemClassLoader()};
289 // @formatter:on
290 final Collection<UrlResource> resources = new LinkedHashSet<>();
291 for (final ClassLoader cl : candidates) {
292 if (cl != null) {
293 try {
294 final Enumeration<URL> resourceEnum = cl.getResources(resource);
295 while (resourceEnum.hasMoreElements()) {
296 resources.add(new UrlResource(cl, resourceEnum.nextElement()));
297 }
298 } catch (final IOException e) {
299 LowLevelLogUtil.logException(e);
300 }
301 }
302 }
303 return resources;
304 }
305
306 /**
307 * {@link URL} and {@link ClassLoader} pair.
308 */
309 static class UrlResource {
310 private final ClassLoader classLoader;
311 private final URL url;
312
313 UrlResource(final ClassLoader classLoader, final URL url) {
314 this.classLoader = classLoader;
315 this.url = url;
316 }
317
318 public ClassLoader getClassLoader() {
319 return classLoader;
320 }
321
322 public URL getUrl() {
323 return url;
324 }
325
326 @Override
327 public boolean equals(final Object o) {
328 if (this == o) {
329 return true;
330 }
331 if (o == null || getClass() != o.getClass()) {
332 return false;
333 }
334
335 final UrlResource that = (UrlResource) o;
336
337 if (classLoader != null ? !classLoader.equals(that.classLoader) : that.classLoader != null) {
338 return false;
339 }
340 if (url != null ? !url.equals(that.url) : that.url != null) {
341 return false;
342 }
343
344 return true;
345 }
346
347 @Override
348 public int hashCode() {
349 return Objects.hashCode(classLoader) + Objects.hashCode(url);
350 }
351 }
352 }