/*

License $Id: SIXBSReader.java,v 1.2 2001/05/11 16:45:16 Hendrik Exp $

Copyright (c) 2001 tagtraum industries.

The sixbs 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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

For LGPL see <http://www.fsf.org/copyleft/lesser.txt>

We encourage your feedback and suggestions and want to use your feedback to
improve the Software. Send all such feedback to:
feedback@tagtraum.com

For more information on tagtraum industries, Hendrik Schreiber and sixbs
please see <http://www.tagtraum.com/>.

*/

package com.tagtraum.sixbs;

import java.util.*;
import java.io.*;
import java.lang.reflect.*;
import java.net.URL;

import javax.xml.parsers.*;

import org.xml.sax.*;
import org.xml.sax.helpers.*;

import com.tagtraum.framework.util.*;

/**
 * DeSerializes beans from XML. Objects are read asynchronously therefore
 * very good performance is ensured. How many object are read ahead, can
 * be specified - you should do this, if you are intending to read many,
 * or very large objects. Also, if speed is very important to you, you
 * should buffer the InputStream or Reader (if this is not done by your SAX2
 * parser) and set readAhead to a high value.
 * 
 * <p>Uses SAX2, therefore part of the documentation
 * is from the SAX2 docs.
 * 
 * @author 	Hendrik Schreiber
 * @version $Id: SIXBSReader.java,v 1.2 2001/05/11 16:45:16 Hendrik Exp $
 */
public class SIXBSReader implements ContentHandler {

    /**
     * Source-Version
     */
    public static String	vcid = 
	"$Id: SIXBSReader.java,v 1.2 2001/05/11 16:45:16 Hendrik Exp $";
    
    private static final Object[] NOARGS = new Object[] {};
    private static final Class[] STRING_OBJECT = new Class[] {String.class};
    private static final Null NULL = Null.UNIQUE_NULL;
    private static final String REFERENCE = Reference.class.getName();
    private static final String TYPED_ARRAY = TypedArray.class.getName();
    private static final String SIXBS = "sixbs";
    
    private static ResourceBundle localStrings = ResourceBundle.getBundle("com.tagtraum.sixbs.localStrings");
    
    private Object[] ONEARG = new Object[] {null};
    private static final int OBJECT = 0;
    private static final int PROPERTY = 1;
    private static final int ARRAY = 2;
    private static final int LITERAL = 3;
    private static SAXParserFactory saxParserFactory;
    
    
    private boolean stillParsing = true;
    private ParseThread parseThread;
    private IOException pendingException;
    private InputSource inputSource;
    private ObjectIdentifier objectIdentifier;
    private ArrayList stack;
    private List objects = new ArrayList();
    private StringBuffer cdata;
    private Object lock = new Object();
    private int readAhead = 10;
    
    public SIXBSReader(Reader in) throws IOException {
        inputSource = new InputSource(in);
        init();
    }
    
    public SIXBSReader(InputStream in) throws IOException {
        inputSource = new InputSource(in);
        init();
    }
    
    private void init() throws IOException {
        objectIdentifier = new ObjectIdentifier();
        cdata = new StringBuffer(256);
        stack = new ArrayList();
        if (parseThread == null) {
            parseThread = new ParseThread(this);
            parseThread.start();
        }
    }
    
    /**
     * Sets the number of Objects which are read in advance.
     * If you have very big objects you want to keep this low, in order
     * to keep memory consumption low. If speed is more important, set
     * this to a high value. The default value is 10.
     *
     * @see #getReadAhead()
     */
    public void setReadAhead(int readAhead) {
        this.readAhead = readAhead;
    }
    
    /**
     * Returns the number of Objects that are read in advance.
     *
     * @see #setReadAhead(int)
     */
    public int getReadAhead() {
        return readAhead;
    }
    
