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      * Determines if a named Class can be loaded or not.
108      *
109      * @param className The class name.
110      * @return {@code true} if the class could be found or {@code false} otherwise.
111      * @since 2.7
112      */
113     public static boolean isClassAvailable(final String className) {
114         try {
115             final Class<?> clazz = loadClass(className);
116             return clazz != null;
117         } catch (final ClassNotFoundException e) {
118             return false;
119         } catch (final Throwable e) {
120             LowLevelLogUtil.logException("Unknown error checking for existence of class: " + className, e);
121             return false;
122         }
123     }
124 
125     /**
126      * Loads a class by name. This method respects the {@link #IGNORE_TCCL_PROPERTY} Log4j property. If this property is
127      * specified and set to anything besides {@code false}, then the default ClassLoader will be used.
128      *
129      * @param className The class name.
130      * @return the Class for the given name.
131      * @throws ClassNotFoundException if the specified class name could not be found
132      * @since 2.1
133      */
134     public static Class<?> loadClass(final String className) throws ClassNotFoundException {
135         if (isIgnoreTccl()) {
136             return Class.forName(className);
137         }
138         try {
139             return getThreadContextClassLoader().loadClass(className);
140         } catch (final Throwable ignored) {
141             return Class.forName(className);
142         }
143     }
144 
145     /**
146      * Loads and instantiates a Class using the default constructor.
147      *
148      * @param clazz The class.
149      * @return new instance of the class.
150      * @throws IllegalAccessException if the class can't be instantiated through a public constructor
151      * @throws InstantiationException if there was an exception whilst instantiating the class
152      * @throws InvocationTargetException if there was an exception whilst constructing the class
153      * @since 2.7
154      */
155     public static <T> T newInstanceOf(final Class<T> clazz)
156             throws InstantiationException, IllegalAccessException, InvocationTargetException {
157         try {
158             return clazz.getConstructor().newInstance();
159         } catch (final NoSuchMethodException ignored) {
160             // FIXME: looking at the code for Class.newInstance(), this seems to do the same thing as above
161             return clazz.newInstance();
162         }
163     }
164 
165     /**
166      * Loads and instantiates a Class using the default constructor.
167      *
168      * @param className The class name.
169      * @return new instance of the class.
170      * @throws ClassNotFoundException if the class isn't available to the usual ClassLoaders
171      * @throws IllegalAccessException if the class can't be instantiated through a public constructor
172      * @throws InstantiationException if there was an exception whilst instantiating the class
173      * @throws NoSuchMethodException if there isn't a no-args constructor on the class
174      * @throws InvocationTargetException if there was an exception whilst constructing the class
175      * @since 2.1
176      */
177     @SuppressWarnings("unchecked")
178     public static <T> T newInstanceOf(final String className) throws ClassNotFoundException, IllegalAccessException,
179             InstantiationException, NoSuchMethodException, InvocationTargetException {
180         return newInstanceOf((Class<T>) loadClass(className));
181     }
182 
183     /**
184      * Loads and instantiates a derived class using its default constructor.
185      *
186      * @param className The class name.
187      * @param clazz The class to cast it to.
188      * @param <T> The type of the class to check.
189      * @return new instance of the class cast to {@code T}
190      * @throws ClassNotFoundException if the class isn't available to the usual ClassLoaders
191      * @throws IllegalAccessException if the class can't be instantiated through a public constructor
192      * @throws InstantiationException if there was an exception whilst instantiating the class
193      * @throws NoSuchMethodException if there isn't a no-args constructor on the class
194      * @throws InvocationTargetException if there was an exception whilst constructing the class
195      * @throws ClassCastException if the constructed object isn't type compatible with {@code T}
196      * @since 2.1
197      */
198     public static <T> T newCheckedInstanceOf(final String className, final Class<T> clazz)
199             throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException,
200             IllegalAccessException {
201         return clazz.cast(newInstanceOf(className));
202     }
203 
204     /**
205      * Loads and instantiates a class given by a property name.
206      *
207      * @param propertyName The property name to look up a class name for.
208      * @param clazz        The class to cast it to.
209      * @param <T>          The type to cast it to.
210      * @return new instance of the class given in the property or {@code null} if the property was unset.
211      * @throws ClassNotFoundException    if the class isn't available to the usual ClassLoaders
212      * @throws IllegalAccessException    if the class can't be instantiated through a public constructor
213      * @throws InstantiationException    if there was an exception whilst instantiating the class
214      * @throws NoSuchMethodException     if there isn't a no-args constructor on the class
215      * @throws InvocationTargetException if there was an exception whilst constructing the class
216      * @throws ClassCastException        if the constructed object isn't type compatible with {@code T}
217      * @since 2.5
218      */
219     public static <T> T newCheckedInstanceOfProperty(final String propertyName, final Class<T> clazz)
220         throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException,
221         IllegalAccessException {
222         final String className = PropertiesUtil.getProperties().getStringProperty(propertyName);
223         if (className == null) {
224             return null;
225         }
226         return newCheckedInstanceOf(className, clazz);
227     }
228 
229     private static boolean isIgnoreTccl() {
230         // we need to lazily initialize this, but concurrent access is not an issue
231         if (ignoreTCCL == null) {
232             final String ignoreTccl = PropertiesUtil.getProperties().getStringProperty(IGNORE_TCCL_PROPERTY, null);
233             ignoreTCCL = ignoreTccl != null && !"false".equalsIgnoreCase(ignoreTccl.trim());
234         }
235         return ignoreTCCL;
236     }
237 
238     /**
239      * Finds classpath {@linkplain URL resources}.
240      *
241      * @param resource the name of the resource to find.
242      * @return a Collection of URLs matching the resource name. If no resources could be found, then this will be empty.
243      * @since 2.1
244      */
245     public static Collection<URL> findResources(final String resource) {
246         final Collection<UrlResource> urlResources = findUrlResources(resource);
247         final Collection<URL> resources = new LinkedHashSet<>(urlResources.size());
248         for (final UrlResource urlResource : urlResources) {
249             resources.add(urlResource.getUrl());
250         }
251         return resources;
252     }
253 
254     static Collection<UrlResource> findUrlResources(final String resource) {
255         final ClassLoader[] candidates = {getThreadContextClassLoader(), LoaderUtil.class.getClassLoader(),
256                 GET_CLASS_LOADER_DISABLED ? null : ClassLoader.getSystemClassLoader()};
257         final Collection<UrlResource> resources = new LinkedHashSet<>();
258         for (final ClassLoader cl : candidates) {
259             if (cl != null) {
260                 try {
261                     final Enumeration<URL> resourceEnum = cl.getResources(resource);
262                     while (resourceEnum.hasMoreElements()) {
263                         resources.add(new UrlResource(cl, resourceEnum.nextElement()));
264                     }
265                 } catch (final IOException e) {
266                     LowLevelLogUtil.logException(e);
267                 }
268             }
269         }
270         return resources;
271     }
272 
273     /**
274      * {@link URL} and {@link ClassLoader} pair.
275      */
276     static class UrlResource {
277         private final ClassLoader classLoader;
278         private final URL url;
279 
280         UrlResource(final ClassLoader classLoader, final URL url) {
281             this.classLoader = classLoader;
282             this.url = url;
283         }
284 
285         public ClassLoader getClassLoader() {
286             return classLoader;
287         }
288 
289         public URL getUrl() {
290             return url;
291         }
292 
293         @Override
294         public boolean equals(final Object o) {
295             if (this == o) {
296                 return true;
297             }
298             if (o == null || getClass() != o.getClass()) {
299                 return false;
300             }
301 
302             final UrlResource that = (UrlResource) o;
303 
304             if (classLoader != null ? !classLoader.equals(that.classLoader) : that.classLoader != null) {
305                 return false;
306             }
307             if (url != null ? !url.equals(that.url) : that.url != null) {
308                 return false;
309             }
310 
311             return true;
312         }
313 
314         @Override
315         public int hashCode() {
316             return Objects.hashCode(classLoader) + Objects.hashCode(url);
317         }
318     }
319 }