// copyright => http://www.jxml.com/mdsax/License.txt

package com.jxml.quick.engine;

import com.jxml.quick.*;
import com.jxml.quick.access.*;
import com.jxml.quick.tf.*;
import com.jxml.quick.recycle.*;
import java.io.*;
import java.net.*;
import org.xml.sax.*;

/**
 * <p>updated by Pavel Curtis to simplify new attribute types and element content--Quick 1.1
 */
public class QCMLBindings
{
    /**
     * If not a URL, make it a file URL.
     */
    public static String forceUrl(String url)
    {
	    if (url.indexOf(':')>1)
		    return url;
	    else
		    return "file:"+url;
    }

    public static QDoc convert(QDoc doc, QContext destination)
	throws SAXException, IOException
    {
	QConvert convert=new QConvert(destination);
	((QConverter)doc.getRoot()).eval(convert);
	QDoc rv=destination.doc;
	return rv;
    }

    /**
     * added by John Aronson to support in non-file based schema sources
     */
    public static QContext parse(QDoc schema, InputSource in, String url)
	throws IOException, SAXException
    {
	QContext context=schema.allocateContext();
	context.cl=((QDocImpl)schema).cl;
	Parser parser;
        parser=null;
	try
	{
            parser=Quick.parserPool.allocate();
	}
	catch (ClassNotFoundException e)
	{
		context.throwPE(e);
	}
	catch (IllegalAccessException e)
	{
		context.throwPE(e);
	}
	catch (InstantiationException e)
	{
		context.throwPE(e);
	}
	QConvert convert;
	convert=new QConvert(context);
	parser.setDocumentHandler(convert);
	if (in==null)
	    parser.parse(url);
	else
	    parser.parse(in);
        Quick.parserPool.release(parser);
	QDoc doc=context.doc;
	doc.setSchema(schema);
	if (url!=null)
	    doc.setKey(url);
	return context;
    }

    public static QDoc createDoc(Object root)
    {
	QDoc doc=new QDocImpl();
	doc.setRoot(root);
	return doc;
    }

    public static QContext createContext(QDoc doc)
	throws SAXException
    {
	synchronized (doc)
	{
	    QContext context=new QContextImpl();
	    Object root=Quick.getRoot(doc);
	    if (!(root instanceof QFilterFactory))
	        context.throwPE("Expecting QFilterFactory, not "+
			    root.getClass().getName());
	    QFilterFactory factory=(QFilterFactory)root;
	    context.filter=factory.createFilter(context);
	    return context;
	}
    }
}