    /**
     * Starts the reading of objects. Note that internally more than 
     * a single object is read. Therefore exception that might occur, do
     * not have to stem from the object you are currently trying to read, but 
     * maybe from an object that is read in advance.
     *
     * @see #setReadAhead(int)
     * @exception EOFException if the end of file is reached.
     */
    public Object readObject() throws IOException {
        handlePendingException();
        Object obj = null;
        synchronized (lock) {
            try {
                while (objects.size() == 0 && stillParsing) {
                    lock.wait(250);
                    handlePendingException();
                }
            }
            catch (InterruptedException ie) {
                //ie.printStackTrace();
                throw new SIXBSException(ie);
            }
            
            if (objects.size() > 0) {
                obj = objects.remove(0);
                lock.notify();
            }
            else {
                throw new EOFException();
            }
        }
        return obj;
    }
    
    /**
     * Indicates whether we can read another object.
     *
     * @return true, if another object can be read.
     */
    public boolean hasNext() {
        synchronized (lock) {
            try {
                while (objects.size() == 0 && stillParsing) {
                    lock.wait(250);
                }
            }
            catch (InterruptedException ie) {
                return false;
            }
            return objects.size() > 0;
        }
    }
        
    /**
     * Receive notification of the beginning of an element.
     *
     * <p>The Parser will invoke this method at the beginning of every
     * element in the XML document; there will be a corresponding
     * {@link #endElement endElement} event for every startElement event
     * (even when the element is empty). All of the element's content will be
     * reported, in order, before the corresponding endElement
     * event.</p>
     *
     * <p>This event allows up to three name components for each
     * element:</p>
     *
     * <ol>
     * <li>the Namespace URI;</li>
     * <li>the local name; and</li>
     * <li>the qualified (prefixed) name.</li>
     * </ol>
     *
     * <p>Any or all of these may be provided, depending on the
     * values of the <var>http://xml.org/sax/features/namespaces</var>
     * and the <var>http://xml.org/sax/features/namespace-prefixes</var>
     * properties:</p>
     *
     * <ul>
     * <li>the Namespace URI and local name are required when 
     * the namespaces property is <var>true</var> (the default), and are
     * optional when the namespaces property is <var>false</var> (if one is
     * specified, both must be);</li>
     * <li>the qualified name is required when the namespace-prefixes property
     * is <var>true</var>, and is optional when the namespace-prefixes property
     * is <var>false</var> (the default).</li>
     * </ul>
     *
     * <p>Note that the attribute list provided will contain only
     * attributes with explicit values (specified or defaulted):
     * #IMPLIED attributes will be omitted.  The attribute list
     * will contain attributes used for Namespace declarations
     * (xmlns* attributes) only if the
     * <code>http://xml.org/sax/features/namespace-prefixes</code>
     * property is true (it is false by default, and support for a 
     * true value is optional).</p>
     *
     * @param uri The Namespace URI, or the empty string if the
     *        element has no Namespace URI or if Namespace
     *        processing is not being performed.
     * @param localName The local name (without prefix), or the
     *        empty string if Namespace processing is not being
     *        performed.
     * @param qName The qualified name (with prefix), or the
     *        empty string if qualified names are not available.
     * @param atts The attributes attached to the element.  If
     *        there are no attributes, it shall be an empty
     *        Attributes object.
     * @exception org.xml.sax.SAXException Any SAX exception, possibly
     *            wrapping another exception.
     * @see #endElement
     * @see Attributes
     */
    public void startElement (String namespaceURI, String localName,
                  String qName, Attributes atts) throws SAXException {
                    
        State state = null;
        if (!empty()) state = peek();
        //System.out.println("<" + localName + ">: " + state);
        try {
            if (state == null || state.getState() == PROPERTY || state.getState() == ARRAY) {
                if (localName.equals(REFERENCE)) {
                    String id = atts.getValue("id");
                    if (id == null || id.equals("")) throw new SAXException(localStrings.getString("attribute_id_missing"));
                    push(new State(OBJECT, objectIdentifier.getObject(id)));
                }
                else if (localName.equals(NULL.getClass().getName())) {
                    push(new State(OBJECT, NULL));
                }
                else if (localName.equals(TYPED_ARRAY)) {
                    String type = atts.getValue("type");
                    boolean array = "true".equals(atts.getValue("array"));
                    if (type == null || type.equals("")) throw new SAXException(localStrings.getString("attribute_type_missing"));
                    push(new State(ARRAY, new TypedArray(type, array)));
                }
                // ignore sixbs tag
                else if (localName.equals(SIXBS)) return;
                else {
                    Class klass = Class.forName(localName);
                    String id = atts.getValue("id");
                    if (id == null || id.equals("")) throw new SAXException(localStrings.getString("attribute_id_missing"));
                    if ((klass != Object.class)
                        && (klass == String.class
                        || klass.getSuperclass() == Number.class
                        || klass == Character.class
                        || klass == Boolean.class
                        || klass == URL.class)) {
                            push(new State(LITERAL, klass.getConstructor(STRING_OBJECT)));
                    }
                    else {
                        Object object = Class.forName(localName).newInstance();
                        objectIdentifier.registerObject(id, object);
                        push(new State(OBJECT, object));
                    }
                }
            }
            else {
                push(new State(PROPERTY, ReflectHelper.getWriteMethods(peek().getContext().getClass()).get(localName)));
            }
        }
        catch (ClassNotFoundException cnfe) {
            cnfe.printStackTrace();
            throw new SAXException(localStrings.getString("class_not_found") + " " + cnfe);
        }
        catch (NoSuchMethodException nsme) {
            throw new SAXException(localStrings.getString("constructor_not_found") + " " + nsme);
        }
        catch (InstantiationException ie) {
            throw new SAXException(localStrings.getString("instantiation_failed") + " " + ie);
        }
        catch (IllegalAccessException iae) {
            throw new SAXException(localStrings.getString("class_instantiation_forbidden") + " " + iae);
        }
        catch (RuntimeException rte) {
            rte.printStackTrace();
        }
    }


