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