/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 1999 Bull S.A.
 * 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
 *
 * Initial developer(s): Guillaume SAUTHIER
 * --------------------------------------------------------------------------
 * $Id$
 * --------------------------------------------------------------------------
 */

package org.ow2.jonas.lib.loader.factory;

import java.net.URL;
import java.io.IOException;

/**
 * An <code>URLFactory</code> is used to create a URL from a base URL.
 *
 * @author Guillaume Sauthier
 */
public abstract class URLFactory {

    /**
     * Returns a new URL basically adding path to the base URL.
     *
     * @param path the path to add to the URL.
     *
     * @return a new URL.
     *
     * @throws IOException when created URL is invalid.
     */
    public abstract URL getURL(String path) throws IOException;

    /**
     * Return a new URLFactory in function of the URL type.
     * an URL pointing to a jar file will return a <code>JarURLFactory</code>
     * and an URL pointing to a directory file will return a <code>DirURLFactory</code>.
     *
     * @param url the base URL
     *
     * @return a new URLFactory in function of the URL type.
     *
     * @throws IOException when cannot find a specialized factory for the given URL.
     */
    public static URLFactory getFactory(URL url) throws IOException {

        String path = url.getPath();
        if (path.matches(".*\\..ar")) {
            // jar detected if path ends with .?ar (*.jar, *.war, *.ear)
            return new JarURLFactory(url);
        } else if (path.endsWith("/")) {
            // directory detected if url ends with a separator /
            return new DirURLFactory(url);
        } else {
            String err = "Unsupported URL '" + url + "' support "
                + "only jar archive and directory";
            throw new IOException(err);
        }
    }

}