    /**
     * Receive notification of the end of an element.
     *
     * <p>The SAX parser will invoke this method at the end of every
     * element in the XML document; there will be a corresponding
     * {@link #startElement startElement} event for every endElement 
     * event (even when the element is empty).</p>
     *
     * <p>For information on the names, see startElement.</p>
     *
     * @param uri The Namespace URI, or the empty string if the
     *        element has no Namespace URI or if Namespace
     *        processing is not being performed.
     * @param localName The local name (without prefix), or the
     *        empty string if Namespace processing is not being
     *        performed.
     * @param qName The qualified XML 1.0 name (with prefix), or the
     *        empty string if qualified names are not available.
     * @exception org.xml.sax.SAXException Any SAX exception, possibly
     *            wrapping another exception.
     */
    public void endElement (String namespaceURI, String localName,
                String qName) throws SAXException {
        if (empty() && localName.equals(SIXBS)) return;
        State state = pop();
        //System.out.println("</" + localName + ">: " + state);
        try {
            switch (state.getState()) {
                case ARRAY:
                    state.set(OBJECT, ((TypedArray)state.getContext()).toTypedArray());
                    break;
                case LITERAL:
                    ONEARG[0] = decode(cdata.toString());
                    cdata.setLength(0);
                    state.set(OBJECT, ((Constructor)state.getContext()).newInstance(ONEARG));
                    break;
                default:
                    break;
            }
            switch (state.getState()) {
                case OBJECT:
                    if (state.getContext() instanceof Null) ONEARG[0]=null;
                    else if (state.getContext() instanceof Adapter) ONEARG[0]=((Adapter)state.getContext()).deserialize();
                    else ONEARG[0]=state.getContext();
                    if (!empty()) {
                        State substate = peek();
                        switch (substate.getState()) {
                            case PROPERTY:
                                if (depth() > 1) {
                                    Object object = peek(2).getContext();
                                    if (state.getContext() instanceof Null) ONEARG[0]=null;
                                    Method method = (Method)substate.getContext();
                                    /*
                                    System.out.println("substate: " + substate);
                                    System.out.println("localName: " + localName);
                                    System.out.println("method: " + method);
                                    System.out.println("object: " + object);
                                    */
                                    method.invoke(object, ONEARG);
                                }
                                else {
                                    throw new SAXException(localStrings.getString("unexpected_property") + " " + substate.getContext());
                                }
                                break;
                            case ARRAY:
                                //System.out.println("adding to typed array: " + ONEARG[0]);
                                ((TypedArray)substate.getContext()).add(ONEARG[0]);
                                break;
                            default:
                                throw new SAXException(localStrings.getString("unexpected_state") + " " + substate);
                        }
                    }
                    else {
                        synchronized (lock) {
                            objects.add(ONEARG[0]);
                            lock.notify();
                            try {
                                // if we already read some objects, better wait a bit, until they are read
                                // in order to keep memory consumption low or at least a bit more controllable.
                                while (objects.size() > readAhead && stillParsing) {
                                    lock.wait(1000);
                                }
                            }
                            catch (InterruptedException ie) {
                                ie.printStackTrace();
                            }
                        }
                    }
                default:
                    break;
            }
        }
        catch (InstantiationException ie) {
            throw new SAXException(localStrings.getString("instantiation_failed") + " " + ie);
        }
        catch (IllegalAccessException iae) {
            throw new SAXException(localStrings.getString("method_invocation_forbidden") + " " + iae);
        }
        catch (InvocationTargetException ite) {
            throw new SAXException(localStrings.getString("property_write_invocation_failed") + " " + ite.getTargetException());
        }
        catch (SIXBSException sixbse) {
            throw new SAXException(sixbse);
        }
        catch (RuntimeException rte) {
            rte.printStackTrace();
        }
    }
    
