/*
 *  eXist Open Source Native XML Database
 *  Copyright (C) 2001-04 The eXist Project
 *  http://exist-db.org
 *  
 *  This program 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
 *  of the License, or (at your option) any later version.
 *  
 *  This program 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 program; if not, write to the Free Software
 *  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 *  
 *  $Id: SourceFactory.java 4163 2006-08-24 14:23:13Z wolfgang_m $
 */
package org.exist.source;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

import org.exist.xquery.Constants;

/**
 * Factory to create a {@link org.exist.source.Source} object for a given
 * URL.
 * 
 * @author wolf
 */
public class SourceFactory {

    /**
     * Create a {@link Source} object for the given URL.
     * 
     * As a special case, if the URL starts with "resource:", the resource
     * will be read from the current context class loader.
     * 
     * @param contextPath
     * @param location
     * @throws MalformedURLException
     * @throws IOException
     */
    public static final Source getSource(String contextPath, String location, boolean checkXQEncoding) 
    throws MalformedURLException, IOException {
        Source source = null;
        //TODO: Xmldb source for xmldbURIs?
        if(location.indexOf(':') == Constants.STRING_NOT_FOUND) {
            File f = new File(contextPath + File.separatorChar + location);
            if(!f.canRead()) {
                f = new File(location);
                if(!f.canRead())
                    throw new FileNotFoundException("cannot read module source from file at " + f.getAbsolutePath());
            }
            location = f.toURI().toASCIIString();
            source = new FileSource(f, "UTF-8", checkXQEncoding);
        } else {
            if(location.startsWith(ClassLoaderSource.PROTOCOL)) {
                source = new ClassLoaderSource(location);
            } else {
                URL url = new URL(location);
                source = new URLSource(url);
            }
        }
        return source;
    }
}
