001/*
002 * ModeShape (http://www.modeshape.org)
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *       http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016package org.modeshape.common.util;
017
018import java.net.URL;
019import java.net.URLClassLoader;
020import org.modeshape.common.logging.Logger;
021
022/**
023 * Class loader which contains a list of classloaders to which it delegates each operation. If none of the delegates are able
024 * to perform the operation, it delegates to the super-class( {@link URLClassLoader} ) which has most of the classloader methods
025 * properly implemented.
026 *
027 * @author Horia Chiorean
028 */
029public final class DelegatingClassLoader extends URLClassLoader {
030
031    private static final Logger LOGGER = Logger.getLogger(DelegatingClassLoader.class);
032
033    private final Iterable<? extends  ClassLoader> delegates;
034
035    public DelegatingClassLoader( ClassLoader parent,
036                                  Iterable<? extends  ClassLoader> delegates ) {
037        super(new URL[0], parent);
038        CheckArg.isNotNull(delegates, "delegates");
039        this.delegates = delegates;
040    }
041
042    @Override
043    protected Class<?> findClass( String name ) throws ClassNotFoundException {
044        for (ClassLoader delegate : delegates) {
045            try {
046                return delegate.loadClass(name);
047            } catch (ClassNotFoundException e) {
048                LOGGER.debug(e, "Cannot load class using delegate: " + delegate.getClass().toString());
049            }
050        }
051        return super.findClass(name);
052    }
053
054
055    @Override
056    public URL findResource( String name ) {
057        for (ClassLoader delegate : delegates) {
058            try {
059                return delegate.getResource(name);
060            } catch (Exception e) {
061                LOGGER.debug(e, "Cannot load resource using delegate: " + delegate.getClass().toString());
062            }
063        }
064        return super.findResource(name);
065    }
066}