    /**
     * Receive notification of character data.
     *
     * <p>The Parser will call this method to report each chunk of
     * character data.  SAX parsers may return all contiguous character
     * data in a single chunk, or they may split it into several
     * chunks; however, all of the characters in any single event
     * must come from the same external entity so that the Locator
     * provides useful information.</p>
     *
     * <p>The application must not attempt to read from the array
     * outside of the specified range.</p>
     *
     * <p>Note that some parsers will report whitespace in element
     * content using the {@link #ignorableWhitespace ignorableWhitespace}
     * method rather than this one (validating parsers <em>must</em> 
     * do so).</p>
     *
     * @param ch The characters from the XML document.
     * @param start The start position in the array.
     * @param length The number of characters to read from the array.
     * @exception org.xml.sax.SAXException Any SAX exception, possibly
     *            wrapping another exception.
     * @see #ignorableWhitespace 
     * @see org.xml.sax.Locator
     */
    public void characters (char ch[], int start, int length)throws SAXException {
        cdata.append(ch, start, length);
    }


    /**
     * Receive an object for locating the origin of SAX document events.
     *
     * <p>SAX parsers are strongly encouraged (though not absolutely
     * required) to supply a locator: if it does so, it must supply
     * the locator to the application by invoking this method before
     * invoking any of the other methods in the ContentHandler
     * interface.</p>
     *
     * <p>The locator allows the application to determine the end
     * position of any document-related event, even if the parser is
     * not reporting an error.  Typically, the application will
     * use this information for reporting its own errors (such as
     * character content that does not match an application's
     * business rules).  The information returned by the locator
     * is probably not sufficient for use with a search engine.</p>
     *
     * <p>Note that the locator will return correct information only
     * during the invocation of the events in this interface.  The
     * application should not attempt to use it at any other time.</p>
     *
     * @param locator An object that can return the location of
     *                any SAX document event.
     * @see org.xml.sax.Locator
     */
    public void setDocumentLocator (Locator locator) {
    }


    /**
     * Receive notification of the beginning of a document.
     *
     * <p>The SAX parser will invoke this method only once, before any
     * other methods in this interface or in {@link org.xml.sax.DTDHandler
     * DTDHandler} (except for {@link #setDocumentLocator 
     * setDocumentLocator}).</p>
     *
     * @exception org.xml.sax.SAXException Any SAX exception, possibly
     *            wrapping another exception.
     * @see #endDocument
     */
    public void startDocument() throws SAXException {
    }


