001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements. See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache license, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License. You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the license for the specific language governing permissions and
015 * limitations under the license.
016 */
017package org.apache.logging.log4j.util;
018
019import java.io.IOException;
020import java.lang.reflect.InvocationTargetException;
021import java.net.URL;
022import java.security.AccessController;
023import java.security.PrivilegedAction;
024import java.util.Collection;
025import java.util.Enumeration;
026import java.util.LinkedHashSet;
027import java.util.Objects;
028
029/**
030 * <em>Consider this class private.</em> Utility class for ClassLoaders.
031 *
032 * @see ClassLoader
033 * @see RuntimePermission
034 * @see Thread#getContextClassLoader()
035 * @see ClassLoader#getSystemClassLoader()
036 */
037public final class LoaderUtil {
038
039    /**
040     * System property to set to ignore the thread context ClassLoader.
041     *
042     * @since 2.1
043     */
044    public static final String IGNORE_TCCL_PROPERTY = "log4j.ignoreTCL";
045
046    private static final SecurityManager SECURITY_MANAGER = System.getSecurityManager();
047
048    // this variable must be lazily loaded; otherwise, we get a nice circular class loading problem where LoaderUtil
049    // wants to use PropertiesUtil, but then PropertiesUtil wants to use LoaderUtil.
050    private static Boolean ignoreTCCL;
051
052    private static final boolean GET_CLASS_LOADER_DISABLED;
053
054    private static final PrivilegedAction<ClassLoader> TCCL_GETTER = new ThreadContextClassLoaderGetter();
055
056    static {
057        if (SECURITY_MANAGER != null) {
058            boolean getClassLoaderDisabled;
059            try {
060                SECURITY_MANAGER.checkPermission(new RuntimePermission("getClassLoader"));
061                getClassLoaderDisabled = false;
062            } catch (final SecurityException ignored) {
063                getClassLoaderDisabled = true;
064            }
065            GET_CLASS_LOADER_DISABLED = getClassLoaderDisabled;
066        } else {
067            GET_CLASS_LOADER_DISABLED = false;
068        }
069    }
070
071    private LoaderUtil() {
072    }
073
074    /**
075     * Gets the current Thread ClassLoader. Returns the system ClassLoader if the TCCL is {@code null}. If the system
076     * ClassLoader is {@code null} as well, then the ClassLoader for this class is returned. If running with a
077     * {@link SecurityManager} that does not allow access to the Thread ClassLoader or system ClassLoader, then the
078     * ClassLoader for this class is returned.
079     *
080     * @return the current ThreadContextClassLoader.
081     */
082    public static ClassLoader getThreadContextClassLoader() {
083        if (GET_CLASS_LOADER_DISABLED) {
084            // we can at least get this class's ClassLoader regardless of security context
085            // however, if this is null, there's really no option left at this point
086            return LoaderUtil.class.getClassLoader();
087        }
088        return SECURITY_MANAGER == null ? TCCL_GETTER.run() : AccessController.doPrivileged(TCCL_GETTER);
089    }
090
091    /**
092     *
093     */
094    private static class ThreadContextClassLoaderGetter implements PrivilegedAction<ClassLoader> {
095        @Override
096        public ClassLoader run() {
097            final ClassLoader cl = Thread.currentThread().getContextClassLoader();
098            if (cl != null) {
099                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}