/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 2010 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 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., 59 Temple Place, Suite 330, Boston, MA  02111-1307
 * USA
 *
 * --------------------------------------------------------------------------
 * $Id$
 * --------------------------------------------------------------------------
 */

package org.ow2.jonas.cdi.weld.internal.resource;

import java.io.IOException;
import java.net.URL;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;

import org.jboss.weld.resources.spi.ResourceLoader;
import org.jboss.weld.resources.spi.ResourceLoadingException;

/**
 * Provides a {@code ResourceLoader} backed by a given ClassLoader.
 * @author Guillaume Sauthier
 */
public class ApplicationResourceLoader implements ResourceLoader {

    /**
     * Delegating ClassLoader.
     */
    private ClassLoader loader;

    public ApplicationResourceLoader(final ClassLoader loader) {
        this.loader = loader;
    }

    /**
     * Creates a class from a given FQCN
     *
     * @param name The name of the clsas
     * @return The class
     */
    public Class<?> classForName(String name) {
        try {
            return Class.forName(name, true, loader);
        } catch (Exception e) {
           throw new ResourceLoadingException(e);
        }
    }

    /**
     * Gets a resource as a URL by name
     *
     * @param name The name of the resource
     * @return An URL to the resource
     */
    public URL getResource(String name) {
        return loader.getResource(name);
    }

    /**
     * Gets resources as URLs by name
     *
     * @param name The name of the resource
     * @return references to the URLS
     */
    public Collection<URL> getResources(String name) {
        try {
            // Convert Enumeration into a Collection
            Enumeration<URL> enumeration = loader.getResources(name);
            if (enumeration.hasMoreElements()) {
                return Collections.list(enumeration);
            } else {
                return Collections.emptySet();
            }
        } catch (IOException e) {
           throw new ResourceLoadingException(e);
        }

    }

    public void cleanup() {
        loader = null;
    }
}