    /**
     * Receive notification of the end of a document.
     *
     * <p>The SAX parser will invoke this method only once, and it will
     * be the last method invoked during the parse.  The parser shall
     * not invoke this method until it has either abandoned parsing
     * (because of an unrecoverable error) or reached the end of
     * input.</p>
     *
     * @exception org.xml.sax.SAXException Any SAX exception, possibly
     *            wrapping another exception.
     * @see #startDocument
     */
    public void endDocument() throws SAXException {
        //System.out.println("EndDocument: " + empty());
        //if (state == OBJECT) throw new SAXException("SIXBSReader: Format error.");
        stillParsing = false;
    }


    /**
     * Begin the scope of a prefix-URI Namespace mapping.
     *
     * <p>The information from this event is not necessary for
     * normal Namespace processing: the SAX XML reader will 
     * automatically replace prefixes for element and attribute
     * names when the <code>http://xml.org/sax/features/namespaces</code>
     * feature is <var>true</var> (the default).</p>
     *
     * <p>There are cases, however, when applications need to
     * use prefixes in character data or in attribute values,
     * where they cannot safely be expanded automatically; the
     * start/endPrefixMapping event supplies the information
     * to the application to expand prefixes in those contexts
     * itself, if necessary.</p>
     *
     * <p>Note that start/endPrefixMapping events are not
     * guaranteed to be properly nested relative to each-other:
     * all startPrefixMapping events will occur before the
     * corresponding {@link #startElement startElement} event, 
     * and all {@link #endPrefixMapping endPrefixMapping}
     * events will occur after the corresponding {@link #endElement
     * endElement} event, but their order is not otherwise 
     * guaranteed.</p>
     *
     * <p>There should never be start/endPrefixMapping events for the
     * "xml" prefix, since it is predeclared and immutable.</p>
     *
     * @param prefix The Namespace prefix being declared.
     * @param uri The Namespace URI the prefix is mapped to.
     * @exception org.xml.sax.SAXException The client may throw
     *            an exception during processing.
     * @see #endPrefixMapping
     * @see #startElement
     */
    public void startPrefixMapping (String prefix, String uri) throws SAXException {
    }


    /**
     * End the scope of a prefix-URI mapping.
     *
     * <p>See {@link #startPrefixMapping startPrefixMapping} for 
     * details.  This event will always occur after the corresponding 
     * {@link #endElement endElement} event, but the order of 
     * {@link #endPrefixMapping endPrefixMapping} events is not otherwise
     * guaranteed.</p>
     *
     * @param prefix The prefix that was being mapping.
     * @exception org.xml.sax.SAXException The client may throw
     *            an exception during processing.
     * @see #startPrefixMapping
     * @see #endElement
     */
    public void endPrefixMapping (String prefix) throws SAXException {
    }


    /**
     * Receive notification of ignorable whitespace in element content.
     *
     * <p>Validating Parsers must use this method to report each chunk
     * of whitespace in element content (see the W3C XML 1.0 recommendation,
     * section 2.10): non-validating parsers may also use this method
     * if they are capable of parsing and using content models.</p>
     *
     * <p>SAX parsers may return all contiguous whitespace in a single
     * chunk, or they may split it into several chunks; however, all of
     * the characters in any single event must come from the same
     * external entity, so that the Locator provides useful
     * information.</p>
     *
     * <p>The application must not attempt to read from the array
     * outside of the specified range.</p>
     *
     * @param ch The characters from the XML document.
     * @param start The start position in the array.
     * @param length The number of characters to read from the array.
     * @exception org.xml.sax.SAXException Any SAX exception, possibly
     *            wrapping another exception.
     * @see #characters
     */
    public void ignorableWhitespace (char ch[], int start, int length) throws SAXException {
    }


    /**
     * Receive notification of a processing instruction.
     *
     * <p>The Parser will invoke this method once for each processing
     * instruction found: note that processing instructions may occur
     * before or after the main document element.</p>
     *
     * <p>A SAX parser must never report an XML declaration (XML 1.0,
     * section 2.8) or a text declaration (XML 1.0, section 4.3.1)
     * using this method.</p>
     *
     * @param target The processing instruction target.
     * @param data The processing instruction data, or null if
     *        none was supplied.  The data does not include any
     *        whitespace separating it from the target.
     * @exception org.xml.sax.SAXException Any SAX exception, possibly
     *            wrapping another exception.
     */
    public void processingInstruction (String target, String data) throws SAXException {
    }


