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    /**
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 <T> T newInstanceOf(final String className) throws ClassNotFoundException, IllegalAccessException,
139            InstantiationException, NoSuchMethodException, InvocationTargetException {
140        final Class<?> clazz = loadClass(className);
141        try {
142            return (T) 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 (T) 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                    LowLevelLogUtil.logException(e);
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        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}