View Javadoc
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     /**
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     @SuppressWarnings("unchecked")
139     public static <T> T newInstanceOf(final String className) throws ClassNotFoundException, IllegalAccessException,
140             InstantiationException, NoSuchMethodException, InvocationTargetException {
141         final Class<?> clazz = loadClass(className);
142         try {
143             return (T) clazz.getConstructor().newInstance();
144         } catch (final NoSuchMethodException ignored) {
145             // FIXME: looking at the code for Class.newInstance(), this seems to do the same thing as above
146             return (T) clazz.newInstance();
147         }
148     }
149 
150     /**
151      * Loads and instantiates a derived class using its default constructor.
152      *
153      * @param className The class name.
154      * @param clazz The class to cast it to.
155      * @param <T> The type of the class to check.
156      * @return new instance of the class cast to {@code T}
157      * @throws ClassNotFoundException if the class isn't available to the usual ClassLoaders
158      * @throws IllegalAccessException if the class can't be instantiated through a public constructor
159      * @throws InstantiationException if there was an exception whilst instantiating the class
160      * @throws NoSuchMethodException if there isn't a no-args constructor on the class
161      * @throws InvocationTargetException if there was an exception whilst constructing the class
162      * @throws ClassCastException if the constructed object isn't type compatible with {@code T}
163      * @since 2.1
164      */
165     public static <T> T newCheckedInstanceOf(final String className, final Class<T> clazz)
166             throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException,
167             IllegalAccessException {
168         return clazz.cast(newInstanceOf(className));
169     }
170 
171     /**
172      * Loads and instantiates a class given by a property name.
173      *
174      * @param propertyName The property name to look up a class name for.
175      * @param clazz        The class to cast it to.
176      * @param <T>          The type to cast it to.
177      * @return new instance of the class given in the property or {@code null} if the property was unset.
178      * @throws ClassNotFoundException    if the class isn't available to the usual ClassLoaders
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 NoSuchMethodException     if there isn't a no-args constructor on the class
182      * @throws InvocationTargetException if there was an exception whilst constructing the class
183      * @throws ClassCastException        if the constructed object isn't type compatible with {@code T}
184      * @since 2.5
185      */
186     public static <T> T newCheckedInstanceOfProperty(final String propertyName, final Class<T> clazz)
187         throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException,
188         IllegalAccessException {
189         final String className = PropertiesUtil.getProperties().getStringProperty(propertyName);
190         if (className == null) {
191             return null;
192         }
193         return newCheckedInstanceOf(className, clazz);
194     }
195 
196     private static boolean isIgnoreTccl() {
197         // we need to lazily initialize this, but concurrent access is not an issue
198         if (ignoreTCCL == null) {
199             final String ignoreTccl = PropertiesUtil.getProperties().getStringProperty(IGNORE_TCCL_PROPERTY, null);
200             ignoreTCCL = ignoreTccl != null && !"false".equalsIgnoreCase(ignoreTccl.trim());
201         }
202         return ignoreTCCL;
203     }
204 
205     /**
206      * Finds classpath {@linkplain URL resources}.
207      *
208      * @param resource the name of the resource to find.
209      * @return a Collection of URLs matching the resource name. If no resources could be found, then this will be empty.
210      * @since 2.1
211      */
212     public static Collection<URL> findResources(final String resource) {
213         final Collection<UrlResource> urlResources = findUrlResources(resource);
214         final Collection<URL> resources = new LinkedHashSet<>(urlResources.size());
215         for (final UrlResource urlResource : urlResources) {
216             resources.add(urlResource.getUrl());
217         }
218         return resources;
219     }
220 
221     static Collection<UrlResource> findUrlResources(final String resource) {
222         final ClassLoader[] candidates = {getThreadContextClassLoader(), LoaderUtil.class.getClassLoader(),
223                 GET_CLASS_LOADER_DISABLED ? null : ClassLoader.getSystemClassLoader()};
224         final Collection<UrlResource> resources = new LinkedHashSet<>();
225         for (final ClassLoader cl : candidates) {
226             if (cl != null) {
227                 try {
228                     final Enumeration<URL> resourceEnum = cl.getResources(resource);
229                     while (resourceEnum.hasMoreElements()) {
230                         resources.add(new UrlResource(cl, resourceEnum.nextElement()));
231                     }
232                 } catch (final IOException e) {
233                     LowLevelLogUtil.logException(e);
234                 }
235             }
236         }
237         return resources;
238     }
239 
240     /**
241      * {@link URL} and {@link ClassLoader} pair.
242      */
243     static class UrlResource {
244         private final ClassLoader classLoader;
245         private final URL url;
246 
247         UrlResource(final ClassLoader classLoader, final URL url) {
248             this.classLoader = classLoader;
249             this.url = url;
250         }
251 
252         public ClassLoader getClassLoader() {
253             return classLoader;
254         }
255 
256         public URL getUrl() {
257             return url;
258         }
259 
260         @Override
261         public boolean equals(final Object o) {
262             if (this == o) {
263                 return true;
264             }
265             if (o == null || getClass() != o.getClass()) {
266                 return false;
267             }
268 
269             final UrlResource that = (UrlResource) o;
270 
271             if (classLoader != null ? !classLoader.equals(that.classLoader) : that.classLoader != null) {
272                 return false;
273             }
274             if (url != null ? !url.equals(that.url) : that.url != null) {
275                 return false;
276             }
277 
278             return true;
279         }
280 
281         @Override
282         public int hashCode() {
283             return Objects.hashCode(classLoader) + Objects.hashCode(url);
284         }
285     }
286 }