    /**
     * Receive notification of a skipped entity.
     *
     * <p>The Parser will invoke this method once for each entity
     * skipped.  Non-validating processors may skip entities if they
     * have not seen the declarations (because, for example, the
     * entity was declared in an external DTD subset).  All processors
     * may skip external entities, depending on the values of the
     * <code>http://xml.org/sax/features/external-general-entities</code>
     * and the
     * <code>http://xml.org/sax/features/external-parameter-entities</code>
     * properties.</p>
     *
     * @param name The name of the skipped entity.  If it is a 
     *        parameter entity, the name will begin with '%', and if
     *        it is the external DTD subset, it will be the string
     *        "[dtd]".
     * @exception org.xml.sax.SAXException Any SAX exception, possibly
     *            wrapping another exception.
     */
    public void skippedEntity (String name) throws SAXException {
    }
    

    private State peek() {
        return (State)stack.get(stack.size()-1);
    }

    private int depth() {
        return stack.size();
    }

    private State peek(int depth) {
        return (State)stack.get(stack.size()-depth);
    }
    
    private State pop() {
        return (State)stack.remove(stack.size()-1);
    }
    
    private void push(State object) {
        stack.add(object);
    }

    private boolean empty() {
        return stack.isEmpty();
    }
    
    public final static String decode(String name) {
        //System.out.println("DECODE: " + name);
        return name;

        // apparently we don't need decoding

        /*
        StringHelper.
        if (name.equals("lt")) {
            return "<";
        } else if (name.equals("gt")) {
            return ">";
        } else if (name.equals("amp")) {
            return "&";
        } else if (name.equals("quot")) {
            return "\"";
        } else if (name.equals("apos")) {
            return "'";
        } else if (name.startsWith("#x")) {
            char[] cbuf = new char[1];
    
            cbuf[0] = (char) Integer.parseInt(name.substring(1), 16);
    
            return new String(cbuf);
        } else if (name.startsWith("#")) {
            char[] cbuf = new char[1];
    
            cbuf[0] = (char) Integer.parseInt(name.substring(1));
    
            return new String(cbuf);
        }
        */
    }
    
    private void setPendingException(IOException e) {
        pendingException = e;
    }

    private void handlePendingException() throws IOException {
        if (pendingException != null) {
            throw pendingException;
        }
    }

    /**
     * Parses the document asynchronously, so that 
     * readObject returns immediately, when a new Object has been read.
     */
    private class ParseThread extends Thread {
        private XMLReader xr;
        public ParseThread(ContentHandler ch) throws SIXBSException {
            super();
            try {
                if (saxParserFactory == null) {
                    saxParserFactory = SAXParserFactory.newInstance();
                    saxParserFactory.setValidating(false);
                }
                // Create a JAXP SAXParser
                SAXParser saxParser = saxParserFactory.newSAXParser();
                xr = saxParser.getXMLReader();
                xr.setContentHandler(ch);
            }
            catch (SAXException se) {
                throw new SIXBSException(se);
            }
            catch (ParserConfigurationException pce) {
                throw new SIXBSException(pce);
            }
        }
        
        /**
         * Does the parsing. Exceptions are reported with {@link SIXBSReader#setPendingException(SIXBSException)}
         * and thrown at the next opportunity in {@link SIXBSReader#readObject()}.
         */
        public void run() {
            try {
                xr.parse(inputSource);
            }
            catch (SAXException se) {
                stillParsing = false;
                setPendingException(new SIXBSException(se));
            }
            catch (IOException ioe) {
                stillParsing = false;
                setPendingException(ioe);
            }
            catch (Throwable t) {
                // shouldn't happen
                t.printStackTrace();
                stillParsing = false;
            }
        }
    }
    

    
}