001/*
002 * (C) Copyright 2006-2012 Nuxeo SA (http://nuxeo.com/) and others.
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 *
016 * Contributors:
017 *     bstefanescu, jcarsique
018 */
019package org.nuxeo.osgi.application;
020
021import java.lang.reflect.Method;
022import java.net.URL;
023
024/**
025 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a>
026 * @since 5.4.2
027 */
028public class MutableClassLoaderDelegate implements MutableClassLoader {
029
030    protected final ClassLoader cl;
031
032    protected Method addURL;
033
034    public MutableClassLoaderDelegate(ClassLoader cl) throws IllegalArgumentException {
035        this.cl = cl;
036        Class<?> clazz = cl.getClass();
037        do {
038            try {
039                addURL = clazz.getDeclaredMethod("addURL", URL.class);
040            } catch (NoSuchMethodException e) {
041                clazz = clazz.getSuperclass();
042            } catch (SecurityException e) {
043                throw new IllegalArgumentException("Failed to adapt class loader: " + cl.getClass(), e);
044            }
045        } while (addURL == null && clazz != null);
046        if (addURL == null) {
047            throw new IllegalArgumentException("Incompatible class loader: " + cl.getClass()
048                    + ". ClassLoader must provide a method: addURL(URL url)");
049        }
050        addURL.setAccessible(true);
051    }
052
053    @Override
054    public void addURL(URL url) {
055        try {
056            addURL.invoke(cl, url);
057        } catch (ReflectiveOperationException e) {
058            throw new RuntimeException("Failed to add URL to class loader: " + url, e);
059        }
060    }
061
062    @Override
063    public ClassLoader getClassLoader() {
064        return cl;
065    }
066
067    @Override
068    public Class<?> loadClass(String startupClass) throws ClassNotFoundException {
069        return cl.loadClass(startupClass);
070    }
071
072}