/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 2007 Bull S.A.S.
 * Contact: jonas-team@ow2.org
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
 *
 * --------------------------------------------------------------------------
 * $Id$
 * --------------------------------------------------------------------------
 */

package org.ow2.jonas.lib.loader;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Enumeration;

import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.FrameworkUtil;
import org.osgi.framework.ServiceReference;

/**
 * {@link OSGiClassLoader} delegates class loading to the OSGi framework.
 * @author Francois Fornaciari
 */
public class OSGiClassLoader extends URLClassLoader {

    /**
     * META-INF path.
     */
    private static final String META_INF = "META-INF";

    /**
     * This bundle's Bundle ClassLoader.
     */
    private ClassLoader classLoader = null;

    /**
     * MetaInf locator.
     */
    private IMetaInfLocator metaInfLocator = null;

    /**
     * Construct a new delegating ClassLoader.
     */
    @SuppressWarnings("unchecked")
    public OSGiClassLoader() {
        super(new URL[0]);
        this.classLoader = getClass().getClassLoader();

        // Search the META-INF locator service
        Bundle bundle = FrameworkUtil.getBundle(OSGiClassLoader.class);
        if (bundle != null) {
            BundleContext bundleContext = bundle.getBundleContext();

            // Now, gets the service
            ServiceReference<IMetaInfLocator> serviceReference = (ServiceReference<IMetaInfLocator>) bundleContext
                    .getServiceReference(IMetaInfLocator.class.getName());
            if (serviceReference != null) {
                this.metaInfLocator = bundleContext.getService(serviceReference);
            }
        } // else we're in a non-OSGi environment (maven plugin for example)
    }

    /**
     * {@inheritDoc}
     * @see java.lang.ClassLoader#loadClass(java.lang.String)
     */
    @Override
    public Class<?> loadClass(final String name) throws ClassNotFoundException {
        return this.classLoader.loadClass(name);
    }

    /**
     * {@inheritDoc}
     * @see java.lang.ClassLoader#loadClass(java.lang.String, boolean)
     */
    @Override
    public Class<?> loadClass(final String name, final boolean flag) throws ClassNotFoundException {
        return loadClass(name);
    }

    /**
     * {@inheritDoc}
     * @see java.lang.ClassLoader#getResource(java.lang.String)
     */
    @Override
    public URL getResource(final String name) {
        // First look if OSGi can find the resource we want
        URL resource = null;

        if (this.metaInfLocator != null && name.startsWith(META_INF)) {
            resource = this.metaInfLocator.getResource(name);
            if (resource != null) {
                return resource;
            }
        }

        try {
            resource = this.classLoader.getResource(name);
        } catch (IllegalArgumentException e) {
            // Fall-back: if not found, try the usual getResource() search mechanism.
            // This will let our services to access properties file that are in JB/conf
            try {
                resource = super.getResource(name);
            } catch (IllegalArgumentException e2) {
                return resource;
            }

        }
        if (resource == null) {
            resource = super.getResource(name);
        }
        // Finally return the resource (may be null)
        return resource;
    }


    /**
     * {@inheritDoc}
     * @see java.lang.ClassLoader#getResources(java.lang.String)
     */
    @Override
    public Enumeration<URL> getResources(final String name) throws IOException {

        Enumeration<URL> enumeration = null;

        if (this.metaInfLocator != null && name.startsWith(META_INF)) {
            enumeration = this.metaInfLocator.getResources(name);
            if (enumeration != null) {
                return enumeration;
            }
        }

        // First look if OSGi can find the resource we want

        try {
            enumeration = this.classLoader.getResources(name);
        } catch (IllegalArgumentException e) {
            // Fall-back: if not found, try the usual getResource() search mechanism.
            // This will let our services to access properties file that are in JB/conf
            try {
                enumeration = super.getResources(name);
            } catch (IllegalArgumentException e2) {
                return enumeration;
            }

        }
        if (enumeration == null || !enumeration.hasMoreElements()) {
            enumeration = super.getResources(name);
        }
        // Finally return the resource (may be null)
        return enumeration;
    }


    /**
     * {@inheritDoc}
     * @see java.lang.ClassLoader#getResourceAsStream(java.lang.String)
     */
    @Override
    public InputStream getResourceAsStream(final String name) {
        InputStream is = null;
        if (this.metaInfLocator != null && name.startsWith(META_INF)) {
            is = this.metaInfLocator.getResourceAsStream(name);
            if (is != null) {
                return is;
            }
        }

        // First look if OSGi can find the resource we want
        is = this.classLoader.getResourceAsStream(name);

        // Fall-back: if not found, try the usual getResourceAsStream() search mechanism.
        // This will let our services to access properties file that are in JB/conf
        if (is == null) {
            is = super.getResourceAsStream(name);
        }

        // Finally return the resource (may be null)
        return is;
    }

}
