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