[llvm-commits] [llvm-gcc-4.2] r43913 [31/80] - in /llvm-gcc-4.2/trunk: boehm-gc/ boehm-gc/Mac_files/ boehm-gc/cord/ boehm-gc/doc/ boehm-gc/include/ boehm-gc/include/private/ boehm-gc/tests/ libffi/ libffi/include/ libffi/src/ libffi/src/alpha/ libffi/src/arm/ libffi/src/cris/ libffi/src/frv/ libffi/src/ia64/ libffi/src/m32r/ libffi/src/m68k/ libffi/src/mips/ libffi/src/pa/ libffi/src/powerpc/ libffi/src/s390/ libffi/src/sh/ libffi/src/sh64/ libffi/src/sparc/ libffi/src/x86/ libffi/testsuite/ libffi/testsuite/config/ li...

Bill Wendling isanbard at gmail.com
Thu Nov 8 14:57:11 PST 2007


Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/stream/XMLOutputFactoryImpl.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/stream/XMLOutputFactoryImpl.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/stream/XMLOutputFactoryImpl.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/stream/XMLOutputFactoryImpl.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,188 @@
+/* XMLOutputFactoryImpl.java -- 
+   Copyright (C) 2005  Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.xml.stream;
+
+import java.io.OutputStream;
+import java.io.OutputStreamWriter;
+import java.io.Writer;
+import java.io.UnsupportedEncodingException;
+
+import javax.xml.transform.Result;
+import javax.xml.transform.stream.StreamResult;
+import javax.xml.stream.XMLEventWriter;
+import javax.xml.stream.XMLOutputFactory;
+import javax.xml.stream.XMLStreamException;
+import javax.xml.stream.XMLStreamWriter;
+
+/**
+ * Standard output factory.
+ *
+ * @author <a href='mailto:dog at gnu.org'>Chris Burdess</a>
+ */
+public class XMLOutputFactoryImpl
+  extends XMLOutputFactory
+{
+
+  protected boolean prefixDefaulting = false;
+
+  public XMLOutputFactoryImpl()
+  {
+  }
+
+  public XMLStreamWriter createXMLStreamWriter(Writer stream)
+    throws XMLStreamException
+  {
+    // XXX try to determine character encoding of writer?
+    return new XMLStreamWriterImpl(stream, null, prefixDefaulting);
+  }
+
+  public XMLStreamWriter createXMLStreamWriter(OutputStream stream)
+    throws XMLStreamException
+  {
+    return createXMLStreamWriter(stream, "UTF-8");
+  }
+
+  public XMLStreamWriter createXMLStreamWriter(OutputStream stream,
+                                               String encoding)
+    throws XMLStreamException
+  {
+    if (encoding == null)
+      encoding = "UTF-8";
+    try
+      {
+        Writer writer = new OutputStreamWriter(stream, encoding);
+        return new XMLStreamWriterImpl(writer, encoding, prefixDefaulting);
+      }
+    catch (UnsupportedEncodingException e)
+      {
+        XMLStreamException e2 = new XMLStreamException(e);
+        e2.initCause(e);
+        throw e2;
+      }
+  }
+
+  public XMLStreamWriter createXMLStreamWriter(Result result)
+    throws XMLStreamException
+  {
+    if (result instanceof StreamResult)
+      {
+        StreamResult sr = (StreamResult) result;
+        OutputStream out = sr.getOutputStream();
+        if (out != null)
+          return createXMLStreamWriter(out);
+        Writer writer = sr.getWriter();
+        if (writer != null)
+          return createXMLStreamWriter(writer);
+      }
+    throw new UnsupportedOperationException();
+  }
+
+  public XMLEventWriter createXMLEventWriter(OutputStream stream)
+    throws XMLStreamException
+  {
+    XMLStreamWriter writer = createXMLStreamWriter(stream);
+    return new XMLEventWriterImpl(writer);
+  }
+
+  public XMLEventWriter createXMLEventWriter(OutputStream stream,
+                                             String encoding)
+    throws XMLStreamException
+  {
+    XMLStreamWriter writer = createXMLStreamWriter(stream, encoding);
+    return new XMLEventWriterImpl(writer);
+  }
+
+  public XMLEventWriter createXMLEventWriter(Writer stream)
+    throws XMLStreamException
+  {
+    XMLStreamWriter writer = createXMLStreamWriter(stream);
+    return new XMLEventWriterImpl(writer);
+  }
+
+  public XMLEventWriter createXMLEventWriter(Result result)
+    throws XMLStreamException
+  {
+    if (result instanceof StreamResult)
+      {
+        StreamResult sr = (StreamResult) result;
+        OutputStream out = sr.getOutputStream();
+        if (out != null)
+          return createXMLEventWriter(out);
+        Writer writer = sr.getWriter();
+        if (writer != null)
+          return createXMLEventWriter(writer);
+      }
+    throw new UnsupportedOperationException();
+  }
+  
+  public void setProperty(String name, Object value)
+    throws IllegalArgumentException
+  {
+    if (IS_REPAIRING_NAMESPACES.equals(name))
+      prefixDefaulting = ((Boolean) value).booleanValue();
+    else
+      throw new IllegalArgumentException(name);
+  }
+
+  public Object getProperty(String name)
+    throws IllegalArgumentException
+  {
+    if (IS_REPAIRING_NAMESPACES.equals(name))
+      return new Boolean(prefixDefaulting);
+    throw new IllegalArgumentException(name);
+  }
+
+  public boolean isPropertySupported(String name)
+  {
+    if (IS_REPAIRING_NAMESPACES.equals(name))
+      return true;
+    return false;
+  }
+
+  public boolean isPrefixDefaulting()
+  {
+    return prefixDefaulting;
+  }
+
+  public void setPrefixDefaulting(boolean value)
+  {
+    prefixDefaulting = value;
+  }
+  
+}
+

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/stream/XMLParser.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/stream/XMLParser.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/stream/XMLParser.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/stream/XMLParser.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,5350 @@
+/* XMLParser.java -- 
+   Copyright (C) 2005  Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version.
+
+Partly derived from code which carried the following notice:
+
+  Copyright (c) 1997, 1998 by Microstar Software Ltd.
+
+  AElfred is free for both commercial and non-commercial use and
+  redistribution, provided that Microstar's copyright and disclaimer are
+  retained intact.  You are free to modify AElfred for your own use and
+  to redistribute AElfred with your modifications, provided that the
+  modifications are clearly documented.
+
+  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.  Please use it AT
+  YOUR OWN RISK.
+*/
+
+package gnu.xml.stream;
+
+import java.io.BufferedInputStream;
+import java.io.EOFException;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.FileWriter;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.IOException;
+import java.io.Reader;
+import java.io.StringReader;
+import java.io.UnsupportedEncodingException;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.LinkedHashMap;
+import java.util.LinkedList;
+import java.util.Map;
+import java.util.NoSuchElementException;
+import java.util.StringTokenizer;
+
+import javax.xml.XMLConstants;
+import javax.xml.namespace.NamespaceContext;
+import javax.xml.namespace.QName;
+import javax.xml.stream.Location;
+import javax.xml.stream.XMLInputFactory;
+import javax.xml.stream.XMLReporter;
+import javax.xml.stream.XMLResolver;
+import javax.xml.stream.XMLStreamConstants;
+import javax.xml.stream.XMLStreamException;
+import javax.xml.stream.XMLStreamReader;
+
+import gnu.java.net.CRLFInputStream;
+import gnu.classpath.debug.TeeInputStream;
+import gnu.classpath.debug.TeeReader;
+
+/**
+ * An XML parser.
+ * This parser supports the following additional StAX properties:
+ * <table>
+ * <tr><td>gnu.xml.stream.stringInterning</td>
+ * <td>Boolean</td>
+ * <td>Indicates whether markup strings will be interned</td></tr>
+ * <tr><td>gnu.xml.stream.xmlBase</td>
+ * <td>Boolean</td>
+ * <td>Indicates whether XML Base processing will be performed</td></tr>
+ * <tr><td>gnu.xml.stream.baseURI</td>
+ * <td>String</td>
+ * <td>Returns the base URI of the current event</td></tr>
+ * </table>
+ *
+ * @see http://www.w3.org/TR/REC-xml/
+ * @see http://www.w3.org/TR/xml11/
+ * @see http://www.w3.org/TR/REC-xml-names
+ * @see http://www.w3.org/TR/xml-names11
+ * @see http://www.w3.org/TR/xmlbase/
+ * 
+ * @author <a href='mailto:dog at gnu.org'>Chris Burdess</a>
+ */
+public class XMLParser
+  implements XMLStreamReader, NamespaceContext
+{
+
+  // -- parser state machine states --
+  private static final int INIT = 0; // start state
+  private static final int PROLOG = 1; // in prolog
+  private static final int CONTENT = 2; // in content
+  private static final int EMPTY_ELEMENT = 3; // empty element state
+  private static final int MISC = 4; // in Misc (after root element)
+
+  // -- parameters for parsing literals --
+  private final static int LIT_ENTITY_REF = 2;
+  private final static int LIT_NORMALIZE = 4;
+  private final static int LIT_ATTRIBUTE = 8;
+  private final static int LIT_DISABLE_PE = 16;
+  private final static int LIT_DISABLE_CREF = 32;
+  private final static int LIT_DISABLE_EREF = 64;
+  private final static int LIT_PUBID = 256;
+
+  // -- types of attribute values --
+  final static int ATTRIBUTE_DEFAULT_UNDECLARED = 30;
+  final static int ATTRIBUTE_DEFAULT_SPECIFIED = 31;
+  final static int ATTRIBUTE_DEFAULT_IMPLIED = 32;
+  final static int ATTRIBUTE_DEFAULT_REQUIRED = 33;
+  final static int ATTRIBUTE_DEFAULT_FIXED = 34;
+
+  // -- additional event types --
+  final static int START_ENTITY = 50;
+  final static int END_ENTITY = 51;
+
+  /**
+   * The current input.
+   */
+  private Input input;
+
+  /**
+   * Stack of inputs representing XML general entities.
+   * The input representing the XML input stream or reader is always the
+   * first element in this stack.
+   */
+  private LinkedList inputStack = new LinkedList();
+
+  /**
+   * Stack of start-entity events to be reported.
+   */
+  private LinkedList startEntityStack = new LinkedList();
+
+  /**
+   * Stack of end-entity events to be reported.
+   */
+  private LinkedList endEntityStack = new LinkedList();
+  
+  /**
+   * Current parser state within the main state machine.
+   */
+  private int state = INIT;
+
+  /**
+   * The (type of the) current event.
+   */
+  private int event;
+
+  /**
+   * Whether we are looking ahead. Used by hasNext.
+   */
+  private boolean lookahead;
+
+  /**
+   * The element name stack. The first element in this stack will be the
+   * root element.
+   */
+  private LinkedList stack = new LinkedList();
+
+  /**
+   * Stack of namespace contexts. These are maps specifying prefix-to-URI
+   * mappings. The first element in this stack is the most recent namespace
+   * context (i.e. the other way around from the element name stack).
+   */
+  private LinkedList namespaces = new LinkedList();
+
+  /**
+   * The base-URI stack. This holds the base URI context for each element.
+   * The first element in this stack is the most recent context (i.e. the
+   * other way around from the element name stack).
+   */
+  private LinkedList bases = new LinkedList();
+
+  /**
+   * The list of attributes for the current element, in the order defined in
+   * the XML stream.
+   */
+  private ArrayList attrs = new ArrayList();
+
+  /**
+   * Buffer for text and character data.
+   */
+  private StringBuffer buf = new StringBuffer();
+
+  /**
+   * Buffer for NMTOKEN strings (markup).
+   */
+  private StringBuffer nmtokenBuf = new StringBuffer();
+
+  /**
+   * Buffer for string literals. (e.g. attribute values)
+   */
+  private StringBuffer literalBuf = new StringBuffer();
+
+  /**
+   * Temporary Unicode character buffer used during character data reads.
+   */
+  private int[] tmpBuf = new int[1024];
+  
+  /**
+   * The element content model for the current element.
+   */
+  private ContentModel currentContentModel;
+
+  /**
+   * The validation stack. This holds lists of the elements seen for each
+   * element, in order to determine whether the names and order of these
+   * elements match the content model for the element. The last entry in
+   * this stack represents the current element.
+   */
+  private LinkedList validationStack;
+
+  /**
+   * These sets contain the IDs and the IDREFs seen in the document, to
+   * ensure that IDs are unique and that each IDREF refers to an ID in the
+   * document.
+   */
+  private HashSet ids, idrefs;
+
+  /**
+   * The target and data associated with the current processing instruction
+   * event.
+   */
+  private String piTarget, piData;
+
+  /**
+   * The XML version declared in the XML declaration.
+   */
+  private String xmlVersion;
+
+  /**
+   * The encoding declared in the XML declaration.
+   */
+  private String xmlEncoding;
+
+  /**
+   * The standalone value declared in the XML declaration.
+   */
+  private Boolean xmlStandalone;
+
+  /**
+   * The document type definition.
+   */
+  Doctype doctype;
+
+  /**
+   * State variables for determining parameter-entity expansion.
+   */
+  private boolean expandPE, peIsError;
+
+  /**
+   * Whether this is a validating parser.
+   */
+  private final boolean validating;
+
+  /**
+   * Whether strings representing markup will be interned.
+   */
+  private final boolean stringInterning;
+
+  /**
+   * If true, CDATA sections will be merged with adjacent text nodes into a
+   * single event.
+   */
+  private final boolean coalescing;
+
+  /**
+   * Whether to replace general entity references with their replacement
+   * text automatically during parsing.
+   * Otherwise entity-reference events will be issued.
+   */
+  private final boolean replaceERefs;
+
+  /**
+   * Whether to support external entities.
+   */
+  private final boolean externalEntities;
+
+  /**
+   * Whether to support DTDs.
+   */
+  private final boolean supportDTD;
+
+  /**
+   * Whether to support XML namespaces. If true, namespace information will
+   * be available. Otherwise namespaces will simply be reported as ordinary
+   * attributes.
+   */
+  private final boolean namespaceAware;
+
+  /**
+   * Whether to support XML Base. If true, URIs specified in xml:base
+   * attributes will be honoured when resolving external entities.
+   */
+  private final boolean baseAware;
+
+  /**
+   * Whether to report extended event types (START_ENTITY and END_ENTITY)
+   * in addition to the standard event types. Used by the SAX parser.
+   */
+  private final boolean extendedEventTypes;
+
+  /**
+   * The reporter to receive parsing warnings.
+   */
+  final XMLReporter reporter;
+
+  /**
+   * Callback interface for resolving external entities.
+   */
+  final XMLResolver resolver;
+
+  // -- Constants for testing the next kind of markup event --
+  private static final String TEST_START_ELEMENT = "<";
+  private static final String TEST_END_ELEMENT = "</";
+  private static final String TEST_COMMENT = "<!--";
+  private static final String TEST_PI = "<?";
+  private static final String TEST_CDATA = "<![CDATA[";
+  private static final String TEST_XML_DECL = "<?xml";
+  private static final String TEST_DOCTYPE_DECL = "<!DOCTYPE";
+  private static final String TEST_ELEMENT_DECL = "<!ELEMENT";
+  private static final String TEST_ATTLIST_DECL = "<!ATTLIST";
+  private static final String TEST_ENTITY_DECL = "<!ENTITY";
+  private static final String TEST_NOTATION_DECL = "<!NOTATION";
+  private static final String TEST_KET = ">";
+  private static final String TEST_END_COMMENT = "--";
+  private static final String TEST_END_PI = "?>";
+  private static final String TEST_END_CDATA = "]]>";
+
+  /**
+   * The general entities predefined by the XML specification.
+   */
+  private static final LinkedHashMap PREDEFINED_ENTITIES = new LinkedHashMap();
+  static
+  {
+    PREDEFINED_ENTITIES.put("amp", "&");
+    PREDEFINED_ENTITIES.put("lt", "<");
+    PREDEFINED_ENTITIES.put("gt", ">");
+    PREDEFINED_ENTITIES.put("apos", "'");
+    PREDEFINED_ENTITIES.put("quot", "\"");
+  }
+
+  /**
+   * Creates a new XML parser for the given input stream.
+   * This constructor should be used where possible, as it allows the
+   * encoding of the XML data to be correctly determined from the stream.
+   * @param in the input stream
+   * @param systemId the URL from which the input stream was retrieved
+   * (necessary if there are external entities to be resolved)
+   * @param validating if the parser is to be a validating parser
+   * @param namespaceAware if the parser should support XML Namespaces
+   * @param coalescing if CDATA sections should be merged into adjacent text
+   * nodes
+   * @param replaceERefs if entity references should be automatically
+   * replaced by their replacement text (otherwise they will be reported as
+   * entity-reference events)
+   * @param externalEntities if external entities should be loaded
+   * @param supportDTD if support for the XML DTD should be enabled
+   * @param baseAware if the parser should support XML Base to resolve
+   * external entities
+   * @param stringInterning whether strings will be interned during parsing
+   * @param reporter the reporter to receive warnings during processing
+   * @param resolver the callback interface used to resolve external
+   * entities
+   */
+  public XMLParser(InputStream in, String systemId,
+                   boolean validating,
+                   boolean namespaceAware,
+                   boolean coalescing,
+                   boolean replaceERefs,
+                   boolean externalEntities,
+                   boolean supportDTD,
+                   boolean baseAware,
+                   boolean stringInterning,
+                   boolean extendedEventTypes,
+                   XMLReporter reporter,
+                   XMLResolver resolver)
+  {
+    this.validating = validating;
+    this.namespaceAware = namespaceAware;
+    this.coalescing = coalescing;
+    this.replaceERefs = replaceERefs;
+    this.externalEntities = externalEntities;
+    this.supportDTD = supportDTD;
+    this.baseAware = baseAware;
+    this.stringInterning = stringInterning;
+    this.extendedEventTypes = extendedEventTypes;
+    this.reporter = reporter;
+    this.resolver = resolver;
+    if (validating)
+      {
+        validationStack = new LinkedList();
+        ids = new HashSet();
+        idrefs = new HashSet();
+      }
+    String debug = System.getProperty("gnu.xml.debug.input");
+    if (debug != null)
+      {
+        try
+          {
+            File file = File.createTempFile(debug, ".xml");
+            in = new TeeInputStream(in, new FileOutputStream(file));
+          }
+        catch (IOException e)
+          {
+            RuntimeException e2 = new RuntimeException();
+            e2.initCause(e);
+            throw e2;
+          }
+      }
+    pushInput(new Input(in, null, null, systemId, null, null, false, true));
+  }
+
+  /**
+   * Creates a new XML parser for the given character stream.
+   * This constructor is only available for compatibility with the JAXP
+   * APIs, which permit XML to be parsed from a character stream. Because
+   * the encoding specified by the character stream may conflict with that
+   * specified in the XML declaration, this method should be avoided where
+   * possible.
+   * @param in the input stream
+   * @param systemId the URL from which the input stream was retrieved
+   * (necessary if there are external entities to be resolved)
+   * @param validating if the parser is to be a validating parser
+   * @param namespaceAware if the parser should support XML Namespaces
+   * @param coalescing if CDATA sections should be merged into adjacent text
+   * nodes
+   * @param replaceERefs if entity references should be automatically
+   * replaced by their replacement text (otherwise they will be reported as
+   * entity-reference events)
+   * @param externalEntities if external entities should be loaded
+   * @param supportDTD if support for the XML DTD should be enabled
+   * @param baseAware if the parser should support XML Base to resolve
+   * external entities
+   * @param stringInterning whether strings will be interned during parsing
+   * @param reporter the reporter to receive warnings during processing
+   * @param resolver the callback interface used to resolve external
+   * entities
+   */
+  public XMLParser(Reader reader, String systemId,
+                   boolean validating,
+                   boolean namespaceAware,
+                   boolean coalescing,
+                   boolean replaceERefs,
+                   boolean externalEntities,
+                   boolean supportDTD,
+                   boolean baseAware,
+                   boolean stringInterning,
+                   boolean extendedEventTypes,
+                   XMLReporter reporter,
+                   XMLResolver resolver)
+  {
+    this.validating = validating;
+    this.namespaceAware = namespaceAware;
+    this.coalescing = coalescing;
+    this.replaceERefs = replaceERefs;
+    this.externalEntities = externalEntities;
+    this.supportDTD = supportDTD;
+    this.baseAware = baseAware;
+    this.stringInterning = stringInterning;
+    this.extendedEventTypes = extendedEventTypes;
+    this.reporter = reporter;
+    this.resolver = resolver;
+    if (validating)
+      {
+        validationStack = new LinkedList();
+        ids = new HashSet();
+        idrefs = new HashSet();
+      }
+    String debug = System.getProperty("gnu.xml.debug.input");
+    if (debug != null)
+      {
+        try
+          {
+            File file = File.createTempFile(debug, ".xml");
+            reader = new TeeReader(reader, new FileWriter(file));
+          }
+        catch (IOException e)
+          {
+            RuntimeException e2 = new RuntimeException();
+            e2.initCause(e);
+            throw e2;
+          }
+      }
+    pushInput(new Input(null, reader, null, systemId, null, null, false, true));
+  }
+
+  // -- NamespaceContext --
+
+  public String getNamespaceURI(String prefix)
+  {
+    if (XMLConstants.XML_NS_PREFIX.equals(prefix))
+      return XMLConstants.XML_NS_URI;
+    if (XMLConstants.XMLNS_ATTRIBUTE.equals(prefix))
+      return XMLConstants.XMLNS_ATTRIBUTE_NS_URI;
+    for (Iterator i = namespaces.iterator(); i.hasNext(); )
+      {
+        LinkedHashMap ctx = (LinkedHashMap) i.next();
+        String namespaceURI = (String) ctx.get(prefix);
+        if (namespaceURI != null)
+          return namespaceURI;
+      }
+    return null;
+  }
+
+  public String getPrefix(String namespaceURI)
+  {
+    if (XMLConstants.XML_NS_URI.equals(namespaceURI))
+      return XMLConstants.XML_NS_PREFIX;
+    if (XMLConstants.XMLNS_ATTRIBUTE_NS_URI.equals(namespaceURI))
+      return XMLConstants.XMLNS_ATTRIBUTE;
+    for (Iterator i = namespaces.iterator(); i.hasNext(); )
+      {
+        LinkedHashMap ctx = (LinkedHashMap) i.next();
+        if (ctx.containsValue(namespaceURI))
+          {
+            for (Iterator j = ctx.entrySet().iterator(); j.hasNext(); )
+              {
+                Map.Entry entry = (Map.Entry) i.next();
+                String uri = (String) entry.getValue();
+                if (uri.equals(namespaceURI))
+                  return (String) entry.getKey();
+              }
+          }
+      }
+    return null;
+  }
+
+  public Iterator getPrefixes(String namespaceURI)
+  {
+    if (XMLConstants.XML_NS_URI.equals(namespaceURI))
+      return Collections.singleton(XMLConstants.XML_NS_PREFIX).iterator();
+    if (XMLConstants.XMLNS_ATTRIBUTE_NS_URI.equals(namespaceURI))
+      return Collections.singleton(XMLConstants.XMLNS_ATTRIBUTE).iterator();
+    LinkedList acc = new LinkedList();
+    for (Iterator i = namespaces.iterator(); i.hasNext(); )
+      {
+        LinkedHashMap ctx = (LinkedHashMap) i.next();
+        if (ctx.containsValue(namespaceURI))
+          {
+            for (Iterator j = ctx.entrySet().iterator(); j.hasNext(); )
+              {
+                Map.Entry entry = (Map.Entry) i.next();
+                String uri = (String) entry.getValue();
+                if (uri.equals(namespaceURI))
+                  acc.add(entry.getKey());
+              }
+          }
+      }
+    return acc.iterator();
+  }
+
+  // -- XMLStreamReader --
+
+  public void close()
+    throws XMLStreamException
+  {
+    stack = null;
+    namespaces = null;
+    bases = null;
+    buf = null;
+    attrs = null;
+    doctype = null;
+
+    inputStack = null;
+    validationStack = null;
+    ids = null;
+    idrefs = null;
+  }
+
+  public NamespaceContext getNamespaceContext()
+  {
+    return this;
+  }
+
+  public int getAttributeCount()
+  {
+    return attrs.size();
+  }
+
+  public String getAttributeLocalName(int index)
+  {
+    Attribute a = (Attribute) attrs.get(index);
+    return a.localName;
+  }
+
+  public String getAttributeNamespace(int index)
+  {
+    String prefix = getAttributePrefix(index);
+    return getNamespaceURI(prefix);
+  }
+
+  public String getAttributePrefix(int index)
+  {
+    Attribute a = (Attribute) attrs.get(index);
+    return a.prefix;
+  }
+
+  public QName getAttributeName(int index)
+  {
+    Attribute a = (Attribute) attrs.get(index);
+    String namespaceURI = getNamespaceURI(a.prefix);
+    return new QName(namespaceURI, a.localName, a.prefix);
+  }
+
+  public String getAttributeType(int index)
+  {
+    Attribute a = (Attribute) attrs.get(index);
+    return a.type;
+  }
+
+  private String getAttributeType(String elementName, String attName)
+  {
+    if (doctype != null)
+      {
+        AttributeDecl att = doctype.getAttributeDecl(elementName, attName);
+        if (att != null)
+          return att.type;
+      }
+    return "CDATA";
+  }
+
+  public String getAttributeValue(int index)
+  {
+    Attribute a = (Attribute) attrs.get(index);
+    return a.value;
+  }
+
+  public String getAttributeValue(String namespaceURI, String localName)
+  {
+    for (Iterator i = attrs.iterator(); i.hasNext(); )
+      {
+        Attribute a = (Attribute) i.next();
+        if (a.localName.equals(localName))
+          {
+            String uri = getNamespaceURI(a.prefix);
+            if ((uri == null && namespaceURI == null) ||
+                (uri != null && uri.equals(namespaceURI)))
+              return a.value;
+          }
+      }
+    return null;
+  }
+
+  boolean isAttributeDeclared(int index)
+  {
+    if (doctype == null)
+      return false;
+    Attribute a = (Attribute) attrs.get(index);
+    String qn = ("".equals(a.prefix)) ? a.localName :
+      a.prefix + ":" + a.localName;
+    String elementName = buf.toString();
+    return doctype.isAttributeDeclared(elementName, qn);
+  }
+  
+  public String getCharacterEncodingScheme()
+  {
+    return xmlEncoding;
+  }
+
+  public String getElementText()
+    throws XMLStreamException
+  {
+    if (event != XMLStreamConstants.START_ELEMENT)
+      throw new XMLStreamException("current event must be START_ELEMENT");
+    StringBuffer elementText = new StringBuffer();
+    int depth = stack.size();
+    while (event != XMLStreamConstants.END_ELEMENT || stack.size() > depth)
+      {
+        switch (next())
+          {
+          case XMLStreamConstants.CHARACTERS:
+          case XMLStreamConstants.SPACE:
+            elementText.append(buf.toString());
+          }
+      }
+    return elementText.toString();
+  }
+
+  public String getEncoding()
+  {
+    return (input.inputEncoding == null) ? "UTF-8" : input.inputEncoding;
+  }
+
+  public int getEventType()
+  {
+    return event;
+  }
+
+  public String getLocalName()
+  {
+    switch (event)
+      {
+      case XMLStreamConstants.START_ELEMENT:
+      case XMLStreamConstants.END_ELEMENT:
+        String qName = buf.toString();
+        int ci = qName.indexOf(':');
+        return (ci == -1) ? qName : qName.substring(ci + 1);
+      default:
+        return null;
+      }
+  }
+
+  public Location getLocation()
+  {
+    return input;
+  }
+
+  public QName getName()
+  {
+    switch (event)
+      {
+      case XMLStreamConstants.START_ELEMENT:
+      case XMLStreamConstants.END_ELEMENT:
+        String qName = buf.toString();
+        int ci = qName.indexOf(':');
+        String localName = (ci == -1) ? qName : qName.substring(ci + 1);
+        String prefix = (ci == -1) ?
+          (namespaceAware ? XMLConstants.DEFAULT_NS_PREFIX : null) :
+          qName.substring(0, ci);
+        String namespaceURI = getNamespaceURI(prefix);
+        return new QName(namespaceURI, localName, prefix);
+      default:
+        return null;
+      }
+  }
+
+  public int getNamespaceCount()
+  {
+    if (!namespaceAware || namespaces.isEmpty())
+      return 0;
+    switch (event)
+      {
+      case XMLStreamConstants.START_ELEMENT:
+      case XMLStreamConstants.END_ELEMENT:
+        LinkedHashMap ctx = (LinkedHashMap) namespaces.getFirst();
+        return ctx.size();
+      default:
+        return 0;
+      }
+  }
+
+  public String getNamespacePrefix(int index)
+  {
+    LinkedHashMap ctx = (LinkedHashMap) namespaces.getFirst();
+    int count = 0;
+    for (Iterator i = ctx.keySet().iterator(); i.hasNext(); )
+      {
+        String prefix = (String) i.next();
+        if (count++ == index)
+          return prefix;
+      }
+    return null;
+  }
+
+  public String getNamespaceURI()
+  {
+    switch (event)
+      {
+      case XMLStreamConstants.START_ELEMENT:
+      case XMLStreamConstants.END_ELEMENT:
+        String qName = buf.toString();
+        int ci = qName.indexOf(':');
+        if (ci == -1)
+          return null;
+        String prefix = qName.substring(0, ci);
+        return getNamespaceURI(prefix);
+      default:
+        return null;
+      }
+  }
+
+  public String getNamespaceURI(int index)
+  {
+    LinkedHashMap ctx = (LinkedHashMap) namespaces.getFirst();
+    int count = 0;
+    for (Iterator i = ctx.values().iterator(); i.hasNext(); )
+      {
+        String uri = (String) i.next();
+        if (count++ == index)
+          return uri;
+      }
+    return null;
+  }
+
+  public String getPIData()
+  {
+    return piData;
+  }
+
+  public String getPITarget()
+  {
+    return piTarget;
+  }
+
+  public String getPrefix()
+  {
+    switch (event)
+      {
+      case XMLStreamConstants.START_ELEMENT:
+      case XMLStreamConstants.END_ELEMENT:
+        String qName = buf.toString();
+        int ci = qName.indexOf(':');
+        return (ci == -1) ?
+          (namespaceAware ? XMLConstants.DEFAULT_NS_PREFIX : null) :
+          qName.substring(0, ci);
+      default:
+        return null;
+      }
+  }
+
+  public Object getProperty(String name)
+    throws IllegalArgumentException
+  {
+    if (name == null)
+      throw new IllegalArgumentException("name is null");
+    if (XMLInputFactory.ALLOCATOR.equals(name))
+      return null;
+    if (XMLInputFactory.IS_COALESCING.equals(name))
+      return coalescing ? Boolean.TRUE : Boolean.FALSE;
+    if (XMLInputFactory.IS_NAMESPACE_AWARE.equals(name))
+      return namespaceAware ? Boolean.TRUE : Boolean.FALSE;
+    if (XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES.equals(name))
+      return replaceERefs ? Boolean.TRUE : Boolean.FALSE;
+    if (XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES.equals(name))
+      return externalEntities ? Boolean.TRUE : Boolean.FALSE;
+    if (XMLInputFactory.IS_VALIDATING.equals(name))
+      return Boolean.FALSE;
+    if (XMLInputFactory.REPORTER.equals(name))
+      return reporter;
+    if (XMLInputFactory.RESOLVER.equals(name))
+      return resolver;
+    if (XMLInputFactory.SUPPORT_DTD.equals(name))
+      return supportDTD ? Boolean.TRUE : Boolean.FALSE;
+    if ("gnu.xml.stream.stringInterning".equals(name))
+      return stringInterning ? Boolean.TRUE : Boolean.FALSE;
+    if ("gnu.xml.stream.xmlBase".equals(name))
+      return baseAware ? Boolean.TRUE : Boolean.FALSE;
+    if ("gnu.xml.stream.baseURI".equals(name))
+      return getXMLBase();
+    return null;
+  }
+
+  public String getText()
+  {
+    return buf.toString();
+  }
+
+  public char[] getTextCharacters()
+  {
+    return buf.toString().toCharArray();
+  }
+
+  public int getTextCharacters(int sourceStart, char[] target,
+                               int targetStart, int length)
+    throws XMLStreamException
+  {
+    length = Math.min(sourceStart + buf.length(), length);
+    int sourceEnd = sourceStart + length;
+    buf.getChars(sourceStart, sourceEnd, target, targetStart);
+    return length;
+  }
+
+  public int getTextLength()
+  {
+    return buf.length();
+  }
+
+  public int getTextStart()
+  {
+    return 0;
+  }
+
+  public String getVersion()
+  {
+    return (xmlVersion == null) ? "1.0" : xmlVersion;
+  }
+
+  public boolean hasName()
+  {
+    switch (event)
+      {
+      case XMLStreamConstants.START_ELEMENT:
+      case XMLStreamConstants.END_ELEMENT:
+        return true;
+      default:
+        return false;
+      }
+  }
+
+  public boolean hasText()
+  {
+    switch (event)
+      {
+      case XMLStreamConstants.CHARACTERS:
+      case XMLStreamConstants.SPACE:
+        return true;
+      default:
+        return false;
+      }
+  }
+
+  public boolean isAttributeSpecified(int index)
+  {
+    Attribute a = (Attribute) attrs.get(index);
+    return a.specified;
+  }
+
+  public boolean isCharacters()
+  {
+    return (event == XMLStreamConstants.CHARACTERS);
+  }
+
+  public boolean isEndElement()
+  {
+    return (event == XMLStreamConstants.END_ELEMENT);
+  }
+
+  public boolean isStandalone()
+  {
+    return Boolean.TRUE.equals(xmlStandalone);
+  }
+
+  public boolean isStartElement()
+  {
+    return (event == XMLStreamConstants.START_ELEMENT);
+  }
+
+  public boolean isWhiteSpace()
+  {
+    return (event == XMLStreamConstants.SPACE);
+  }
+
+  public int nextTag()
+    throws XMLStreamException
+  {
+    do
+      {
+        switch (next())
+          {
+          case XMLStreamConstants.START_ELEMENT:
+          case XMLStreamConstants.END_ELEMENT:
+          case XMLStreamConstants.CHARACTERS:
+          case XMLStreamConstants.SPACE:
+          case XMLStreamConstants.COMMENT:
+          case XMLStreamConstants.PROCESSING_INSTRUCTION:
+            break;
+          default:
+            throw new XMLStreamException("Unexpected event type: " + event);
+          }
+      }
+    while (event != XMLStreamConstants.START_ELEMENT &&
+           event != XMLStreamConstants.END_ELEMENT);
+    return event;
+  }
+
+  public void require(int type, String namespaceURI, String localName)
+    throws XMLStreamException
+  {
+    if (event != type)
+      throw new XMLStreamException("Current event type is " + event);
+    if (event == XMLStreamConstants.START_ELEMENT ||
+        event == XMLStreamConstants.END_ELEMENT)
+      {
+        String ln = getLocalName();
+        if (!ln.equals(localName))
+          throw new XMLStreamException("Current local-name is " + ln);
+        String uri = getNamespaceURI();
+        if ((uri == null && namespaceURI != null) ||
+            (uri != null && !uri.equals(namespaceURI)))
+          throw new XMLStreamException("Current namespace URI is " + uri);
+      }
+  }
+
+  public boolean standaloneSet()
+  {
+    return (xmlStandalone != null);
+  }
+
+  public boolean hasNext()
+    throws XMLStreamException
+  {
+    if (event == XMLStreamConstants.END_DOCUMENT)
+      return false;
+    if (!lookahead)
+      {
+        next();
+        lookahead = true;
+      }
+    return event != -1;
+  }
+  
+  public int next()
+    throws XMLStreamException
+  {
+    if (lookahead)
+      {
+        lookahead = false;
+        return event;
+      }
+    if (event == XMLStreamConstants.END_ELEMENT)
+      {
+        // Pop namespace context
+        if (namespaceAware && !namespaces.isEmpty())
+          namespaces.removeFirst();
+        // Pop base context
+        if (baseAware && !bases.isEmpty())
+          bases.removeFirst();
+      }
+    if (!startEntityStack.isEmpty())
+      {
+        String entityName = (String) startEntityStack.removeFirst();
+        buf.setLength(0);
+        buf.append(entityName);
+        event = START_ENTITY;
+        return extendedEventTypes ? event : next();
+      }
+    else if (!endEntityStack.isEmpty())
+      {
+        String entityName = (String) endEntityStack.removeFirst();
+        buf.setLength(0);
+        buf.append(entityName);
+        event = END_ENTITY;
+        return extendedEventTypes ? event : next();
+      }
+    try
+      {
+        if (!input.initialized)
+          input.init();
+        switch (state)
+          {
+          case CONTENT:
+            if (tryRead(TEST_END_ELEMENT))
+              {
+                readEndElement();
+                if (stack.isEmpty())
+                  state = MISC;
+                event = XMLStreamConstants.END_ELEMENT;
+              }
+            else if (tryRead(TEST_COMMENT))
+              {
+                readComment(false);
+                event = XMLStreamConstants.COMMENT;
+              }
+            else if (tryRead(TEST_PI))
+              {
+                readPI(false);
+                event = XMLStreamConstants.PROCESSING_INSTRUCTION;
+              }
+            else if (tryRead(TEST_CDATA))
+              {
+                readCDSect();
+                event = XMLStreamConstants.CDATA;
+              }
+            else if (tryRead(TEST_START_ELEMENT))
+              {
+                state = readStartElement();
+                event = XMLStreamConstants.START_ELEMENT;
+              }
+            else
+              {
+                // Check for character reference or predefined entity
+                mark(8);
+                int c = readCh();
+                if (c == 0x26) // '&'
+                  {
+                    c = readCh();
+                    if (c == 0x23) // '#'
+                      {
+                        reset();
+                        event = readCharData(null);
+                      }
+                    else
+                      {
+                        // entity reference
+                        reset();
+                        readCh(); // &
+                        readReference();
+                        String ref = buf.toString();
+                        String text = (String) PREDEFINED_ENTITIES.get(ref);
+                        if (text != null)
+                          {
+                            event = readCharData(text);
+                          }
+                        else if (replaceERefs && !isUnparsedEntity(ref))
+                          {
+                            // this will report a start-entity event
+                            boolean external = false;
+                            if (doctype != null)
+                              {
+                                Object entity = doctype.getEntity(ref);
+                                if (entity instanceof ExternalIds)
+                                  external = true;
+                              }
+                            expandEntity(ref, false, external);
+                            event = next();
+                          }
+                        else
+                          {
+                            event = XMLStreamConstants.ENTITY_REFERENCE;
+                          }
+                      }
+                  }
+                else
+                  {
+                    reset();
+                    event = readCharData(null);
+                    if (validating && doctype != null)
+                      validatePCData(buf.toString());
+                  }
+              }
+            break;
+          case EMPTY_ELEMENT:
+            String elementName = (String) stack.removeLast();
+            buf.setLength(0);
+            buf.append(elementName);
+            state = stack.isEmpty() ? MISC : CONTENT;
+            event = XMLStreamConstants.END_ELEMENT;
+            if (validating && doctype != null)
+              endElementValidationHook();
+            break;
+          case INIT: // XMLDecl?
+            if (tryRead(TEST_XML_DECL))
+              readXMLDecl();
+            input.finalizeEncoding();
+            event = XMLStreamConstants.START_DOCUMENT;
+            state = PROLOG;
+            break;
+          case PROLOG: // Misc* (doctypedecl Misc*)?
+            skipWhitespace();
+            if (doctype == null && tryRead(TEST_DOCTYPE_DECL))
+              {
+                readDoctypeDecl();
+                event = XMLStreamConstants.DTD;
+              }
+            else if (tryRead(TEST_COMMENT))
+              {
+                readComment(false);
+                event = XMLStreamConstants.COMMENT;
+              }
+            else if (tryRead(TEST_PI))
+              {
+                readPI(false);
+                event = XMLStreamConstants.PROCESSING_INSTRUCTION;
+              }
+            else if (tryRead(TEST_START_ELEMENT))
+              {
+                state = readStartElement();
+                event = XMLStreamConstants.START_ELEMENT;
+              }
+            else
+              {
+                int c = readCh();
+                error("no root element: U+" + Integer.toHexString(c));
+              }
+            break;
+          case MISC: // Comment | PI | S
+            skipWhitespace();
+            if (tryRead(TEST_COMMENT))
+              {
+                readComment(false);
+                event = XMLStreamConstants.COMMENT;
+              }
+            else if (tryRead(TEST_PI))
+              {
+                readPI(false);
+                event = XMLStreamConstants.PROCESSING_INSTRUCTION;
+              }
+            else
+              {
+                if (event == XMLStreamConstants.END_DOCUMENT)
+                  throw new NoSuchElementException();
+                int c = readCh();
+                if (c != -1)
+                  error("Only comments and PIs may appear after " +
+                        "the root element");
+                event = XMLStreamConstants.END_DOCUMENT;
+              }
+            break;
+          default:
+            event = -1;
+          }
+        return event;
+      }
+    catch (IOException e)
+      {
+        XMLStreamException e2 = new XMLStreamException();
+        e2.initCause(e);
+        throw e2;
+      }
+  }
+
+  // package private
+
+  /**
+   * Returns the current element name.
+   */
+  String getCurrentElement()
+  {
+    return (String) stack.getLast();
+  }
+
+  // private
+
+  private void mark(int limit)
+    throws IOException
+  {
+    input.mark(limit);
+  }
+
+  private void reset()
+    throws IOException
+  {
+    input.reset();
+  }
+
+  private int read()
+    throws IOException
+  {
+    return input.read();
+  }
+
+  private int read(int[] b, int off, int len)
+    throws IOException
+  {
+    return input.read(b, off, len);
+  }
+  
+  /**
+   * Parsed character read.
+   */
+  private int readCh()
+    throws IOException, XMLStreamException
+  {
+    int c = read();
+    if (expandPE && c == 0x25) // '%'
+      {
+        if (peIsError)
+          error("PE reference within decl in internal subset.");
+        expandPEReference();
+        return readCh();
+      }
+    return c;
+  }
+
+  /**
+   * Reads the next character, ensuring it is the character specified.
+   * @param delim the character to match
+   * @exception XMLStreamException if the next character is not the
+   * specified one
+   */
+  private void require(char delim)
+    throws IOException, XMLStreamException
+  {
+    mark(1);
+    int c = readCh();
+    if (delim != c)
+      {
+        reset();
+        error("required character (got U+" + Integer.toHexString(c) + ")",
+              new Character(delim));
+      }
+  }
+
+  /**
+   * Reads the next few characters, ensuring they match the string specified.
+   * @param delim the string to match
+   * @exception XMLStreamException if the next characters do not match the
+   * specified string
+   */
+  private void require(String delim)
+    throws IOException, XMLStreamException
+  {
+    char[] chars = delim.toCharArray();
+    int len = chars.length;
+    mark(len);
+    int off = 0;
+    do
+      {
+        int l2 = read(tmpBuf, off, len - off);
+        if (l2 == -1)
+          {
+            reset();
+            error("EOF before required string", delim);
+          }
+        off += l2;
+      }
+    while (off < len);
+    for (int i = 0; i < chars.length; i++)
+      {
+        if (chars[i] != tmpBuf[i])
+          {
+            reset();
+            error("required string", delim);
+          }
+      }
+  }
+
+  /**
+   * Try to read a single character. On failure, reset the stream.
+   * @param delim the character to test
+   * @return true if the character matched delim, false otherwise.
+   */
+  private boolean tryRead(char delim)
+    throws IOException, XMLStreamException
+  {
+    mark(1);
+    int c = readCh();
+    if (delim != c)
+      {
+        reset();
+        return false;
+      }
+    return true;
+  }
+
+  /**
+   * Tries to read the specified characters.
+   * If successful, the stream is positioned after the last character,
+   * otherwise it is reset.
+   * @param test the string to test
+   * @return true if the characters matched the test string, false otherwise.
+   */
+  private boolean tryRead(String test)
+    throws IOException
+  {
+    char[] chars = test.toCharArray();
+    int len = chars.length;
+    mark(len);
+    int count = 0;
+    int l2 = read(tmpBuf, 0, len);
+    if (l2 == -1)
+      {
+        reset();
+        return false;
+      }
+    count += l2;
+    // check the characters we received first before doing additional reads
+    for (int i = 0; i < count; i++)
+      {
+        if (chars[i] != tmpBuf[i])
+          {
+            reset();
+            return false;
+          }
+      }
+    while (count < len)
+      {
+        // force read
+        int c = read();
+        if (c == -1)
+          {
+            reset();
+            return false;
+          }
+        tmpBuf[count] = (char) c;
+        // check each character as it is read
+        if (chars[count] != tmpBuf[count])
+          {
+            reset();
+            return false;
+          }
+        count++;
+      }
+    return true;
+  }
+
+  /**
+   * Reads characters until the specified test string is encountered.
+   * @param delim the string delimiting the end of the characters
+   */
+  private void readUntil(String delim)
+    throws IOException, XMLStreamException
+  {
+    int startLine = input.line;
+    try
+      {
+        while (!tryRead(delim))
+          {
+            int c = readCh();
+            if (c == -1)
+              throw new EOFException();
+            else if (input.xml11)
+              {
+                if (!isXML11Char(c) || isXML11RestrictedChar(c))
+                  error("illegal XML 1.1 character",
+                        "U+" + Integer.toHexString(c));
+              }
+            else if (!isChar(c))
+              error("illegal XML character", 
+                    "U+" + Integer.toHexString(c));
+            buf.append(Character.toChars(c));
+          }
+      }
+    catch (EOFException e)
+      {
+        error("end of input while looking for delimiter "+
+              "(started on line " + startLine + ')', delim);
+      }
+  }
+
+  /**
+   * Reads any whitespace characters.
+   * @return true if whitespace characters were read, false otherwise
+   */
+  private boolean tryWhitespace()
+    throws IOException, XMLStreamException
+  {
+    boolean white;
+    boolean ret = false;
+    do
+      {
+        mark(1);
+        int c = readCh();
+        while (c == -1 && inputStack.size() > 1)
+          {
+            popInput();
+            c = readCh();
+          }
+        white = (c == 0x20 || c == 0x09 || c == 0x0a || c == 0x0d);
+        if (white)
+          ret = true;
+      }
+    while (white);
+    reset();
+    return ret;
+  }
+
+  /**
+   * Skip over any whitespace characters.
+   */
+  private void skipWhitespace()
+    throws IOException, XMLStreamException
+  {
+    boolean white;
+    do
+      {
+        mark(1);
+        int c = readCh();
+        while (c == -1 && inputStack.size() > 1)
+          {
+            popInput();
+            c = readCh();
+          }
+        white = (c == 0x20 || c == 0x09 || c == 0x0a || c == 0x0d);
+      }
+    while (white);
+    reset();
+  }
+
+  /**
+   * Try to read as many whitespace characters as are available.
+   * @exception XMLStreamException if no whitespace characters were seen
+   */
+  private void requireWhitespace()
+    throws IOException, XMLStreamException
+  {
+    if (!tryWhitespace())
+      error("whitespace required");
+  }
+
+  /**
+   * Returns the current base URI for resolving external entities.
+   */
+  String getXMLBase()
+  {
+    if (baseAware)
+      {
+        for (Iterator i = bases.iterator(); i.hasNext(); )
+          {
+            String base = (String) i.next();
+            if (base != null)
+              return base;
+          }
+      }
+    return input.systemId;
+  }
+
+  /**
+   * Push the specified text input source.
+   */
+  private void pushInput(String name, String text, boolean report,
+                         boolean normalize)
+    throws IOException, XMLStreamException
+  {
+    // Check for recursion
+    if (name != null && !"".equals(name))
+      {
+        for (Iterator i = inputStack.iterator(); i.hasNext(); )
+          {
+            Input ctx = (Input) i.next();
+            if (name.equals(ctx.name))
+              error("entities may not be self-recursive", name);
+          }
+      }
+    else
+      report = false;
+    pushInput(new Input(null, new StringReader(text), input.publicId,
+                        input.systemId, name, input.inputEncoding, report,
+                        normalize));
+  }
+
+  /**
+   * Push the specified external input source.
+   */
+  private void pushInput(String name, ExternalIds ids, boolean report,
+                         boolean normalize)
+    throws IOException, XMLStreamException
+  {
+    if (!externalEntities)
+      return;
+    String url = absolutize(input.systemId, ids.systemId);
+    // Check for recursion
+    for (Iterator i = inputStack.iterator(); i.hasNext(); )
+      {
+        Input ctx = (Input) i.next();
+        if (url.equals(ctx.systemId))
+          error("entities may not be self-recursive", url);
+        if (name != null && !"".equals(name) && name.equals(ctx.name))
+          error("entities may not be self-recursive", name);
+      }
+    if (name == null || "".equals(name))
+      report = false;
+    InputStream in = null;
+    if (resolver != null)
+      {
+        Object obj = resolver.resolveEntity(ids.publicId, url, getXMLBase(),
+                                            null);
+        if (obj instanceof InputStream)
+          in = (InputStream) obj;
+      }
+    if (in == null)
+      in = resolve(url);
+    if (in == null)
+      error("unable to resolve external entity",
+            (ids.systemId != null) ? ids.systemId : ids.publicId);
+    pushInput(new Input(in, null, ids.publicId, url, name, null, report,
+                        normalize));
+    input.init();
+    if (tryRead(TEST_XML_DECL))
+      readTextDecl();
+    input.finalizeEncoding();
+  }
+
+  /**
+   * Push the specified input source (general entity) onto the input stack.
+   */
+  private void pushInput(Input input)
+  {
+    if (input.report)
+      startEntityStack.addFirst(input.name);
+    inputStack.addLast(input);
+    if (this.input != null)
+      input.xml11 = this.input.xml11;
+    this.input = input;
+  }
+
+  /**
+   * "Absolutize" a URL. This resolves a relative URL into an absolute one.
+   * @param base the current base URL
+   * @param href the (absolute or relative) URL to resolve
+   */
+  public static String absolutize(String base, String href)
+    throws MalformedURLException
+  {
+    if (href == null)
+      return null;
+    int ci = href.indexOf(':');
+    if (ci > 1 && isURLScheme(href.substring(0, ci)))
+      {
+        // href is absolute already
+        return href;
+      }
+    if (base == null)
+      base = "";
+    else
+      {
+        int i = base.lastIndexOf('/');
+        if (i != -1)
+          base = base.substring(0, i + 1);
+        else
+          base = "";
+      }
+    if ("".equals(base))
+      {
+        // assume file URL relative to current directory
+        base = System.getProperty("user.dir");
+        if (base.charAt(0) == '/')
+          base = base.substring(1);
+        base = "file:///" + base.replace(File.separatorChar, '/');
+        if (!base.endsWith("/"))
+          base += "/";
+      }
+    return new URL(new URL(base), href).toString();
+  }
+
+  /**
+   * Indicates whether the specified characters match the scheme portion of
+   * a URL.
+   * @see RFC 1738 section 2.1
+   */
+  private static boolean isURLScheme(String text)
+  {
+    int len = text.length();
+    for (int i = 0; i < len; i++)
+      {
+        char c = text.charAt(i);
+        if (c == '+' || c == '.' || c == '-')
+          continue;
+        if (c < 65 || (c > 90 && c < 97) || c > 122)
+          return false;
+      }
+    return true;
+  }
+
+  /**
+   * Returns an input stream for the given URL.
+   */
+  static InputStream resolve(String url)
+    throws IOException
+  {
+    try
+      {
+        return new URL(url).openStream();
+      }
+    catch (MalformedURLException e)
+      {
+        return null;
+      }
+    catch (IOException e)
+      {
+        IOException e2 = new IOException("error resolving " + url);
+        e2.initCause(e);
+        throw e2;
+      }
+  }
+
+  /**
+   * Pops the current input source (general entity) off the stack.
+   */
+  private void popInput()
+  {
+    Input old = (Input) inputStack.removeLast();
+    if (old.report)
+      endEntityStack.addFirst(old.name);
+    input = (Input) inputStack.getLast();
+  }
+
+  /**
+   * Parse an entity text declaration.
+   */
+  private void readTextDecl()
+    throws IOException, XMLStreamException
+  {
+    final int flags = LIT_DISABLE_CREF | LIT_DISABLE_PE | LIT_DISABLE_EREF;
+    requireWhitespace();
+    if (tryRead("version"))
+      {
+        readEq();
+        String v = readLiteral(flags, false);
+        if ("1.0".equals(v))
+          input.xml11 = false;
+        else if ("1.1".equals(v))
+          {
+            Input i1 = (Input) inputStack.getFirst();
+            if (!i1.xml11)
+              error("external entity specifies later version number");
+            input.xml11 = true;
+          }
+        else
+          throw new XMLStreamException("illegal XML version: " + v);
+        requireWhitespace();
+      }
+    require("encoding");
+    readEq();
+    String enc = readLiteral(flags, false);
+    skipWhitespace();
+    require("?>");
+    input.setInputEncoding(enc);
+  }
+
+  /**
+   * Parse the XML declaration.
+   */
+  private void readXMLDecl()
+    throws IOException, XMLStreamException
+  {
+    final int flags = LIT_DISABLE_CREF | LIT_DISABLE_PE | LIT_DISABLE_EREF;
+    
+    requireWhitespace();
+    require("version");
+    readEq();
+    xmlVersion = readLiteral(flags, false);
+    if ("1.0".equals(xmlVersion))
+      input.xml11 = false;
+    else if ("1.1".equals(xmlVersion))
+      input.xml11 = true;
+    else
+      throw new XMLStreamException("illegal XML version: " + xmlVersion);
+    
+    boolean white = tryWhitespace();
+    
+    if (tryRead("encoding"))
+      {
+        if (!white)
+          error("whitespace required before 'encoding='");
+        readEq();
+        xmlEncoding = readLiteral(flags, false);
+        white = tryWhitespace();
+      }
+    
+    if (tryRead("standalone"))
+      {
+        if (!white)
+          error("whitespace required before 'standalone='");
+        readEq();
+        String standalone = readLiteral(flags, false);
+        if ("yes".equals(standalone))
+          xmlStandalone = Boolean.TRUE;
+        else if ("no".equals(standalone))
+          xmlStandalone = Boolean.FALSE;
+        else
+          error("standalone flag must be 'yes' or 'no'", standalone);
+      }
+
+    skipWhitespace();
+    require("?>");
+    if (xmlEncoding != null)
+      input.setInputEncoding(xmlEncoding);
+  }
+
+  /**
+   * Parse the DOCTYPE declaration.
+   */
+  private void readDoctypeDecl()
+    throws IOException, XMLStreamException
+  {
+    if (!supportDTD)
+      error("parser was configured not to support DTDs");
+    requireWhitespace();
+    String rootName = readNmtoken(true);
+    skipWhitespace();
+    ExternalIds ids = readExternalIds(false, true);
+    doctype =
+      this.new Doctype(rootName, ids.publicId, ids.systemId);
+    
+    // Parse internal subset first
+    skipWhitespace();
+    if (tryRead('['))
+      {
+        while (true)
+          {
+            expandPE = true;
+            skipWhitespace();
+            expandPE = false;
+            if (tryRead(']'))
+              break;
+            else
+              readMarkupdecl(false);
+          }
+      }
+    skipWhitespace();
+    require('>');
+
+    // Parse external subset
+    if (ids.systemId != null && externalEntities)
+      {
+        pushInput("", ">", false, false);
+        pushInput("[dtd]", ids, true, true);
+        // loop until we get back to ">"
+        while (true)
+          {
+            expandPE = true;
+            skipWhitespace();
+            expandPE = false;
+            mark(1);
+            int c = readCh();
+            if (c == 0x3e) // '>'
+              break;
+            else if (c == -1)
+              popInput();
+            else
+              {
+                reset();
+                expandPE = true;
+                readMarkupdecl(true);
+                expandPE = true;
+              }
+          }
+        if (inputStack.size() != 2)
+          error("external subset has unmatched '>'");
+        popInput();
+      }
+    checkDoctype();
+    if (validating)
+      validateDoctype();
+
+    // Make rootName available for reading
+    buf.setLength(0);
+    buf.append(rootName);
+  }
+
+  /**
+   * Checks the well-formedness of the DTD.
+   */
+  private void checkDoctype()
+    throws XMLStreamException
+  {
+    // TODO check entity recursion
+  }
+
+  /**
+   * Parse the markupdecl production.
+   */
+  private void readMarkupdecl(boolean inExternalSubset)
+    throws IOException, XMLStreamException
+  {
+    boolean saved = expandPE;
+    mark(1);
+    require('<');
+    reset();
+    expandPE = false;
+    if (tryRead(TEST_ELEMENT_DECL))
+      {
+        expandPE = saved;
+        readElementDecl();
+      }
+    else if (tryRead(TEST_ATTLIST_DECL))
+      {
+        expandPE = saved;
+        readAttlistDecl();
+      }
+    else if (tryRead(TEST_ENTITY_DECL))
+      {
+        expandPE = saved;
+        readEntityDecl(inExternalSubset);
+      }
+    else if (tryRead(TEST_NOTATION_DECL))
+      {
+        expandPE = saved;
+        readNotationDecl(inExternalSubset);
+      }
+    else if (tryRead(TEST_PI))
+      {
+        readPI(true);
+        expandPE = saved;
+      }
+    else if (tryRead(TEST_COMMENT))
+      {
+        readComment(true);
+        expandPE = saved;
+      }
+    else if (tryRead("<!["))
+      {
+        // conditional section
+        expandPE = saved;
+        if (inputStack.size() < 2)
+          error("conditional sections illegal in internal subset");
+        skipWhitespace();
+        if (tryRead("INCLUDE"))
+          {
+            skipWhitespace();
+            require('[');
+            skipWhitespace();
+            while (!tryRead("]]>"))
+              {
+                readMarkupdecl(inExternalSubset);
+                skipWhitespace();
+              }
+          }
+        else if (tryRead("IGNORE"))
+          {
+            skipWhitespace();
+            require('[');
+            expandPE = false;
+            for (int nesting = 1; nesting > 0; )
+              {
+                int c = readCh();
+                switch (c)
+                  {
+                  case 0x3c: // '<'
+                    if (tryRead("!["))
+                      nesting++;
+                    break;
+                  case 0x5d: // ']'
+                    if (tryRead("]>"))
+                      nesting--;
+                    break;
+                  case -1:
+                    throw new EOFException();
+                  }
+              }
+            expandPE = saved;
+          }
+        else
+          error("conditional section must begin with INCLUDE or IGNORE");
+      }
+    else
+      error("expected markup declaration");
+  }
+
+  /**
+   * Parse the elementdecl production.
+   */
+  private void readElementDecl()
+    throws IOException, XMLStreamException
+  {
+    requireWhitespace();
+    boolean saved = expandPE;
+    expandPE = (inputStack.size() > 1);
+    String name = readNmtoken(true);
+    expandPE = saved;
+    requireWhitespace();
+    readContentspec(name);
+    skipWhitespace();
+    require('>');
+  }
+
+  /**
+   * Parse the contentspec production.
+   */
+  private void readContentspec(String elementName)
+    throws IOException, XMLStreamException
+  {
+    if (tryRead("EMPTY"))
+      doctype.addElementDecl(elementName, "EMPTY", new EmptyContentModel());
+    else if (tryRead("ANY"))
+      doctype.addElementDecl(elementName, "ANY", new AnyContentModel());
+    else
+      {
+        ContentModel model;
+        StringBuffer acc = new StringBuffer();
+        require('(');
+        acc.append('(');
+        skipWhitespace();
+        if (tryRead("#PCDATA"))
+          {
+            // mixed content
+            acc.append("#PCDATA");
+            MixedContentModel mm = new MixedContentModel();
+            model = mm;
+            skipWhitespace();
+            if (tryRead(')'))
+              {
+                acc.append(")");
+                if (tryRead('*'))
+                  {
+                    mm.min = 0;
+                    mm.max = -1;
+                  }
+              }
+            else
+              {
+                while (!tryRead(")"))
+                  {
+                    require('|');
+                    acc.append('|');
+                    skipWhitespace();
+                    String name = readNmtoken(true);
+                    acc.append(name);
+                    mm.addName(name);
+                    skipWhitespace();
+                  }
+                require('*');
+                acc.append(")*");
+                mm.min = 0;
+                mm.max = -1;
+              }
+          }
+        else
+          model = readElements(acc);
+        doctype.addElementDecl(elementName, acc.toString(), model);
+      }
+  }
+
+  /**
+   * Parses an element content model.
+   */
+  private ElementContentModel readElements(StringBuffer acc)
+    throws IOException, XMLStreamException
+  {
+    int separator;
+    ElementContentModel model = new ElementContentModel();
+    
+    // Parse first content particle
+    skipWhitespace();
+    model.addContentParticle(readContentParticle(acc));
+    // End or separator
+    skipWhitespace();
+    int c = readCh();
+    switch (c)
+      {
+      case 0x29: // ')'
+        acc.append(')');
+        mark(1);
+        c = readCh();
+        switch (c)
+          {
+          case 0x3f: // '?'
+            acc.append('?');
+            model.min = 0;
+            model.max = 1;
+            break;
+          case 0x2a: // '*'
+            acc.append('*');
+            model.min = 0;
+            model.max = -1;
+            break;
+          case 0x2b: // '+'
+            acc.append('+');
+            model.min = 1;
+            model.max = -1;
+            break;
+          default:
+            reset();
+          }
+        return model; // done
+      case 0x7c: // '|'
+        model.or = true;
+        // fall through
+      case 0x2c: // ','
+        separator = c;
+        acc.append(Character.toChars(c));
+        break;
+      default:
+        error("bad separator in content model",
+              "U+" + Integer.toHexString(c));
+        return model;
+      }
+    // Parse subsequent content particles
+    while (true)
+      {
+        skipWhitespace();
+        model.addContentParticle(readContentParticle(acc));
+        skipWhitespace();
+        c = readCh();
+        if (c == 0x29) // ')'
+          {
+            acc.append(')');
+            break;
+          }
+        else if (c != separator)
+          {
+            error("bad separator in content model",
+                  "U+" + Integer.toHexString(c));
+            return model;
+          }
+        else
+          acc.append(c);
+      }
+    // Check for occurrence indicator
+    mark(1);
+    c = readCh();
+    switch (c)
+      {
+      case 0x3f: // '?'
+        acc.append('?');
+        model.min = 0;
+        model.max = 1;
+        break;
+      case 0x2a: // '*'
+        acc.append('*');
+        model.min = 0;
+        model.max = -1;
+        break;
+      case 0x2b: // '+'
+        acc.append('+');
+        model.min = 1;
+        model.max = -1;
+        break;
+      default:
+        reset();
+      }
+    return model;
+  }
+
+  /**
+   * Parse a cp production.
+   */
+  private ContentParticle readContentParticle(StringBuffer acc)
+    throws IOException, XMLStreamException
+  {
+    ContentParticle cp = new ContentParticle();
+    if (tryRead('('))
+      {
+        acc.append('(');
+        cp.content = readElements(acc);
+      }
+    else
+      {
+        String name = readNmtoken(true);
+        acc.append(name);
+        cp.content = name;
+        mark(1);
+        int c = readCh();
+        switch (c)
+          {
+          case 0x3f: // '?'
+            acc.append('?');
+            cp.min = 0;
+            cp.max = 1;
+            break;
+          case 0x2a: // '*'
+            acc.append('*');
+            cp.min = 0;
+            cp.max = -1;
+            break;
+          case 0x2b: // '+'
+            acc.append('+');
+            cp.min = 1;
+            cp.max = -1;
+            break;
+          default:
+            reset();
+          }
+      }
+    return cp;
+  }
+
+  /**
+   * Parse an attribute-list definition.
+   */
+  private void readAttlistDecl()
+    throws IOException, XMLStreamException
+  {
+    requireWhitespace();
+    boolean saved = expandPE;
+    expandPE = (inputStack.size() > 1);
+    String elementName = readNmtoken(true);
+    expandPE = saved;
+    boolean white = tryWhitespace();
+    while (!tryRead('>'))
+      {
+        if (!white)
+          error("whitespace required before attribute definition");
+        readAttDef(elementName);
+        white = tryWhitespace();
+      }
+  }
+
+  /**
+   * Parse a single attribute definition.
+   */
+  private void readAttDef(String elementName)
+    throws IOException, XMLStreamException
+  {
+    String name = readNmtoken(true);
+    requireWhitespace();
+    StringBuffer acc = new StringBuffer();
+    HashSet values = new HashSet();
+    String type = readAttType(acc, values);
+    if (validating)
+      {
+        if ("ID".equals(type))
+          {
+            // VC: One ID per Element Type
+            for (Iterator i = doctype.attlistIterator(elementName);
+                 i.hasNext(); )
+              {
+                Map.Entry entry = (Map.Entry) i.next();
+                AttributeDecl decl = (AttributeDecl) entry.getValue();
+                if ("ID".equals(decl.type))
+                  error("element types must not have more than one ID " +
+                        "attribute");
+              }
+          }
+        else if ("NOTATION".equals(type))
+          {
+            // VC: One Notation Per Element Type
+            for (Iterator i = doctype.attlistIterator(elementName);
+                 i.hasNext(); )
+              {
+                Map.Entry entry = (Map.Entry) i.next();
+                AttributeDecl decl = (AttributeDecl) entry.getValue();
+                if ("NOTATION".equals(decl.type))
+                  error("element types must not have more than one NOTATION " +
+                        "attribute");
+              }
+            // VC: No Notation on Empty Element
+            ContentModel model = doctype.getElementModel(elementName);
+            if (model != null && model.type == ContentModel.EMPTY)
+              error("attributes of type NOTATION must not be declared on an " +
+                    "element declared EMPTY");
+          }
+      }
+    String enumer = null;
+    if ("ENUMERATION".equals(type) || "NOTATION".equals(type))
+      enumer = acc.toString();
+    else
+      values = null;
+    requireWhitespace();
+    readDefault(elementName, name, type, enumer, values);
+  }
+
+  /**
+   * Parse an attribute type.
+   */
+  private String readAttType(StringBuffer acc, HashSet values)
+    throws IOException, XMLStreamException
+  {
+    if (tryRead('('))
+      {
+        readEnumeration(false, acc, values);
+        return "ENUMERATION";
+      }
+    else
+      {
+        String typeString = readNmtoken(true);
+        if ("NOTATION".equals(typeString))
+          {
+            readNotationType(acc, values);
+            return typeString;
+          }
+        else if ("CDATA".equals(typeString) ||
+                 "ID".equals(typeString) ||
+                 "IDREF".equals(typeString) ||
+                 "IDREFS".equals(typeString) ||
+                 "ENTITY".equals(typeString) ||
+                 "ENTITIES".equals(typeString) ||
+                 "NMTOKEN".equals(typeString) ||
+                 "NMTOKENS".equals(typeString))
+          return typeString;
+        else
+          {
+            error("illegal attribute type", typeString);
+            return null;
+          }
+      }
+  }
+
+  /**
+   * Parse an enumeration.
+   */
+  private void readEnumeration(boolean isNames, StringBuffer acc,
+                               HashSet values)
+    throws IOException, XMLStreamException
+  {
+    acc.append('(');
+    // first token
+    skipWhitespace();
+    String token = readNmtoken(isNames);
+    acc.append(token);
+    values.add(token);
+    // subsequent tokens
+    skipWhitespace();
+    while (!tryRead(')'))
+      {
+        require('|');
+        acc.append('|');
+        skipWhitespace();
+        token = readNmtoken(isNames);
+        // VC: No Duplicate Tokens
+        if (validating && values.contains(token))
+          error("duplicate token", token);
+        acc.append(token);
+        values.add(token);
+        skipWhitespace();
+      }
+    acc.append(')');
+  }
+
+  /**
+   * Parse a notation type for an attribute.
+   */
+  private void readNotationType(StringBuffer acc, HashSet values)
+    throws IOException, XMLStreamException
+  {
+    requireWhitespace();
+    require('(');
+    readEnumeration(true, acc, values);
+  }
+
+  /**
+   * Parse the default value for an attribute.
+   */
+  private void readDefault(String elementName, String name,
+                           String type, String enumeration, HashSet values)
+    throws IOException, XMLStreamException
+  {
+    int valueType = ATTRIBUTE_DEFAULT_SPECIFIED;
+    int flags = LIT_ATTRIBUTE;
+    String value = null, defaultType = null;
+    boolean saved = expandPE;
+    
+    if (!"CDATA".equals(type))
+      flags |= LIT_NORMALIZE;
+
+    expandPE = false;
+    if (tryRead('#'))
+      {
+        if (tryRead("FIXED"))
+          {
+            defaultType = "#FIXED";
+            valueType = ATTRIBUTE_DEFAULT_FIXED;
+            requireWhitespace();
+            value = readLiteral(flags, false);
+          }
+        else if (tryRead("REQUIRED"))
+          {
+            defaultType = "#REQUIRED";
+            valueType = ATTRIBUTE_DEFAULT_REQUIRED;
+          }
+        else if (tryRead("IMPLIED"))
+          {
+            defaultType = "#IMPLIED";
+            valueType = ATTRIBUTE_DEFAULT_IMPLIED;
+          }
+        else
+          error("illegal keyword for attribute default value");
+      }
+    else
+      value = readLiteral(flags, false);
+    expandPE = saved;
+    if (validating)
+      {
+        if ("ID".equals(type))
+          {
+            // VC: Attribute Default Value Syntactically Correct
+            if (value != null && !isNmtoken(value, true))
+              error("default value must match Name production", value);
+            // VC: ID Attribute Default
+            if (valueType != ATTRIBUTE_DEFAULT_REQUIRED &&
+                valueType != ATTRIBUTE_DEFAULT_IMPLIED)
+              error("ID attributes must have a declared default of " +
+                    "#IMPLIED or #REQUIRED");
+          }
+        else if (value != null)
+          {
+            // VC: Attribute Default Value Syntactically Correct
+            if ("IDREF".equals(type) || "ENTITY".equals(type))
+              {
+                if (!isNmtoken(value, true))
+                  error("default value must match Name production", value);
+              }
+            else if ("IDREFS".equals(type) || "ENTITIES".equals(type))
+              {
+                StringTokenizer st = new StringTokenizer(value);
+                while (st.hasMoreTokens())
+                  {
+                    String token = st.nextToken();
+                    if (!isNmtoken(token, true))
+                      error("default value must match Name production", token);
+                  }
+              }
+            else if ("NMTOKEN".equals(type) || "ENUMERATION".equals(type))
+              {
+                if (!isNmtoken(value, false))
+                  error("default value must match Nmtoken production", value);
+              }
+            else if ("NMTOKENS".equals(type))
+              {
+                StringTokenizer st = new StringTokenizer(value);
+                while (st.hasMoreTokens())
+                  {
+                    String token = st.nextToken();
+                    if (!isNmtoken(token, false))
+                      error("default value must match Nmtoken production",
+                            token);
+                  }
+              }
+          }
+      }
+    // Register attribute def
+    AttributeDecl attribute =
+      new AttributeDecl(type, value, valueType, enumeration, values,
+                        inputStack.size() != 1);
+    doctype.addAttributeDecl(elementName, name, attribute);
+  }
+
+  /**
+   * Parse the EntityDecl production.
+   */
+  private void readEntityDecl(boolean inExternalSubset)
+    throws IOException, XMLStreamException
+  {
+    int flags = 0;
+    // Check if parameter entity
+    boolean peFlag = false;
+    expandPE = false;
+    requireWhitespace();
+    if (tryRead('%'))
+      {
+        peFlag = true;
+        requireWhitespace();
+      }
+    expandPE = true;
+    // Read entity name
+    String name = readNmtoken(true);
+    if (name.indexOf(':') != -1)
+      error("illegal character ':' in entity name", name);
+    if (peFlag)
+      name = "%" + name;
+    requireWhitespace();
+    mark(1);
+    int c = readCh();
+    reset();
+    if (c == 0x22 || c == 0x27) // " | '
+      {
+        // Internal entity replacement text
+        String value = readLiteral(flags | LIT_DISABLE_EREF, true);
+        int ai = value.indexOf('&');
+        while (ai != -1)
+          {
+            int sci = value.indexOf(';', ai);
+            if (sci == -1)
+              error("malformed reference in entity value", value);
+            String ref = value.substring(ai + 1, sci);
+            int[] cp = UnicodeReader.toCodePointArray(ref);
+            if (cp.length == 0)
+              error("malformed reference in entity value", value);
+            if (cp[0] == 0x23) // #
+              {
+                if (cp.length == 1)
+                  error("malformed reference in entity value", value);
+                if (cp[1] == 0x78) // 'x'
+                  {
+                    if (cp.length == 2)
+                      error("malformed reference in entity value", value);
+                    for (int i = 2; i < cp.length; i++)
+                      {
+                        int x = cp[i];
+                        if (x < 0x30 ||
+                            (x > 0x39 && x < 0x41) ||
+                            (x > 0x46 && x < 0x61) ||
+                            x > 0x66)
+                          error("malformed character reference in entity value",
+                                value);
+                      }
+                  }
+                else
+                  {
+                    for (int i = 1; i < cp.length; i++)
+                      {
+                        int x = cp[i];
+                        if (x < 0x30 || x > 0x39)
+                          error("malformed character reference in entity value",
+                                value);
+                      }
+                  }
+              }
+            else
+              {
+                if (!isNameStartCharacter(cp[0], input.xml11))
+                  error("malformed reference in entity value", value);
+                for (int i = 1; i < cp.length; i++)
+                  {
+                    if (!isNameCharacter(cp[i], input.xml11))
+                      error("malformed reference in entity value", value);
+                  }
+              }
+            ai = value.indexOf('&', sci);
+          }
+        doctype.addEntityDecl(name, value, inExternalSubset);
+      }
+    else
+      {
+        ExternalIds ids = readExternalIds(false, false);
+        // Check for NDATA
+        boolean white = tryWhitespace();
+        if (!peFlag && tryRead("NDATA"))
+          {
+            if (!white)
+              error("whitespace required before NDATA");
+            requireWhitespace();
+            ids.notationName = readNmtoken(true);
+          }
+        doctype.addEntityDecl(name, ids, inExternalSubset);
+      }
+    // finish
+    skipWhitespace();
+    require('>');
+  }
+
+  /**
+   * Parse the NotationDecl production.
+   */
+  private void readNotationDecl(boolean inExternalSubset)
+    throws IOException, XMLStreamException
+  {
+    requireWhitespace();
+    String notationName = readNmtoken(true);
+    if (notationName.indexOf(':') != -1)
+      error("illegal character ':' in notation name", notationName);
+    if (validating)
+      {
+        // VC: Unique Notation Name
+        ExternalIds notation = doctype.getNotation(notationName);
+        if (notation != null)
+          error("duplicate notation name", notationName);
+      }
+    requireWhitespace();
+    ExternalIds ids = readExternalIds(true, false);
+    ids.notationName = notationName;
+    doctype.addNotationDecl(notationName, ids, inExternalSubset);
+    skipWhitespace();
+    require('>');
+  }
+
+  /**
+   * Returns a tuple {publicId, systemId}.
+   */
+  private ExternalIds readExternalIds(boolean inNotation, boolean isSubset)
+    throws IOException, XMLStreamException
+  {
+    int c;
+    int flags = LIT_DISABLE_CREF | LIT_DISABLE_PE | LIT_DISABLE_EREF;
+    ExternalIds ids = new ExternalIds();
+    
+    if (tryRead("PUBLIC"))
+      {
+        requireWhitespace();
+        ids.publicId = readLiteral(LIT_NORMALIZE | LIT_PUBID | flags, false);
+        if (inNotation)
+          {
+            skipWhitespace();
+            mark(1);
+            c = readCh();
+            reset();
+            if (c == 0x22 || c == 0x27) // " | '
+              {
+                String href = readLiteral(flags, false);
+                ids.systemId = absolutize(input.systemId, href);
+              }
+          }
+        else
+          {
+            requireWhitespace();
+            String href = readLiteral(flags, false);
+            ids.systemId = absolutize(input.systemId, href);
+          }
+        // Check valid URI characters
+        for (int i = 0; i < ids.publicId.length(); i++)
+          {
+            char d = ids.publicId.charAt(i);
+            if (d >= 'a' && d <= 'z')
+              continue;
+            if (d >= 'A' && d <= 'Z')
+              continue;
+            if (" \r\n0123456789-' ()+,./:=?;!*#@$_%".indexOf(d) != -1)
+              continue;
+            error("illegal PUBLIC id character",
+                  "U+" + Integer.toHexString(d));
+          }
+      }
+    else if (tryRead("SYSTEM"))
+      {
+        requireWhitespace();
+        String href = readLiteral(flags, false);
+        ids.systemId = absolutize(input.systemId, href);
+      }
+    else if (!isSubset)
+      {
+        error("missing SYSTEM or PUBLIC keyword");
+      }
+    if (ids.systemId != null && !inNotation)
+      {
+        if (ids.systemId.indexOf('#') != -1)
+          error("SYSTEM id has a URI fragment", ids.systemId);
+      }
+    return ids;
+  }
+
+  /**
+   * Parse the start of an element.
+   * @return the state of the parser afterwards (EMPTY_ELEMENT or CONTENT)
+   */
+  private int readStartElement()
+    throws IOException, XMLStreamException
+  {
+    // Read element name
+    String elementName = readNmtoken(true);
+    attrs.clear();
+    // Push namespace context
+    if (namespaceAware)
+      {
+        if (elementName.charAt(0) == ':' ||
+            elementName.charAt(elementName.length() - 1) == ':')
+          error("not a QName", elementName);
+        namespaces.addFirst(new LinkedHashMap());
+      }
+    // Read element content
+    boolean white = tryWhitespace();
+    mark(1);
+    int c = readCh();
+    while (c != 0x2f && c != 0x3e) // '/' | '>'
+      {
+        // Read attribute
+        reset();
+        if (!white)
+          error("need whitespace between attributes");
+        readAttribute(elementName);
+        white = tryWhitespace();
+        mark(1);
+        c = readCh();
+      }
+    // supply defaulted attributes
+    if (doctype != null)
+      {
+        for (Iterator i = doctype.attlistIterator(elementName); i.hasNext(); )
+          {
+            Map.Entry entry = (Map.Entry) i.next();
+            String attName = (String) entry.getKey();
+            AttributeDecl decl = (AttributeDecl) entry.getValue();
+            if (validating)
+              {
+                switch (decl.valueType)
+                  {
+                  case ATTRIBUTE_DEFAULT_REQUIRED:
+                    // VC: Required Attribute
+                    if (decl.value == null && !attributeSpecified(attName))
+                      error("value for " + attName + " attribute is required");
+                    break;
+                  case ATTRIBUTE_DEFAULT_FIXED:
+                    // VC: Fixed Attribute Default
+                    for (Iterator j = attrs.iterator(); j.hasNext(); )
+                      {
+                        Attribute a = (Attribute) j.next();
+                        if (attName.equals(a.name) &&
+                            !decl.value.equals(a.value))
+                          error("value for " + attName + " attribute must be " +
+                                decl.value);
+                      }
+                    break;
+                  }
+              }
+            if (namespaceAware && attName.equals("xmlns"))
+              {
+                LinkedHashMap ctx =
+                  (LinkedHashMap) namespaces.getFirst();
+                if (ctx.containsKey(XMLConstants.DEFAULT_NS_PREFIX))
+                  continue; // namespace was specified
+              }
+            else if (namespaceAware && attName.startsWith("xmlns:"))
+              {
+                LinkedHashMap ctx =
+                  (LinkedHashMap) namespaces.getFirst();
+                if (ctx.containsKey(attName.substring(6)))
+                  continue; // namespace was specified
+              }
+            else if (attributeSpecified(attName))
+              continue;
+            if (decl.value == null)
+              continue;
+            // VC: Standalone Document Declaration
+            if (validating && decl.external && xmlStandalone == Boolean.TRUE)
+              error("standalone must be 'no' if attributes inherit values " +
+                    "from externally declared markup declarations");
+            Attribute attr =
+              new Attribute(attName, decl.type, false, decl.value);
+            if (namespaceAware)
+              {
+                if (!addNamespace(attr))
+                  attrs.add(attr);
+              }
+            else
+              attrs.add(attr);
+          }
+      }
+    if (baseAware)
+      {
+        String uri = getAttributeValue(XMLConstants.XML_NS_URI, "base");
+        String base = getXMLBase();
+        bases.addFirst(absolutize(base, uri));
+      }
+    if (namespaceAware)
+      {
+        // check prefix bindings
+        int ci = elementName.indexOf(':');
+        if (ci != -1)
+          {
+            String prefix = elementName.substring(0, ci);
+            String uri = getNamespaceURI(prefix);
+            if (uri == null)
+              error("unbound element prefix", prefix);
+            else if (input.xml11 && "".equals(uri))
+              error("XML 1.1 unbound element prefix", prefix);
+          }
+        for (Iterator i = attrs.iterator(); i.hasNext(); )
+          {
+            Attribute attr = (Attribute) i.next();
+            if (attr.prefix != null &&
+                !XMLConstants.XMLNS_ATTRIBUTE.equals(attr.prefix))
+              {
+                String uri = getNamespaceURI(attr.prefix);
+                if (uri == null)
+                  error("unbound attribute prefix", attr.prefix);
+                else if (input.xml11 && "".equals(uri))
+                  error("XML 1.1 unbound attribute prefix", attr.prefix);
+              }
+          }
+      }
+    if (validating && doctype != null)
+      {
+        validateStartElement(elementName);
+        currentContentModel = doctype.getElementModel(elementName);
+        if (currentContentModel == null)
+          error("no element declaration", elementName);
+        validationStack.add(new LinkedList());
+      }
+    // make element name available for read
+    buf.setLength(0);
+    buf.append(elementName);
+    // push element onto stack
+    stack.addLast(elementName);
+    switch (c)
+      {
+      case 0x3e: // '>'
+        return CONTENT;
+      case 0x2f: // '/'
+        require('>');
+        return EMPTY_ELEMENT;
+      }
+    return -1; // to satisfy compiler
+  }
+
+  /**
+   * Indicates whether the specified attribute name was specified for the
+   * current element.
+   */
+  private boolean attributeSpecified(String attName)
+  {
+    for (Iterator j = attrs.iterator(); j.hasNext(); )
+      {
+        Attribute a = (Attribute) j.next();
+        if (attName.equals(a.name))
+          return true;
+      }
+    return false;
+  }
+
+  /**
+   * Parse an attribute.
+   */
+  private void readAttribute(String elementName)
+    throws IOException, XMLStreamException
+  {
+    // Read attribute name
+    String attributeName = readNmtoken(true);
+    String type = getAttributeType(elementName, attributeName);
+    readEq();
+    // Read literal
+    final int flags = LIT_ATTRIBUTE |  LIT_ENTITY_REF;
+    String value = (type == null || "CDATA".equals(type)) ?
+      readLiteral(flags, false) : readLiteral(flags | LIT_NORMALIZE, false);
+    // add attribute event
+    Attribute attr = this.new Attribute(attributeName, type, true, value);
+    if (namespaceAware)
+      {
+        if (attributeName.charAt(0) == ':' ||
+            attributeName.charAt(attributeName.length() - 1) == ':')
+          error("not a QName", attributeName);
+        else if (attributeName.equals("xmlns"))
+          {
+            LinkedHashMap ctx = (LinkedHashMap) namespaces.getFirst();
+            if (ctx.containsKey(XMLConstants.DEFAULT_NS_PREFIX))
+              error("duplicate default namespace");
+          }
+        else if (attributeName.startsWith("xmlns:"))
+          {
+            LinkedHashMap ctx = (LinkedHashMap) namespaces.getFirst();
+            if (ctx.containsKey(attributeName.substring(6)))
+              error("duplicate namespace", attributeName.substring(6));
+          }
+        else if (attrs.contains(attr))
+          error("duplicate attribute", attributeName);
+      }
+    else if (attrs.contains(attr))
+      error("duplicate attribute", attributeName);
+    if (validating && doctype != null)
+      {
+        // VC: Attribute Value Type
+        AttributeDecl decl =
+          doctype.getAttributeDecl(elementName, attributeName);
+        if (decl == null)
+          error("attribute must be declared", attributeName);
+        if ("ENUMERATION".equals(decl.type))
+          {
+            // VC: Enumeration
+            if (!decl.values.contains(value))
+              error("value does not match enumeration " + decl.enumeration,
+                    value);
+          }
+        else if ("ID".equals(decl.type))
+          {
+            // VC: ID
+            if (!isNmtoken(value, true))
+              error("ID values must match the Name production");
+            if (ids.contains(value))
+              error("Duplicate ID", value);
+            ids.add(value);
+          }
+        else if ("IDREF".equals(decl.type) || "IDREFS".equals(decl.type))
+          {
+            StringTokenizer st = new StringTokenizer(value);
+            while (st.hasMoreTokens())
+              {
+                String token = st.nextToken();
+                // VC: IDREF
+                if (!isNmtoken(token, true))
+                  error("IDREF values must match the Name production");
+                idrefs.add(token);
+              }
+          }
+        else if ("NMTOKEN".equals(decl.type) || "NMTOKENS".equals(decl.type))
+          {
+            StringTokenizer st = new StringTokenizer(value);
+            while (st.hasMoreTokens())
+              {
+                String token = st.nextToken();
+                // VC: Name Token
+                if (!isNmtoken(token, false))
+                  error("NMTOKEN values must match the Nmtoken production");
+              }
+          }
+        else if ("ENTITY".equals(decl.type))
+          {
+            // VC: Entity Name
+            if (!isNmtoken(value, true))
+              error("ENTITY values must match the Name production");
+            Object entity = doctype.getEntity(value);
+            if (entity == null || !(entity instanceof ExternalIds) ||
+                ((ExternalIds) entity).notationName == null)
+              error("ENTITY values must match the name of an unparsed " +
+                    "entity declared in the DTD");
+          }
+        else if ("NOTATION".equals(decl.type))
+          {
+            if (!decl.values.contains(value))
+              error("NOTATION values must match a declared notation name",
+                    value);
+            // VC: Notation Attributes
+            ExternalIds notation = doctype.getNotation(value);
+            if (notation == null)
+              error("NOTATION values must match the name of a notation " +
+                    "declared in the DTD", value);
+          }
+      }
+    if (namespaceAware)
+      {
+        if (!addNamespace(attr))
+          attrs.add(attr);
+      }
+    else
+      attrs.add(attr);
+  }
+
+  /**
+   * Determines whether the specified attribute is a namespace declaration,
+   * and adds it to the current namespace context if so. Returns false if
+   * the attribute is an ordinary attribute.
+   */
+  private boolean addNamespace(Attribute attr)
+    throws XMLStreamException
+  {
+    if ("xmlns".equals(attr.name))
+      {
+        LinkedHashMap ctx = (LinkedHashMap) namespaces.getFirst();
+        if (ctx.get(XMLConstants.DEFAULT_NS_PREFIX) != null)
+          error("Duplicate default namespace declaration");
+        if (XMLConstants.XML_NS_URI.equals(attr.value))
+          error("can't bind XML namespace");
+        ctx.put(XMLConstants.DEFAULT_NS_PREFIX, attr.value);
+        return true;
+      }
+    else if ("xmlns".equals(attr.prefix))
+      {
+        LinkedHashMap ctx = (LinkedHashMap) namespaces.getFirst();
+        if (ctx.get(attr.localName) != null)
+          error("Duplicate namespace declaration for prefix",
+                attr.localName);
+        if (XMLConstants.XML_NS_PREFIX.equals(attr.localName))
+          {
+            if (!XMLConstants.XML_NS_URI.equals(attr.value))
+              error("can't redeclare xml prefix");
+            else
+              return false; // treat as attribute
+          }
+        if (XMLConstants.XML_NS_URI.equals(attr.value))
+          error("can't bind non-xml prefix to XML namespace");
+        if (XMLConstants.XMLNS_ATTRIBUTE.equals(attr.localName))
+          error("can't redeclare xmlns prefix");
+        if (XMLConstants.XMLNS_ATTRIBUTE_NS_URI.equals(attr.value))
+          error("can't bind non-xmlns prefix to XML Namespace namespace");
+        if ("".equals(attr.value) && !input.xml11)
+          error("illegal use of 1.1-style prefix unbinding in 1.0 document");
+        ctx.put(attr.localName, attr.value);
+        return true;
+      }
+    return false;
+  }
+
+  /**
+   * Parse a closing tag.
+   */
+  private void readEndElement()
+    throws IOException, XMLStreamException
+  {
+    // pop element off stack
+    String expected = (String) stack.removeLast();
+    require(expected);
+    skipWhitespace();
+    require('>');
+    // Make element name available
+    buf.setLength(0);
+    buf.append(expected);
+    if (validating && doctype != null)
+      endElementValidationHook();
+  }
+
+  /**
+   * Validate the end of an element.
+   * Called on an end-element or empty element if validating.
+   */
+  private void endElementValidationHook()
+    throws XMLStreamException
+  {
+    validateEndElement();
+    validationStack.removeLast();
+    if (stack.isEmpty())
+      currentContentModel = null;
+    else
+      {
+        String parent = (String) stack.getLast();
+        currentContentModel = doctype.getElementModel(parent);
+      }
+  }
+
+  /**
+   * Parse a comment.
+   */
+  private void readComment(boolean inDTD)
+    throws IOException, XMLStreamException
+  {
+    boolean saved = expandPE;
+    expandPE = false;
+    buf.setLength(0);
+    readUntil(TEST_END_COMMENT);
+    require('>');
+    expandPE = saved;
+    if (inDTD)
+      doctype.addComment(buf.toString());
+  }
+
+  /**
+   * Parse a processing instruction.
+   */
+  private void readPI(boolean inDTD)
+    throws IOException, XMLStreamException
+  {
+    boolean saved = expandPE;
+    expandPE = false;
+    piTarget = readNmtoken(true);
+    if (piTarget.indexOf(':') != -1)
+      error("illegal character in PI target", new Character(':'));
+    if ("xml".equalsIgnoreCase(piTarget))
+      error("illegal PI target", piTarget);
+    if (tryRead(TEST_END_PI))
+      piData = null;
+    else
+      {
+        if (!tryWhitespace())
+          error("whitespace required between PI target and data");
+        buf.setLength(0);
+        readUntil(TEST_END_PI);
+        piData = buf.toString();
+      }
+    expandPE = saved;
+    if (inDTD)
+      doctype.addPI(piTarget, piData);
+  }
+
+  /**
+   * Parse an entity reference.
+   */
+  private void readReference()
+    throws IOException, XMLStreamException
+  {
+    buf.setLength(0);
+    String entityName = readNmtoken(true);
+    require(';');
+    buf.setLength(0);
+    buf.append(entityName);
+  }
+
+  /**
+   * Read an CDATA section.
+   */
+  private void readCDSect()
+    throws IOException, XMLStreamException
+  {
+    buf.setLength(0);
+    readUntil(TEST_END_CDATA);
+  }
+
+  /**
+   * Read character data.
+   * @return the type of text read (CHARACTERS or SPACE)
+   */
+  private int readCharData(String prefix)
+    throws IOException, XMLStreamException
+  {
+    boolean white = true;
+    buf.setLength(0);
+    if (prefix != null)
+      buf.append(prefix);
+    boolean done = false;
+    boolean entities = false;
+    while (!done)
+      {
+        // Block read
+        mark(tmpBuf.length);
+        int len = read(tmpBuf, 0, tmpBuf.length);
+        if (len == -1)
+          {
+            if (inputStack.size() > 1)
+              {
+                popInput();
+                // report end-entity
+                done = true;
+              }
+            else
+              throw new EOFException();
+          }
+        for (int i = 0; i < len && !done; i++)
+          {
+            int c = tmpBuf[i];
+            switch (c)
+              {
+              case 0x20:
+              case 0x09:
+              case 0x0a:
+              case 0x0d:
+                buf.append(Character.toChars(c));
+                break; // whitespace
+              case 0x26: // '&'
+                reset();
+                read(tmpBuf, 0, i);
+                // character reference?
+                mark(3);
+                c = readCh(); // &
+                c = readCh();
+                if (c == 0x23) // '#'
+                  {
+                    mark(1);
+                    c = readCh();
+                    boolean hex = (c == 0x78); // 'x'
+                    if (!hex)
+                      reset();
+                    char[] ch = readCharacterRef(hex ? 16 : 10);
+                    buf.append(ch, 0, ch.length);
+                    for (int j = 0; j < ch.length; j++)
+                      {
+                        switch (ch[j])
+                          {
+                          case 0x20:
+                          case 0x09:
+                          case 0x0a:
+                          case 0x0d:
+                            break; // whitespace
+                          default:
+                            white = false;
+                          }
+                      }
+                  }
+                else
+                  {
+                    // entity reference
+                    reset();
+                    c = readCh(); // &
+                    String entityName = readNmtoken(true);
+                    require(';');
+                    String text =
+                      (String) PREDEFINED_ENTITIES.get(entityName);
+                    if (text != null)
+                      buf.append(text);
+                    else
+                      {
+                        pushInput("", "&" + entityName + ";", false, false);
+                        done = true;
+                        break;
+                      }
+                  }
+                // continue processing
+                i = -1;
+                mark(tmpBuf.length);
+                len = read(tmpBuf, 0, tmpBuf.length);
+                if (len == -1)
+                  {
+                    if (inputStack.size() > 1)
+                      {
+                        popInput();
+                        done = true;
+                      }
+                    else
+                      throw new EOFException();
+                  }
+                entities = true;
+                break; // end of text sequence
+              case 0x3e: // '>'
+                int l = buf.length();
+                if (l > 1 &&
+                    buf.charAt(l - 1) == ']' &&
+                    buf.charAt(l - 2) == ']')
+                  error("Character data may not contain unescaped ']]>'");
+                buf.append(Character.toChars(c));
+                break;
+              case 0x3c: // '<'
+                reset();
+                // read i characters
+                int count = 0, remaining = i;
+                do
+                  {
+                    int r = read(tmpBuf, 0, remaining);
+                    count += r;
+                    remaining -= r;
+                  }
+                while (count < i);
+                i = len;
+                if (coalescing && tryRead(TEST_CDATA))
+                  readUntil(TEST_END_CDATA); // read CDATA section into buf
+                else
+                  done = true; // end of text sequence
+                break;
+              default:
+                if (input.xml11)
+                  {
+                    if (!isXML11Char(c) || isXML11RestrictedChar(c))
+                      error("illegal XML 1.1 character",
+                            "U+" + Integer.toHexString(c));
+                  }
+                else if (!isChar(c))
+                  error("illegal XML character",
+                        "U+" + Integer.toHexString(c));
+                white = false;
+                buf.append(Character.toChars(c));
+              }
+          }
+        // if text buffer >= 2MB, return it as a chunk
+        // to avoid excessive memory use
+        if (buf.length() >= 2097152)
+          done = true;
+      }
+    if (entities)
+      normalizeCRLF(buf);
+    return white ? XMLStreamConstants.SPACE : XMLStreamConstants.CHARACTERS;
+  }
+
+  /**
+   * Expands the specified entity.
+   */
+  private void expandEntity(String name, boolean inAttr, boolean normalize)
+    throws IOException, XMLStreamException
+  {
+    if (doctype != null)
+      {
+        Object value = doctype.getEntity(name);
+        if (value != null)
+          {
+            if (xmlStandalone == Boolean.TRUE)
+              {
+                // VC: Standalone Document Declaration
+                if (doctype.isEntityExternal(name))
+                  error("reference to external entity in standalone document");
+                else if (value instanceof ExternalIds)
+                  {
+                    ExternalIds ids = (ExternalIds) value;
+                    if (ids.notationName != null &&
+                        doctype.isNotationExternal(ids.notationName))
+                      error("reference to external notation in " +
+                            "standalone document");
+                  }
+              }
+            if (value instanceof String)
+              {
+                String text = (String) value;
+                if (inAttr && text.indexOf('<') != -1)
+                  error("< in attribute value");
+                pushInput(name, text, !inAttr, normalize);
+              }
+            else if (inAttr)
+              error("reference to external entity in attribute value", name);
+            else
+              pushInput(name, (ExternalIds) value, !inAttr, normalize);
+            return;
+          }
+      }
+    error("reference to undeclared entity", name);
+  }
+
+  /**
+   * Indicates whether the specified entity is unparsed.
+   */
+  private boolean isUnparsedEntity(String name)
+  {
+    if (doctype != null)
+      {
+        Object value = doctype.getEntity(name);
+        if (value != null && value instanceof ExternalIds)
+          return ((ExternalIds) value).notationName != null;
+      }
+    return false;
+  }
+
+  /**
+   * Read an equals sign.
+   */
+  private void readEq()
+    throws IOException, XMLStreamException
+  { 
+    skipWhitespace();
+    require('=');
+    skipWhitespace();
+  }
+
+  /**
+   * Character read for reading literals.
+   * @param recognizePEs whether to recognize parameter-entity references
+   */
+  private int literalReadCh(boolean recognizePEs)
+    throws IOException, XMLStreamException
+  {
+    int c = recognizePEs ? readCh() : read();
+    while (c == -1)
+      {
+        if (inputStack.size() > 1)
+          {
+            inputStack.removeLast();
+            input = (Input) inputStack.getLast();
+            // Don't issue end-entity
+            c = recognizePEs ? readCh() : read();
+          }
+        else
+          throw new EOFException();
+      }
+    return c;
+  }
+
+  /**
+   * Read a string literal.
+   */
+  private String readLiteral(int flags, boolean recognizePEs)
+    throws IOException, XMLStreamException
+  {
+    boolean saved = expandPE;
+    int delim = readCh();
+    if (delim != 0x27 && delim != 0x22)
+      error("expected '\"' or \"'\"", "U+" + Integer.toHexString(delim));
+    literalBuf.setLength(0);
+    if ((flags & LIT_DISABLE_PE) != 0)
+      expandPE = false;
+    boolean entities = false;
+    int inputStackSize = inputStack.size();
+    do
+      {
+        int c = literalReadCh(recognizePEs);
+        if (c == delim && inputStackSize == inputStack.size())
+          break;
+        switch (c)
+          {
+          case 0x0a:
+          case 0x0d:
+            if ((flags & (LIT_ATTRIBUTE | LIT_PUBID)) != 0)
+              c = 0x20; // normalize to space
+            break;
+          case 0x09:
+            if ((flags & LIT_ATTRIBUTE) != 0)
+              c = 0x20; // normalize to space
+            break;
+          case 0x26: // '&'
+            mark(2);
+            c = readCh();
+            if (c == 0x23) // '#'
+              {
+                if ((flags & LIT_DISABLE_CREF) != 0)
+                  {
+                    reset();
+                    c = 0x26; // '&'
+                  }
+                else
+                  {
+                    mark(1);
+                    c = readCh();
+                    boolean hex = (c == 0x78); // 'x'
+                    if (!hex)
+                      reset();
+                    char[] ref = readCharacterRef(hex ? 16 : 10);
+                    for (int i = 0; i < ref.length; i++)
+                      literalBuf.append(ref[i]);
+                    entities = true;
+                    continue;
+                  }
+              }
+            else
+              {
+                if ((flags & LIT_DISABLE_EREF) != 0)
+                  {
+                    reset();
+                    c = 0x26; // '&'
+                  }
+                else
+                  {
+                    reset();
+                    String entityName = readNmtoken(true);
+                    require(';');
+                    String text =
+                      (String) PREDEFINED_ENTITIES.get(entityName);
+                    if (text != null)
+                      literalBuf.append(text);
+                    else
+                      expandEntity(entityName,
+                                   (flags & LIT_ATTRIBUTE) != 0,
+                                   true);
+                    entities = true;
+                    continue;
+                  }
+              }
+            break;
+          case 0x3c: // '<'
+            if ((flags & LIT_ATTRIBUTE) != 0)
+              error("attribute values may not contain '<'");
+            break;
+          case -1:
+            if (inputStack.size() > 1)
+              {
+                popInput();
+                continue;
+              }
+            throw new EOFException();
+          default:
+            if ((c < 0x0020 || c > 0xfffd) ||
+                (c >= 0xd800 && c < 0xdc00) ||
+                (input.xml11 && (c >= 0x007f) &&
+                 (c <= 0x009f) && (c != 0x0085)))
+              error("illegal character", "U+" + Integer.toHexString(c));
+          }
+        literalBuf.append(Character.toChars(c));
+      }
+    while (true);
+    expandPE = saved;
+    if (entities)
+      normalizeCRLF(literalBuf);
+    if ((flags & LIT_NORMALIZE) > 0)
+      literalBuf = normalize(literalBuf);
+    return literalBuf.toString();
+  }
+
+  /**
+   * Performs attribute-value normalization of the text buffer.
+   * This discards leading and trailing whitespace, and replaces sequences
+   * of whitespace with a single space.
+   */
+  private StringBuffer normalize(StringBuffer buf)
+  {
+    StringBuffer acc = new StringBuffer();
+    int len = buf.length();
+    int avState = 0;
+    for (int i = 0; i < len; i++)
+      {
+        char c = buf.charAt(i);
+        if (c == ' ')
+          avState = (avState == 0) ? 0 : 1;
+        else
+          {
+            if (avState == 1)
+              acc.append(' ');
+            acc.append(c);
+            avState = 2;
+          }
+      }
+    return acc;
+  }
+
+  /**
+   * Replace any CR/LF pairs in the buffer with LF.
+   * This may be necessary if combinations of CR or LF were declared as
+   * (character) entity references in the input.
+   */
+  private void normalizeCRLF(StringBuffer buf)
+  {
+    int len = buf.length() - 1;
+    for (int i = 0; i < len; i++)
+      {
+        char c = buf.charAt(i);
+        if (c == '\r' && buf.charAt(i + 1) == '\n')
+          {
+            buf.deleteCharAt(i--);
+            len--;
+          }
+      }
+  }
+
+  /**
+   * Parse and expand a parameter entity reference.
+   */
+  private void expandPEReference()
+    throws IOException, XMLStreamException
+  {
+    String name = readNmtoken(true, new StringBuffer());
+    require(';');
+    mark(1); // ensure we don't reset to before the semicolon
+    if (doctype != null)
+      {
+        String entityName = "%" + name;
+        Object entity = doctype.getEntity(entityName);
+        if (entity != null)
+          {
+            if (xmlStandalone == Boolean.TRUE)
+              {
+                if (doctype.isEntityExternal(entityName))
+                  error("reference to external parameter entity in " +
+                        "standalone document");
+              }
+            if (entity instanceof String)
+              {
+                pushInput(name, (String) entity, false, input.normalize);
+                //pushInput(name, " " + (String) entity + " ");
+              }
+            else
+              {
+                //pushInput("", " ");
+                pushInput(name, (ExternalIds) entity, false, input.normalize);
+                //pushInput("", " ");
+              }
+          }
+        else
+          error("reference to undeclared parameter entity", name);
+      }
+    else
+      error("reference to parameter entity without doctype", name);
+  }
+
+  /**
+   * Parse the digits in a character reference.
+   * @param base the base of the digits (10 or 16)
+   */
+  private char[] readCharacterRef(int base)
+    throws IOException, XMLStreamException
+  {
+    StringBuffer b = new StringBuffer();
+    for (int c = readCh(); c != 0x3b && c != -1; c = readCh())
+      b.append(Character.toChars(c));
+    try
+      {
+        int ord = Integer.parseInt(b.toString(), base);
+        if (input.xml11)
+          {
+            if (!isXML11Char(ord))
+              error("illegal XML 1.1 character reference " +
+                    "U+" + Integer.toHexString(ord));
+          }
+        else
+          {
+            if ((ord < 0x20 && !(ord == 0x0a || ord == 0x09 || ord == 0x0d))
+                || (ord >= 0xd800 && ord <= 0xdfff)
+                || ord == 0xfffe || ord == 0xffff
+                || ord > 0x0010ffff)
+              error("illegal XML character reference " +
+                    "U+" + Integer.toHexString(ord));
+          }
+        return Character.toChars(ord);
+      }
+    catch (NumberFormatException e)
+      {
+        error("illegal characters in character reference", b.toString());
+        return null;
+      }
+  }
+
+  /**
+   * Parses an NMTOKEN or Name production.
+   * @param isName if a Name, otherwise an NMTOKEN
+   */
+  private String readNmtoken(boolean isName)
+    throws IOException, XMLStreamException
+  {
+    return readNmtoken(isName, nmtokenBuf);
+  }
+  
+  /**
+   * Parses an NMTOKEN or Name production using the specified buffer.
+   * @param isName if a Name, otherwise an NMTOKEN
+   * @param buf the character buffer to use
+   */
+  private String readNmtoken(boolean isName, StringBuffer buf)
+    throws IOException, XMLStreamException
+  {
+    buf.setLength(0);
+    int c = readCh();
+    if (isName)
+      {
+        if (!isNameStartCharacter(c, input.xml11))
+          error("not a name start character",
+                "U+" + Integer.toHexString(c));
+      }
+    else
+      {
+        if (!isNameCharacter(c, input.xml11))
+          error("not a name character",
+                "U+" + Integer.toHexString(c));
+      }
+    buf.append(Character.toChars(c));
+    do
+      {
+        mark(1);
+        c = readCh();
+        switch (c)
+          {
+          case 0x25: // '%'
+          case 0x3c: // '<'
+          case 0x3e: // '>'
+          case 0x26: // '&'
+          case 0x2c: // ','
+          case 0x7c: // '|'
+          case 0x2a: // '*'
+          case 0x2b: // '+'
+          case 0x3f: // '?'
+          case 0x29: // ')'
+          case 0x3d: // '='
+          case 0x27: // '\''
+          case 0x22: // '"'
+          case 0x5b: // '['
+          case 0x20: // ' '
+          case 0x09: // '\t'
+          case 0x0a: // '\n'
+          case 0x0d: // '\r'
+          case 0x3b: // ';'
+          case 0x2f: // '/'
+          case -1:
+            reset();
+            return intern(buf.toString());
+          default:
+            if (!isNameCharacter(c, input.xml11))
+              error("not a name character",
+                    "U+" + Integer.toHexString(c));
+            else
+              buf.append(Character.toChars(c));
+          }
+      }
+    while (true);
+  }
+
+  /**
+   * Indicates whether the specified Unicode character is an XML 1.1 Char.
+   */
+  public static boolean isXML11Char(int c)
+  {
+    return ((c >= 0x0001 && c <= 0xD7FF) ||
+            (c >= 0xE000 && c < 0xFFFE) ||
+            (c >= 0x10000 && c <= 0x10FFFF));
+  }
+
+  /**
+   * Indicates whether the specified Unicode character is an XML 1.1
+   * RestrictedChar.
+   */
+  public static boolean isXML11RestrictedChar(int c)
+  {
+    return ((c >= 0x0001 && c <= 0x0008) ||
+            (c >= 0x000B && c <= 0x000C) ||
+            (c >= 0x000E && c <= 0x001F) ||
+            (c >= 0x007F && c <= 0x0084) ||
+            (c >= 0x0086 && c <= 0x009F));
+  }
+
+  /**
+   * Indicates whether the specified text matches the Name or Nmtoken
+   * production.
+   */
+  private boolean isNmtoken(String text, boolean isName)
+  {
+    try
+      {
+        int[] cp = UnicodeReader.toCodePointArray(text);
+        if (cp.length == 0)
+          return false;
+        if (isName)
+          {
+            if (!isNameStartCharacter(cp[0], input.xml11))
+              return false;
+          }
+        else
+          {
+            if (!isNameCharacter(cp[0], input.xml11))
+              return false;
+          }
+        for (int i = 1; i < cp.length; i++)
+          {
+            if (!isNameCharacter(cp[i], input.xml11))
+              return false;
+          }
+        return true;
+      }
+    catch (IOException e)
+      {
+        return false;
+      }
+  }
+
+  /**
+   * Indicates whether the specified Unicode character is a Name start
+   * character.
+   */
+  public static boolean isNameStartCharacter(int c, boolean xml11)
+  {
+    if (xml11)
+      return ((c >= 0x0041 && c <= 0x005a) ||
+              (c >= 0x0061 && c <= 0x007a) ||
+              c == 0x3a |
+              c == 0x5f |
+              (c >= 0xC0 && c <= 0xD6) ||
+              (c >= 0xD8 && c <= 0xF6) ||
+              (c >= 0xF8 && c <= 0x2FF) ||
+              (c >= 0x370 && c <= 0x37D) ||
+              (c >= 0x37F && c <= 0x1FFF) ||
+              (c >= 0x200C && c <= 0x200D) ||
+              (c >= 0x2070 && c <= 0x218F) ||
+              (c >= 0x2C00 && c <= 0x2FEF) ||
+              (c >= 0x3001 && c <= 0xD7FF) ||
+              (c >= 0xF900 && c <= 0xFDCF) ||
+              (c >= 0xFDF0 && c <= 0xFFFD) ||
+              (c >= 0x10000 && c <= 0xEFFFF));
+    else
+      return (c == 0x5f || c == 0x3a || isLetter(c));
+  }
+
+  /**
+   * Indicates whether the specified Unicode character is a Name non-initial
+   * character.
+   */
+  public static boolean isNameCharacter(int c, boolean xml11)
+  {
+    if (xml11)
+      return ((c >= 0x0041 && c <= 0x005a) ||
+              (c >= 0x0061 && c <= 0x007a) ||
+              (c >= 0x0030 && c <= 0x0039) ||
+              c == 0x3a |
+              c == 0x5f |
+              c == 0x2d |
+              c == 0x2e |
+              c == 0xB7 |
+              (c >= 0xC0 && c <= 0xD6) ||
+              (c >= 0xD8 && c <= 0xF6) ||
+              (c >= 0xF8 && c <= 0x2FF) ||
+              (c >= 0x300 && c <= 0x37D) ||
+              (c >= 0x37F && c <= 0x1FFF) ||
+              (c >= 0x200C && c <= 0x200D) ||
+              (c >= 0x203F && c <= 0x2040) ||
+              (c >= 0x2070 && c <= 0x218F) ||
+              (c >= 0x2C00 && c <= 0x2FEF) ||
+              (c >= 0x3001 && c <= 0xD7FF) ||
+              (c >= 0xF900 && c <= 0xFDCF) ||
+              (c >= 0xFDF0 && c <= 0xFFFD) ||
+              (c >= 0x10000 && c <= 0xEFFFF));
+    else
+      return (c == 0x2e || c == 0x2d || c == 0x5f || c == 0x3a ||
+              isLetter(c) || isDigit(c) ||
+              isCombiningChar(c) || isExtender(c));
+  }
+
+  /**
+   * Indicates whether the specified Unicode character matches the Letter
+   * production.
+   */
+  public static boolean isLetter(int c)
+  {
+    if ((c >= 0x0041 && c <= 0x005A) ||
+        (c >= 0x0061 && c <= 0x007A) ||
+        (c >= 0x00C0 && c <= 0x00D6) ||
+        (c >= 0x00D8 && c <= 0x00F6) ||
+        (c >= 0x00F8 && c <= 0x00FF) ||
+        (c >= 0x0100 && c <= 0x0131) ||
+        (c >= 0x0134 && c <= 0x013E) ||
+        (c >= 0x0141 && c <= 0x0148) ||
+        (c >= 0x014A && c <= 0x017E) ||
+        (c >= 0x0180 && c <= 0x01C3) ||
+        (c >= 0x01CD && c <= 0x01F0) ||
+        (c >= 0x01F4 && c <= 0x01F5) ||
+        (c >= 0x01FA && c <= 0x0217) ||
+        (c >= 0x0250 && c <= 0x02A8) ||
+        (c >= 0x02BB && c <= 0x02C1) ||
+        c == 0x0386 ||
+        (c >= 0x0388 && c <= 0x038A) ||
+        c == 0x038C ||
+        (c >= 0x038E && c <= 0x03A1) ||
+        (c >= 0x03A3 && c <= 0x03CE) ||
+        (c >= 0x03D0 && c <= 0x03D6) ||
+        c == 0x03DA ||
+      c == 0x03DC ||
+        c == 0x03DE ||
+        c == 0x03E0 ||
+        (c >= 0x03E2 && c <= 0x03F3) ||
+        (c >= 0x0401 && c <= 0x040C) ||
+        (c >= 0x040E && c <= 0x044F) ||
+        (c >= 0x0451 && c <= 0x045C) ||
+        (c >= 0x045E && c <= 0x0481) ||
+        (c >= 0x0490 && c <= 0x04C4) ||
+        (c >= 0x04C7 && c <= 0x04C8) ||
+        (c >= 0x04CB && c <= 0x04CC) ||
+        (c >= 0x04D0 && c <= 0x04EB) ||
+        (c >= 0x04EE && c <= 0x04F5) ||
+        (c >= 0x04F8 && c <= 0x04F9) ||
+        (c >= 0x0531 && c <= 0x0556) ||
+        c == 0x0559 ||
+        (c >= 0x0561 && c <= 0x0586) ||
+        (c >= 0x05D0 && c <= 0x05EA) ||
+        (c >= 0x05F0 && c <= 0x05F2) ||
+        (c >= 0x0621 && c <= 0x063A) ||
+        (c >= 0x0641 && c <= 0x064A) ||
+        (c >= 0x0671 && c <= 0x06B7) ||
+        (c >= 0x06BA && c <= 0x06BE) ||
+        (c >= 0x06C0 && c <= 0x06CE) ||
+        (c >= 0x06D0 && c <= 0x06D3) ||
+        c == 0x06D5 ||
+        (c >= 0x06E5 && c <= 0x06E6) ||
+        (c >= 0x0905 && c <= 0x0939) ||
+        c == 0x093D ||
+        (c >= 0x0958 && c <= 0x0961) ||
+        (c >= 0x0985 && c <= 0x098C) ||
+        (c >= 0x098F && c <= 0x0990) ||
+        (c >= 0x0993 && c <= 0x09A8) ||
+        (c >= 0x09AA && c <= 0x09B0) ||
+        c == 0x09B2 ||
+        (c >= 0x09B6 && c <= 0x09B9) ||
+        (c >= 0x09DC && c <= 0x09DD) ||
+        (c >= 0x09DF && c <= 0x09E1) ||
+        (c >= 0x09F0 && c <= 0x09F1) ||
+        (c >= 0x0A05 && c <= 0x0A0A) ||
+        (c >= 0x0A0F && c <= 0x0A10) ||
+        (c >= 0x0A13 && c <= 0x0A28) ||
+        (c >= 0x0A2A && c <= 0x0A30) ||
+        (c >= 0x0A32 && c <= 0x0A33) ||
+        (c >= 0x0A35 && c <= 0x0A36) ||
+        (c >= 0x0A38 && c <= 0x0A39) ||
+        (c >= 0x0A59 && c <= 0x0A5C) ||
+        c == 0x0A5E ||
+        (c >= 0x0A72 && c <= 0x0A74) ||
+        (c >= 0x0A85 && c <= 0x0A8B) ||
+        c == 0x0A8D ||
+        (c >= 0x0A8F && c <= 0x0A91) ||
+        (c >= 0x0A93 && c <= 0x0AA8) ||
+        (c >= 0x0AAA && c <= 0x0AB0) ||
+        (c >= 0x0AB2 && c <= 0x0AB3) ||
+        (c >= 0x0AB5 && c <= 0x0AB9) ||
+        c == 0x0ABD ||
+        c == 0x0AE0 ||
+        (c >= 0x0B05 && c <= 0x0B0C) ||
+        (c >= 0x0B0F && c <= 0x0B10) ||
+        (c >= 0x0B13 && c <= 0x0B28) ||
+        (c >= 0x0B2A && c <= 0x0B30) ||
+        (c >= 0x0B32 && c <= 0x0B33) ||
+        (c >= 0x0B36 && c <= 0x0B39) ||
+        c == 0x0B3D ||
+        (c >= 0x0B5C && c <= 0x0B5D) ||
+        (c >= 0x0B5F && c <= 0x0B61) ||
+        (c >= 0x0B85 && c <= 0x0B8A) ||
+        (c >= 0x0B8E && c <= 0x0B90) ||
+        (c >= 0x0B92 && c <= 0x0B95) ||
+        (c >= 0x0B99 && c <= 0x0B9A) ||
+        c == 0x0B9C ||
+        (c >= 0x0B9E && c <= 0x0B9F) ||
+        (c >= 0x0BA3 && c <= 0x0BA4) ||
+        (c >= 0x0BA8 && c <= 0x0BAA) ||
+        (c >= 0x0BAE && c <= 0x0BB5) ||
+        (c >= 0x0BB7 && c <= 0x0BB9) ||
+        (c >= 0x0C05 && c <= 0x0C0C) ||
+        (c >= 0x0C0E && c <= 0x0C10) ||
+        (c >= 0x0C12 && c <= 0x0C28) ||
+        (c >= 0x0C2A && c <= 0x0C33) ||
+        (c >= 0x0C35 && c <= 0x0C39) ||
+        (c >= 0x0C60 && c <= 0x0C61) ||
+        (c >= 0x0C85 && c <= 0x0C8C) ||
+        (c >= 0x0C8E && c <= 0x0C90) ||
+        (c >= 0x0C92 && c <= 0x0CA8) ||
+        (c >= 0x0CAA && c <= 0x0CB3) ||
+        (c >= 0x0CB5 && c <= 0x0CB9) ||
+        c == 0x0CDE ||
+        (c >= 0x0CE0 && c <= 0x0CE1) ||
+        (c >= 0x0D05 && c <= 0x0D0C) ||
+        (c >= 0x0D0E && c <= 0x0D10) ||
+        (c >= 0x0D12 && c <= 0x0D28) ||
+        (c >= 0x0D2A && c <= 0x0D39) ||
+        (c >= 0x0D60 && c <= 0x0D61) ||
+        (c >= 0x0E01 && c <= 0x0E2E) ||
+        c == 0x0E30 ||
+        (c >= 0x0E32 && c <= 0x0E33) ||
+        (c >= 0x0E40 && c <= 0x0E45) ||
+        (c >= 0x0E81 && c <= 0x0E82) ||
+        c == 0x0E84 ||
+        (c >= 0x0E87 && c <= 0x0E88) ||
+        c == 0x0E8A ||
+        c == 0x0E8D ||
+        (c >= 0x0E94 && c <= 0x0E97) ||
+        (c >= 0x0E99 && c <= 0x0E9F) ||
+        (c >= 0x0EA1 && c <= 0x0EA3) ||
+        c == 0x0EA5 ||
+        c == 0x0EA7 ||
+        (c >= 0x0EAA && c <= 0x0EAB) ||
+        (c >= 0x0EAD && c <= 0x0EAE) ||
+        c == 0x0EB0 ||
+        (c >= 0x0EB2 && c <= 0x0EB3) ||
+        c == 0x0EBD ||
+        (c >= 0x0EC0 && c <= 0x0EC4) ||
+        (c >= 0x0F40 && c <= 0x0F47) ||
+        (c >= 0x0F49 && c <= 0x0F69) ||
+        (c >= 0x10A0 && c <= 0x10C5) ||
+        (c >= 0x10D0 && c <= 0x10F6) ||
+        c == 0x1100 ||
+        (c >= 0x1102 && c <= 0x1103) ||
+        (c >= 0x1105 && c <= 0x1107) ||
+        c == 0x1109 ||
+        (c >= 0x110B && c <= 0x110C) ||
+        (c >= 0x110E && c <= 0x1112) ||
+        c == 0x113C ||
+        c == 0x113E ||
+        c == 0x1140 ||
+        c == 0x114C ||
+        c == 0x114E ||
+        c == 0x1150 ||
+        (c >= 0x1154 && c <= 0x1155) ||
+        c == 0x1159 ||
+        (c >= 0x115F && c <= 0x1161) ||
+        c == 0x1163 ||
+        c == 0x1165 ||
+        c == 0x1167 ||
+        c == 0x1169 ||
+        (c >= 0x116D && c <= 0x116E) ||
+        (c >= 0x1172 && c <= 0x1173) ||
+        c == 0x1175 ||
+        c == 0x119E ||
+        c == 0x11A8 ||
+        c == 0x11AB ||
+        (c >= 0x11AE && c <= 0x11AF) ||
+        (c >= 0x11B7 && c <= 0x11B8) ||
+        c == 0x11BA ||
+        (c >= 0x11BC && c <= 0x11C2) ||
+        c == 0x11EB ||
+        c == 0x11F0 ||
+        c == 0x11F9 ||
+        (c >= 0x1E00 && c <= 0x1E9B) ||
+        (c >= 0x1EA0 && c <= 0x1EF9) ||
+        (c >= 0x1F00 && c <= 0x1F15) ||
+        (c >= 0x1F18 && c <= 0x1F1D) ||
+        (c >= 0x1F20 && c <= 0x1F45) ||
+        (c >= 0x1F48 && c <= 0x1F4D) ||
+        (c >= 0x1F50 && c <= 0x1F57) ||
+        c == 0x1F59 ||
+        c == 0x1F5B ||
+        c == 0x1F5D ||
+        (c >= 0x1F5F && c <= 0x1F7D) ||
+        (c >= 0x1F80 && c <= 0x1FB4) ||
+        (c >= 0x1FB6 && c <= 0x1FBC) ||
+        c == 0x1FBE ||
+        (c >= 0x1FC2 && c <= 0x1FC4) ||
+        (c >= 0x1FC6 && c <= 0x1FCC) ||
+        (c >= 0x1FD0 && c <= 0x1FD3) ||
+        (c >= 0x1FD6 && c <= 0x1FDB) ||
+        (c >= 0x1FE0 && c <= 0x1FEC) ||
+        (c >= 0x1FF2 && c <= 0x1FF4) ||
+        (c >= 0x1FF6 && c <= 0x1FFC) ||
+        c == 0x2126 ||
+        (c >= 0x212A && c <= 0x212B) ||
+        c == 0x212E ||
+        (c >= 0x2180 && c <= 0x2182) ||
+        (c >= 0x3041 && c <= 0x3094) ||
+        (c >= 0x30A1 && c <= 0x30FA) ||
+        (c >= 0x3105 && c <= 0x312C) ||
+        (c >= 0xAC00 && c <= 0xD7A3))
+        return true; // BaseChar
+    if ((c >= 0x4e00 && c <= 0x9fa5) ||
+        c == 0x3007 ||
+        (c >= 0x3021 && c <= 0x3029))
+      return true; // Ideographic
+    return false;
+  }
+
+  /**
+   * Indicates whether the specified Unicode character matches the Digit
+   * production.
+   */
+  public static boolean isDigit(int c)
+  {
+    return ((c >= 0x0030 && c <= 0x0039) ||
+            (c >= 0x0660 && c <= 0x0669) ||
+            (c >= 0x06F0 && c <= 0x06F9) ||
+            (c >= 0x0966 && c <= 0x096F) ||
+            (c >= 0x09E6 && c <= 0x09EF) ||
+            (c >= 0x0A66 && c <= 0x0A6F) ||
+            (c >= 0x0AE6 && c <= 0x0AEF) ||
+            (c >= 0x0B66 && c <= 0x0B6F) ||
+            (c >= 0x0BE7 && c <= 0x0BEF) ||
+            (c >= 0x0C66 && c <= 0x0C6F) ||
+            (c >= 0x0CE6 && c <= 0x0CEF) ||
+            (c >= 0x0D66 && c <= 0x0D6F) ||
+            (c >= 0x0E50 && c <= 0x0E59) ||
+            (c >= 0x0ED0 && c <= 0x0ED9) ||
+            (c >= 0x0F20 && c <= 0x0F29));
+  }
+
+  /**
+   * Indicates whether the specified Unicode character matches the
+   * CombiningChar production.
+   */
+  public static boolean isCombiningChar(int c)
+  {
+    return ((c >= 0x0300 && c <= 0x0345) ||
+            (c >= 0x0360 && c <= 0x0361) ||
+            (c >= 0x0483 && c <= 0x0486) ||
+            (c >= 0x0591 && c <= 0x05A1) ||
+            (c >= 0x05A3 && c <= 0x05B9) ||
+            (c >= 0x05BB && c <= 0x05BD) ||
+            c == 0x05BF ||
+            (c >= 0x05C1 && c <= 0x05C2) ||
+            c == 0x05C4 ||
+            (c >= 0x064B && c <= 0x0652) ||
+            c == 0x0670 ||
+            (c >= 0x06D6 && c <= 0x06DC) ||
+            (c >= 0x06DD && c <= 0x06DF) ||
+            (c >= 0x06E0 && c <= 0x06E4) ||
+            (c >= 0x06E7 && c <= 0x06E8) ||
+            (c >= 0x06EA && c <= 0x06ED) ||
+            (c >= 0x0901 && c <= 0x0903) ||
+            c == 0x093C ||
+            (c >= 0x093E && c <= 0x094C) ||
+            c == 0x094D ||
+            (c >= 0x0951 && c <= 0x0954) ||
+            (c >= 0x0962 && c <= 0x0963) ||
+            (c >= 0x0981 && c <= 0x0983) ||
+            c == 0x09BC ||
+            c == 0x09BE ||
+            c == 0x09BF ||
+            (c >= 0x09C0 && c <= 0x09C4) ||
+            (c >= 0x09C7 && c <= 0x09C8) ||
+            (c >= 0x09CB && c <= 0x09CD) ||
+            c == 0x09D7 ||
+            (c >= 0x09E2 && c <= 0x09E3) ||
+            c == 0x0A02 ||
+            c == 0x0A3C ||
+            c == 0x0A3E ||
+            c == 0x0A3F ||
+            (c >= 0x0A40 && c <= 0x0A42) ||
+            (c >= 0x0A47 && c <= 0x0A48) ||
+            (c >= 0x0A4B && c <= 0x0A4D) ||
+            (c >= 0x0A70 && c <= 0x0A71) ||
+            (c >= 0x0A81 && c <= 0x0A83) ||
+            c == 0x0ABC ||
+            (c >= 0x0ABE && c <= 0x0AC5) ||
+            (c >= 0x0AC7 && c <= 0x0AC9) ||
+            (c >= 0x0ACB && c <= 0x0ACD) ||
+            (c >= 0x0B01 && c <= 0x0B03) ||
+            c == 0x0B3C ||
+            (c >= 0x0B3E && c <= 0x0B43) ||
+            (c >= 0x0B47 && c <= 0x0B48) ||
+            (c >= 0x0B4B && c <= 0x0B4D) ||
+            (c >= 0x0B56 && c <= 0x0B57) ||
+            (c >= 0x0B82 && c <= 0x0B83) ||
+            (c >= 0x0BBE && c <= 0x0BC2) ||
+            (c >= 0x0BC6 && c <= 0x0BC8) ||
+            (c >= 0x0BCA && c <= 0x0BCD) ||
+            c == 0x0BD7 ||
+            (c >= 0x0C01 && c <= 0x0C03) ||
+            (c >= 0x0C3E && c <= 0x0C44) ||
+            (c >= 0x0C46 && c <= 0x0C48) ||
+            (c >= 0x0C4A && c <= 0x0C4D) ||
+            (c >= 0x0C55 && c <= 0x0C56) ||
+            (c >= 0x0C82 && c <= 0x0C83) ||
+            (c >= 0x0CBE && c <= 0x0CC4) ||
+            (c >= 0x0CC6 && c <= 0x0CC8) ||
+            (c >= 0x0CCA && c <= 0x0CCD) ||
+            (c >= 0x0CD5 && c <= 0x0CD6) ||
+            (c >= 0x0D02 && c <= 0x0D03) ||
+            (c >= 0x0D3E && c <= 0x0D43) ||
+            (c >= 0x0D46 && c <= 0x0D48) ||
+            (c >= 0x0D4A && c <= 0x0D4D) ||
+            c == 0x0D57 ||
+            c == 0x0E31 ||
+            (c >= 0x0E34 && c <= 0x0E3A) ||
+            (c >= 0x0E47 && c <= 0x0E4E) ||
+            c == 0x0EB1 ||
+            (c >= 0x0EB4 && c <= 0x0EB9) ||
+            (c >= 0x0EBB && c <= 0x0EBC) ||
+            (c >= 0x0EC8 && c <= 0x0ECD) ||
+            (c >= 0x0F18 && c <= 0x0F19) ||
+            c == 0x0F35 ||
+            c == 0x0F37 ||
+            c == 0x0F39 ||
+            c == 0x0F3E ||
+            c == 0x0F3F ||
+            (c >= 0x0F71 && c <= 0x0F84) ||
+            (c >= 0x0F86 && c <= 0x0F8B) ||
+            (c >= 0x0F90 && c <= 0x0F95) ||
+            c == 0x0F97 ||
+            (c >= 0x0F99 && c <= 0x0FAD) ||
+            (c >= 0x0FB1 && c <= 0x0FB7) ||
+            c == 0x0FB9 ||
+            (c >= 0x20D0 && c <= 0x20DC) ||
+            c == 0x20E1 ||
+            (c >= 0x302A && c <= 0x302F) ||
+            c == 0x3099 ||
+            c == 0x309A);
+  }
+
+  /**
+   * Indicates whether the specified Unicode character matches the Extender
+   * production.
+   */
+  public static boolean isExtender(int c)
+  {
+    return (c == 0x00B7 ||
+            c == 0x02D0 ||
+            c == 0x02D1 ||
+            c == 0x0387 ||
+            c == 0x0640 ||
+            c == 0x0E46 ||
+            c == 0x0EC6 ||
+            c == 0x3005 ||
+            (c >= 0x3031 && c <= 0x3035) ||
+            (c >= 0x309D && c <= 0x309E) ||
+            (c >= 0x30FC && c <= 0x30FE));
+  }
+
+  /**
+   * Indicates whether the specified Unicode character matches the Char
+   * production.
+   */
+  public static boolean isChar(int c)
+  {
+    return (c >= 0x20 && c < 0xd800) ||
+      (c >= 0xe00 && c < 0xfffe) ||
+      (c >= 0x10000 && c < 0x110000) ||
+      c == 0xa || c == 0x9 || c == 0xd;
+  }
+  
+  /**
+   * Interns the specified text or not, depending on the value of
+   * stringInterning.
+   */
+  private String intern(String text)
+  {
+    return stringInterning ? text.intern() : text;
+  }
+
+  /**
+   * Report a parsing error.
+   */
+  private void error(String message)
+    throws XMLStreamException
+  {
+    error(message, null);
+  }
+  
+  /**
+   * Report a parsing error.
+   */
+  private void error(String message, Object info)
+    throws XMLStreamException
+  {
+    if (info != null)
+      {
+        if (info instanceof String)
+          message += ": \"" + ((String) info) + "\"";
+        else if (info instanceof Character)
+          message += ": '" + ((Character) info) + "'";
+      }
+    throw new XMLStreamException(message);
+  }
+
+  /**
+   * Perform validation of a start-element event.
+   */
+  private void validateStartElement(String elementName)
+    throws XMLStreamException
+  {
+    if (currentContentModel == null)
+      {
+        // root element
+        // VC: Root Element Type
+        if (!elementName.equals(doctype.rootName))
+          error("root element name must match name in DTD");
+        return;
+      }
+    // VC: Element Valid
+    switch (currentContentModel.type)
+      {
+      case ContentModel.EMPTY:
+        error("child element found in empty element", elementName);
+        break;
+      case ContentModel.ELEMENT:
+        LinkedList ctx = (LinkedList) validationStack.getLast();
+        ctx.add(elementName);
+        break;
+      case ContentModel.MIXED:
+        MixedContentModel mm = (MixedContentModel) currentContentModel;
+        if (!mm.containsName(elementName))
+          error("illegal element for content model", elementName);
+        break;
+      }
+  }
+
+  /**
+   * Perform validation of an end-element event.
+   */
+  private void validateEndElement()
+    throws XMLStreamException
+  {
+    if (currentContentModel == null)
+      {
+        // root element
+        // VC: IDREF
+        if (!idrefs.containsAll(ids))
+          error("IDREF values must match the value of some ID attribute");
+        return;
+      }
+    // VC: Element Valid
+    switch (currentContentModel.type)
+      {
+      case ContentModel.ELEMENT:
+        LinkedList ctx = (LinkedList) validationStack.getLast();
+        ElementContentModel ecm = (ElementContentModel) currentContentModel;
+        validateElementContent(ecm, ctx);
+        break;
+      }
+  }
+
+  /**
+   * Perform validation of character data.
+   */
+  private void validatePCData(String text)
+    throws XMLStreamException
+  {
+    // VC: Element Valid
+    switch (currentContentModel.type)
+      {
+      case ContentModel.EMPTY:
+        error("character data found in empty element", text);
+        break;
+      case ContentModel.ELEMENT:
+        boolean white = true;
+        int len = text.length();
+        for (int i = 0; i < len; i++)
+          {
+            char c = text.charAt(i);
+            if (c != ' ' && c != '\t' && c != '\n' && c != '\r')
+              {
+                white = false;
+                break;
+              }
+          }
+        if (!white)
+          error("character data found in element with element content", text);
+        else if (xmlStandalone == Boolean.TRUE && currentContentModel.external)
+          // VC: Standalone Document Declaration
+          error("whitespace in element content of externally declared " +
+                "element in standalone document");
+        break;
+      }
+  }
+
+  /**
+   * Validates the specified validation context (list of child elements)
+   * against the element content model for the current element.
+   */
+  private void validateElementContent(ElementContentModel model,
+                                      LinkedList children)
+    throws XMLStreamException
+  {
+    // Use regular expression
+    StringBuffer buf = new StringBuffer();
+    for (Iterator i = children.iterator(); i.hasNext(); )
+      {
+        buf.append((String) i.next());
+        buf.append(' ');
+      }
+    String c = buf.toString();
+    String regex = createRegularExpression(model);
+    if (!c.matches(regex))
+      error("element content "+model.text+" does not match expression "+regex, c);
+  }
+
+  /**
+   * Creates the regular expression used to validate an element content
+   * model.
+   */
+  private String createRegularExpression(ElementContentModel model)
+  {
+    if (model.regex == null)
+      {
+        StringBuffer buf = new StringBuffer();
+        buf.append('(');
+        for (Iterator i = model.contentParticles.iterator(); i.hasNext(); )
+          {
+            ContentParticle cp = (ContentParticle) i.next();
+            if (cp.content instanceof String)
+              {
+                buf.append('(');
+                buf.append((String) cp.content);
+                buf.append(' ');
+                buf.append(')');
+                if (cp.max == -1)
+                  {
+                    if (cp.min == 0)
+                      buf.append('*');
+                    else
+                      buf.append('+');
+                  }
+                else if (cp.min == 0)
+                  buf.append('?');
+              }
+            else
+              {
+                ElementContentModel ecm = (ElementContentModel) cp.content;
+                buf.append(createRegularExpression(ecm));
+              }
+            if (model.or && i.hasNext())
+              buf.append('|');
+          }
+        buf.append(')');
+        if (model.max == -1)
+          {
+            if (model.min == 0)
+              buf.append('*');
+            else
+              buf.append('+');
+          }
+        else if (model.min == 0)
+          buf.append('?');
+        model.regex = buf.toString();
+      }
+    return model.regex;
+  }
+
+  /**
+   * Performs validation of a document type declaration event.
+   */
+  void validateDoctype()
+    throws XMLStreamException
+  {
+    for (Iterator i = doctype.entityIterator(); i.hasNext(); )
+      {
+        Map.Entry entry = (Map.Entry) i.next();
+        Object entity = entry.getValue();
+        if (entity instanceof ExternalIds)
+          {
+            ExternalIds ids = (ExternalIds) entity;
+            if (ids.notationName != null)
+              {
+                // VC: Notation Declared
+                ExternalIds notation = doctype.getNotation(ids.notationName);
+                if (notation == null)
+                  error("Notation name must match the declared name of a " +
+                        "notation", ids.notationName);
+              }
+          }
+      }
+  }
+
+  /**
+   * Simple test harness for reading an XML file.
+   * args[0] is the filename of the XML file
+   * If args[1] is "-x", enable XInclude processing
+   */
+  public static void main(String[] args)
+    throws Exception
+  {
+    boolean validating = false;
+    boolean namespaceAware = false;
+    boolean xIncludeAware = false;
+    int pos = 0;
+    while (pos < args.length && args[pos].startsWith("-"))
+      {
+        if ("-x".equals(args[pos]))
+          xIncludeAware = true;
+        else if ("-v".equals(args[pos]))
+          validating = true;
+        else if ("-n".equals(args[pos]))
+          namespaceAware = true;
+        pos++;
+      }
+    if (pos >= args.length)
+      {
+        System.out.println("Syntax: XMLParser [-n] [-v] [-x] <file> [<file2> [...]]");
+        System.out.println("\t-n: use namespace aware mode");
+        System.out.println("\t-v: use validating parser");
+        System.out.println("\t-x: use XInclude aware mode");
+        System.exit(2);
+      }
+    while (pos < args.length)
+      {
+        XMLParser p = new XMLParser(new java.io.FileInputStream(args[pos]),
+                                    absolutize(null, args[pos]),
+                                    validating, // validating
+                                    namespaceAware, // namespaceAware
+                                    true, // coalescing,
+                                    true, // replaceERefs
+                                    true, // externalEntities
+                                    true, // supportDTD
+                                    true, // baseAware
+                                    true, // stringInterning
+                                    true, // extendedEventTypes
+                                    null,
+                                    null);
+        XMLStreamReader reader = p;
+        if (xIncludeAware)
+          reader = new XIncludeFilter(p, args[pos], true, true, true);
+        try
+          {
+            int event;
+            //do
+            while (reader.hasNext())
+              {
+                event = reader.next();
+                Location loc = reader.getLocation();
+                System.out.print(loc.getLineNumber() + ":" + 
+                                 loc.getColumnNumber() + " ");
+                switch (event)
+                  {
+                  case XMLStreamConstants.START_DOCUMENT:
+                    System.out.println("START_DOCUMENT version=" +
+                                       reader.getVersion() +
+                                       " encoding=" +
+                                       reader.getEncoding());
+                    break;
+                  case XMLStreamConstants.END_DOCUMENT:
+                    System.out.println("END_DOCUMENT");
+                    break;
+                  case XMLStreamConstants.START_ELEMENT:
+                    System.out.println("START_ELEMENT " +
+                                       reader.getName());
+                    int l = reader.getNamespaceCount();
+                    for (int i = 0; i < l; i++)
+                      System.out.println("\tnamespace " +
+                                         reader.getNamespacePrefix(i) + "='" +
+                                         reader.getNamespaceURI(i)+"'");
+                    l = reader.getAttributeCount();
+                    for (int i = 0; i < l; i++)
+                      System.out.println("\tattribute " +
+                                         reader.getAttributeName(i) + "='" +
+                                         reader.getAttributeValue(i) + "'");
+                    break;
+                  case XMLStreamConstants.END_ELEMENT:
+                    System.out.println("END_ELEMENT " + reader.getName());
+                    break;
+                  case XMLStreamConstants.CHARACTERS:
+                    System.out.println("CHARACTERS '" +
+                                       encodeText(reader.getText()) + "'");
+                    break;
+                  case XMLStreamConstants.CDATA:
+                    System.out.println("CDATA '" +
+                                       encodeText(reader.getText()) + "'");
+                    break;
+                  case XMLStreamConstants.SPACE:
+                    System.out.println("SPACE '" +
+                                       encodeText(reader.getText()) + "'");
+                    break;
+                  case XMLStreamConstants.DTD:
+                    System.out.println("DTD " + reader.getText());
+                    break;
+                  case XMLStreamConstants.ENTITY_REFERENCE:
+                    System.out.println("ENTITY_REFERENCE " + reader.getText());
+                    break;
+                  case XMLStreamConstants.COMMENT:
+                    System.out.println("COMMENT '" +
+                                       encodeText(reader.getText()) + "'");
+                    break;
+                  case XMLStreamConstants.PROCESSING_INSTRUCTION:
+                    System.out.println("PROCESSING_INSTRUCTION " +
+                                       reader.getPITarget() + " " +
+                                       reader.getPIData());
+                    break;
+                  case START_ENTITY:
+                    System.out.println("START_ENTITY " + reader.getText());
+                    break;
+                  case END_ENTITY:
+                    System.out.println("END_ENTITY " + reader.getText());
+                    break;
+                  default:
+                    System.out.println("Unknown event: " + event);
+                  }
+              }
+          }
+        catch (XMLStreamException e)
+          {
+            Location l = reader.getLocation();
+            System.out.println("At line "+l.getLineNumber()+
+                               ", column "+l.getColumnNumber()+
+                               " of "+l.getSystemId());
+            throw e;
+          }
+        pos++;
+      }
+  }
+
+  /**
+   * Escapes control characters in the specified text. For debugging.
+   */
+  private static String encodeText(String text)
+  {
+    StringBuffer b = new StringBuffer();
+    int len = text.length();
+    for (int i = 0; i < len; i++)
+      {
+        char c = text.charAt(i);
+        switch (c)
+          {
+          case '\t':
+            b.append("\\t");
+            break;
+          case '\n':
+            b.append("\\n");
+            break;
+          case '\r':
+            b.append("\\r");
+            break;
+          default:
+            b.append(c);
+          }
+      }
+    return b.toString();
+  }
+
+  /**
+   * An attribute instance.
+   */
+  class Attribute
+  {
+
+    /**
+     * Attribute name.
+     */
+    final String name;
+
+    /**
+     * Attribute type as declared in the DTD, or CDATA otherwise.
+     */
+    final String type;
+
+    /**
+     * Whether the attribute was specified or defaulted.
+     */
+    final boolean specified;
+
+    /**
+     * The attribute value.
+     */
+    final String value;
+
+    /**
+     * The namespace prefix.
+     */
+    final String prefix;
+
+    /**
+     * The namespace local-name.
+     */
+    final String localName;
+
+    Attribute(String name, String type, boolean specified, String value)
+    {
+      this.name = name;
+      this.type = type;
+      this.specified = specified;
+      this.value = value;
+      int ci = name.indexOf(':');
+      if (ci == -1)
+        {
+          prefix = null;
+          localName = intern(name);
+        }
+      else
+        {
+          prefix = intern(name.substring(0, ci));
+          localName = intern(name.substring(ci + 1));
+        }
+    }
+
+    public boolean equals(Object other)
+    {
+      if (other instanceof Attribute)
+        {
+          Attribute a = (Attribute) other;
+          if (namespaceAware)
+            {
+              if (!a.localName.equals(localName))
+                return false;
+              String auri = getNamespaceURI(a.prefix);
+              String uri = getNamespaceURI(prefix);
+              if (uri == null && (auri == null ||
+                                  (input.xml11 && "".equals(auri))))
+               return true; 
+              if (uri != null)
+                {
+                  if ("".equals(uri) && input.xml11 && "".equals(auri))
+                    return true;
+                  return uri.equals(auri);
+                }
+              return false;
+            }
+          else
+            return a.name.equals(name);
+        }
+      return false;
+    }
+    
+  }
+
+  /**
+   * Representation of a DTD.
+   */
+  class Doctype
+  {
+
+    /**
+     * Name of the root element.
+     */
+    final String rootName;
+
+    /**
+     * Public ID, if any, of external subset.
+     */
+    final String publicId;
+
+    /**
+     * System ID (URL), if any, of external subset.
+     */
+    final String systemId;
+
+    /**
+     * Map of element names to content models.
+     */
+    private final LinkedHashMap elements = new LinkedHashMap();
+
+    /**
+     * Map of element names to maps of attribute declarations.
+     */
+    private final LinkedHashMap attlists = new LinkedHashMap();
+
+    /**
+     * Map of entity names to entities (String or ExternalIds).
+     */
+    private final LinkedHashMap entities = new LinkedHashMap();
+
+    /**
+     * Map of notation names to ExternalIds.
+     */
+    private final LinkedHashMap notations = new LinkedHashMap();
+
+    /**
+     * Map of anonymous keys to comments.
+     */    
+    private final LinkedHashMap comments = new LinkedHashMap();
+
+    /**
+     * Map of anonymous keys to processing instructions (String[2]
+     * containing {target, data}).
+     */
+    private final LinkedHashMap pis = new LinkedHashMap();
+
+    /**
+     * List of keys to all markup entries in the DTD.
+     */
+    private final LinkedList entries = new LinkedList();
+
+    /**
+     * Set of the entities defined in the external subset.
+     */
+    private final HashSet externalEntities = new HashSet();
+
+    /**
+     * Set of the notations defined in the external subset.
+     */
+    private final HashSet externalNotations = new HashSet();
+
+    /**
+     * Counter for making anonymous keys.
+     */
+    private int anon = 1;
+
+    /**
+     * Constructor.
+     */
+    Doctype(String rootName, String publicId, String systemId)
+    {
+      this.rootName = rootName;
+      this.publicId = publicId;
+      this.systemId = systemId;
+    }
+
+    /**
+     * Adds an element declaration.
+     * @param name the element name
+     * @param text the content model text
+     * @param model the parsed content model
+     */
+    void addElementDecl(String name, String text, ContentModel model)
+    {
+      if (elements.containsKey(name))
+        return;
+      model.text = text;
+      model.external = (inputStack.size() != 1);
+      elements.put(name, model);
+      entries.add("E" + name);
+    }
+
+    /**
+     * Adds an attribute declaration.
+     * @param ename the element name
+     * @param aname the attribute name
+     * @param decl the attribute declaration details
+     */
+    void addAttributeDecl(String ename, String aname, AttributeDecl decl)
+    {
+      LinkedHashMap attlist = (LinkedHashMap) attlists.get(ename);
+      if (attlist == null)
+        {
+          attlist = new LinkedHashMap();
+          attlists.put(ename, attlist);
+        }
+      else if (attlist.containsKey(aname))
+        return;
+      attlist.put(aname, decl);
+      String key = "A" + ename;
+      if (!entries.contains(key))
+        entries.add(key);
+    }
+
+    /**
+     * Adds an entity declaration.
+     * @param name the entity name
+     * @param text the entity replacement text
+     * @param inExternalSubset if we are in the exernal subset
+     */
+    void addEntityDecl(String name, String text, boolean inExternalSubset)
+    {
+      if (entities.containsKey(name))
+        return;
+      entities.put(name, text);
+      entries.add("e" + name);
+      if (inExternalSubset)
+        externalEntities.add(name);
+    }
+    
+    /**
+     * Adds an entity declaration.
+     * @param name the entity name
+     * @param ids the external IDs
+     * @param inExternalSubset if we are in the exernal subset
+     */
+    void addEntityDecl(String name, ExternalIds ids, boolean inExternalSubset)
+    {
+      if (entities.containsKey(name))
+        return;
+      entities.put(name, ids);
+      entries.add("e" + name);
+      if (inExternalSubset)
+        externalEntities.add(name);
+    }
+
+    /**
+     * Adds a notation declaration.
+     * @param name the notation name
+     * @param ids the external IDs
+     * @param inExternalSubset if we are in the exernal subset
+     */
+    void addNotationDecl(String name, ExternalIds ids, boolean inExternalSubset)
+    {
+      if (notations.containsKey(name))
+        return;
+      notations.put(name, ids);
+      entries.add("n" + name);
+      if (inExternalSubset)
+        externalNotations.add(name);
+    }
+
+    /**
+     * Adds a comment.
+     */
+    void addComment(String text)
+    {
+      String key = Integer.toString(anon++);
+      comments.put(key, text);
+      entries.add("c" + key);
+    }
+
+    /**
+     * Adds a processing instruction.
+     */
+    void addPI(String target, String data)
+    {
+      String key = Integer.toString(anon++);
+      pis.put(key, new String[] {target, data});
+      entries.add("p" + key);
+    }
+
+    /**
+     * Returns the content model for the specified element.
+     * @param name the element name
+     */
+    ContentModel getElementModel(String name)
+    {
+      return (ContentModel) elements.get(name);
+    }
+
+    /**
+     * Returns the attribute definition for the given attribute
+     * @param ename the element name
+     * @param aname the attribute name
+     */
+    AttributeDecl getAttributeDecl(String ename, String aname)
+    {
+      LinkedHashMap attlist = (LinkedHashMap) attlists.get(ename);
+      return (attlist == null) ? null : (AttributeDecl) attlist.get(aname);
+    }
+
+    /**
+     * Indicates whether the specified attribute was declared in the DTD.
+     * @param ename the element name
+     * @param aname the attribute name
+     */
+    boolean isAttributeDeclared(String ename, String aname)
+    {
+      LinkedHashMap attlist = (LinkedHashMap) attlists.get(ename);
+      return (attlist == null) ? false : attlist.containsKey(aname);
+    }
+
+    /**
+     * Returns an iterator over the entries in the attribute list for the
+     * given element.
+     * @param ename the element name
+     */
+    Iterator attlistIterator(String ename)
+    {
+      LinkedHashMap attlist = (LinkedHashMap) attlists.get(ename);
+      return (attlist == null) ? Collections.EMPTY_LIST.iterator() :
+        attlist.entrySet().iterator();
+    }
+
+    /**
+     * Returns the entity (String or ExternalIds) for the given entity name.
+     */
+    Object getEntity(String name)
+    {
+      return entities.get(name);
+    }
+
+    /**
+     * Indicates whether the specified entity was declared in the external
+     * subset.
+     */
+    boolean isEntityExternal(String name)
+    {
+      return externalEntities.contains(name);
+    }
+
+    /**
+     * Returns an iterator over the entity map entries.
+     */
+    Iterator entityIterator()
+    {
+      return entities.entrySet().iterator();
+    }
+
+    /**
+     * Returns the notation IDs for the given notation name.
+     */
+    ExternalIds getNotation(String name)
+    {
+      return (ExternalIds) notations.get(name);
+    }
+
+    /**
+     * Indicates whether the specified notation was declared in the external
+     * subset.
+     */
+    boolean isNotationExternal(String name)
+    {
+      return externalNotations.contains(name);
+    }
+
+    /**
+     * Returns the comment associated with the specified (anonymous) key.
+     */
+    String getComment(String key)
+    {
+      return (String) comments.get(key);
+    }
+
+    /**
+     * Returns the processing instruction associated with the specified
+     * (anonymous) key.
+     */
+    String[] getPI(String key)
+    {
+      return (String[]) pis.get(key);
+    }
+
+    /**
+     * Returns an iterator over the keys of the markup entries in this DTD,
+     * in the order declared.
+     */
+    Iterator entryIterator()
+    {
+      return entries.iterator();
+    }
+    
+  }
+
+  /**
+   * Combination of an ExternalID and an optional NDataDecl.
+   */
+  class ExternalIds
+  {
+
+    /**
+     * The public ID.
+     */
+    String publicId;
+
+    /**
+     * The system ID.
+     */
+    String systemId;
+
+    /**
+     * The notation name declared with the NDATA keyword.
+     */
+    String notationName;
+  }
+
+  /**
+   * A content model.
+   */
+  abstract class ContentModel
+  {
+    static final int EMPTY = 0;
+    static final int ANY = 1;
+    static final int ELEMENT = 2;
+    static final int MIXED = 3;
+    
+    int min;
+    int max;
+    final int type;
+    String text;
+    boolean external;
+
+    ContentModel(int type)
+    {
+      this.type = type;
+      min = 1;
+      max = 1;
+    }
+    
+  }
+
+  /**
+   * The EMPTY content model.
+   */
+  class EmptyContentModel
+    extends ContentModel
+  {
+    
+    EmptyContentModel()
+    {
+      super(ContentModel.EMPTY);
+      min = 0;
+      max = 0;
+    }
+    
+  }
+
+  /**
+   * The ANY content model.
+   */
+  class AnyContentModel
+    extends ContentModel
+  {
+    
+    AnyContentModel()
+    {
+      super(ContentModel.ANY);
+      min = 0;
+      max = -1;
+    }
+    
+  }
+
+  /**
+   * An element content model.
+   */
+  class ElementContentModel
+    extends ContentModel
+  {
+
+    LinkedList contentParticles;
+    boolean or;
+    String regex; // regular expression cache
+    
+    ElementContentModel()
+    {
+      super(ContentModel.ELEMENT);
+      contentParticles = new LinkedList();
+    }
+
+    void addContentParticle(ContentParticle cp)
+    {
+      contentParticles.add(cp);
+    }
+    
+  }
+
+  class ContentParticle
+  {
+
+    int min = 1;
+    int max = 1;
+    Object content; // Name (String) or ElementContentModel
+    
+  }
+
+  /**
+   * A mixed content model.
+   */
+  class MixedContentModel
+    extends ContentModel
+  {
+
+    private HashSet names;
+    
+    MixedContentModel()
+    {
+      super(ContentModel.MIXED);
+      names = new HashSet();
+    }
+
+    void addName(String name)
+    {
+      names.add(name);
+    }
+
+    boolean containsName(String name)
+    {
+      return names.contains(name);
+    }
+    
+  }
+
+  /**
+   * An attribute definition.
+   */
+  class AttributeDecl
+  {
+    
+    /**
+     * The attribute type (CDATA, ID, etc).
+     */
+    final String type;
+
+    /**
+     * The default value.
+     */
+    final String value;
+
+    /**
+     * The value type (#FIXED, #IMPLIED, etc).
+     */
+    final int valueType;
+
+    /**
+     * The enumeration text.
+     */
+    final String enumeration;
+
+    /**
+     * The enumeration tokens.
+     */
+    final HashSet values;
+
+    /**
+     * Whether this attribute declaration occurred in the external subset.
+     */
+    final boolean external;
+
+    AttributeDecl(String type, String value,
+                  int valueType, String enumeration,
+                  HashSet values, boolean external)
+    {
+      this.type = type;
+      this.value = value;
+      this.valueType = valueType;
+      this.enumeration = enumeration;
+      this.values = values;
+      this.external = external;
+    }
+    
+  }
+
+  /**
+   * An XML input source.
+   */
+  static class Input
+    implements Location
+  {
+    
+    int line = 1, markLine;
+    int column, markColumn;
+    int offset, markOffset;
+    final String publicId, systemId, name;
+    final boolean report; // report start- and end-entity
+    final boolean normalize; // normalize CR, etc to LF
+    
+    InputStream in;
+    Reader reader;
+    UnicodeReader unicodeReader;
+    boolean initialized;
+    boolean encodingDetected;
+    String inputEncoding;
+    boolean xml11;
+
+    Input(InputStream in, Reader reader, String publicId, String systemId,
+          String name, String inputEncoding, boolean report,
+          boolean normalize)
+    {
+      if (inputEncoding == null)
+        inputEncoding = "UTF-8";
+      this.inputEncoding = inputEncoding;
+      this.publicId = publicId;
+      this.systemId = systemId;
+      this.name = name;
+      this.report = report;
+      this.normalize = normalize;
+      if (in != null)
+        {
+          if (reader != null)
+            throw new IllegalStateException("both byte and char streams "+
+                                            "specified");
+          if (normalize)
+            in = new CRLFInputStream(in);
+          in = new BufferedInputStream(in);
+          this.in = in;
+        }
+      else
+        {
+          this.reader = normalize ? new CRLFReader(reader) : reader;
+          unicodeReader = new UnicodeReader(this.reader);
+        }
+      initialized = false;
+    }
+
+    // -- Location --
+    
+    public int getCharacterOffset()
+    {
+      return offset;
+    }
+    
+    public int getColumnNumber()
+    {
+      return column;
+    }
+
+    public int getLineNumber()
+    {
+      return line;
+    }
+
+    public String getPublicId()
+    {
+      return publicId;
+    }
+
+    public String getSystemId()
+    {
+      return systemId;
+    }
+
+    void init()
+      throws IOException
+    {
+      if (initialized)
+        return;
+      if (in != null)
+        detectEncoding();
+      initialized = true;
+    }
+
+    void mark(int len)
+      throws IOException
+    {
+      markOffset = offset;
+      markLine = line;
+      markColumn = column;
+      if (unicodeReader != null)
+        unicodeReader.mark(len);
+      else
+        in.mark(len);
+    }
+
+    /**
+     * Character read.
+     */
+    int read()
+      throws IOException
+    {
+      offset++;
+      int ret = (unicodeReader != null) ? unicodeReader.read() : in.read();
+      if (normalize &&
+          (ret == 0x0d || (xml11 && (ret == 0x85 || ret == 0x2028))))
+        {
+          // Normalize CR etc to LF
+          ret = 0x0a;
+        }
+      // Locator handling
+      if (ret == 0x0a)
+        {
+          line++;
+          column = 0;
+        }
+      else
+        column++;
+      return ret;
+    }
+
+    /**
+     * Block read.
+     */
+    int read(int[] b, int off, int len)
+      throws IOException
+    {
+      int ret;
+      if (unicodeReader != null)
+        {
+          ret = unicodeReader.read(b, off, len);
+        }
+      else
+        {
+          byte[] b2 = new byte[len];
+          ret = in.read(b2, 0, len);
+          if (ret != -1)
+            {
+              String s = new String(b2, 0, ret, inputEncoding);
+              int[] c = UnicodeReader.toCodePointArray(s);
+              ret = c.length;
+              System.arraycopy(c, 0, b, off, ret);
+            }
+        }
+      if (ret != -1)
+        {
+          // Locator handling
+          for (int i = 0; i < ret; i++)
+            {
+              int c = b[off + i];
+              if (normalize &&
+                  (c == 0x0d || (xml11 && (c == 0x85 || c == 0x2028))))
+                {
+                  // Normalize CR etc to LF
+                  c = 0x0a;
+                  b[off + i] = c;
+                }
+              if (c == 0x0a)
+                {
+                  line++;
+                  column = 0;
+                }
+              else
+                column++;
+            }
+        }
+      return ret;
+    }
+
+    void reset()
+      throws IOException
+    {
+      if (unicodeReader != null)
+        unicodeReader.reset();
+      else
+        in.reset();
+      offset = markOffset;
+      line = markLine;
+      column = markColumn;
+    }
+
+    // Detection of input encoding
+    
+    private static final int[] SIGNATURE_UCS_4_1234 =
+      new int[] { 0x00, 0x00, 0x00, 0x3c };
+    private static final int[] SIGNATURE_UCS_4_4321 =
+      new int[] { 0x3c, 0x00, 0x00, 0x00 };
+    private static final int[] SIGNATURE_UCS_4_2143 =
+      new int[] { 0x00, 0x00, 0x3c, 0x00 };
+    private static final int[] SIGNATURE_UCS_4_3412 =
+      new int[] { 0x00, 0x3c, 0x00, 0x00 };
+    private static final int[] SIGNATURE_UCS_2_12 =
+      new int[] { 0xfe, 0xff };
+    private static final int[] SIGNATURE_UCS_2_21 =
+      new int[] { 0xff, 0xfe };
+    private static final int[] SIGNATURE_UCS_2_12_NOBOM =
+      new int[] { 0x00, 0x3c, 0x00, 0x3f };
+    private static final int[] SIGNATURE_UCS_2_21_NOBOM =
+      new int[] { 0x3c, 0x00, 0x3f, 0x00 };
+    private static final int[] SIGNATURE_UTF_8 =
+      new int[] { 0x3c, 0x3f, 0x78, 0x6d };
+    private static final int[] SIGNATURE_UTF_8_BOM =
+      new int[] { 0xef, 0xbb, 0xbf };
+    
+    /**
+     * Detect the input encoding.
+     */
+    private void detectEncoding()
+      throws IOException
+    {
+      int[] signature = new int[4];
+      in.mark(4);
+      for (int i = 0; i < 4; i++)
+        signature[i] = in.read();
+      in.reset();
+
+      // 4-byte encodings
+      if (equals(SIGNATURE_UCS_4_1234, signature))
+        {
+          in.read();
+          in.read();
+          in.read();
+          in.read();
+          setInputEncoding("UTF-32BE");
+          encodingDetected = true;
+        }
+      else if (equals(SIGNATURE_UCS_4_4321, signature))
+        {
+          in.read();
+          in.read();
+          in.read();
+          in.read();
+          setInputEncoding("UTF-32LE");
+          encodingDetected = true;
+        }
+      else if (equals(SIGNATURE_UCS_4_2143, signature) ||
+               equals(SIGNATURE_UCS_4_3412, signature))
+        throw new UnsupportedEncodingException("unsupported UCS-4 byte ordering");
+      
+      // 2-byte encodings
+      else if (equals(SIGNATURE_UCS_2_12, signature))
+        {
+          in.read();
+          in.read();
+          setInputEncoding("UTF-16BE");
+          encodingDetected = true;
+        }
+      else if (equals(SIGNATURE_UCS_2_21, signature))
+        {
+          in.read();
+          in.read();
+          setInputEncoding("UTF-16LE");
+          encodingDetected = true;
+        }
+      else if (equals(SIGNATURE_UCS_2_12_NOBOM, signature))
+        {
+          //setInputEncoding("UTF-16BE");
+          throw new UnsupportedEncodingException("no byte-order mark for UCS-2 entity");
+        }
+      else if (equals(SIGNATURE_UCS_2_21_NOBOM, signature))
+        {
+          //setInputEncoding("UTF-16LE");
+          throw new UnsupportedEncodingException("no byte-order mark for UCS-2 entity");
+        }
+      // ASCII-derived encodings
+      else if (equals(SIGNATURE_UTF_8, signature))
+        {
+          // UTF-8 input encoding implied, TextDecl
+        }
+      else if (equals(SIGNATURE_UTF_8_BOM, signature))
+        {
+          in.read();
+          in.read();
+          in.read();
+          setInputEncoding("UTF-8");
+          encodingDetected = true;
+        }
+    }
+
+    private static boolean equals(int[] b1, int[] b2)
+    {
+      for (int i = 0; i < b1.length; i++)
+        {
+          if (b1[i] != b2[i])
+            return false;
+        }
+      return true;
+    }
+    
+    void setInputEncoding(String encoding)
+      throws IOException
+    {
+      if (encoding.equals(inputEncoding))
+        return;
+      if ("UTF-16".equalsIgnoreCase(encoding) &&
+          inputEncoding.startsWith("UTF-16"))
+        return;
+      if (encodingDetected)
+        throw new UnsupportedEncodingException("document is not in its " +
+                                               "declared encoding " +
+                                               inputEncoding +
+                                               ": " + encoding);
+      inputEncoding = encoding;
+      finalizeEncoding();
+    }
+
+    void finalizeEncoding()
+      throws IOException
+    {
+      if (reader != null)
+        return;
+      reader = new BufferedReader(new InputStreamReader(in, inputEncoding));
+      unicodeReader = new UnicodeReader(reader);
+      mark(1);
+    }
+
+  }
+
+}
+

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/stream/XMLStreamWriterImpl.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/stream/XMLStreamWriterImpl.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/stream/XMLStreamWriterImpl.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/stream/XMLStreamWriterImpl.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,1005 @@
+/* XMLStreamWriterImpl.java -- 
+   Copyright (C) 2005  Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.xml.stream;
+
+import java.io.IOException;
+import java.io.Writer;
+import java.util.Enumeration;
+import java.util.HashSet;
+import java.util.LinkedList;
+import java.util.Set;
+
+import javax.xml.XMLConstants;
+import javax.xml.namespace.NamespaceContext;
+import javax.xml.stream.XMLStreamException;
+import javax.xml.stream.XMLStreamWriter;
+
+import org.xml.sax.helpers.NamespaceSupport;
+
+/**
+ * Simple XML stream writer.
+ *
+ * @author <a href='mailto:dog at gnu.org'>Chris Burdess</a>
+ */
+public class XMLStreamWriterImpl
+  implements XMLStreamWriter
+{
+
+  /**
+   * The underlying character stream to write to.
+   */
+  protected final Writer writer;
+
+  /**
+   * The encoding being used.
+   * Note that this must match the encoding of the character stream.
+   */
+  protected final String encoding;
+
+  /**
+   * Whether prefix defaulting is being used.
+   * If true and a prefix has not been defined for a namespace specified on
+   * an element or an attribute, a new prefix and namespace declaration will
+   * be created.
+   */
+  protected final boolean prefixDefaulting;
+
+  /**
+   * The namespace context used to determine the namespace-prefix mappings
+   * in scope.
+   */
+  protected NamespaceContext namespaceContext;
+  
+  /**
+   * The stack of elements in scope.
+   * Used to close the remaining elements.
+   */
+  private LinkedList elements;
+
+  /**
+   * Whether a start element has been opened but not yet closed.
+   */
+  private boolean inStartElement;
+
+  /**
+   * Whether we are in an empty element.
+   */
+  private boolean emptyElement;
+  
+  private NamespaceSupport namespaces;
+  private int count = 0;
+
+  private boolean xml11;
+  private boolean hasXML11RestrictedChars;
+
+  /**
+   * Constructor.
+   * @see #writer
+   * @see #encoding
+   * @see #prefixDefaulting
+   */
+  protected XMLStreamWriterImpl(Writer writer, String encoding,
+                                boolean prefixDefaulting)
+  {
+    this.writer = writer;
+    this.encoding = encoding;
+    this.prefixDefaulting = prefixDefaulting;
+    elements = new LinkedList();
+    namespaces = new NamespaceSupport();
+  }
+
+  /**
+   * Write the end of a start-element event.
+   * This will close the element if it was defined to be an empty element.
+   */
+  private void endStartElement()
+    throws IOException
+  {
+    if (!inStartElement)
+      return;
+    if (emptyElement)
+      {
+        writer.write('/');
+        elements.removeLast();
+        namespaces.popContext();
+        emptyElement = false;
+      }
+    writer.write('>');
+    inStartElement = false;
+  }
+
+  public void writeStartElement(String localName)
+    throws XMLStreamException
+  {
+    try
+      {
+        if (!isName(localName))
+          throw new IllegalArgumentException("illegal Name: " + localName);
+
+        endStartElement();
+        namespaces.pushContext();
+        
+        writer.write('<');
+        writer.write(localName);
+        
+        elements.addLast(new String[] { null, localName });
+        inStartElement = true;
+      }
+    catch (IOException e)
+      {
+        XMLStreamException e2 = new XMLStreamException(e);
+        e2.initCause(e);
+        throw e2;
+      }
+  }
+
+  public void writeStartElement(String namespaceURI, String localName)
+    throws XMLStreamException
+  {
+    try
+      {
+        if (namespaceURI != null && !isURI(namespaceURI))
+          throw new IllegalArgumentException("illegal URI: " + namespaceURI);
+        if (!isName(localName))
+          throw new IllegalArgumentException("illegal Name: " + localName);
+
+        endStartElement();
+        namespaces.pushContext();
+        
+        String prefix = getPrefix(namespaceURI);
+        boolean isDeclared = (prefix != null);
+        if (!isDeclared)
+          {
+            if (prefixDefaulting)
+              prefix = createPrefix(namespaceURI);
+            else
+              throw new XMLStreamException("namespace " + namespaceURI +
+                                           " has not been declared");
+          }
+        writer.write('<');
+        if (!"".equals(prefix))
+          {
+            writer.write(prefix);
+            writer.write(':');
+          }
+        writer.write(localName);
+        inStartElement = true;
+        if (!isDeclared)
+          {
+            writeNamespaceImpl(prefix, namespaceURI);
+          }
+        
+        elements.addLast(new String[] { prefix, localName });
+      }
+    catch (IOException e)
+      {
+        XMLStreamException e2 = new XMLStreamException(e);
+        e2.initCause(e);
+        throw e2;
+      }
+  }
+
+  /**
+   * Creates a new unique prefix in the document.
+   * Subclasses may override this method to provide a suitably unique prefix
+   * for the given namespace.
+   * @param namespaceURI the namespace URI
+   */
+  protected String createPrefix(String namespaceURI)
+  {
+    Set prefixes = new HashSet();
+    for (Enumeration e = namespaces.getPrefixes(); e.hasMoreElements(); )
+      prefixes.add(e.nextElement());
+    String ret;
+    do
+      {
+        ret = "ns" + (count++);
+      }
+    while (prefixes.contains(ret));
+    return ret;
+  }
+
+  public void writeStartElement(String prefix, String localName,
+                                String namespaceURI)
+    throws XMLStreamException
+  {
+    try
+      {
+        if (namespaceURI != null && !isURI(namespaceURI))
+          throw new IllegalArgumentException("illegal URI: " + namespaceURI);
+        if (prefix != null && !isNCName(prefix))
+          throw new IllegalArgumentException("illegal NCName: " + prefix);
+        if (!isNCName(localName))
+          throw new IllegalArgumentException("illegal NCName: " + localName);
+
+        endStartElement();
+        namespaces.pushContext();
+        
+        String currentPrefix = getPrefix(namespaceURI);
+        boolean isCurrent = prefix.equals(currentPrefix);
+        writer.write('<');
+        if (!"".equals(prefix))
+          {
+            writer.write(prefix);
+            writer.write(':');
+          }
+        writer.write(localName);
+        if (prefixDefaulting && !isCurrent)
+          {
+            writeNamespaceImpl(prefix, namespaceURI);
+          }
+        
+        elements.addLast(new String[] { prefix, localName });
+        inStartElement = true;
+      }
+    catch (IOException e)
+      {
+        XMLStreamException e2 = new XMLStreamException(e);
+        e2.initCause(e);
+        throw e2;
+      }
+  }
+
+  public void writeEmptyElement(String namespaceURI, String localName)
+    throws XMLStreamException
+  {
+    writeStartElement(namespaceURI, localName);
+    emptyElement = true;
+  }
+
+  public void writeEmptyElement(String prefix, String localName,
+                                String namespaceURI)
+    throws XMLStreamException
+  {
+    writeStartElement(prefix, localName, namespaceURI);
+    emptyElement = true;
+  }
+
+  public void writeEmptyElement(String localName)
+    throws XMLStreamException
+  {
+    writeStartElement(localName);
+    emptyElement = true;
+  }
+
+  public void writeEndElement()
+    throws XMLStreamException
+  {
+    if (elements.isEmpty())
+      throw new IllegalStateException("no matching start element");
+    try
+      {
+        endStartElement();
+        String[] element = (String[]) elements.removeLast();
+        namespaces.popContext();
+
+        writer.write('<');
+        writer.write('/');
+        if (element[0] != null && !"".equals(element[0]))
+          {
+            writer.write(element[0]);
+            writer.write(':');
+          }
+        writer.write(element[1]);
+        writer.write('>');
+      }
+    catch (IOException e)
+      {
+        XMLStreamException e2 = new XMLStreamException(e);
+        e2.initCause(e);
+        throw e2;
+      }
+  }
+
+  public void writeEndDocument()
+    throws XMLStreamException
+  {
+    while (!elements.isEmpty())
+      writeEndElement();
+  }
+
+  public void close()
+    throws XMLStreamException
+  {
+    flush();
+  }
+
+  public void flush()
+    throws XMLStreamException
+  {
+    try
+      {
+        writer.flush();
+      }
+    catch (IOException e)
+      {
+        XMLStreamException e2 = new XMLStreamException(e);
+        e2.initCause(e);
+        throw e2;
+      }
+  }
+
+  public void writeAttribute(String localName, String value)
+    throws XMLStreamException
+  {
+    if (!inStartElement)
+      throw new IllegalStateException();
+    try
+      {
+        if (!isName(localName))
+          throw new IllegalArgumentException("illegal Name: " + localName);
+        if (!isChars(value))
+          throw new IllegalArgumentException("illegal character: " + value);
+
+        writer.write(' ');
+        writer.write(localName);
+        writer.write('=');
+        writer.write('"');
+        if (hasXML11RestrictedChars)
+          writeEncodedWithRestrictedChars(value, true);
+        else
+          writeEncoded(value, true);
+        writer.write('"');
+      }
+    catch (IOException e)
+      {
+        XMLStreamException e2 = new XMLStreamException(e);
+        e2.initCause(e);
+        throw e2;
+      }
+  }
+
+  public void writeAttribute(String prefix, String namespaceURI,
+                             String localName, String value)
+    throws XMLStreamException
+  {
+    if (!inStartElement)
+      throw new IllegalStateException();
+    try
+      {
+        if (namespaceURI != null && !isURI(namespaceURI))
+          throw new IllegalArgumentException("illegal URI: " + namespaceURI);
+        if (prefix != null && !isNCName(prefix))
+          throw new IllegalArgumentException("illegal NCName: " + prefix);
+        if (!isNCName(localName))
+          throw new IllegalArgumentException("illegal NCName: " + localName);
+        if (!isChars(value))
+          throw new IllegalArgumentException("illegal character: " + value);
+
+        String currentPrefix = getPrefix(namespaceURI);
+        if (currentPrefix == null)
+          {
+            if (prefixDefaulting)
+              writeNamespaceImpl(prefix, namespaceURI);
+            else
+              throw new XMLStreamException("namespace " + namespaceURI +
+                                           " is not bound");
+          }
+        else if (!currentPrefix.equals(prefix))
+          throw new XMLStreamException("namespace " + namespaceURI +
+                                       " is bound to prefix " +
+                                       currentPrefix);
+        writer.write(' ');
+        if (!"".equals(prefix))
+          {
+            writer.write(prefix);
+            writer.write(':');
+          }
+        writer.write(localName);
+        writer.write('=');
+        writer.write('"');
+        if (hasXML11RestrictedChars)
+          writeEncodedWithRestrictedChars(value, true);
+        else
+          writeEncoded(value, true);
+        writer.write('"');
+      }
+    catch (IOException e)
+      {
+        XMLStreamException e2 = new XMLStreamException(e);
+        e2.initCause(e);
+        throw e2;
+      }
+  }
+
+  public void writeAttribute(String namespaceURI, String localName,
+                             String value)
+    throws XMLStreamException
+  {
+    if (!inStartElement)
+      throw new IllegalStateException();
+    try
+      {
+        if (namespaceURI != null && !isURI(namespaceURI))
+          throw new IllegalArgumentException("illegal URI: " + namespaceURI);
+        if (!isName(localName))
+          throw new IllegalArgumentException("illegal Name: " + localName);
+        if (!isChars(value))
+          throw new IllegalArgumentException("illegal character: " + value);
+        
+        String prefix = getPrefix(namespaceURI);
+        if (prefix == null)
+          {
+            if (prefixDefaulting)
+              {
+                prefix = XMLConstants.DEFAULT_NS_PREFIX;
+                writeNamespaceImpl(prefix, namespaceURI);
+              }
+            else
+              throw new XMLStreamException("namespace " + namespaceURI +
+                                           " is not bound");
+          }
+        writer.write(' ');
+        if (!"".equals(prefix))
+          {
+            writer.write(prefix);
+            writer.write(':');
+          }
+        writer.write(localName);
+        writer.write('=');
+        writer.write('"');
+        if (hasXML11RestrictedChars)
+          writeEncodedWithRestrictedChars(value, true);
+        else
+          writeEncoded(value, true);
+        writer.write('"');
+      }
+    catch (IOException e)
+      {
+        XMLStreamException e2 = new XMLStreamException(e);
+        e2.initCause(e);
+        throw e2;
+      }
+  }
+
+  public void writeNamespace(String prefix, String namespaceURI)
+    throws XMLStreamException
+  {
+    if (!inStartElement)
+      throw new IllegalStateException();
+    try
+      {
+        if (!isURI(namespaceURI))
+          throw new IllegalArgumentException("illegal URI: " + namespaceURI);
+        if (!isNCName(prefix))
+          throw new IllegalArgumentException("illegal NCName: " + prefix);
+      }
+    catch (IOException e)
+      {
+        XMLStreamException e2 = new XMLStreamException(e);
+        e2.initCause(e);
+        throw e2;
+      }
+    writeNamespaceImpl(prefix, namespaceURI);
+  }
+
+  private void writeNamespaceImpl(String prefix, String namespaceURI)
+    throws XMLStreamException
+  {
+    try
+      {
+        if (prefix == null)
+          prefix = XMLConstants.DEFAULT_NS_PREFIX;
+
+        setPrefix(prefix, namespaceURI);
+        
+        writer.write(' ');
+        writer.write("xmlns");
+        if (!XMLConstants.DEFAULT_NS_PREFIX.equals(prefix))
+          {
+            writer.write(':');
+            writer.write(prefix);
+          }
+        writer.write('=');
+        writer.write('"');
+        writer.write(namespaceURI);
+        writer.write('"');
+      }
+    catch (IOException e)
+      {
+        XMLStreamException e2 = new XMLStreamException(e);
+        e2.initCause(e);
+        throw e2;
+      }
+  }
+
+  public void writeDefaultNamespace(String namespaceURI)
+    throws XMLStreamException
+  {
+    if (!inStartElement)
+      throw new IllegalStateException();
+    if (!isURI(namespaceURI))
+      throw new IllegalArgumentException("illegal URI: " + namespaceURI);
+    writeNamespaceImpl(XMLConstants.DEFAULT_NS_PREFIX, namespaceURI);
+  }
+
+  public void writeComment(String data)
+    throws XMLStreamException
+  {
+    if (data == null)
+      return;
+    try
+      {
+        if (!isChars(data))
+          throw new IllegalArgumentException("illegal XML character: " + data);
+        if (data.indexOf("--") != -1)
+          throw new IllegalArgumentException("illegal comment: " + data);
+
+        endStartElement();
+        
+        writer.write("<!--");
+        if (hasXML11RestrictedChars)
+          {
+            int[] seq = UnicodeReader.toCodePointArray(data);
+            for (int i = 0; i < seq.length; i++)
+              {
+                int c = seq[i];
+                if (XMLParser.isXML11RestrictedChar(c))
+                  writer.write("&#x" + Integer.toHexString(c) + ";");
+                else
+                  writer.write(Character.toChars(i));
+              }
+          }
+        else
+          writer.write(data);
+        writer.write("-->");
+      }
+    catch (IOException e)
+      {
+        XMLStreamException e2 = new XMLStreamException(e);
+        e2.initCause(e);
+        throw e2;
+      }
+  }
+
+  public void writeProcessingInstruction(String target)
+    throws XMLStreamException
+  {
+    writeProcessingInstruction(target, null);
+  }
+
+  public void writeProcessingInstruction(String target, String data)
+    throws XMLStreamException
+  {
+    try
+      {
+        if (!isName(target) || "xml".equalsIgnoreCase(target))
+          throw new IllegalArgumentException("illegal PITarget: " + target);
+        if (data != null && !isChars(data))
+          throw new IllegalArgumentException("illegal XML character: " + data);
+
+        endStartElement();
+
+        writer.write('<');
+        writer.write('?');
+        writer.write(target);
+        if (data != null)
+          {
+            writer.write(' ');
+            if (hasXML11RestrictedChars)
+              {
+                int[] seq = UnicodeReader.toCodePointArray(data);
+                for (int i = 0; i < seq.length; i++)
+                  {
+                    int c = seq[i];
+                    if (XMLParser.isXML11RestrictedChar(c))
+                      writer.write("&#x" + Integer.toHexString(c) + ";");
+                    else
+                      writer.write(Character.toChars(i));
+                  }
+              }
+            else
+              writer.write(data);
+          }
+        writer.write('?');
+        writer.write('>');
+      }
+    catch (IOException e)
+      {
+        XMLStreamException e2 = new XMLStreamException(e);
+        e2.initCause(e);
+        throw e2;
+      }
+  }
+
+  public void writeCData(String data)
+    throws XMLStreamException
+  {
+    try
+      {
+        if (!isChars(data) || hasXML11RestrictedChars)
+          throw new IllegalArgumentException("illegal XML character: " + data);
+        if (data.indexOf("]]") != -1)
+          throw new IllegalArgumentException("illegal CDATA section: " + data);
+        
+        endStartElement();
+
+        writer.write("<![CDATA[");
+        writer.write(data);
+        writer.write("]]>");
+      }
+    catch (IOException e)
+      {
+        XMLStreamException e2 = new XMLStreamException(e);
+        e2.initCause(e);
+        throw e2;
+      }
+  }
+
+  public void writeDTD(String dtd)
+    throws XMLStreamException
+  {
+    // Really thoroughly pointless method...
+    try
+      {
+        if (!isName(dtd))
+          throw new IllegalArgumentException("illegal Name: " + dtd);
+
+        writer.write("<!DOCTYPE ");
+        writer.write(dtd);
+        writer.write('>');
+      }
+    catch (IOException e)
+      {
+        XMLStreamException e2 = new XMLStreamException(e);
+        e2.initCause(e);
+        throw e2;
+      }
+  }
+
+  public void writeEntityRef(String name)
+    throws XMLStreamException
+  {
+    try
+      {
+        if (!isName(name))
+          throw new IllegalArgumentException("illegal Name: " + name);
+
+        endStartElement();
+
+        writer.write('&');
+        writer.write(name);
+        writer.write(';');
+      }
+    catch (IOException e)
+      {
+        XMLStreamException e2 = new XMLStreamException(e);
+        e2.initCause(e);
+        throw e2;
+      }
+  }
+
+  public void writeStartDocument()
+    throws XMLStreamException
+  {
+    writeStartDocument(null, null);
+  }
+
+  public void writeStartDocument(String version)
+    throws XMLStreamException
+  {
+    writeStartDocument(null, version);
+  }
+
+  public void writeStartDocument(String encoding, String version)
+    throws XMLStreamException
+  {
+    if (version == null)
+      version = "1.0";
+    else if ("1.1".equals(version))
+      xml11 = true;
+    encoding = this.encoding; // YES: the parameter must be ignored
+    if (encoding == null)
+      encoding = "UTF-8";
+    if (!"1.0".equals(version) && !"1.1".equals(version))
+      throw new IllegalArgumentException(version);
+    try
+      {
+        writer.write("<?xml version=\"");
+        writer.write(version);
+        writer.write("\" encoding=\"");
+        writer.write(encoding);
+        writer.write("\"?>");
+        writer.write(System.getProperty("line.separator"));
+      }
+    catch (IOException e)
+      {
+        XMLStreamException e2 = new XMLStreamException(e);
+        e2.initCause(e);
+        throw e2;
+      }
+  }
+
+  public void writeCharacters(String text)
+    throws XMLStreamException
+  {
+    if (text == null)
+      return;
+    try
+      {
+        if (!isChars(text))
+          throw new IllegalArgumentException("illegal XML character: " + text);
+
+        endStartElement();
+
+        if (hasXML11RestrictedChars)
+          writeEncodedWithRestrictedChars(text, false);
+        else
+          writeEncoded(text, false);
+      }
+    catch (IOException e)
+      {
+        XMLStreamException e2 = new XMLStreamException(e);
+        e2.initCause(e);
+        throw e2;
+      }
+  }
+
+  public void writeCharacters(char[] text, int start, int len)
+    throws XMLStreamException
+  {
+    writeCharacters(new String(text, start, len));
+  }
+
+  public String getPrefix(String uri)
+    throws XMLStreamException
+  {
+    String prefix = namespaces.getPrefix(uri);
+    if (prefix == null && namespaceContext != null)
+      prefix = namespaceContext.getPrefix(uri);
+    return prefix;
+  }
+
+  public void setPrefix(String prefix, String uri)
+    throws XMLStreamException
+  {
+    try
+      {
+        if (!isURI(uri))
+          throw new IllegalArgumentException("illegal URI: " + uri);
+        if (!isNCName(prefix))
+          throw new IllegalArgumentException("illegal NCName: " + prefix);
+      }
+    catch (IOException e)
+      {
+        XMLStreamException e2 = new XMLStreamException(e);
+        e2.initCause(e);
+        throw e2;
+      }
+    if (!namespaces.declarePrefix(prefix, uri))
+      throw new XMLStreamException("illegal prefix " + prefix);
+  }
+
+  public void setDefaultNamespace(String uri)
+    throws XMLStreamException
+  {
+    if (!isURI(uri))
+      throw new IllegalArgumentException("illegal URI: " + uri);
+    if (!namespaces.declarePrefix(XMLConstants.DEFAULT_NS_PREFIX, uri))
+      throw new XMLStreamException("illegal default namespace prefix");
+  }
+
+  public void setNamespaceContext(NamespaceContext context)
+    throws XMLStreamException
+  {
+    namespaceContext = context;
+  }
+
+  public NamespaceContext getNamespaceContext()
+  {
+    return namespaceContext;
+  }
+
+  public Object getProperty(String name)
+    throws IllegalArgumentException
+  {
+    throw new IllegalArgumentException(name);
+  }
+
+  /**
+   * Write the specified text, ensuring that the content is suitably encoded
+   * for XML.
+   * @param text the text to write
+   * @param inAttr whether we are in an attribute value
+   */
+  private void writeEncoded(String text, boolean inAttr)
+    throws IOException
+  {
+    char[] chars = text.toCharArray();
+    int start = 0;
+    int end = chars.length;
+    int len = 0;
+    for (int i = start; i < end; i++)
+      {
+        char c = chars[i];
+        if (c == '<' || c == '>' || c == '&')
+          {
+            writer.write(chars, start, len);
+            if (c == '<')
+              writer.write("<");
+            else if (c == '>')
+              writer.write(">");
+            else
+              writer.write("&");
+            start = i + 1;
+            len = 0;
+          }
+        else if (inAttr && (c == '"' || c == '\''))
+          {
+            writer.write(chars, start, len);
+            if (c == '"')
+              writer.write(""");
+            else
+              writer.write("'");
+            start = i + 1;
+            len = 0;
+          }
+        else
+          len++;
+      }
+    if (len > 0)
+      writer.write(chars, start, len);
+  }
+
+  /**
+   * Writes the specified text, in the knowledge that some of the
+   * characters are XML 1.1 restricted characters.
+   */
+  private void writeEncodedWithRestrictedChars(String text, boolean inAttr)
+    throws IOException
+  {
+    int[] seq = UnicodeReader.toCodePointArray(text);
+    for (int i = 0; i < seq.length; i++)
+      {
+        int c = seq[i];
+        switch (c)
+          {
+          case 0x3c: // '<'
+            writer.write("<");
+            break;
+          case 0x3e: // '>'
+            writer.write(">");
+            break;
+          case 0x26: // '&'
+            writer.write("&");
+            break;
+          case 0x22: // '"'
+            if (inAttr)
+              writer.write(""");
+            else
+              writer.write(c);
+            break;
+          case 0x27: // '\''
+            if (inAttr)
+              writer.write("'");
+            else
+              writer.write(c);
+            break;
+          default:
+            if (XMLParser.isXML11RestrictedChar(c))
+              writer.write("&#x" + Integer.toHexString(c) + ";");
+            else
+              {
+                char[] chars = Character.toChars(c);
+                writer.write(chars, 0, chars.length);
+              }
+          }
+      }
+  }
+
+  private boolean isName(String text)
+    throws IOException
+  {
+    if (text == null)
+      return false;
+    int[] seq = UnicodeReader.toCodePointArray(text);
+    if (seq.length < 1)
+      return false;
+    if (!XMLParser.isNameStartCharacter(seq[0], xml11))
+      return false;
+    for (int i = 1; i < seq.length; i++)
+      {
+        if (!XMLParser.isNameCharacter(seq[i], xml11))
+          return false;
+      }
+    return true;
+  }
+
+  private boolean isNCName(String text)
+    throws IOException
+  {
+    if (text == null)
+      return false;
+    int[] seq = UnicodeReader.toCodePointArray(text);
+    if (seq.length < 1)
+      return false;
+    if (!XMLParser.isNameStartCharacter(seq[0], xml11) || seq[0] == 0x3a)
+      return false;
+    for (int i = 1; i < seq.length; i++)
+      {
+        if (!XMLParser.isNameCharacter(seq[i], xml11) || seq[i] == 0x3a)
+          return false;
+      }
+    return true;
+  }
+
+  private boolean isChars(String text)
+    throws IOException
+  {
+    if (text == null)
+      return false;
+    int[] seq = UnicodeReader.toCodePointArray(text);
+    hasXML11RestrictedChars = false;
+    if (xml11)
+      {
+        for (int i = 0; i < seq.length; i++)
+          {
+            if (!XMLParser.isXML11Char(seq[i]))
+              return false;
+            if (XMLParser.isXML11RestrictedChar(seq[i]))
+              hasXML11RestrictedChars = true;
+          }
+      }
+    else
+      {
+        for (int i = 0; i < seq.length; i++)
+          {
+            if (!XMLParser.isChar(seq[i]))
+              return false;
+          }
+      }
+    return true;
+  }
+
+  private boolean isURI(String text)
+  {
+    if (text == null)
+      return false;
+    char[] chars = text.toCharArray();
+    if (chars.length < 1)
+      return false;
+    for (int i = 0; i < chars.length; i++)
+      {
+        if (chars[i] < 0x20 || chars[i] >= 0x7f)
+          return false;
+      }
+    return true;
+  }
+  
+}
+

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/AbstractNumberNode.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/AbstractNumberNode.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/AbstractNumberNode.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/AbstractNumberNode.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,328 @@
+/* AbstractNumberNode.java -- 
+   Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.xml.transform;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import javax.xml.namespace.QName;
+import javax.xml.transform.TransformerException;
+import org.w3c.dom.Document;
+import org.w3c.dom.DocumentFragment;
+import org.w3c.dom.Node;
+import org.w3c.dom.Text;
+import gnu.xml.xpath.Expr;
+
+/**
+ * A template node representing the XSL <code>number</code> instruction.
+ *
+ * @author <a href='mailto:dog at gnu.org'>Chris Burdess</a>
+ */
+abstract class AbstractNumberNode
+  extends TemplateNode
+{
+
+  static final int ALPHABETIC = 0;
+  static final int TRADITIONAL = 1;
+
+  final TemplateNode format;
+  final String lang;
+  final int letterValue;
+  final String groupingSeparator;
+  final int groupingSize;
+
+  AbstractNumberNode(TemplateNode format, String lang,
+                     int letterValue, String groupingSeparator,
+                     int groupingSize)
+  {
+    this.format = format;
+    this.lang = lang;
+    this.letterValue = letterValue;
+    this.groupingSeparator = groupingSeparator;
+    this.groupingSize = groupingSize;
+  }
+
+  void doApply(Stylesheet stylesheet, QName mode,
+               Node context, int pos, int len,
+               Node parent, Node nextSibling)
+    throws TransformerException
+  {
+    Document doc = (parent instanceof Document) ? (Document) parent :
+      parent.getOwnerDocument();
+    DocumentFragment fragment = doc.createDocumentFragment();
+    format.apply(stylesheet, mode, context, pos, len, fragment, null);
+    String f = Expr._string(context, Collections.singleton(fragment));
+    String value = format(f, compute(stylesheet, context, pos, len));
+    Text text = doc.createTextNode(value);
+    if (nextSibling != null)
+      {
+        parent.insertBefore(text, nextSibling);
+      }
+    else
+      {
+        parent.appendChild(text);
+      }
+    // xsl:number doesn't process children
+    if (next != null)
+      {
+        next.apply(stylesheet, mode, 
+                   context, pos, len,
+                   parent, nextSibling);
+      }
+  }
+
+  String format(String format, int[] number)
+  {
+    if (number.length == 0)
+      {
+        return "";
+      }
+    int start = 0, end = 0, len = format.length(); // region of format
+    // Tokenize
+    List tokens = new ArrayList((number.length * 2) + 1);
+    List types = new ArrayList(tokens.size());
+    while (end < len)
+      {
+        while (end < len && !isAlphanumeric(format.charAt(end)))
+          {
+            end++;
+          }
+        if (end > start)
+          {
+            tokens.add(format.substring(start, end));
+            types.add(Boolean.FALSE);
+          }
+        start = end;
+        while (end < len && isAlphanumeric(format.charAt(end)))
+          {
+            end++;
+          }
+        if (end > start)
+          {
+            tokens.add(format.substring(start, end));
+            types.add(Boolean.TRUE);
+          }
+        start = end;
+      }
+    // Process tokens
+    StringBuffer buf = new StringBuffer();
+    len = tokens.size();
+    int pos = 0;
+    for (int i = 0; i < len; i++)
+      {
+        String token = (i < 0) ? "." : (String) tokens.get(i);
+        boolean alpha = (i < 0) ? true : 
+          ((Boolean) types.get(i)).booleanValue();
+        if (!alpha)
+          {
+            buf.append(token);
+          }
+        else
+          {
+            if (pos < number.length)
+              {
+                format(buf, number[pos++], token);
+                if (((i + 1 == len) || (i + 2 == len)) &&
+                    (pos < number.length))
+                  {
+                    // More numbers than tokens, reuse last token
+                    i -= 2;
+                  }
+              }
+            if (pos == number.length && i < (len - 2))
+              {
+                // No more numbers. Skip to the end...
+                i = len - 2;
+                if (((Boolean) types.get(i + 1)).booleanValue())
+                  {
+                    // number formatting token, ignore
+                    i++;
+                  }
+              }
+          }
+      }
+    //System.err.println("format: '"+format+"' "+asList(number)+" = '"+buf.toString()+"'");
+    return buf.toString();
+  }
+
+  /*List asList(int[] number)
+    {
+      List l = new ArrayList();
+      for (int i = 0; i < number.length; i++)
+        l.add(new Integer(number[i]));
+      return l;
+    }*/
+
+  void format(StringBuffer buf, int number, String formatToken)
+  {
+    int len = formatToken.length();
+    char c = formatToken.charAt(len - 1);
+    if (Character.digit(c, 10) == 1)
+      {
+        // Check preceding characters
+        for (int i = len - 2; i >= 0; i--)
+          {
+            if (formatToken.charAt(i) != (c - 1))
+              {
+                format(buf, number, "1");
+                return;
+              }
+          }
+        // Decimal representation
+        String val = Integer.toString(number);
+        for (int d = len - val.length(); d > 0; d--)
+          {
+            buf.append('0');
+          }
+        buf.append(val);
+      }
+    else if ("A".equals(formatToken))
+      {
+        buf.append(alphabetic('@', number));
+      }
+    else if ("a".equals(formatToken))
+      {
+        buf.append(alphabetic('`', number));
+      }
+    else if ("i".equals(formatToken))
+      {
+        buf.append(roman(false, number));
+      }
+    else if ("I".equals(formatToken))
+      {
+        buf.append(roman(true, number));
+      }
+    else
+      {
+        // Unknown numbering sequence
+        format(buf, number, "1");
+      }
+  }
+
+  static final boolean isAlphanumeric(char c)
+  {
+    switch (Character.getType(c))
+      {
+      case Character.DECIMAL_DIGIT_NUMBER: // Nd
+      case Character.LETTER_NUMBER: // Nl
+      case Character.OTHER_NUMBER: // No
+      case Character.UPPERCASE_LETTER: // Lu
+      case Character.LOWERCASE_LETTER: // Ll
+      case Character.TITLECASE_LETTER: // Lt
+      case Character.MODIFIER_LETTER: // Lm
+      case Character.OTHER_LETTER: // Lo
+        return true;
+      default:
+        return false;
+      }
+  }
+
+  static final String alphabetic(char offset, int number)
+  {
+    StringBuffer buf = new StringBuffer();
+    while (number > 0)
+      {
+        int r = number % 26;
+        number = number / 26;
+        buf.insert(0, (char) (offset + r));
+      }
+    return buf.toString();
+  }
+
+  static final int[] roman_numbers = {1, 5, 10, 50, 100, 500, 1000};
+  static final char[] roman_chars = {'i', 'v', 'x', 'l', 'c', 'd', 'm'};
+
+  static final String roman(boolean upper, int number)
+  {
+    StringBuffer buf = new StringBuffer();
+    for (int pos = roman_numbers.length - 1; pos >= 0; pos -= 2)
+      {
+        int f = number / roman_numbers[pos];
+        if (f != 0)
+          {
+            number = number % (f * roman_numbers[pos]);
+          }
+        if (f > 4 && f < 9)
+          {
+            buf.append(roman_chars[pos + 1]);
+            f -= 5;
+          }
+        if (f == 4)
+          {
+            buf.append(roman_chars[pos]);
+            buf.append(roman_chars[pos + 1]);
+          }
+        else if (f == 9)
+          {
+            buf.append(roman_chars[pos]);
+            buf.append(roman_chars[pos + 2]);
+          }
+        else
+          {
+            for (; f > 0; f--)
+              {
+                buf.append(roman_chars[pos]);
+              }
+          }
+      }
+    return upper ? buf.toString().toUpperCase() : buf.toString();
+  }
+  
+  abstract int[] compute(Stylesheet stylesheet, Node context, int pos, int len)
+    throws TransformerException;
+
+  public boolean references(QName var)
+  {
+    if (format.references(var))
+      {
+        return true;
+      }
+    return super.references(var);
+  }
+
+  public String toString()
+  {
+    StringBuffer buf = new StringBuffer("number");
+    buf.append('[');
+    buf.append("format=");
+    buf.append(format);
+    buf.append(']');
+    return buf.toString();
+  }
+
+}

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/ApplyImportsNode.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/ApplyImportsNode.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/ApplyImportsNode.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/ApplyImportsNode.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,83 @@
+/* ApplyImportsNode.java -- 
+   Copyright (C) 2004,2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.xml.transform;
+
+import javax.xml.namespace.QName;
+import javax.xml.transform.TransformerException;
+import org.w3c.dom.Node;
+
+/**
+ * A template node representing an XSLT <code>apply-imports</code> instruction.
+ *
+ * @author <a href='mailto:dog at gnu.org'>Chris Burdess</a>
+ */
+final class ApplyImportsNode
+  extends TemplateNode
+{
+
+  TemplateNode clone(Stylesheet stylesheet)
+  {
+    TemplateNode ret = new ApplyImportsNode();
+    if (children != null)
+      ret.children = children.clone(stylesheet);
+    if (next != null)
+      ret.next = next.clone(stylesheet);
+    return ret;
+  }
+  
+  void doApply(Stylesheet stylesheet, QName mode,
+             Node context, int pos, int len,
+             Node parent, Node nextSibling)
+    throws TransformerException
+  {
+    TemplateNode t = stylesheet.getTemplate(mode, context, true);
+    if (t != null)
+      t.apply(stylesheet, mode, context, pos, len,
+              parent, nextSibling);
+    if (next != null)
+      next.apply(stylesheet, mode, context, pos, len,
+                 parent, nextSibling);
+  }
+
+  public String toString()
+  {
+    return "apply-imports";
+  }
+
+}
+

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/ApplyTemplatesNode.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/ApplyTemplatesNode.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/ApplyTemplatesNode.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/ApplyTemplatesNode.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,217 @@
+/* ApplyTemplatesNode.java -- 
+   Copyright (C) 2004,2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.xml.transform;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.List;
+import javax.xml.namespace.QName;
+import javax.xml.transform.TransformerException;
+import org.w3c.dom.Node;
+import gnu.xml.xpath.Expr;
+
+/**
+ * A template node representing the XSL <code>apply-templates</code>
+ * instruction.
+ *
+ * @author <a href='mailto:dog at gnu.org'>Chris Burdess</a>
+ */
+final class ApplyTemplatesNode
+  extends TemplateNode
+{
+
+  final Expr select;
+  final QName mode;
+  final List sortKeys;
+  final List withParams;
+  final boolean isDefault;
+
+  ApplyTemplatesNode(Expr select, QName mode,
+                     List sortKeys, List withParams, boolean isDefault)
+  {
+    this.select = select;
+    this.mode = mode;
+    this.sortKeys = sortKeys;
+    this.withParams = withParams;
+    this.isDefault = isDefault;
+  }
+
+  TemplateNode clone(Stylesheet stylesheet)
+  {
+    int len = sortKeys != null ? sortKeys.size() : 0;
+    List sortKeys2 = new ArrayList(len);
+    for (int i = 0; i < len; i++)
+      sortKeys2.add(((Key) sortKeys.get(i)).clone(stylesheet));
+    len = withParams != null ? withParams.size() : 0;
+    List withParams2 = new ArrayList(len);
+    for (int i = 0; i < len; i++)
+      withParams2.add(((WithParam) withParams.get(i)).clone(stylesheet));
+    TemplateNode ret = new ApplyTemplatesNode(select.clone(stylesheet),
+                                              mode, sortKeys2, withParams2,
+                                              isDefault);
+    if (children != null)
+      ret.children = children.clone(stylesheet);
+    if (next != null)
+      ret.next = next.clone(stylesheet);
+    return ret;
+  }
+
+  void doApply(Stylesheet stylesheet, QName mode,
+               Node context, int pos, int len,
+               Node parent, Node nextSibling)
+    throws TransformerException
+  {
+    Object ret = select.evaluate(context, pos, len);
+    if (ret != null && ret instanceof Collection)
+      {
+        if (withParams != null)
+          {
+            // compute the parameter values
+            LinkedList values = new LinkedList();
+            for (Iterator i = withParams.iterator(); i.hasNext(); )
+              {
+                WithParam p = (WithParam) i.next();
+                Object value = p.getValue(stylesheet, mode, context, pos, len);
+                Object[] pair = new Object[2];
+                pair[0] = p.name;
+                pair[1] = value;
+                values.add(pair);
+              }
+            // push the parameter context
+            stylesheet.bindings.push(Bindings.WITH_PARAM);
+            // set the parameters
+            for (Iterator i = values.iterator(); i.hasNext(); )
+              {
+                Object[] pair = (Object[]) i.next();
+                QName name = (QName) pair[0];
+                Object value = pair[1];
+                stylesheet.bindings.set(name, value, Bindings.WITH_PARAM);
+              }
+          }
+        Collection ns = (Collection) ret;
+        List nodes = new ArrayList(ns);
+        if (sortKeys != null)
+          {
+            for (Iterator i = sortKeys.iterator(); i.hasNext(); )
+              {
+                SortKey sortKey = (SortKey) i.next();
+                sortKey.init(stylesheet, mode, context, pos, len, parent,
+                             nextSibling);
+              }
+            Collections.sort(nodes, new XSLComparator(sortKeys));
+          }
+        else
+          Collections.sort(nodes, documentOrderComparator);
+        int l = nodes.size();
+        QName effectiveMode = isDefault ? mode : this.mode;
+        for (int i = 0; i < l; i++)
+          {
+            Node node = (Node) nodes.get(i);
+            TemplateNode t = stylesheet.getTemplate(effectiveMode, node,
+                                                    false);
+            if (t != null)
+              {
+                stylesheet.current = node;
+                t.apply(stylesheet, effectiveMode, node, i + 1, l,
+                        parent, nextSibling);
+              }
+          }
+        if (withParams != null)
+          {
+            // pop the variable context
+            stylesheet.bindings.pop(Bindings.WITH_PARAM);
+          }
+      }
+    // apply-templates doesn't have processable children
+    if (next != null)
+      next.apply(stylesheet, mode,
+                 context, pos, len,
+                 parent, nextSibling);
+  }
+
+  public boolean references(QName var)
+  {
+    if (select != null && select.references(var))
+      return true;
+    if (withParams != null)
+      {
+        for (Iterator i = withParams.iterator(); i.hasNext(); )
+          {
+            if (((WithParam) i.next()).references(var))
+              return true;
+          }
+      }
+    if (sortKeys != null)
+      {
+        for (Iterator i = sortKeys.iterator(); i.hasNext(); )
+          {
+            if (((SortKey) i.next()).references(var))
+              return true;
+          }
+      }
+    return super.references(var);
+  }
+  
+  public String toString()
+  {
+    StringBuffer buf = new StringBuffer("apply-templates");
+    buf.append('[');
+    boolean o = false;
+    if (select != null)
+      {
+        buf.append("select=");
+        buf.append(select);
+        o = true;
+      }
+    if (mode != null)
+      {
+        if (o)
+          {
+            buf.append(',');
+          }
+        buf.append("mode=");
+        buf.append(mode);
+      }
+    buf.append(']');
+    return buf.toString();
+  }
+  
+}

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/AttributeNode.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/AttributeNode.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/AttributeNode.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/AttributeNode.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,242 @@
+/* AttributeNode.java -- 
+   Copyright (C) 2004,2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.xml.transform;
+
+import javax.xml.XMLConstants;
+import javax.xml.namespace.QName;
+import javax.xml.transform.TransformerException;
+import org.w3c.dom.Document;
+import org.w3c.dom.DocumentFragment;
+import org.w3c.dom.Attr;
+import org.w3c.dom.NamedNodeMap;
+import org.w3c.dom.Node;
+import gnu.xml.xpath.Expr;
+
+/**
+ * A template node representing an XSL <code>attribute</code> instruction.
+ *
+ * @author <a href='mailto:dog at gnu.org'>Chris Burdess</a>
+ */
+final class AttributeNode
+  extends TemplateNode
+{
+
+  final TemplateNode name;
+  final TemplateNode namespace;
+  final Node source;
+  
+  AttributeNode(TemplateNode name,
+                TemplateNode namespace, Node source)
+  {
+    this.name = name;
+    this.namespace = namespace;
+    this.source = source;
+  }
+
+  TemplateNode clone(Stylesheet stylesheet)
+  {
+    TemplateNode ret = new AttributeNode(name.clone(stylesheet),
+                                         (namespace == null) ? null :
+                                         namespace.clone(stylesheet),
+                                         source);
+    if (children != null)
+      ret.children = children.clone(stylesheet);
+    if (next != null)
+      ret.next = next.clone(stylesheet);
+    return ret;
+  }
+
+  void doApply(Stylesheet stylesheet, QName mode,
+               Node context, int pos, int len,
+               Node parent, Node nextSibling)
+    throws TransformerException
+  {
+    Document doc = (parent instanceof Document) ? (Document) parent :
+      parent.getOwnerDocument();
+    // Create a document fragment to hold the name
+    DocumentFragment fragment = doc.createDocumentFragment();
+    // Apply name to the fragment
+    name.apply(stylesheet, mode,
+               context, pos, len,
+               fragment, null);
+    // Use XPath string-value of fragment
+    String nameValue = Expr.stringValue(fragment);
+  
+    String namespaceValue = null;
+    if (namespace != null)
+      {  
+        // Create a document fragment to hold the namespace
+        fragment = doc.createDocumentFragment();
+        // Apply namespace to the fragment
+        namespace.apply(stylesheet, mode,
+                        context, pos, len,
+                        fragment, null);
+        // Use XPath string-value of fragment
+        namespaceValue = Expr.stringValue(fragment);
+        if (namespaceValue.length() == 0)
+          namespaceValue = null;
+      }
+    
+    String prefix = getPrefix(nameValue);
+    if (namespaceValue == null)
+      {
+        if (prefix != null)
+          {
+            if (XMLConstants.XML_NS_PREFIX.equals(prefix))
+              namespaceValue = XMLConstants.XML_NS_URI;
+            else
+              {
+                // Resolve namespace for this prefix
+                namespaceValue = source.lookupNamespaceURI(prefix);
+              }
+          }
+      }
+    else
+      {
+        if (prefix != null)
+          {
+            String ns2 = source.lookupNamespaceURI(prefix);
+            if (ns2 != null && !ns2.equals(namespaceValue))
+              {
+                // prefix clashes, reset it
+                prefix = null;
+                int ci = nameValue.indexOf(':');
+                nameValue = nameValue.substring(ci + 1);
+              }
+          }
+      }
+    if (prefix == null)
+      {
+        // Resolve prefix for this namespace
+        prefix = source.lookupPrefix(namespaceValue);
+        if (prefix != null)
+          nameValue = prefix + ":" + nameValue;
+        else
+          {
+            if (namespaceValue != null)
+              {
+                // Must invent a prefix
+                prefix = inventPrefix(parent);
+                nameValue = prefix + ":" + nameValue;
+              }
+          }
+      }
+    NamedNodeMap attrs = parent.getAttributes();
+    boolean insert = true;
+    if (XMLConstants.XMLNS_ATTRIBUTE_NS_URI.equals(namespaceValue) ||
+        XMLConstants.XMLNS_ATTRIBUTE.equals(nameValue) ||
+        nameValue.startsWith("xmlns:"))
+      {
+        // Namespace declaration, do not output
+        insert = false;
+      }
+    if (prefix != null && namespaceValue == null)
+      {
+        // Not a QName
+        insert = false;
+      }
+    if (parent.getNodeType() == Node.ELEMENT_NODE &&
+        parent.getFirstChild() != null)
+      {
+        // XSLT 7.1.3 Adding an attribute to an element after children have
+        // been added to it is an error
+        insert = false;
+      }
+    if (insert)
+      {
+        // Insert attribute
+        Attr attr = (namespaceValue != null) ?
+          doc.createAttributeNS(namespaceValue, nameValue) :
+              doc.createAttribute(nameValue);
+        if (attrs != null)
+          {
+            if (namespace != null)
+              attrs.setNamedItemNS(attr);
+            else
+              attrs.setNamedItem(attr);
+          }
+        if (children != null)
+          children.apply(stylesheet, mode,
+                         context, pos, len,
+                         attr, null);
+      }
+    if (next != null)
+      next.apply(stylesheet, mode,
+                 context, pos, len,
+                 parent, nextSibling);
+  }
+
+  final String getPrefix(String name)
+  {
+    int ci = name.indexOf(':');
+    return (ci == -1) ? null : name.substring(0, ci);
+  }
+
+  final String inventPrefix(Node parent)
+  {
+    String base = "ns";
+    int count = 0;
+    String ret = base + Integer.toString(count);
+    while (parent.lookupNamespaceURI(ret) != null)
+      {
+        count++;
+        ret = base + Integer.toString(count);
+      }
+    return ret;
+  }
+
+  public boolean references(QName var)
+  {
+    if (name != null && name.references(var))
+      return true;
+    if (namespace != null && namespace.references(var))
+      return true;
+    return super.references(var);
+  }
+  
+  public String toString()
+  {
+    StringBuffer buf = new StringBuffer("attribute");
+    buf.append('[');
+    buf.append("name=");
+    buf.append(name);
+    buf.append(']');
+    return buf.toString();
+  }
+  
+}

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/AttributeSet.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/AttributeSet.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/AttributeSet.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/AttributeSet.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,67 @@
+/* AttributeSet.java -- 
+   Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.xml.transform;
+
+/**
+ * An attribute-set entry in a stylesheet.
+ *
+ * @author <a href='mailto:dog at gnu.org'>Chris Burdess</a>
+ */
+final class AttributeSet
+{
+
+  final TemplateNode children;
+  final String name;
+  final String uas;
+
+  AttributeSet(TemplateNode children, String name, String uas)
+  {
+    this.children = children;
+    this.name = name;
+    this.uas = uas;
+  }
+
+  AttributeSet clone(Stylesheet stylesheet)
+  {
+    return new AttributeSet((children == null) ? null :
+                            children.clone(stylesheet),
+                            name, uas);
+  }
+  
+}
+

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/Bindings.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/Bindings.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/Bindings.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/Bindings.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,347 @@
+/* Bindings.java -- 
+   Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.xml.transform;
+
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.Map;
+import javax.xml.namespace.QName;
+import javax.xml.xpath.XPathVariableResolver;
+import org.w3c.dom.Node;
+
+/**
+ * The set of variable bindings in effect for a stylesheet.
+ *
+ * @author <a href='mailto:dog at gnu.org'>Chris Burdess</a>
+ */
+public class Bindings
+  implements XPathVariableResolver, Cloneable
+{
+
+  static final int VARIABLE = 0;
+  static final int PARAM = 1;
+  static final int WITH_PARAM = 2;
+
+  final Stylesheet stylesheet;
+
+  /**
+   * Global variables.
+   */
+  final LinkedList variables;
+
+  /**
+   * Parameter value stack.
+   */
+  final LinkedList parameters;
+
+  /**
+   * Argument (with-param) value stack.
+   */
+  final LinkedList withParameters;
+
+  /**
+   * Only search globals.
+   */
+  boolean global;
+
+  Bindings(Stylesheet stylesheet)
+  {
+    this.stylesheet = stylesheet;
+    variables = new LinkedList();
+    parameters = new LinkedList();
+    withParameters = new LinkedList();
+    for (int i = 0; i < 3; i++)
+      {
+        push(i);
+      }
+  }
+
+  public Object clone()
+  {
+    try
+      {
+        return (Bindings) super.clone();
+      }
+    catch (CloneNotSupportedException e)
+      {
+        throw new Error(e.getMessage());
+      }
+  }
+
+  void push(int type)
+  {
+    switch (type)
+      {
+      case VARIABLE:
+        variables.addFirst(new HashMap());
+        break;
+      case PARAM:
+        parameters.addFirst(new HashMap());
+        break;
+      case WITH_PARAM:
+        withParameters.addFirst(new HashMap());
+        break;
+      }
+  }
+
+  void pop(int type)
+  {
+    switch (type)
+      {
+      case VARIABLE:
+        variables.removeFirst();
+        break;
+      case PARAM:
+        parameters.removeFirst();
+        break;
+      case WITH_PARAM:
+        withParameters.removeFirst();
+        break;
+      }
+  }
+
+  public boolean containsKey(QName name, int type)
+  {
+    if (global)
+      {
+        Map ctx1 = (Map) variables.getLast();
+        Map ctx2 = (Map) parameters.getLast();
+        return (ctx1.containsKey(name) || ctx2.containsKey(name));
+      }
+    Iterator i = null;
+    switch (type)
+      {
+      case VARIABLE:
+        i = variables.iterator();
+        break;
+      case PARAM:
+        i = parameters.iterator();
+        break;
+      case WITH_PARAM:
+        Map ctx = (Map) withParameters.getFirst();
+        return ctx.containsKey(name);
+      }
+    if (i != null)
+      {
+        while (i.hasNext())
+          {
+            Map ctx = (Map) i.next();
+            if (ctx.containsKey(name))
+              {
+                return true;
+              }
+          }
+      }
+    return false;
+  }
+
+  public Object get(QName name, Node context, int pos, int len)
+  {
+    if (global)
+      {
+        Map ctx = (Map) variables.getLast();
+        Object ret = ctx.get(name);
+        if (ret == null)
+          {
+            ctx = (Map) parameters.getLast();
+            ret = ctx.get(name);
+          }
+        return ret;
+      }
+    //System.err.println("bindings.get: "+name);
+    //System.err.println("\t"+toString());
+    Object ret = null;
+    //if (parameters.size() > 1 && containsKey(name, PARAM))
+      // check that template defines parameter
+      {
+        Map cwp = (Map) withParameters.getFirst();
+        ret = cwp.get(name);
+        //System.err.println("\twith-param: ret="+ret);
+      }
+    if (ret == null)
+      {
+        for (Iterator i = variables.iterator(); i.hasNext() && ret == null; )
+          {
+            Map vctx = (Map) i.next();
+            ret = vctx.get(name);
+          }
+        //System.err.println("\tvariable: ret="+ret);
+      }
+    if (ret == null)
+      {
+        for (Iterator i = parameters.iterator(); i.hasNext() && ret == null; )
+          {
+            Map pctx = (Map) i.next();
+            ret = pctx.get(name);
+          }
+        //System.err.println("\tparam: ret="+ret);
+      }
+    /*if (ret instanceof Expr && context != null)
+      {
+        Expr expr = (Expr) ret;
+        ret = expr.evaluate(context, 1, 1);
+      }*/
+    if (ret instanceof Node)
+      {
+        ret = Collections.singleton(ret);
+      }
+    if (ret == null)
+      {
+        ret = "";
+      }
+    //System.err.println("\tret="+ret);
+    return ret;
+  }
+
+  void set(QName name, Object value, int type)
+  {
+    switch (type)
+      {
+      case VARIABLE:
+        Map vctx = (Map) variables.getFirst();
+        vctx.put(name, value);
+        break;
+      case PARAM:
+        Map pctx = (Map) parameters.getFirst();
+        pctx.put(name, value);
+        break;
+      case WITH_PARAM:
+        Map wctx = (Map) withParameters.getFirst();
+        wctx.put(name, value);
+        break;
+      }
+    //System.err.println("Set "+name+"="+value);
+  }
+
+  public Object resolveVariable(QName qName)
+  {
+    return get(qName, null, 1, 1);
+  }
+  
+  public String toString()
+  {
+    StringBuffer buf = new StringBuffer();
+    boolean next = false;
+    Collection seen = new HashSet();
+    Map wctx = (Map) withParameters.getFirst();
+    buf.append('(');
+    for (Iterator i = wctx.entrySet().iterator(); i.hasNext(); )
+      {
+        if (next)
+          {
+            buf.append(',');
+          }
+        else
+          {
+            next = true;
+          }
+        Map.Entry entry = (Map.Entry) i.next();
+        Object key = entry.getKey();
+        if (!seen.contains(key))
+          {
+            buf.append(key);
+            buf.append('=');
+            buf.append(entry.getValue());
+            seen.add(key);
+          }
+      }
+    buf.append(')');
+    next = false;
+    seen.clear();
+    buf.append('{');
+    for (Iterator i = variables.iterator(); i.hasNext(); )
+      {
+        Map ctx = (Map) i.next();
+        for (Iterator j = ctx.entrySet().iterator(); j.hasNext(); )
+          {
+            if (next)
+              {
+                buf.append(',');
+              }
+            else
+              {
+                next = true;
+              }
+            Map.Entry entry = (Map.Entry) j.next();
+            Object key = entry.getKey();
+            if (!seen.contains(key))
+              {
+                buf.append(key);
+                buf.append('=');
+                buf.append(entry.getValue());
+                seen.add(key);
+              }
+          } 
+      }
+    buf.append('}');
+    next = false;
+    seen.clear();
+    buf.append('[');
+    for (Iterator i = parameters.iterator(); i.hasNext(); )
+      {
+        Map ctx = (Map) i.next();
+        for (Iterator j = ctx.entrySet().iterator(); j.hasNext(); )
+          {
+            if (next)
+              {
+                buf.append(',');
+              }
+            else
+              {
+                next = true;
+              }
+            Map.Entry entry = (Map.Entry) j.next();
+            Object key = entry.getKey();
+            if (!seen.contains(key))
+              {
+                buf.append(key);
+                buf.append('=');
+                buf.append(entry.getValue());
+                seen.add(key);
+              }
+          } 
+      }
+    buf.append(']');
+    return buf.toString();
+  }
+
+}

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/CallTemplateNode.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/CallTemplateNode.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/CallTemplateNode.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/CallTemplateNode.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,157 @@
+/* CallTemplateNode.java -- 
+   Copyright (C) 2004,2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.xml.transform;
+
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.List;
+import javax.xml.namespace.QName;
+import javax.xml.transform.TransformerException;
+import org.w3c.dom.Node;
+
+/**
+ * A template node representing the XSL <code>call-template</code>
+ * instruction.
+ *
+ * @author <a href='mailto:dog at gnu.org'>Chris Burdess</a>
+ */
+final class CallTemplateNode
+  extends TemplateNode
+{
+
+  final QName name;
+  final List withParams;
+
+  CallTemplateNode(QName name, List withParams)
+  {
+    this.name = name;
+    this.withParams = withParams;
+  }
+
+  TemplateNode clone(Stylesheet stylesheet)
+  {
+    int len = withParams.size();
+    List withParams2 = new ArrayList(len);
+    for (int i = 0; i < len; i++)
+      withParams2.add(((WithParam) withParams.get(i)).clone(stylesheet));
+    TemplateNode ret = new CallTemplateNode(name, withParams2);
+    if (children != null)
+      ret.children = children.clone(stylesheet);
+    if (next != null)
+      ret.next = next.clone(stylesheet);
+    return ret;
+  }
+
+  void doApply(Stylesheet stylesheet, QName mode,
+               Node context, int pos, int len,
+               Node parent, Node nextSibling)
+    throws TransformerException
+  {
+    TemplateNode t = stylesheet.getTemplate(mode, name);
+    if (t != null)
+      {
+        if (withParams != null)
+          {
+            // compute the parameter values
+            LinkedList values = new LinkedList();
+            for (Iterator i = withParams.iterator(); i.hasNext(); )
+              {
+                WithParam p = (WithParam) i.next();
+                if (t.hasParam(p.name)) // ignore parameters not specified
+                  {
+                    Object value = p.getValue(stylesheet, mode, context,
+                                              pos, len);
+                    Object[] pair = new Object[2];
+                    pair[0] = p.name;
+                    pair[1] = value;
+                    values.add(pair);
+                  }
+              }
+            // push the parameter context
+            stylesheet.bindings.push(Bindings.WITH_PARAM);
+            // set the parameters
+            for (Iterator i = values.iterator(); i.hasNext(); )
+              {
+                Object[] pair = (Object[]) i.next();
+                QName name = (QName) pair[0];
+                Object value = pair[1];
+                stylesheet.bindings.set(name, value, Bindings.WITH_PARAM);
+                if (stylesheet.debug)
+                  System.err.println("with-param: " + name + " = " + value);
+              }
+          }
+        t.apply(stylesheet, mode, context, pos, len,
+                parent, nextSibling);
+        if (withParams != null)
+          {
+            // pop the variable context
+            stylesheet.bindings.pop(Bindings.WITH_PARAM);
+          }
+      }
+    // call-template doesn't have processable children
+    if (next != null)
+        next.apply(stylesheet, mode,
+                   context, pos, len,
+                   parent, nextSibling);
+  }
+  
+  public boolean references(QName var)
+  {
+    if (withParams != null)
+      {
+        for (Iterator i = withParams.iterator(); i.hasNext(); )
+          {
+            if (((WithParam) i.next()).references(var))
+              return true;
+          }
+      }
+    return super.references(var);
+  }
+  
+  public String toString()
+  {
+    StringBuffer buf = new StringBuffer("call-template");
+    buf.append('[');
+    buf.append("name=");
+    buf.append(name);
+    buf.append(']');
+    return buf.toString();
+  }
+  
+}

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/ChooseNode.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/ChooseNode.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/ChooseNode.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/ChooseNode.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,86 @@
+/* ChooseNode.java -- 
+   Copyright (C) 2004,2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.xml.transform;
+
+import javax.xml.namespace.QName;
+import javax.xml.transform.TransformerException;
+import org.w3c.dom.Node;
+
+/**
+ * A template node representing an XSL <code>choose</code> instruction.
+ *
+ * @author <a href='mailto:dog at gnu.org'>Chris Burdess</a>
+ */
+final class ChooseNode
+  extends TemplateNode
+{
+
+  TemplateNode clone(Stylesheet stylesheet)
+  {
+    TemplateNode ret = new ChooseNode();
+    if (children != null)
+      ret.children = children.clone(stylesheet);
+    if (next != null)
+      ret.next = next.clone(stylesheet);
+    return ret;
+  }
+
+  void doApply(Stylesheet stylesheet, QName mode,
+               Node context, int pos, int len,
+               Node parent, Node nextSibling)
+    throws TransformerException
+  {
+    if (children != null)
+      children.apply(stylesheet, mode,
+                     context, pos, len,
+                     parent, nextSibling);
+    if (next != null)
+      next.apply(stylesheet, mode,
+                 context, pos, len,
+                 parent, nextSibling);
+  }
+  
+  public String toString()
+  {
+    StringBuffer buf = new StringBuffer("choose");
+    buf.append('[');
+    buf.append(']');
+    return buf.toString();
+  }
+  
+}

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/CommentNode.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/CommentNode.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/CommentNode.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/CommentNode.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,103 @@
+/* CommentNode.java -- 
+   Copyright (C) 2004,2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.xml.transform;
+
+import javax.xml.namespace.QName;
+import javax.xml.transform.TransformerException;
+import org.w3c.dom.Comment;
+import org.w3c.dom.Document;
+import org.w3c.dom.DocumentFragment;
+import org.w3c.dom.Node;
+import gnu.xml.xpath.Expr;
+
+/**
+ * A template node representing the XSL <code>comment</code> instruction.
+ *
+ * @author <a href='mailto:dog at gnu.org'>Chris Burdess</a>
+ */
+final class CommentNode
+  extends TemplateNode
+{
+
+  TemplateNode clone(Stylesheet stylesheet)
+  {
+    TemplateNode ret = new CommentNode();
+    if (children != null)
+      ret.children = children.clone(stylesheet);
+    if (next != null)
+      ret.next = next.clone(stylesheet);
+    return ret;
+  }
+
+  void doApply(Stylesheet stylesheet, QName mode,
+               Node context, int pos, int len,
+               Node parent, Node nextSibling)
+    throws TransformerException
+  {
+    String value = "";
+    Document doc = (parent instanceof Document) ? (Document) parent :
+      parent.getOwnerDocument();
+    if (children != null)
+      {
+        // Create a document fragment to hold the text
+        DocumentFragment fragment = doc.createDocumentFragment();
+        // Apply children to the fragment
+        children.apply(stylesheet, mode,
+                       context, pos, len,
+                       fragment, null);
+        // Use XPath string-value of fragment
+        value = Expr.stringValue(fragment);
+      }
+    Comment comment = doc.createComment(value);
+    // Insert into result tree
+    if (nextSibling != null)
+      parent.insertBefore(comment, nextSibling);
+    else
+      parent.appendChild(comment);
+    if (next != null)
+      next.apply(stylesheet, mode,
+                 context, pos, len,
+                 parent, nextSibling);
+  }
+  
+  public String toString()
+  {
+    return "comment";
+  }
+  
+}

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/CopyNode.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/CopyNode.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/CopyNode.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/CopyNode.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,166 @@
+/* CopyNode.java -- 
+   Copyright (C) 2004,2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.xml.transform;
+
+import java.util.Iterator;
+import java.util.StringTokenizer;
+import javax.xml.namespace.QName;
+import javax.xml.transform.TransformerException;
+import org.w3c.dom.Document;
+import org.w3c.dom.NamedNodeMap;
+import org.w3c.dom.Node;
+
+/**
+ * A template node representing the XSL <code>copy</code> instruction.
+ *
+ * @author <a href='mailto:dog at gnu.org'>Chris Burdess</a>
+ */
+final class CopyNode
+  extends TemplateNode
+{
+
+  final String uas;
+
+  CopyNode(String uas)
+  {
+    this.uas = uas;
+  }
+
+  TemplateNode clone(Stylesheet stylesheet)
+  {
+    TemplateNode ret = new CopyNode(uas);
+    if (children != null)
+      ret.children = children.clone(stylesheet);
+    if (next != null)
+      ret.next = next.clone(stylesheet);
+    return ret;
+  }
+
+  void doApply(Stylesheet stylesheet, QName mode,
+               Node context, int pos, int len,
+               Node parent, Node nextSibling)
+    throws TransformerException
+  {
+    Node copy = parent;
+    switch (context.getNodeType())
+      {
+      case Node.TEXT_NODE:
+      case Node.ATTRIBUTE_NODE:
+      case Node.ELEMENT_NODE:
+      case Node.PROCESSING_INSTRUCTION_NODE:
+      case Node.COMMENT_NODE:
+        Document doc = (parent instanceof Document) ? (Document) parent :
+          parent.getOwnerDocument();
+        copy = context.cloneNode(false);
+        copy = doc.adoptNode(copy);
+        if (copy.getNodeType() == Node.ATTRIBUTE_NODE)
+          {
+            if (parent.getFirstChild() != null)
+              {
+                // Ignore attempt to add attribute after children
+              }
+            else
+              {
+                NamedNodeMap attrs = parent.getAttributes();
+                if (attrs != null)
+                  attrs.setNamedItemNS(copy);
+              }
+          }
+        else
+          {
+            if (nextSibling != null)
+              parent.insertBefore(copy, nextSibling);
+            else
+              parent.appendChild(copy);
+          }
+      }
+    if (uas != null)
+      {
+        StringTokenizer st = new StringTokenizer(uas, " ");
+        while (st.hasMoreTokens())
+          addAttributeSet(stylesheet, mode, context, pos, len,
+                          copy, null, st.nextToken());
+      }
+    if (children != null)
+      children.apply(stylesheet, mode,
+                     context, pos, len,
+                     copy, null);
+    if (next != null)
+      next.apply(stylesheet, mode,
+                 context, pos, len,
+                 parent, nextSibling);
+  }
+  
+  void addAttributeSet(Stylesheet stylesheet, QName mode,
+                       Node context, int pos, int len,
+                       Node parent, Node nextSibling, String attributeSet)
+    throws TransformerException
+  {
+    for (Iterator i = stylesheet.attributeSets.iterator(); i.hasNext(); )
+      {
+        AttributeSet as = (AttributeSet) i.next();
+        if (!as.name.equals(attributeSet))
+          continue;
+        if (as.uas != null)
+          {
+            StringTokenizer st = new StringTokenizer(as.uas, " ");
+            while (st.hasMoreTokens())
+              addAttributeSet(stylesheet, mode, context, pos, len,
+                              parent, nextSibling, st.nextToken());
+          }
+        if (as.children != null)
+          as.children.apply(stylesheet, mode,
+                            context, pos, len,
+                            parent, nextSibling);
+      }
+  }
+
+  public String toString()
+  {
+    StringBuffer buf = new StringBuffer("copy");
+    if (uas != null)
+      {
+        buf.append('[');
+        buf.append("uas=");
+        buf.append(uas);
+        buf.append(']');
+      }
+    return buf.toString();
+  }
+
+}

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/CopyOfNode.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/CopyOfNode.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/CopyOfNode.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/CopyOfNode.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,172 @@
+/* CopyOfNode.java -- 
+   Copyright (C) 2004,2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.xml.transform;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Iterator;
+import java.util.List;
+import javax.xml.namespace.QName;
+import javax.xml.transform.TransformerException;
+import org.w3c.dom.Document;
+import org.w3c.dom.NamedNodeMap;
+import org.w3c.dom.Node;
+import org.w3c.dom.Text;
+import gnu.xml.xpath.Expr;
+
+/**
+ * A template node representing an XSLT <code>copy-of</code> instruction.
+ *
+ * @author <a href='mailto:dog at gnu.org'>Chris Burdess</a>
+ */
+final class CopyOfNode
+  extends TemplateNode
+{
+
+  final Expr select;
+
+  CopyOfNode(Expr select)
+  {
+    this.select = select;
+  }
+
+  TemplateNode clone(Stylesheet stylesheet)
+  {
+    TemplateNode ret = new CopyOfNode(select.clone(stylesheet));
+    if (children != null)
+      ret.children = children.clone(stylesheet);
+    if (next != null)
+      ret.next = next.clone(stylesheet);
+    return ret;
+  }
+
+  void doApply(Stylesheet stylesheet, QName mode,
+               Node context, int pos, int len,
+               Node parent, Node nextSibling)
+    throws TransformerException
+  {
+    Object ret = select.evaluate(context, pos, len);
+    Document doc = (parent instanceof Document) ? (Document) parent :
+      parent.getOwnerDocument();
+    if (ret instanceof Collection)
+      {
+        Collection ns = (Collection) ret;
+        List list = new ArrayList(ns);
+        Collections.sort(list, documentOrderComparator);
+        for (Iterator i = list.iterator(); i.hasNext(); )
+          {
+            Node src = (Node) i.next();
+            short nodeType = src.getNodeType();
+            if (nodeType == Node.DOCUMENT_NODE)
+              {
+                // Use document element
+                src = ((Document) src).getDocumentElement();
+                if (src == null)
+                  continue;
+                nodeType = Node.ELEMENT_NODE;
+              }
+            else if (nodeType == Node.ATTRIBUTE_NODE)
+              {
+                if (parent.getFirstChild() != null)
+                  {
+                    // Ignore attempt to add attribute after children
+                    continue;
+                  }
+              }
+            if (parent.getNodeType() == Node.ATTRIBUTE_NODE &&
+                nodeType != Node.TEXT_NODE &&
+                nodeType != Node.ENTITY_REFERENCE_NODE)
+              {
+                // Ignore
+                continue;
+              }
+            Node node = src.cloneNode(true);
+            node = doc.adoptNode(node);
+            if (nodeType == Node.ATTRIBUTE_NODE)
+              {
+                NamedNodeMap attrs = parent.getAttributes();
+                if (attrs != null)
+                  attrs.setNamedItemNS(node);
+              }
+            else
+              {
+                if (nextSibling != null)
+                  parent.insertBefore(node, nextSibling);
+                else
+                  parent.appendChild(node);
+              }
+          }
+      }
+    else
+      {
+        String value = Expr._string(context, ret);
+        if (value != null && value.length() > 0)
+          {
+            Text textNode = doc.createTextNode(value);
+            if (nextSibling != null)
+              parent.insertBefore(textNode, nextSibling);
+            else
+              parent.appendChild(textNode);
+          }
+      }
+    // copy-of doesn't process children
+    if (next != null)
+      next.apply(stylesheet, mode,
+                 context, pos, len,
+                 parent, nextSibling);
+  }
+  
+  public boolean references(QName var)
+  {
+    if (select != null && select.references(var))
+      return true;
+    return super.references(var);
+  }
+  
+  public String toString()
+  {
+    StringBuffer buf = new StringBuffer("copy-of");
+    buf.append('[');
+    buf.append("select=");
+    buf.append(select);
+    buf.append(']');
+    return buf.toString();
+  }
+  
+}

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/CurrentFunction.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/CurrentFunction.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/CurrentFunction.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/CurrentFunction.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,104 @@
+/* CurrentFunction.java -- 
+   Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.xml.transform;
+
+import java.util.Collections;
+import java.util.List;
+import javax.xml.namespace.QName;
+import javax.xml.xpath.XPathFunction;
+import javax.xml.xpath.XPathFunctionException;
+import org.w3c.dom.Node;
+import gnu.xml.xpath.Expr;
+import gnu.xml.xpath.Function;
+
+/**
+ * The XSLT <code>current()</code>function.
+ *
+ * @author <a href='mailto:dog at gnu.org'>Chris Burdess</a>
+ */
+final class CurrentFunction
+  extends Expr
+  implements Function, XPathFunction
+{
+
+  final Stylesheet stylesheet;
+
+  CurrentFunction(Stylesheet stylesheet)
+  {
+    this.stylesheet = stylesheet;
+  }
+
+  public Object evaluate(List args)
+    throws XPathFunctionException
+  {
+    // We can't do anything useful here.
+    // So much for the JAXP API...
+    return Collections.EMPTY_SET;
+  }
+
+  public void setArguments(List args)
+  {
+  }
+
+  public Object evaluate(Node context, int pos, int len)
+  {
+    return Collections.singleton(stylesheet.current);
+  }
+
+  public Expr clone(Object context)
+  {
+    Stylesheet s = stylesheet;
+    if (context instanceof Stylesheet)
+      {
+        s = (Stylesheet) context;
+      }
+    return new CurrentFunction(s);
+  }
+
+  public boolean references(QName var)
+  {
+    return false;
+  }
+
+  public String toString()
+  {
+    return "current()";
+  }
+
+}
+

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/DOMSourceLocator.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/DOMSourceLocator.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/DOMSourceLocator.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/DOMSourceLocator.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,84 @@
+/* DOMSourceLocator.java -- 
+   Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.xml.transform;
+
+import javax.xml.transform.dom.DOMLocator;
+import org.w3c.dom.Node;
+
+/**
+ * Simple DOMLocator implementation.
+ *
+ * @author <a href='mailto:dog at gnu.org'>Chris Burdess</a>
+ */
+class DOMSourceLocator
+  implements DOMLocator
+{
+
+  final Node node;
+
+  DOMSourceLocator(Node node)
+  {
+    this.node = node;
+  }
+
+  public Node getOriginatingNode()
+  {
+    return node;
+  }
+
+  public String getPublicId()
+  {
+    return null;
+  }
+
+  public String getSystemId()
+  {
+    return null;
+  }
+
+  public int getLineNumber()
+  {
+    return -1;
+  }
+
+  public int getColumnNumber()
+  {
+    return -1;
+  }
+  
+}

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/DocumentFunction.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/DocumentFunction.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/DocumentFunction.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/DocumentFunction.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,244 @@
+/* DocumentFunction.java -- 
+   Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.xml.transform;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Iterator;
+import java.util.List;
+import java.util.TreeSet;
+import javax.xml.namespace.QName;
+import javax.xml.transform.TransformerException;
+import javax.xml.transform.dom.DOMSource;
+import javax.xml.xpath.XPathFunction;
+import javax.xml.xpath.XPathFunctionException;
+import org.w3c.dom.Node;
+import gnu.xml.xpath.Constant;
+import gnu.xml.xpath.Expr;
+import gnu.xml.xpath.Function;
+import gnu.xml.xpath.IdFunction;
+
+/**
+ * The XSLT <code>document()</code>function.
+ *
+ * @author <a href='mailto:dog at gnu.org'>Chris Burdess</a>
+ */
+final class DocumentFunction
+  extends Expr
+  implements Function, XPathFunction
+{
+
+  final Stylesheet stylesheet;
+  final Node base;
+  List args;
+  List values;
+
+  DocumentFunction(Stylesheet stylesheet, Node base)
+  {
+    this.stylesheet = stylesheet;
+    this.base = base;
+  }
+
+  public Object evaluate(List args)
+    throws XPathFunctionException
+  {
+    values = args;
+    return evaluate(null, 1, 1);
+  }
+
+  public void setArguments(List args)
+  {
+    this.args = args;
+  }
+  
+  public Object evaluate(Node context, int pos, int len)
+  {
+    int arity = args.size();
+    if (values == null)
+      {
+        values = new ArrayList(arity);
+        for (int i = 0; i < arity; i++)
+          {
+            Expr arg = (Expr) args.get(i);
+            values.add(arg.evaluate(context, pos, len));
+          }
+      }
+    Object ret;
+    switch (arity)
+      {
+      case 1:
+        Object arg = values.get(0);
+        if (arg instanceof Collection)
+          {
+            Collection ns = (Collection) arg;
+            Collection acc = new TreeSet();
+            for (Iterator i = ns.iterator(); i.hasNext(); )
+              {
+                Node node = (Node) i.next();
+                String s = Expr.stringValue(node);
+                acc.addAll(document(s, node.getBaseURI()));
+              }
+            ret = acc;
+          }
+        else
+          {
+            String s = Expr._string(context, arg);
+            ret = document(s, base.getBaseURI());
+          }
+        break;
+      case 2:
+        Object arg1 = values.get(0);
+        Object arg2 = values.get(1);
+        if (!(arg2 instanceof Collection))
+          throw new RuntimeException("second argument is not a node-set");
+        Collection arg2ns = (Collection) arg2;
+        String base2 = arg2ns.isEmpty() ? null :
+          ((Node) arg2ns.iterator().next()).getBaseURI();
+        if (arg1 instanceof Collection)
+          {
+            Collection arg1ns = (Collection) arg1;
+            Collection acc = new TreeSet();
+            for (Iterator i = arg1ns.iterator(); i.hasNext(); )
+              {
+                Node node = (Node) i.next();
+                String s = Expr.stringValue(node);
+                acc.addAll(document(s, base2));
+              }
+            ret = acc;
+          }
+        else
+          {
+            String s = Expr._string(context, arg1);
+            ret = document(s, base2);
+          }
+        break;
+      default:
+        throw new RuntimeException("invalid arity");
+      }
+    values = null;
+    return ret;
+  }
+
+  /**
+   * The XSL <code>document</code> function.
+   * @see XSLT 12.1
+   * @param uri the URI from which to retrieve nodes
+   * @param base the base URI for relative URIs
+   */
+  Collection document(String uri, String base)
+  {
+    if ("".equals(uri) || uri == null)
+      uri = this.base.getBaseURI();
+    
+    // Get fragment
+    Expr fragment = null;
+    int hi = uri.indexOf('#');
+    if (hi != -1)
+      {
+        String f = uri.substring(hi + 1);
+        uri = uri.substring(0, hi);
+        // TODO handle xpointer() here
+        // this only handles IDs
+        fragment = new IdFunction(new Constant(f));
+      }
+
+    // Get document source
+    try
+      {
+        DOMSource source;
+        XSLURIResolver resolver = stylesheet.factory.resolver;
+        synchronized (resolver)
+          {
+            if (stylesheet.transformer != null)
+              {
+                resolver.setUserResolver(stylesheet.transformer.uriResolver);
+                resolver.setUserListener(stylesheet.transformer.errorListener);
+              }
+            source = resolver.resolveDOM(null, base, uri);
+          }
+        Node node = source.getNode();
+        // Strip whitespace
+        TransformerImpl.strip(stylesheet, node);
+        if (fragment == null)
+          return Collections.singleton(node);
+        else
+          {
+            Object ret = fragment.evaluate(node, 1, 1);
+            if (!(ret instanceof Collection))
+              {
+                // XXX Report error?
+                return Collections.EMPTY_SET;
+              }
+            return (Collection) ret;
+          }
+      }
+    catch (TransformerException e)
+      {
+        String msg = "can't open " + uri;
+        if (base != null)
+          msg += " with base " + base;
+        throw new RuntimeException(msg);
+      }
+  }
+
+  public Expr clone(Object context)
+  {
+    Stylesheet s = stylesheet;
+    if (context instanceof Stylesheet)
+      s = (Stylesheet) context;
+    DocumentFunction f = new DocumentFunction(s, base);
+    int len = args.size();
+    List args2 = new ArrayList(len);
+    for (int i = 0; i < len; i++)
+      args2.add(((Expr) args.get(i)).clone(context));
+    f.setArguments(args2);
+    return f;
+  }
+
+  public boolean references(QName var)
+  {
+    for (Iterator i = args.iterator(); i.hasNext(); )
+      {
+        if (((Expr) i.next()).references(var))
+          return true;
+      }
+    return false;
+  }
+  
+}

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/ElementAvailableFunction.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/ElementAvailableFunction.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/ElementAvailableFunction.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/ElementAvailableFunction.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,182 @@
+/* ElementAvailableFunction.java -- 
+   Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.xml.transform;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Iterator;
+import java.util.List;
+import java.util.TreeSet;
+import javax.xml.namespace.QName;
+import javax.xml.namespace.NamespaceContext;
+import javax.xml.xpath.XPathFunction;
+import javax.xml.xpath.XPathFunctionException;
+import org.w3c.dom.Node;
+import gnu.xml.xpath.Expr;
+import gnu.xml.xpath.Function;
+
+/**
+ * The XSLT <code>element-available</code> function.
+ *
+ * @author <a href='mailto:dog at gnu.org'>Chris Burdess</a>
+ */
+class ElementAvailableFunction
+  extends Expr
+  implements Function, XPathFunction
+{
+
+  static final Collection elements;
+  static
+  {
+    TreeSet acc = new TreeSet();
+    acc.add("stylesheet");
+    acc.add("template");
+    acc.add("param");
+    acc.add("variable");
+    acc.add("include");
+    acc.add("import");
+    acc.add("output");
+    acc.add("preserve-space");
+    acc.add("strip-space");
+    acc.add("key");
+    acc.add("decimal-format");
+    acc.add("namespace-alias");
+    acc.add("attribute-set");
+    acc.add("apply-templates");
+    acc.add("call-template");
+    acc.add("value-of");
+    acc.add("for-each");
+    acc.add("if");
+    acc.add("choose");
+    acc.add("when");
+    acc.add("otherwise");
+    acc.add("element");
+    acc.add("attribute");
+    acc.add("text");
+    acc.add("copy");
+    acc.add("processing-instruction");
+    acc.add("comment");
+    acc.add("number");
+    acc.add("copy-of");
+    acc.add("message");
+    acc.add("sort");
+    acc.add("with-param");
+    acc.add("fallback");
+    acc.add("apply-imports");
+    elements = Collections.unmodifiableSet(acc);
+  }
+
+  final NamespaceContext nsctx;
+  List args;
+
+  ElementAvailableFunction(NamespaceContext nsctx)
+  {
+    this.nsctx = nsctx;
+  }
+
+  public Object evaluate(List args)
+    throws XPathFunctionException
+  {
+    // Useless...
+    return Collections.EMPTY_SET;
+  }
+
+  public void setArguments(List args)
+  {
+    this.args = args;
+  }
+
+  public Object evaluate(Node context, int pos, int len)
+  {
+    Expr arg = (Expr) args.get(0);
+    Object val = arg.evaluate(context, pos, len);
+    String name = _string(context, val);
+    String prefix, localName, uri;
+    int ci = name.indexOf(':');
+    if (ci == -1)
+      {
+        prefix = null;
+        localName = name;
+      }
+    else
+      {
+        prefix = name.substring(0, ci);
+        localName = name.substring(ci + 1);
+      }
+    uri = nsctx.getNamespaceURI(prefix);
+    if (Stylesheet.XSL_NS.equals(uri))
+      {
+        return elements.contains(localName) ?
+          Boolean.TRUE : Boolean.FALSE;
+      }
+    // TODO extension elements
+    return Boolean.FALSE;
+  }
+  
+  public Expr clone(Object context)
+  {
+    NamespaceContext n = nsctx;
+    if (context instanceof NamespaceContext)
+      n = (NamespaceContext) context;
+    ElementAvailableFunction f = new ElementAvailableFunction(n);
+    int len = args.size();
+    List args2 = new ArrayList(len);
+    for (int i = 0; i < len; i++)
+      args2.add(((Expr) args.get(i)).clone(context));
+    f.setArguments(args2);
+    return f;
+  }
+
+  public boolean references(QName var)
+  {
+    for (Iterator i = args.iterator(); i.hasNext(); )
+      {
+        if (((Expr) i.next()).references(var))
+          return true;
+      }
+    return false;
+  }
+
+  public String toString()
+  {
+    return "element-available(" + args.get(0) + ")";
+  }
+
+}
+

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/ElementNode.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/ElementNode.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/ElementNode.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/ElementNode.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,259 @@
+/* ElementNode.java -- 
+   Copyright (C) 2004,2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.xml.transform;
+
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.StringTokenizer;
+import javax.xml.XMLConstants;
+import javax.xml.namespace.QName;
+import javax.xml.transform.TransformerException;
+import org.w3c.dom.Document;
+import org.w3c.dom.DocumentFragment;
+import org.w3c.dom.Element;
+import org.w3c.dom.NamedNodeMap;
+import org.w3c.dom.Node;
+import gnu.xml.xpath.Expr;
+
+/**
+ * A template node representing an XSL <code>element</code> instruction.
+ *
+ * @author <a href='mailto:dog at gnu.org'>Chris Burdess</a>
+ */
+final class ElementNode
+  extends TemplateNode
+{
+
+  final TemplateNode name;
+  final TemplateNode namespace;
+  final String uas;
+  final Node source;
+  final Collection elementExcludeResultPrefixes;
+  
+  ElementNode(TemplateNode name,
+              TemplateNode namespace, String uas, Node source)
+  {
+    this.name = name;
+    this.namespace = namespace;
+    this.uas = uas;
+    this.source = source;
+    NamedNodeMap attrs = source.getAttributes();
+    Node attr = attrs.getNamedItemNS(Stylesheet.XSL_NS,
+                                     "exclude-result-prefixes");
+    if (attr != null)
+      {
+        elementExcludeResultPrefixes = new HashSet();
+        StringTokenizer st = new StringTokenizer(attr.getNodeValue());
+        while (st.hasMoreTokens())
+          elementExcludeResultPrefixes.add(st.nextToken());
+      }
+    else
+      elementExcludeResultPrefixes = Collections.EMPTY_SET;
+  }
+
+  TemplateNode clone(Stylesheet stylesheet)
+  {
+    TemplateNode ret = new ElementNode(name.clone(stylesheet),
+                                       (namespace == null) ? null :
+                                       namespace.clone(stylesheet),
+                                       uas, source);
+    if (children != null)
+      ret.children = children.clone(stylesheet);
+    if (next != null)
+      ret.next = next.clone(stylesheet);
+    return ret;
+  }
+
+  void doApply(Stylesheet stylesheet, QName mode,
+               Node context, int pos, int len,
+               Node parent, Node nextSibling)
+    throws TransformerException
+  {
+    Document doc = (parent instanceof Document) ? (Document) parent :
+      parent.getOwnerDocument();
+    // Create a document fragment to hold the name
+    DocumentFragment fragment = doc.createDocumentFragment();
+    // Apply name to the fragment
+    name.apply(stylesheet, mode,
+               context, pos, len,
+               fragment, null);
+    // Use XPath string-value of fragment
+    String nameValue = Expr.stringValue(fragment);
+
+    String namespaceValue = null;
+    if (namespace != null)
+      {
+        // Create a document fragment to hold the namespace
+        fragment = doc.createDocumentFragment();
+        // Apply namespace to the fragment
+        namespace.apply(stylesheet, mode,
+                        context, pos, len,
+                        fragment, null);
+        // Use XPath string-value of fragment
+        namespaceValue = Expr.stringValue(fragment);
+        if (namespaceValue.length() == 0)
+          namespaceValue = null;
+      }
+    else
+      {    
+        String prefix = getPrefix(nameValue);
+        if (XMLConstants.XMLNS_ATTRIBUTE.equals(prefix))
+          {
+            int ci = nameValue.indexOf(':');
+            nameValue = nameValue.substring(ci + 1);
+          }
+        else
+          {
+            // Namespace aliasing
+            if (prefix == null)
+              prefix = "#default";
+            String resultPrefix =
+              (String) stylesheet.namespaceAliases.get(prefix);
+            if (resultPrefix != null)
+              {
+                if ("#default".equals(resultPrefix))
+                  resultPrefix = null;
+                namespaceValue = source.lookupNamespaceURI(resultPrefix);
+              }
+            if (prefix == "#default")
+              prefix = null;
+            // Look up ordinary namespace for this prefix
+            if (namespaceValue == null)
+              {
+                if (XMLConstants.XML_NS_PREFIX.equals(prefix))
+                  namespaceValue = XMLConstants.XML_NS_URI;
+                else
+                  {
+                    // Resolve namespace for this prefix
+                    namespaceValue = source.lookupNamespaceURI(prefix);
+                  }
+              }
+          }
+      }
+    
+    // Create element
+    Element element = (namespaceValue != null) ?
+      doc.createElementNS(namespaceValue, nameValue) :
+      doc.createElement(nameValue);
+    if (nextSibling != null)
+      parent.insertBefore(element, nextSibling);
+    else
+      parent.appendChild(element);
+    stylesheet.addNamespaceNodes(source, element, doc,
+                                 elementExcludeResultPrefixes);
+    if (uas != null)
+      {
+        StringTokenizer st = new StringTokenizer(uas, " ");
+        while (st.hasMoreTokens())
+          addAttributeSet(stylesheet, mode, context, pos, len,
+                          element, null, st.nextToken());
+      }
+    if (children != null)
+      children.apply(stylesheet, mode,
+                     context, pos, len,
+                     element, null);
+    if (next != null)
+      next.apply(stylesheet, mode,
+                 context, pos, len,
+                 parent, nextSibling);
+  }
+
+  final String getPrefix(String name)
+  {
+    int ci = name.indexOf(':');
+    return (ci == -1) ? null : name.substring(0, ci);
+  }
+
+  void addAttributeSet(Stylesheet stylesheet, QName mode,
+                       Node context, int pos, int len,
+                       Node parent, Node nextSibling, String attributeSet)
+    throws TransformerException
+  {
+    stylesheet.bindings.global = true;
+    for (Iterator i = stylesheet.attributeSets.iterator(); i.hasNext(); )
+      {
+        AttributeSet as = (AttributeSet) i.next();
+        if (!as.name.equals(attributeSet))
+          continue;
+        if (as.uas != null)
+          {
+            StringTokenizer st = new StringTokenizer(as.uas, " ");
+            while (st.hasMoreTokens())
+              addAttributeSet(stylesheet, mode, context, pos, len,
+                              parent, nextSibling, st.nextToken());
+          }
+        if (as.children != null)
+          as.children.apply(stylesheet, mode,
+                            context, pos, len,
+                            parent, nextSibling);
+      }
+    stylesheet.bindings.global = false;
+  }
+
+  public boolean references(QName var)
+  {
+    if (name != null && name.references(var))
+      return true;
+    if (namespace != null && namespace.references(var))
+      return true;
+    return super.references(var);
+  }
+  
+  public String toString()
+  {
+    StringBuffer buf = new StringBuffer("element");
+    buf.append('[');
+    buf.append("name=");
+    if (namespace != null)
+      {
+        buf.append(",namespace=");
+        buf.append(namespace);
+      }
+    buf.append(name);
+    if (uas != null)
+      {
+        buf.append(",uas=");
+        buf.append(uas);
+      }
+    buf.append(']');
+    return buf.toString();
+  }
+  
+}

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/ErrorListenerErrorHandler.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/ErrorListenerErrorHandler.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/ErrorListenerErrorHandler.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/ErrorListenerErrorHandler.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,101 @@
+/* ErrorListenerErrorHandler.java -- 
+   Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.xml.transform;
+
+import javax.xml.transform.ErrorListener;
+import javax.xml.transform.TransformerException;
+import org.xml.sax.ErrorHandler;
+import org.xml.sax.SAXException;
+import org.xml.sax.SAXParseException;
+
+/**
+ * An ErrorHandler that wraps an ErrorListener.
+ *
+ * @author <a href='mailto:dog at gnu.org'>Chris Burdess</a>
+ */
+class ErrorListenerErrorHandler
+  implements ErrorHandler
+{
+
+  final ErrorListener listener;
+
+  ErrorListenerErrorHandler(ErrorListener listener)
+  {
+    this.listener = listener;
+  }
+
+  public void warning(SAXParseException e)
+    throws SAXException
+  {
+    try
+      {
+        listener.warning(new TransformerException(e));
+      }
+    catch (TransformerException e2)
+      {
+        throw new SAXException(e2);
+      }
+  }
+  
+  public void error(SAXParseException e)
+    throws SAXException
+  {
+    try
+      {
+        listener.error(new TransformerException(e));
+      }
+    catch (TransformerException e2)
+      {
+        throw new SAXException(e2);
+      }
+  }
+  
+  public void fatalError(SAXParseException e)
+    throws SAXException
+  {
+    try
+      {
+        listener.fatalError(new TransformerException(e));
+      }
+    catch (TransformerException e2)
+      {
+        throw new SAXException(e2);
+      }
+  }
+  
+}

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/ForEachNode.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/ForEachNode.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/ForEachNode.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/ForEachNode.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,157 @@
+/* ForEachNode.java -- 
+   Copyright (C) 2004,2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.xml.transform;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Iterator;
+import java.util.List;
+import javax.xml.namespace.QName;
+import javax.xml.transform.TransformerException;
+import org.w3c.dom.Node;
+import gnu.xml.xpath.Expr;
+
+/**
+ * A template node representing an XSLT <code>for-each</code> instruction.
+ *
+ * @author <a href='mailto:dog at gnu.org'>Chris Burdess</a>
+ */
+final class ForEachNode
+  extends TemplateNode
+{
+
+  final Expr select;
+  final List sortKeys;
+
+  ForEachNode(Expr select, List sortKeys)
+  {
+    this.select = select;
+    this.sortKeys = sortKeys;
+  }
+
+  TemplateNode clone(Stylesheet stylesheet)
+  {
+    int len = sortKeys != null ? sortKeys.size() : 0;
+    List sortKeys2 = new ArrayList(len);
+    for (int i = 0; i < len; i++)
+      sortKeys2.add(((Key) sortKeys.get(i)).clone(stylesheet));
+    TemplateNode ret = new ForEachNode(select.clone(stylesheet),
+                                       sortKeys2);
+    if (children != null)
+      ret.children = children.clone(stylesheet);
+    if (next != null)
+      ret.next = next.clone(stylesheet);
+    return ret;
+  }
+
+  void doApply(Stylesheet stylesheet, QName mode,
+             Node context, int pos, int len,
+             Node parent, Node nextSibling)
+    throws TransformerException
+  {
+    if (children != null)
+      {
+        // Set current template to null
+        Template saved = stylesheet.currentTemplate;
+        stylesheet.currentTemplate = null;
+        Object ret = select.evaluate(context, pos, len);
+        //System.err.println(toString() + ": " + context+" -> "+ret);
+        if (ret instanceof Collection)
+          {
+            Collection ns = (Collection) ret;
+            List list = new ArrayList(ns);
+            if (sortKeys != null)
+              {
+                for (Iterator i = sortKeys.iterator(); i.hasNext(); )
+                  {
+                    SortKey sortKey = (SortKey) i.next();
+                    sortKey.init(stylesheet, mode, context, pos, len, parent,
+                                 nextSibling);
+                  }
+                Collections.sort(list, new XSLComparator(sortKeys));
+              }
+            else
+              Collections.sort(list, documentOrderComparator);
+            // Perform children for each node
+            int l = list.size();
+            int p = 1;
+            for (Iterator i = list.iterator(); i.hasNext(); )
+              {
+                Node node = (Node) i.next();
+                stylesheet.current = node;
+                children.apply(stylesheet, mode,
+                               node, p++, l,
+                               parent, nextSibling);
+              }
+          }
+        // Restore current template
+        stylesheet.currentTemplate = saved;
+      }
+    if (next != null)
+      next.apply(stylesheet, mode,
+                 context, pos, len,
+                 parent, nextSibling);
+  }
+
+  public boolean references(QName var)
+  {
+    if (select != null && select.references(var))
+      return true;
+    if (sortKeys != null)
+      {
+        for (Iterator i = sortKeys.iterator(); i.hasNext(); )
+          {
+            if (((SortKey) i.next()).references(var))
+              return true;
+          }
+      }
+    return super.references(var);
+  }
+  
+  public String toString()
+  {
+    StringBuffer buf = new StringBuffer("for-each");
+    buf.append('[');
+    buf.append("select=");
+    buf.append(select);
+    buf.append(']');
+    return buf.toString();
+  }
+  
+}

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/FormatNumberFunction.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/FormatNumberFunction.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/FormatNumberFunction.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/FormatNumberFunction.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,146 @@
+/* FormatNumberFunction.java -- 
+   Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.xml.transform;
+
+import java.text.DecimalFormat;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Iterator;
+import java.util.List;
+import javax.xml.namespace.QName;
+import javax.xml.xpath.XPathFunction;
+import javax.xml.xpath.XPathFunctionException;
+import org.w3c.dom.Node;
+import gnu.xml.xpath.Expr;
+import gnu.xml.xpath.Function;
+
+/**
+ * The XSLT <code>format-number()</code>function.
+ *
+ * @author <a href='mailto:dog at gnu.org'>Chris Burdess</a>
+ */
+final class FormatNumberFunction
+  extends Expr
+  implements XPathFunction, Function
+{
+
+  final Stylesheet stylesheet;
+  List args;
+
+  FormatNumberFunction(Stylesheet stylesheet)
+  {
+    this.stylesheet = stylesheet;
+  }
+
+  public Object evaluate(List args)
+    throws XPathFunctionException
+  {
+    // Useless...
+    return Collections.EMPTY_SET;
+  }
+
+  public void setArguments(List args)
+  {
+    this.args = args;
+  }
+
+  public Object evaluate(Node context, int pos, int len)
+  {
+    int arity = args.size();
+    List values = new ArrayList(arity);
+    for (int i = 0; i < arity; i++)
+      {
+        Expr arg = (Expr) args.get(i);
+        values.add(arg.evaluate(context, pos, len));
+      }
+    double number = _number(context, values.get(0));
+    String pattern = _string(context, values.get(1));
+    // Currency symbol &#x00a4; is not supposed to be present
+    if (pattern.indexOf('\u00a4') != -1)
+      {
+        // Replace with $ (Xalan does this)
+        pattern = pattern.replace('\u00a4', '$');
+      }
+    String dfName = null;
+    if (arity > 2)
+      {
+        dfName = _string(context, values.get(2));
+        // otherwise the default decimal-format will be used
+      }
+    DecimalFormat df = (DecimalFormat) stylesheet.decimalFormats.get(dfName);
+    if (df == null)
+      {
+        throw new IllegalArgumentException("No such decimal-format: " +
+                                           dfName);
+      }
+    df.applyLocalizedPattern(pattern);
+    return df.format(number);
+  }
+
+  public Expr clone(Object context)
+  {
+    Stylesheet s = stylesheet;
+    if (context instanceof Stylesheet)
+      {
+        s = (Stylesheet) context;
+      }
+    FormatNumberFunction f = new FormatNumberFunction(s);
+    int len = args.size();
+    List args2 = new ArrayList(len);
+    for (int i = 0; i < len; i++)
+      {
+        args2.add(((Expr) args.get(i)).clone(context));
+      }
+    f.setArguments(args2);
+    return f;
+  }
+
+  public boolean references(QName var)
+  {
+    for (Iterator i = args.iterator(); i.hasNext(); )
+      {
+        if (((Expr) i.next()).references(var))
+          {
+            return true;
+          }
+      }
+    return false;
+  }
+
+}
+

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/FunctionAvailableFunction.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/FunctionAvailableFunction.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/FunctionAvailableFunction.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/FunctionAvailableFunction.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,193 @@
+/* FunctionAvailableFunction.java -- 
+   Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.xml.transform;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Iterator;
+import java.util.List;
+import java.util.TreeSet;
+import javax.xml.namespace.NamespaceContext;
+import javax.xml.namespace.QName;
+import javax.xml.xpath.XPathFunction;
+import javax.xml.xpath.XPathFunctionException;
+import org.w3c.dom.Node;
+import gnu.xml.xpath.Expr;
+import gnu.xml.xpath.Function;
+
+/**
+ * The XSLT <code>function-available</code> function.
+ *
+ * @author <a href='mailto:dog at gnu.org'>Chris Burdess</a>
+ */
+class FunctionAvailableFunction
+  extends Expr
+  implements Function, XPathFunction
+{
+
+  static final Collection xsltFunctions;
+  static final Collection xpathFunctions;
+  static
+  {
+    TreeSet acc = new TreeSet();
+    acc.add("document");
+    acc.add("key");
+    acc.add("format-number");
+    acc.add("current");
+    acc.add("unparsed-entity-uri");
+    acc.add("generate-id");
+    acc.add("system-property");
+    acc.add("element-available");
+    acc.add("function-available");
+    xsltFunctions = Collections.unmodifiableSet(acc);
+    acc = new TreeSet();
+    acc.add("boolean");
+    acc.add("ceiling");
+    acc.add("concat");
+    acc.add("contains");
+    acc.add("count");
+    acc.add("false");
+    acc.add("floor");
+    acc.add("id");
+    acc.add("lang");
+    acc.add("last");
+    acc.add("local-name");
+    acc.add("name");
+    acc.add("namespace-uri");
+    acc.add("normalize-space");
+    acc.add("not");
+    acc.add("number");
+    acc.add("position");
+    acc.add("round");
+    acc.add("starts-with");
+    acc.add("string");
+    acc.add("string-length");
+    acc.add("substring-after");
+    acc.add("substring-before");
+    acc.add("substring");
+    acc.add("sum");
+    acc.add("translate");
+    acc.add("true");
+    xpathFunctions = Collections.unmodifiableSet(acc);
+  }
+
+  final NamespaceContext nsctx;
+  List args;
+
+  FunctionAvailableFunction(NamespaceContext nsctx)
+  {
+    this.nsctx = nsctx;
+  }
+
+  public Object evaluate(List args)
+    throws XPathFunctionException
+  {
+    // Useless...
+    return Collections.EMPTY_SET;
+  }
+
+  public void setArguments(List args)
+  {
+    this.args = args;
+  }
+
+  public Object evaluate(Node context, int pos, int len)
+  {
+    Expr arg = (Expr) args.get(0);
+    Object val = arg.evaluate(context, pos, len);
+    String name = _string(context, val);
+    String prefix, localName, uri;
+    int ci = name.indexOf(':');
+    if (ci == -1)
+      {
+        prefix = null;
+        localName = name;
+      }
+    else
+      {
+        prefix = name.substring(0, ci);
+        localName = name.substring(ci + 1);
+      }
+    uri = nsctx.getNamespaceURI(prefix);
+    if (uri == null)
+      {
+        return (xpathFunctions.contains(localName)  ||
+                xsltFunctions.contains(localName)) ?
+          Boolean.TRUE : Boolean.FALSE;
+      }
+    else if (Stylesheet.XSL_NS.equals(uri))
+      {
+        return xsltFunctions.contains(localName) ?
+          Boolean.TRUE : Boolean.FALSE;
+      }
+    // TODO extension functions
+    return Boolean.FALSE;
+  }
+  
+  public Expr clone(Object context)
+  {
+    NamespaceContext n = nsctx;
+    if (context instanceof NamespaceContext)
+      n = (NamespaceContext) context;
+    FunctionAvailableFunction f = new FunctionAvailableFunction(n);
+    int len = args.size();
+    List args2 = new ArrayList(len);
+    for (int i = 0; i < len; i++)
+      args2.add(((Expr) args.get(i)).clone(context));
+    f.setArguments(args2);
+    return f;
+  }
+
+  public boolean references(QName var)
+  {
+    for (Iterator i = args.iterator(); i.hasNext(); )
+      {
+        if (((Expr) i.next()).references(var))
+          return true;
+      }
+    return false;
+  }
+
+  public String toString()
+  {
+    return "function-available(" + args.get(0) + ")";
+  }
+
+}
+

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/GenerateIdFunction.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/GenerateIdFunction.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/GenerateIdFunction.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/GenerateIdFunction.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,140 @@
+/* GenerateIdFunction.java -- 
+   Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.xml.transform;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Iterator;
+import java.util.List;
+import javax.xml.namespace.QName;
+import javax.xml.xpath.XPathFunction;
+import javax.xml.xpath.XPathFunctionException;
+import org.w3c.dom.Node;
+import gnu.xml.xpath.Expr;
+import gnu.xml.xpath.Function;
+
+/**
+ * The XSLT <code>generate-id()</code>function.
+ *
+ * @author <a href='mailto:dog at gnu.org'>Chris Burdess</a>
+ */
+final class GenerateIdFunction
+  extends Expr
+  implements XPathFunction, Function
+{
+
+  List args;
+
+  public Object evaluate(List args)
+    throws XPathFunctionException
+  {
+    // Useless...
+    return Collections.EMPTY_SET;
+  }
+
+  public void setArguments(List args)
+  {
+    this.args = args;
+  }
+
+  public Object evaluate(Node context, int pos, int len)
+  {
+    int arity = args.size();
+    List values = new ArrayList(arity);
+    for (int i = 0; i < arity; i++)
+      {
+        Expr arg = (Expr) args.get(i);
+        values.add(arg.evaluate(context, pos, len));
+      }
+    Node node;
+    Collection ns = (arity == 0) ? Collections.EMPTY_SET :
+      (Collection) values.get(0);
+    if (ns.isEmpty())
+      {
+        node = context;
+      }
+    else
+      {
+        List list = new ArrayList(ns);
+        Collections.sort(list, documentOrderComparator);
+        node = (Node) list.get(0);
+      }
+
+    String name = node.getNodeName();
+    int index = 0, depth = 0;
+    for (Node ctx = node.getPreviousSibling(); ctx != null;
+         ctx = ctx.getPreviousSibling())
+      {
+        index++;
+      }
+    for (Node ctx = node.getParentNode(); ctx != null;
+         ctx = ctx.getParentNode())
+      {
+        depth++;
+      }
+    return name + "-" + index + "-" + depth;
+  }
+
+  public Expr clone(Object context)
+  {
+    GenerateIdFunction f = new GenerateIdFunction();
+    int len = args.size();
+    List args2 = new ArrayList(len);
+    for (int i = 0; i < len; i++)
+      {
+        args2.add(((Expr) args.get(i)).clone(context));
+      }
+    f.setArguments(args2);
+    return f;
+  }
+
+  public boolean references(QName var)
+  {
+    for (Iterator i = args.iterator(); i.hasNext(); )
+      {
+        if (((Expr) i.next()).references(var))
+          {
+            return true;
+          }
+      }
+    return false;
+  }
+
+}
+

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/IfNode.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/IfNode.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/IfNode.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/IfNode.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,110 @@
+/* IfNode.java -- 
+   Copyright (C) 2004,2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.xml.transform;
+
+import javax.xml.namespace.QName;
+import javax.xml.transform.TransformerException;
+import org.w3c.dom.Node;
+import gnu.xml.xpath.Expr;
+
+/**
+ * A template node representing an XSL <code>if</code> instruction.
+ *
+ * @author <a href='mailto:dog at gnu.org'>Chris Burdess</a>
+ */
+final class IfNode
+  extends TemplateNode
+{
+
+  final Expr test;
+
+  IfNode(Expr test)
+  {
+    this.test = test;
+  }
+
+  TemplateNode clone(Stylesheet stylesheet)
+  {
+    TemplateNode ret = new IfNode(test.clone(stylesheet));
+    if (children != null)
+      ret.children = children.clone(stylesheet);
+    if (next != null)
+      ret.next = next.clone(stylesheet);
+    return ret;
+  }
+
+  void doApply(Stylesheet stylesheet, QName mode,
+               Node context, int pos, int len,
+               Node parent, Node nextSibling)
+    throws TransformerException
+  {
+    Object ret = test.evaluate(context, pos, len);
+    boolean success = (ret instanceof Boolean) ?
+      ((Boolean) ret).booleanValue() :
+      Expr._boolean(context, ret);
+    if (success)
+      {
+        if (children != null)
+          children.apply(stylesheet, mode,
+                         context, pos, len,
+                         parent, nextSibling);
+      }
+    if (next != null)
+      next.apply(stylesheet, mode,
+                 context, pos, len,
+                 parent, nextSibling);
+  }
+  
+  public boolean references(QName var)
+  {
+    if (test != null && test.references(var))
+      return true;
+    return super.references(var);
+  }
+  
+  public String toString()
+  {
+    StringBuffer buf = new StringBuffer("if");
+    buf.append('[');
+    buf.append("test=");
+    buf.append(test);
+    buf.append(']');
+    return buf.toString();
+  }
+  
+}

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/Key.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/Key.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/Key.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/Key.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,71 @@
+/* Key.java -- 
+   Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.xml.transform;
+
+import javax.xml.namespace.QName;
+import gnu.xml.xpath.Expr;
+import gnu.xml.xpath.Pattern;
+
+/**
+ * An XSL key.
+ *
+ * @author <a href='mailto:dog at gnu.org'>Chris Burdess</a>
+ */
+class Key
+{
+
+  final QName name;
+  final Pattern match;
+  final Expr use;
+
+  Key(QName name, Pattern match, Expr use)
+  {
+    this.name = name;
+    this.match = match;
+    this.use = use;
+  }
+
+  Key clone(Stylesheet stylesheet)
+  {
+    return new Key(name,
+                   (Pattern) match.clone(stylesheet),
+                   use.clone(stylesheet));
+  }
+  
+}
+

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/KeyFunction.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/KeyFunction.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/KeyFunction.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/KeyFunction.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,228 @@
+/* KeyFunction.java -- 
+   Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.xml.transform;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Iterator;
+import java.util.LinkedHashSet;
+import java.util.LinkedList;
+import java.util.List;
+import javax.xml.namespace.QName;
+import javax.xml.xpath.XPathFunction;
+import javax.xml.xpath.XPathFunctionException;
+import org.w3c.dom.Document;
+import org.w3c.dom.Node;
+import gnu.xml.xpath.Expr;
+import gnu.xml.xpath.Function;
+import gnu.xml.xpath.Pattern;
+
+/**
+ * The XSLT <code>key()</code>function.
+ *
+ * @author <a href='mailto:dog at gnu.org'>Chris Burdess</a>
+ */
+final class KeyFunction
+  extends Pattern
+  implements XPathFunction, Function
+{
+
+  final Stylesheet stylesheet;
+  List args;
+
+  KeyFunction(Stylesheet stylesheet)
+  {
+    this.stylesheet = stylesheet;
+  }
+
+  public Object evaluate(List args)
+    throws XPathFunctionException
+  {
+    // Useless...
+    return Collections.EMPTY_SET;
+  }
+
+  public void setArguments(List args)
+  {
+    this.args = args;
+  }
+
+  public boolean matches(Node context)
+  {
+    Object ret = evaluate(context, 1, 1);
+    return !((Collection) ret).isEmpty();
+  }
+
+  public Object evaluate(Node context, int pos, int len)
+  {
+    // Evaluate arguments
+    int arity = args.size();
+    List values = new ArrayList(arity);
+    for (int i = 0; i < arity; i++)
+      {
+        Expr arg = (Expr) args.get(i);
+        values.add(arg.evaluate(context, pos, len));
+      }
+    // Get key name
+    QName keyName = QName.valueOf(_string(context, values.get(0)));
+    // Expand qualified name
+    String uri = keyName.getNamespaceURI();
+    String prefix = keyName.getPrefix();
+    if ((uri == null || uri.length() == 0) && 
+        (prefix != null && prefix.length() > 0))
+      {
+        uri = stylesheet.getNamespaceURI(prefix);
+        if (uri != null && uri.length() > 0)
+          {
+            String localName = keyName.getLocalPart();
+            keyName = new QName(uri, localName, prefix);
+          }
+      }
+    // Compute matching key set
+    Collection keySet = new LinkedList();
+    for (Iterator i = stylesheet.keys.iterator(); i.hasNext(); )
+      {
+        Key key = (Key) i.next();
+        if (key.name.equals(keyName))
+          {
+            keySet.add(key);
+          }
+      }
+    // Get target
+    Object target = values.get(1);
+    Collection acc = new LinkedHashSet();
+    Document doc = (context instanceof Document) ? (Document) context :
+      context.getOwnerDocument();
+    if (target instanceof Collection)
+      {
+        for (Iterator i = ((Collection) target).iterator(); i.hasNext(); )
+          {
+            String val = Expr.stringValue((Node) i.next());
+            addKeyNodes(doc, keySet, val, acc);
+          }
+      }
+    else
+      {
+        String val = Expr._string(context, target);
+        addKeyNodes(doc, keySet, val, acc);
+      }
+    List ret = new ArrayList(acc);
+    Collections.sort(ret, documentOrderComparator);
+    return ret;
+  }
+
+  final void addKeyNodes(Node node, Collection keySet,
+                         String value, Collection acc)
+  {
+    addKeyNodeIfMatch(node, keySet, value, acc);
+    // Apply children
+    for (Node ctx = node.getFirstChild(); ctx != null;
+         ctx = ctx.getNextSibling())
+      {
+        addKeyNodes(ctx, keySet, value, acc);
+      }
+  }
+  
+  final void addKeyNodeIfMatch(Node node, Collection keySet,
+                               String value, Collection acc)
+  {
+    for (Iterator i = keySet.iterator(); i.hasNext(); )
+      {
+        Key key = (Key) i.next();
+        if (key.match.matches(node))
+          {
+            Object eval = key.use.evaluate(node, 1, 1);
+            if (eval instanceof Collection)
+              {
+                for (Iterator j = ((Collection) eval).iterator();
+                     j.hasNext(); )
+                  {
+                    String keyValue = Expr.stringValue((Node) j.next());
+                    if (value.equals(keyValue))
+                      {
+                        acc.add(node);
+                        return;
+                      }
+                  }
+              }
+            else
+              {
+                String keyValue = Expr._string(node, eval);
+                if (value.equals(keyValue))
+                  {
+                    acc.add(node);
+                    return;
+                  }
+              }
+          }
+      }
+  }
+
+  public Expr clone(Object context)
+  {
+    Stylesheet s = stylesheet;
+    if (context instanceof Stylesheet)
+      {
+        s = (Stylesheet) context;
+      }
+    KeyFunction f = new KeyFunction(s);
+    int len = args.size();
+    List args2 = new ArrayList(len);
+    for (int i = 0; i < len; i++)
+      {
+        args2.add(((Expr) args.get(i)).clone(context));
+      }
+    f.setArguments(args2);
+    return f;
+  }
+
+  public boolean references(QName var)
+  {
+    for (Iterator i = args.iterator(); i.hasNext(); )
+      {
+        if (((Expr) i.next()).references(var))
+          {
+            return true;
+          }
+      }
+    return false;
+  }
+
+}
+

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/LiteralNode.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/LiteralNode.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/LiteralNode.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/LiteralNode.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,202 @@
+/* LiteralNode.java -- 
+   Copyright (C) 2004,2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.xml.transform;
+
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.StringTokenizer;
+import javax.xml.namespace.QName;
+import javax.xml.transform.TransformerException;
+import org.w3c.dom.Document;
+import org.w3c.dom.NamedNodeMap;
+import org.w3c.dom.Node;
+
+/**
+ * A template node that copies a DOM node in the template to the result
+ * tree.
+ *
+ * @author <a href='mailto:dog at gnu.org'>Chris Burdess</a>
+ */
+final class LiteralNode
+  extends TemplateNode
+{
+
+  /**
+   * The source node in the XSL template.
+   */
+  final Node source;
+
+  final Collection elementExcludeResultPrefixes;
+
+  LiteralNode(Node source)
+  {
+    this.source = source;
+    if (source.getNodeType() == Node.ELEMENT_NODE)
+      {
+        NamedNodeMap attrs = source.getAttributes();
+        Node attr = attrs.getNamedItemNS(Stylesheet.XSL_NS,
+                                         "exclude-result-prefixes");
+        if (attr != null)
+          {
+            elementExcludeResultPrefixes = new HashSet();
+            StringTokenizer st = new StringTokenizer(attr.getNodeValue());
+            while (st.hasMoreTokens())
+              elementExcludeResultPrefixes.add(st.nextToken());
+          }
+        else
+          elementExcludeResultPrefixes = Collections.EMPTY_SET;
+      }
+    else
+      elementExcludeResultPrefixes = null;
+  }
+
+  TemplateNode clone(Stylesheet stylesheet)
+  {
+    TemplateNode ret = new LiteralNode(source);
+    if (children != null)
+      ret.children = children.clone(stylesheet);
+    if (next != null)
+      ret.next = next.clone(stylesheet);
+    return ret;
+  }
+
+  void doApply(Stylesheet stylesheet, QName mode,
+               Node context, int pos, int len,
+               Node parent, Node nextSibling)
+    throws TransformerException
+  {
+    Node result = null;
+    Document doc = (parent instanceof Document) ? (Document) parent :
+      parent.getOwnerDocument();
+    short nodeType = source.getNodeType();
+    if (nodeType == Node.ATTRIBUTE_NODE &&
+        parent.getFirstChild() != null)
+      {
+        // Ignore attributes added after child elements
+      }
+    else
+      {
+        // Namespace aliasing
+        if (nodeType == Node.ELEMENT_NODE)
+          {
+            String prefix = source.getPrefix();
+            if (prefix == null)
+              prefix = "#default";
+            String resultPrefix =
+              (String) stylesheet.namespaceAliases.get(prefix);
+            if (resultPrefix != null)
+              {
+                if ("#default".equals(resultPrefix))
+                  resultPrefix = null;
+                String uri = source.lookupNamespaceURI(resultPrefix);
+                String name = source.getNodeName();
+                // Create a new element node in the result document
+                result = doc.createElementNS(uri, name);
+                // copy attributes
+                NamedNodeMap srcAttrs = source.getAttributes();
+                NamedNodeMap dstAttrs = result.getAttributes();
+                int l = srcAttrs.getLength();
+                for (int i = 0; i < l; i++)
+                  {
+                    Node attr = srcAttrs.item(i);
+                    if (!Stylesheet.XSL_NS.equals(attr.getNamespaceURI()))
+                      {
+                        attr = attr.cloneNode(true);
+                        attr = doc.adoptNode(attr);
+                        dstAttrs.setNamedItemNS(attr);
+                      }
+                  }
+              }
+          }
+        if (result == null)
+          {
+            // Create result node
+            result = source.cloneNode(false);
+            // Remove any XSL attributes
+            NamedNodeMap attrs = result.getAttributes();
+            if (attrs != null)
+              {
+                int l = attrs.getLength();
+                for (int i = 0; i < l; i++)
+                  {
+                    Node attr = attrs.item(i);
+                    if (Stylesheet.XSL_NS.equals(attr.getNamespaceURI()))
+                      {
+                        attrs.removeNamedItem(attr.getNodeName());
+                        i--;
+                        l--;
+                      }
+                  }
+              }
+            Node result2 = doc.adoptNode(result);
+            if (result2 == null)
+              {
+                String msg = "Error adopting node to result tree: " +
+                  result + " (" + result.getClass().getName() + ")";
+                DOMSourceLocator l = new DOMSourceLocator(context);
+                throw new TransformerException(msg, l);
+              }
+            result = result2;
+          }
+        if (nextSibling != null)
+          parent.insertBefore(result, nextSibling);
+        else
+          parent.appendChild(result);
+        if (nodeType == Node.ELEMENT_NODE)
+          stylesheet.addNamespaceNodes(source, result, doc,
+                                       elementExcludeResultPrefixes);
+        // children
+        if (children != null)
+          children.apply(stylesheet, mode,
+                         context, pos, len,
+                         result, null);
+      }
+    // next sibling
+    if (next != null)
+      next.apply(stylesheet, mode,
+                 context, pos, len,
+                 parent, nextSibling);
+  }
+
+  public String toString()
+  {
+    return source.toString();
+  }
+  
+}

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/MessageNode.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/MessageNode.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/MessageNode.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/MessageNode.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,108 @@
+/* MessageNode.java -- 
+   Copyright (C) 2004,2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.xml.transform;
+
+import java.util.logging.Logger;
+import javax.xml.namespace.QName;
+import javax.xml.transform.TransformerException;
+import org.w3c.dom.Document;
+import org.w3c.dom.DocumentFragment;
+import org.w3c.dom.Node;
+import gnu.xml.xpath.Expr;
+
+/**
+ * An XSL <code>message</code> instruction.
+ *
+ * @author <a href='mailto:dog at gnu.org'>Chris Burdess</a>
+ */
+final class MessageNode
+  extends TemplateNode
+{
+
+  static final Logger logger = Logger.getLogger("gnu.xml.transform");
+
+  final boolean terminate;
+
+  MessageNode(boolean terminate)
+  {
+    this.terminate = terminate;
+  }
+
+  TemplateNode clone(Stylesheet stylesheet)
+  {
+    TemplateNode ret = new MessageNode(terminate);
+    if (children != null)
+      ret.children = children.clone(stylesheet);
+    if (next != null)
+      ret.next = next.clone(stylesheet);
+    return ret;
+  }
+
+  void doApply(Stylesheet stylesheet, QName mode,
+               Node context, int pos, int len,
+               Node parent, Node nextSibling)
+    throws TransformerException
+  {
+    if (children != null)
+      {
+        Document doc = (parent instanceof Document) ? (Document) parent :
+          parent.getOwnerDocument();
+        DocumentFragment fragment = doc.createDocumentFragment();
+        children.apply(stylesheet, mode, context, pos, len, fragment, null);
+        String message = Expr.stringValue(fragment);
+        logger.info(message);
+        if (terminate)
+          stylesheet.terminated = true;
+      }
+    if (next != null && !terminate)
+      next.apply(stylesheet, mode, context, pos, len, parent, nextSibling);
+  }
+
+  public String toString()
+  {
+    StringBuffer buf = new StringBuffer("message");
+    if (terminate)
+      {
+        buf.append('[');
+        buf.append("terminate");
+        buf.append(']');
+      }
+    return buf.toString();
+  }
+  
+}

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/NamespaceProxy.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/NamespaceProxy.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/NamespaceProxy.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/NamespaceProxy.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,77 @@
+/* NamespaceProxy.java -- 
+   Copyright (C) 2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.xml.transform;
+
+import java.util.Collections;
+import java.util.Iterator;
+import javax.xml.namespace.NamespaceContext;
+import org.w3c.dom.Node;
+
+/**
+ * A namespace context using a DOM node to resolve the namespace.
+ *
+ * @author <a href='mailto:dog at gnu.org'>Chris Burdess</a>
+ */
+class NamespaceProxy
+  implements NamespaceContext
+{
+
+  private final Node node;
+
+  NamespaceProxy(Node node)
+  {
+    this.node = node;
+  }
+  
+  public String getNamespaceURI(String prefix)
+  {
+    return (node == null) ? null : node.lookupNamespaceURI(prefix);
+  }
+
+  public String getPrefix(String namespaceURI)
+  {
+    return (node == null) ? null : node.lookupPrefix(namespaceURI);
+  }
+
+  public Iterator getPrefixes(String namespaceURI)
+  {
+    // TODO
+    return Collections.singleton(getPrefix(namespaceURI)).iterator();
+  }
+
+}

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/NodeNumberNode.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/NodeNumberNode.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/NodeNumberNode.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/NodeNumberNode.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,269 @@
+/* NodeNumberNode.java -- 
+   Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.xml.transform;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Iterator;
+import java.util.List;
+import javax.xml.transform.TransformerException;
+import org.w3c.dom.Node;
+import gnu.xml.xpath.Expr;
+import gnu.xml.xpath.Pattern;
+import gnu.xml.xpath.Selector;
+import gnu.xml.xpath.UnionExpr;
+
+/**
+ * A template node representing the XSL <code>number</code> instruction
+ * with no <code>value</code> expression, i.e. the value is computed from
+ * the document position of the context node.
+ *
+ * @author <a href='mailto:dog at gnu.org'>Chris Burdess</a>
+ */
+final class NodeNumberNode
+  extends AbstractNumberNode
+{
+
+  static final int SINGLE = 0;
+  static final int MULTIPLE = 1;
+  static final int ANY = 2;
+
+  final int level;
+  final Pattern count;
+  final Pattern from;
+
+  NodeNumberNode(int level, Pattern count, Pattern from,
+                 TemplateNode format, String lang,
+                 int letterValue, String groupingSeparator, int groupingSize)
+  {
+    super(format, lang, letterValue, groupingSeparator, groupingSize);
+    this.level = level;
+    this.count = count;
+    this.from = from;
+  }
+
+  TemplateNode clone(Stylesheet stylesheet)
+  {
+    TemplateNode ret = new NodeNumberNode(level,
+                                          (count == null) ? null :
+                                          (Pattern) count.clone(stylesheet),
+                                          (from == null) ? from :
+                                          (Pattern) from.clone(stylesheet),
+                                          format, lang, letterValue,
+                                          groupingSeparator, groupingSize);
+    if (children != null)
+      {
+        ret.children = children.clone(stylesheet);
+      }
+    if (next != null)
+      {
+        ret.next = next.clone(stylesheet);
+      }
+    return ret;
+  }
+
+  int[] compute(Stylesheet stylesheet, Node context, int pos, int len)
+    throws TransformerException
+  {
+    /*if (from != null)
+      {
+        Object ret = from.evaluate(context, pos, len);
+        if (ret instanceof Collection)
+          {
+            Collection ns = (Collection) ret;
+            if (ns.size() > 0)
+              {
+                List list = new ArrayList(ns);
+                Collections.sort(list, documentOrderComparator);
+                context = (Node) list.get(0);
+              }
+            else
+              {
+                return new int[0];
+              }
+          }
+        else
+          {
+            return new int[0];
+          }
+      }*/
+    Node current = context;
+    switch (level)
+      {
+      case SINGLE:
+        if (from == null)
+          {
+            while (context != null && !countMatches(current, context))
+              {
+                context = context.getParentNode();
+              }
+          }
+        else
+          {
+            while (context != null && !countMatches(current, context) &&
+                   !fromMatches(context))
+              {
+                context = context.getParentNode();
+              }
+          }
+        return (context == null) ? new int[0] :
+          new int[] { (context == current) ? pos : getIndex(current, context) };
+      case MULTIPLE:
+        List ancestors = new ArrayList();
+        while (context != null)
+          {
+            if (countMatches(current, context))
+              {
+                if (from == null || fromMatches(context))
+                  {
+                    ancestors.add(context);
+                  }
+              }
+            context = context.getParentNode();
+          }
+        Collections.sort(ancestors, documentOrderComparator);
+        int[] ret = new int[ancestors.size()];
+        for (int i = 0; i < ret.length; i++)
+          {
+            ret[i] = getIndex(current, (Node) ancestors.get(i));
+          }
+        return ret;
+      case ANY:
+        Expr preceding = new Selector(Selector.PRECEDING,
+                                      Collections.EMPTY_LIST);
+        Expr ancestorOrSelf = new Selector(Selector.ANCESTOR_OR_SELF,
+                                           Collections.EMPTY_LIST);
+        Expr any = new UnionExpr(preceding, ancestorOrSelf);
+        Object eval = any.evaluate(context, pos, len);
+        if (eval instanceof Collection)
+          {
+            Collection ns = (Collection) eval;
+            List candidates = new ArrayList();
+            for (Iterator i = ns.iterator(); i.hasNext(); )
+              {
+                Node candidate = (Node) i.next();
+                if (countMatches(current, candidate))
+                  {
+                    candidates.add(candidate);
+                    if (from != null && from.matches(candidate))
+                      {
+                        break;
+                      }
+                  }
+              }
+            return new int[] { candidates.size() };
+          }
+        return new int[0];
+      default:
+        throw new TransformerException("invalid level");
+      }
+  }
+
+  boolean countMatches(Node current, Node node)
+  {
+    if (count == null)
+      {
+        int cnt = current.getNodeType();
+        int nnt = node.getNodeType();
+        if (cnt != nnt)
+          {
+            return false;
+          }
+        if (nnt == Node.ELEMENT_NODE || nnt == Node.ATTRIBUTE_NODE)
+          {
+            String curi = current.getNamespaceURI();
+            String nuri = node.getNamespaceURI();
+            if ((curi == null && nuri != null) ||
+                (curi != null && !curi.equals(nuri)))
+              {
+                return false;
+              }
+            String cn = current.getLocalName();
+            if (cn == null)
+              {
+                cn = current.getNodeName();
+              }
+            String nn = node.getLocalName();
+            if (nn == null)
+              {
+                nn = node.getNodeName();
+              }
+            if (!cn.equals(nn))
+              {
+                return false;
+              }
+          }
+        return true;
+      }
+    else
+      {
+        return count.matches(node);
+      }
+  }
+
+  boolean fromMatches(Node node)
+  {
+    for (Node ctx = node.getParentNode(); ctx != null;
+         ctx = ctx.getParentNode())
+      {
+        if (from.matches(ctx))
+          {
+            return true;
+          }
+      }
+    return false;
+  }
+
+  int getIndex(Node current, Node node)
+  {
+    int index = 0;
+    do
+      {
+        do
+          {
+            node = node.getPreviousSibling();
+          }
+        while (node != null && !countMatches(current, node));
+        index++;
+      }
+    while (node != null);
+    return index;
+  }
+  
+}

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/NumberNode.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/NumberNode.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/NumberNode.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/NumberNode.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,88 @@
+/* NumberNode.java -- 
+   Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.xml.transform;
+
+import javax.xml.transform.TransformerException;
+import org.w3c.dom.Node;
+import gnu.xml.xpath.Expr;
+
+/**
+ * A template node representing the XSL <code>number</code> instruction
+ * with a <code>value</code> expression.
+ *
+ * @author <a href='mailto:dog at gnu.org'>Chris Burdess</a>
+ */
+final class NumberNode
+  extends AbstractNumberNode
+{
+
+  final Expr value;
+
+  NumberNode(Expr value, TemplateNode format, String lang,
+             int letterValue, String groupingSeparator, int groupingSize)
+  {
+    super(format, lang, letterValue, groupingSeparator, groupingSize);
+    this.value = value;
+  }
+
+  TemplateNode clone(Stylesheet stylesheet)
+  {
+    TemplateNode ret = new NumberNode(value.clone(stylesheet),
+                                      format, lang, letterValue,
+                                      groupingSeparator, groupingSize);
+    if (children != null)
+      {
+        ret.children = children.clone(stylesheet);
+      }
+    if (next != null)
+      {
+        ret.next = next.clone(stylesheet);
+      }
+    return ret;
+  }
+
+  int[] compute(Stylesheet stylesheet, Node context, int pos, int len)
+    throws TransformerException
+  {
+    Object ret = value.evaluate(context, pos, len);
+    Double d = (ret instanceof Double) ? ((Double) ret) :
+      new Double(Expr._number(context, ret));
+    return new int[] { d.intValue() };
+  }
+  
+}

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/OtherwiseNode.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/OtherwiseNode.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/OtherwiseNode.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/OtherwiseNode.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,83 @@
+/* OtherwiseNode.java -- 
+   Copyright (C) 2004,2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.xml.transform;
+
+import javax.xml.namespace.QName;
+import javax.xml.transform.TransformerException;
+import org.w3c.dom.Node;
+
+/**
+ * A template node representing an XSL <code>otherwise</code> instruction.
+ *
+ * @author <a href='mailto:dog at gnu.org'>Chris Burdess</a>
+ */
+final class OtherwiseNode
+  extends TemplateNode
+{
+
+  TemplateNode clone(Stylesheet stylesheet)
+  {
+    TemplateNode ret = new OtherwiseNode();
+    if (children != null)
+      ret.children = children.clone(stylesheet);
+    if (next != null)
+      ret.next = next.clone(stylesheet);
+    return ret;
+  }
+
+  void doApply(Stylesheet stylesheet, QName mode,
+             Node context, int pos, int len,
+             Node parent, Node nextSibling)
+    throws TransformerException
+  {
+    if (children != null)
+      children.apply(stylesheet, mode,
+                     context, pos, len,
+                     parent, nextSibling);
+    if (next != null)
+      next.apply(stylesheet, mode,
+                 context, pos, len,
+                 parent, nextSibling);
+  }
+  
+  public String toString()
+  {
+    return "otherwise";
+  }
+  
+}

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/ParameterNode.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/ParameterNode.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/ParameterNode.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/ParameterNode.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,177 @@
+/* ParameterNode.java -- 
+   Copyright (C) 2004,2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.xml.transform;
+
+import java.util.Collections;
+import javax.xml.namespace.QName;
+import javax.xml.transform.TransformerException;
+import org.w3c.dom.Document;
+import org.w3c.dom.DocumentFragment;
+import org.w3c.dom.Node;
+import gnu.xml.xpath.Expr;
+
+/**
+ * A template node that sets a variable or parameter during template
+ * processing.
+ *
+ * @author <a href='mailto:dog at gnu.org'>Chris Burdess</a>
+ */
+final class ParameterNode
+  extends TemplateNode
+  implements Comparable
+{
+
+  final QName name;
+  final Expr select;
+  final int type;
+
+  ParameterNode(QName name, Expr select, int type)
+  {
+    this.name = name;
+    this.select = select;
+    this.type = type;
+  }
+
+  TemplateNode clone(Stylesheet stylesheet)
+  {
+    TemplateNode ret = new ParameterNode(name,
+                                         select.clone(stylesheet),
+                                         type);
+    if (children != null)
+      ret.children = children.clone(stylesheet);
+    if (next != null)
+      ret.next = next.clone(stylesheet);
+    return ret;
+  }
+
+  void doApply(Stylesheet stylesheet, QName mode,
+               Node context, int pos, int len,
+               Node parent, Node nextSibling)
+    throws TransformerException
+  {
+    // push the variable context
+    stylesheet.bindings.push(type);
+    // set the variable
+    Object value = getValue(stylesheet, mode, context, pos, len);
+    if (value != null)
+      {
+        stylesheet.bindings.set(name, value, type);
+        if (stylesheet.debug)
+          System.err.println(this + ": set to " + value);
+      }
+    // variable and param don't process children as such
+    // all subsequent instructions are processed with that variable context
+    if (next != null)
+      next.apply(stylesheet, mode,
+                 context, pos, len,
+                 parent, nextSibling);
+    // pop the variable context
+    stylesheet.bindings.pop(type);
+  }
+  
+  Object getValue(Stylesheet stylesheet, QName mode,
+                  Node context, int pos, int len)
+    throws TransformerException
+  {
+    if (select != null)
+      return select.evaluate(context, pos, len);
+    else if (children != null)
+      {
+        Document doc = (context instanceof Document) ? (Document) context :
+          context.getOwnerDocument();
+        DocumentFragment fragment = doc.createDocumentFragment();
+        children.apply(stylesheet, mode, context, pos, len, fragment, null);
+        return Collections.singleton(fragment);
+      }
+    else
+      return null;
+  }
+  
+  public boolean references(QName var)
+  {
+    if (select != null && select.references(var))
+      return true;
+    return super.references(var);
+  }
+
+  public int compareTo(Object other)
+  {
+    if (other instanceof ParameterNode)
+      {
+        ParameterNode pn = (ParameterNode) other;
+        boolean r1 = references(pn.name);
+        boolean r2 = pn.references(name);
+        if (r1 && r2)
+          throw new IllegalArgumentException("circular definitions");
+        if (r1)
+          return 1;
+        if (r2)
+          return -1;
+      }
+    return 0;
+  }
+  
+  public String toString()
+  {
+    StringBuffer buf = new StringBuffer();
+    switch (type)
+      {
+      case Bindings.VARIABLE:
+        buf.append("variable");
+        break;
+      case Bindings.PARAM:
+        buf.append("param");
+        break;
+      case Bindings.WITH_PARAM:
+        buf.append("with-param");
+        break;
+      }
+    buf.append('[');
+    buf.append("name=");
+    buf.append(name);
+    if (select != null)
+      {
+        buf.append(",select=");
+        buf.append(select);
+      }
+    buf.append(']');
+    return buf.toString();
+  }
+
+}
+

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/ProcessingInstructionNode.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/ProcessingInstructionNode.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/ProcessingInstructionNode.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/ProcessingInstructionNode.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,116 @@
+/* ProcessingInstructionNode.java -- 
+   Copyright (C) 2004,2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.xml.transform;
+
+import javax.xml.namespace.QName;
+import javax.xml.transform.TransformerException;
+import org.w3c.dom.Document;
+import org.w3c.dom.DocumentFragment;
+import org.w3c.dom.Node;
+import org.w3c.dom.ProcessingInstruction;
+import gnu.xml.xpath.Expr;
+
+/**
+ * A template node representing the XSL <code>processing-instruction</code>
+ * instruction.
+ *
+ * @author <a href='mailto:dog at gnu.org'>Chris Burdess</a>
+ */
+final class ProcessingInstructionNode
+  extends TemplateNode
+{
+
+  final String name;
+
+  ProcessingInstructionNode(String name)
+  {
+    this.name = name;
+  }
+
+  TemplateNode clone(Stylesheet stylesheet)
+  {
+    TemplateNode ret = new ProcessingInstructionNode(name);
+    if (children != null)
+      ret.children = children.clone(stylesheet);
+    if (next != null)
+      ret.next = next.clone(stylesheet);
+    return ret;
+  }
+
+  void doApply(Stylesheet stylesheet, QName mode,
+               Node context, int pos, int len,
+               Node parent, Node nextSibling)
+    throws TransformerException
+  {
+    String data = null;
+    Document doc = (parent instanceof Document) ? (Document) parent :
+      parent.getOwnerDocument();
+    if (children != null)
+      {
+        // Create a document fragment to hold the text
+        DocumentFragment fragment = doc.createDocumentFragment();
+        // Apply children to the fragment
+        children.apply(stylesheet, mode,
+                       context, pos, len,
+                       fragment, null);
+        // Use XPath string-value of fragment
+        data = Expr.stringValue(fragment);
+      }
+    ProcessingInstruction pi = doc.createProcessingInstruction(name, data);
+    // Insert into result tree
+    if (nextSibling != null)
+      parent.insertBefore(pi, nextSibling);
+    else
+      parent.appendChild(pi);
+    if (next != null)
+      next.apply(stylesheet, mode,
+                 context, pos, len,
+                 parent, nextSibling);
+  }
+  
+  public String toString()
+  {
+    StringBuffer buf = new StringBuffer("processing-instruction");
+    buf.append('[');
+    buf.append("name=");
+    buf.append(name);
+    buf.append(']');
+    return buf.toString();
+  }
+  
+}

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/SAXSerializer.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/SAXSerializer.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/SAXSerializer.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/SAXSerializer.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,305 @@
+/* SAXSerializer.java -- 
+   Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.xml.transform;
+
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.LinkedList;
+import org.w3c.dom.Attr;
+import org.w3c.dom.DocumentType;
+import org.w3c.dom.NamedNodeMap;
+import org.w3c.dom.Node;
+import org.xml.sax.Attributes;
+import org.xml.sax.ContentHandler;
+import org.xml.sax.SAXException;
+import org.xml.sax.ext.LexicalHandler;
+
+/**
+ * Serializes a DOM node to a sequence of SAX events.
+ *
+ * @author <a href='mailto:dog at gnu.org'>Chris Burdess</a>
+ */
+class SAXSerializer
+  implements Attributes
+{
+
+  transient NamedNodeMap attrs;
+  transient LinkedList namespaces = new LinkedList();
+
+  boolean isDefined(String prefix, String uri)
+  {
+    for (Iterator i = namespaces.iterator(); i.hasNext(); )
+      {
+        HashMap ctx = (HashMap) i.next();
+        if (uri.equals(ctx.get(prefix)))
+          {
+            return true;
+          }
+      }
+    return false;
+  }
+
+  void define(String prefix, String uri)
+  {
+    for (Iterator i = namespaces.iterator(); i.hasNext(); )
+      {
+        HashMap ctx = (HashMap) i.next();
+        if (ctx.containsKey(prefix))
+          {
+            HashMap newCtx = new HashMap();
+            newCtx.put(prefix, uri);
+            namespaces.addFirst(newCtx);
+            return;
+          }
+      }
+    HashMap ctx;
+    if (namespaces.isEmpty())
+      {
+        ctx = new HashMap();
+        namespaces.add(ctx);
+      }
+    else
+      {
+        ctx = (HashMap) namespaces.getFirst();
+      }
+    ctx.put(prefix, uri);
+  }
+
+  void undefine(String prefix, String uri)
+  {
+    for (Iterator i = namespaces.iterator(); i.hasNext(); )
+      {
+        HashMap ctx = (HashMap) i.next();
+        if (uri.equals(ctx.get(prefix)))
+          {
+            ctx.remove(prefix);
+            if (ctx.isEmpty())
+              {
+                namespaces.remove(ctx);
+              }
+            return;
+          }
+      }
+  }
+
+  public int getLength()
+  {
+    return attrs.getLength();
+  }
+
+  public String getURI(int index)
+  {
+    return attrs.item(index).getNamespaceURI();
+  }
+
+  public String getLocalName(int index)
+  {
+    return attrs.item(index).getLocalName();
+  }
+
+  public String getQName(int index)
+  {
+    return attrs.item(index).getNodeName();
+  }
+
+  public String getType(int index)
+  {
+    Attr attr = (Attr) attrs.item(index);
+    return attr.isId() ? "ID" : "CDATA";
+  }
+
+  public String getValue(int index)
+  {
+    return attrs.item(index).getNodeValue();
+  }
+
+  public int getIndex(String uri, String localName)
+  {
+    int len = attrs.getLength();
+    for (int i = 0; i < len; i++)
+      {
+        Node attr = attrs.item(i);
+        String a_uri = attr.getNamespaceURI();
+        String a_localName = attr.getLocalName();
+        if (((a_uri == null && uri == null) ||
+             (a_uri != null && a_uri.equals(uri))) &&
+            a_localName.equals(localName))
+          {
+            return i;
+          }
+      }
+    return -1;
+  }
+
+  public int getIndex(String qName)
+  {
+    int len = attrs.getLength();
+    for (int i = 0; i < len; i++)
+      {
+        Node attr = attrs.item(i);
+        String a_name = attr.getNodeName();
+        if (a_name.equals(qName))
+          {
+            return i;
+          }
+      }
+    return -1;
+  }
+
+  public String getType(String uri, String localName)
+  {
+    Attr attr = (Attr) attrs.getNamedItemNS(uri, localName);
+    return attr.isId() ? "ID" : "CDATA";
+  }
+
+  public String getType(String qName)
+  {
+    Attr attr = (Attr) attrs.getNamedItem(qName);
+    return attr.isId() ? "ID" : "CDATA";
+  }
+
+  public String getValue(String uri, String localName)
+  {
+    return attrs.getNamedItemNS(uri, localName).getNodeValue();
+  }
+
+  public String getValue(String qName)
+  {
+    return attrs.getNamedItem(qName).getNodeValue();
+  }
+
+  void serialize(Node node, ContentHandler ch, LexicalHandler lh)
+    throws SAXException
+  {
+    attrs = node.getAttributes();
+    Node children;
+    Node next = node.getNextSibling();
+    switch (node.getNodeType())
+      {
+      case Node.ELEMENT_NODE:
+        String uri = node.getNamespaceURI();
+        String prefix = node.getPrefix();
+        boolean defined = isDefined(prefix, uri);
+        if (!defined)
+          {
+            define(prefix, uri);
+            ch.startPrefixMapping(prefix, uri);
+          }
+        String localName = node.getLocalName();
+        String qName = node.getNodeName();
+        ch.startElement(uri, localName, qName, this);
+        children = node.getFirstChild();
+        if (children != null)
+          {
+            serialize(children, ch, lh);
+          }
+        ch.endElement(uri, localName, qName);
+        if (!defined)
+          {
+            ch.endPrefixMapping(prefix);
+            undefine(prefix, uri);
+          }
+        break;
+      case Node.TEXT_NODE:
+        char[] chars = node.getNodeValue().toCharArray();
+        ch.characters(chars, 0, chars.length);
+        break;
+      case Node.CDATA_SECTION_NODE:
+        char[] cdata = node.getNodeValue().toCharArray();
+        if (lh != null)
+          {
+            lh.startCDATA();
+            ch.characters(cdata, 0, cdata.length);
+            lh.endCDATA();
+          }
+        else
+          {
+            ch.characters(cdata, 0, cdata.length);
+          }
+        break;
+      case Node.COMMENT_NODE:
+        if (lh != null)
+          {
+            char[] comment = node.getNodeValue().toCharArray();
+            lh.comment(comment, 0, comment.length);
+          }
+        break;
+      case Node.DOCUMENT_NODE:
+      case Node.DOCUMENT_FRAGMENT_NODE:
+        ch.startDocument();
+        children = node.getFirstChild();
+        if (children != null)
+          {
+            serialize(children, ch, lh);
+          }
+        ch.endDocument();
+        break;
+      case Node.DOCUMENT_TYPE_NODE:
+        if (lh != null)
+          {
+            DocumentType doctype = (DocumentType) node;
+            String publicId = doctype.getPublicId();
+            String systemId = doctype.getSystemId();
+            lh.startDTD(node.getNodeName(), publicId, systemId);
+            NamedNodeMap entities = doctype.getEntities();
+            int len = entities.getLength();
+            for (int i = 0; i < len; i++)
+              {
+                Node entity = entities.item(i);
+                String entityName = entity.getNodeName();
+                lh.startEntity(entityName);
+                lh.endEntity(entityName);
+              }
+            lh.endDTD();
+          }
+        break;
+      case Node.PROCESSING_INSTRUCTION_NODE:
+        ch.processingInstruction(node.getNodeName(), node.getNodeValue());
+        break;
+      case Node.ENTITY_REFERENCE_NODE:
+        ch.skippedEntity(node.getNodeName());
+        break;
+      }
+    attrs = null;
+    if (next != null)
+      {
+        serialize(next, ch, lh);
+      }
+  }
+
+}

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/SortKey.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/SortKey.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/SortKey.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/SortKey.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,179 @@
+/* SortKey.java -- 
+   Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.xml.transform;
+
+import javax.xml.namespace.QName;
+import javax.xml.transform.TransformerException;
+import org.w3c.dom.Document;
+import org.w3c.dom.DocumentFragment;
+import org.w3c.dom.Node;
+import gnu.xml.xpath.Expr;
+
+/**
+ * An XSL sort key.
+ *
+ * @author <a href='mailto:dog at gnu.org'>Chris Burdess</a>
+ */
+final class SortKey
+{
+
+  static final int DEFAULT = 0;
+  static final int UPPER_FIRST = 1;
+  static final int LOWER_FIRST = 2;
+
+  final Expr select;
+  final TemplateNode langTemplate;
+  final TemplateNode dataTypeTemplate;
+  final TemplateNode orderTemplate;
+  final TemplateNode caseOrderTemplate;
+
+  transient String lang;
+  transient String dataType;
+  transient boolean descending;
+  transient int caseOrder;
+
+  SortKey(Expr select, TemplateNode lang, TemplateNode dataType,
+          TemplateNode order, TemplateNode caseOrder)
+  {
+    this.select = select;
+    this.langTemplate = lang;
+    this.dataTypeTemplate = dataType;
+    this.orderTemplate = order;
+    this.caseOrderTemplate = caseOrder;
+  }
+
+  String key(Node node)
+  {
+    Object ret = select.evaluate(node, 1, 1);
+    if (ret instanceof String)
+      {
+        return (String) ret;
+      }
+    else
+      {
+        return Expr._string(node, ret);
+      }
+  }
+
+  /**
+   * Prepare for a sort.
+   * This sets all transient variables from their AVTs.
+   */
+  void init(Stylesheet stylesheet, QName mode,
+            Node context, int pos, int len,
+            Node parent, Node nextSibling)
+    throws TransformerException
+  {
+    Document doc = (context instanceof Document) ? (Document) context :
+      context.getOwnerDocument();
+    if (langTemplate == null)
+      {
+        lang = null;
+      }
+    else
+      {
+        DocumentFragment fragment = doc.createDocumentFragment();
+        langTemplate.apply(stylesheet, mode, context, pos, len,
+                           fragment, null);
+        lang = Expr.stringValue(fragment);
+      }
+    if (dataTypeTemplate == null)
+      {
+        dataType = "text";
+      }
+    else
+      {
+        DocumentFragment fragment = doc.createDocumentFragment();
+        dataTypeTemplate.apply(stylesheet, mode, context, pos, len,
+                               fragment, null);
+        dataType = Expr.stringValue(fragment);
+      }
+    if (orderTemplate == null)
+      {
+        descending = false;
+      }
+    else
+      {
+        DocumentFragment fragment = doc.createDocumentFragment();
+        orderTemplate.apply(stylesheet, mode, context, pos, len,
+                            fragment, null);
+        String order = Expr.stringValue(fragment);
+        descending = "descending".equals(order);
+      }
+    if (caseOrderTemplate == null)
+      {
+        caseOrder = DEFAULT;
+      }
+    else
+      {
+        DocumentFragment fragment = doc.createDocumentFragment();
+        caseOrderTemplate.apply(stylesheet, mode, context, pos, len,
+                                fragment, null);
+        String co = Expr.stringValue(fragment);
+        caseOrder = "upper-first".equals(co) ? UPPER_FIRST :
+          "lower-first".equals(co) ? LOWER_FIRST :
+          DEFAULT;
+      }
+  }
+
+  boolean references(QName var)
+  {
+    if (select != null && select.references(var))
+      {
+        return true;
+      }
+    if (langTemplate != null && langTemplate.references(var))
+      {
+        return true;
+      }
+    if (dataTypeTemplate != null && dataTypeTemplate.references(var))
+      {
+        return true;
+      }
+    if (orderTemplate != null && orderTemplate.references(var))
+      {
+        return true;
+      }
+    if (caseOrderTemplate != null && caseOrderTemplate.references(var))
+      {
+        return true;
+      }
+    return false;
+  }
+
+}

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/StreamSerializer.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/StreamSerializer.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/StreamSerializer.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/StreamSerializer.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,852 @@
+/* StreamSerializer.java -- 
+   Copyright (C) 2004,2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.xml.transform;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.io.UnsupportedEncodingException;
+import java.nio.ByteBuffer;
+import java.nio.CharBuffer;
+import java.nio.charset.Charset;
+import java.nio.charset.CharsetEncoder;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.Map;
+import javax.xml.XMLConstants;
+import org.w3c.dom.Attr;
+import org.w3c.dom.Document;
+import org.w3c.dom.DocumentType;
+import org.w3c.dom.NamedNodeMap;
+import org.w3c.dom.Node;
+
+/**
+ * Serializes a DOM node to an output stream.
+ *
+ * @author <a href='mailto:dog at gnu.org'>Chris Burdess</a>
+ */
+public class StreamSerializer
+{
+  
+  static final int SPACE = 0x20;
+  static final int BANG = 0x21; // !
+  static final int APOS = 0x27; // '
+  static final int SLASH = 0x2f; // /
+  static final int BRA = 0x3c; // <
+  static final int KET = 0x3e; // >
+  static final int EQ = 0x3d; // =
+
+  /**
+   * HTML 4.01 boolean attributes
+   */
+  static final Map HTML_BOOLEAN_ATTRIBUTES = new HashMap();
+  static
+  {
+    HashSet set;
+    
+    set = new HashSet();
+    set.add("nohref");
+    HTML_BOOLEAN_ATTRIBUTES.put("area", set);
+
+    set = new HashSet();
+    set.add("ismap");
+    HTML_BOOLEAN_ATTRIBUTES.put("img", set);
+
+    set = new HashSet();
+    set.add("declare");
+    HTML_BOOLEAN_ATTRIBUTES.put("object", set);
+    
+    set = new HashSet();
+    set.add("noshade");
+    HTML_BOOLEAN_ATTRIBUTES.put("hr", set);
+    
+    set = new HashSet();
+    set.add("compact");
+    HTML_BOOLEAN_ATTRIBUTES.put("dl", set);
+    HTML_BOOLEAN_ATTRIBUTES.put("ol", set);
+    HTML_BOOLEAN_ATTRIBUTES.put("ul", set);
+    HTML_BOOLEAN_ATTRIBUTES.put("dir", set);
+    HTML_BOOLEAN_ATTRIBUTES.put("menu", set);
+    
+    set = new HashSet();
+    set.add("checked");
+    set.add("disabled");
+    set.add("readonly");
+    set.add("ismap");
+    HTML_BOOLEAN_ATTRIBUTES.put("input", set);
+    
+    set = new HashSet();
+    set.add("multiple");
+    set.add("disabled");
+    HTML_BOOLEAN_ATTRIBUTES.put("select", set);
+    
+    set = new HashSet();
+    set.add("disabled");
+    HTML_BOOLEAN_ATTRIBUTES.put("optgroup", set);
+    
+    set = new HashSet();
+    set.add("selected");
+    set.add("disabled");
+    HTML_BOOLEAN_ATTRIBUTES.put("option", set);
+    
+    set = new HashSet();
+    set.add("disabled");
+    set.add("readonly");
+    HTML_BOOLEAN_ATTRIBUTES.put("textarea", set);
+    
+    set = new HashSet();
+    set.add("disabled");
+    HTML_BOOLEAN_ATTRIBUTES.put("button", set);
+    
+    set = new HashSet();
+    set.add("nowrap");
+    HTML_BOOLEAN_ATTRIBUTES.put("th", set);
+    HTML_BOOLEAN_ATTRIBUTES.put("td", set);
+    
+    set = new HashSet();
+    set.add("noresize");
+    HTML_BOOLEAN_ATTRIBUTES.put("frame", set);
+    
+    set = new HashSet();
+    set.add("defer");
+    HTML_BOOLEAN_ATTRIBUTES.put("script", set);
+  }
+
+  // HTML namespace URIs
+  static final HashSet HTML_URIS = new HashSet();
+  static {
+    HTML_URIS.add("http://www.w3.org/1999/xhtml");
+  }
+
+  protected final String encoding;
+  final Charset charset;
+  final CharsetEncoder encoder;
+  final int mode;
+  final LinkedList namespaces;
+  protected String eol;
+  Collection cdataSectionElements = Collections.EMPTY_SET;
+
+  protected boolean discardDefaultContent;
+  protected boolean xmlDeclaration = true;
+  
+  // has a META element with the encoding been added?
+  private boolean htmlEncoded;
+
+  public StreamSerializer()
+  {
+    this(Stylesheet.OUTPUT_XML, null, null);
+  }
+
+  public StreamSerializer(String encoding)
+  {
+    this(Stylesheet.OUTPUT_XML, encoding, null);
+  }
+
+  public StreamSerializer(int mode, String encoding, String eol)
+  {
+    this.mode = mode;
+    if (encoding == null)
+      encoding = (mode == Stylesheet.OUTPUT_HTML) ? "ISO-8859-1" : "UTF-8";
+    this.encoding = encoding.intern();
+    charset = Charset.forName(this.encoding);
+    encoder = charset.newEncoder();
+    this.eol = (eol != null) ? eol : System.getProperty("line.separator");
+    namespaces = new LinkedList();
+  }
+
+  void setCdataSectionElements(Collection c)
+  {
+    cdataSectionElements = c;
+  }
+
+  public void serialize(final Node node, final OutputStream out)
+    throws IOException
+  {
+    serialize(node, out, false);
+  }
+  
+  void serialize(Node node, final OutputStream out,
+                 boolean convertToCdata)
+    throws IOException
+  {
+    while (node != null)
+      {
+        Node next = node.getNextSibling();
+        doSerialize(node, out, convertToCdata);
+        node = next;
+      }
+  }
+
+  private void doSerialize(final Node node, final OutputStream out,
+                           boolean convertToCdata)
+    throws IOException
+  {
+    if (out == null)
+      throw new NullPointerException("no output stream");
+    htmlEncoded = false;
+    String value, prefix;
+    Node children;
+    String uri = node.getNamespaceURI();
+    short nt = node.getNodeType();
+    if (convertToCdata && nt == Node.TEXT_NODE)
+      nt = Node.CDATA_SECTION_NODE;
+    switch (nt)
+      {
+      case Node.ATTRIBUTE_NODE:
+        prefix = node.getPrefix();
+        if (XMLConstants.XMLNS_ATTRIBUTE_NS_URI.equals(uri) ||
+            XMLConstants.XMLNS_ATTRIBUTE.equals(prefix) ||
+            (prefix != null && prefix.startsWith("xmlns:")))
+          {
+            String nsuri = node.getNodeValue();
+            if (isDefined(nsuri, prefix))
+              break;
+            String name = node.getLocalName();
+            if (name == null)
+              {
+                // Namespace-unaware
+                name = node.getNodeName();
+                int ci = name.indexOf(':');
+                if (ci != -1)
+                  name = name.substring(ci + 1);
+              }
+            define(nsuri, name);
+          }
+        else if (uri != null && !isDefined(uri, prefix))
+          {
+            prefix = define(uri, prefix);
+            String nsname = (prefix == null) ? "xmlns" : "xmlns:" + prefix;
+            out.write(SPACE);
+            out.write(encodeText(nsname));
+            out.write(EQ);
+            String nsvalue = "\"" + encode(uri, true, true) + "\"";
+            out.write(nsvalue.getBytes(encoding));
+          }
+        out.write(SPACE);
+        String a_nodeName = node.getNodeName();
+        out.write(encodeText(a_nodeName));
+        String a_nodeValue = node.getNodeValue();
+        if (mode == Stylesheet.OUTPUT_HTML &&
+            a_nodeName.equals(a_nodeValue) &&
+            isHTMLBoolean((Attr) node, a_nodeName))
+          break;
+        out.write(EQ);
+        value = "\"" + encode(a_nodeValue, true, true) + "\"";
+        out.write(encodeText(value));
+        break;
+      case Node.ELEMENT_NODE:
+        pushNamespaceContext();
+        value = node.getNodeName();
+        out.write(BRA);
+        out.write(encodeText(value));
+        prefix = node.getPrefix();
+        if (uri != null && !isDefined(uri, prefix))
+          {
+            prefix = define(uri, prefix);
+            String nsname = (prefix == null) ? "xmlns" : "xmlns:" + prefix;
+            out.write(SPACE);
+            out.write(encodeText(nsname));
+            out.write(EQ);
+            String nsvalue = "\"" + encode(uri, true, true) + "\"";
+            out.write(encodeText(nsvalue));
+          }
+        NamedNodeMap attrs = node.getAttributes();
+        if (attrs != null)
+          {
+            int len = attrs.getLength();
+            for (int i = 0; i < len; i++)
+              {
+                Attr attr = (Attr) attrs.item(i);
+                if (discardDefaultContent && !attr.getSpecified())
+                  {
+                    // NOOP
+                  }
+                else
+                  serialize(attr, out, false);
+              }
+          }
+        convertToCdata = cdataSectionElements.contains(value);
+        children = node.getFirstChild();
+        if (children == null)
+          {
+            out.write(SLASH);
+            out.write(KET);
+          }
+        else
+          {
+            out.write(KET);
+            serialize(children, out, convertToCdata);
+            out.write(BRA);
+            out.write(SLASH);
+            out.write(encodeText(value));
+            out.write(KET);
+          }
+        popNamespaceContext();
+        break;
+      case Node.TEXT_NODE:
+        value = node.getNodeValue();
+        if (!"yes".equals(node.getUserData("disable-output-escaping")))
+          value = encode(value, false, false);
+        out.write(encodeText(value));
+        break;
+      case Node.CDATA_SECTION_NODE:
+        value = node.getNodeValue();
+        // Where any instanceof of ]]> occur, split into multiple CDATA
+        // sections
+        int bbk = value.indexOf("]]>");
+        while (bbk != -1)
+          {
+            String head = value.substring(0, bbk + 2);
+            out.write(encodeText("<![CDATA[" + head + "]]>"));
+            value = value.substring(bbk + 2);
+            bbk = value.indexOf("]]>");
+          }
+        // Write final tail value
+        out.write(encodeText("<![CDATA[" + value + "]]>"));
+        break;
+      case Node.COMMENT_NODE:
+        value = "<!--" + node.getNodeValue() + "-->";
+        out.write(encodeText(value));
+        Node cp = node.getParentNode();
+        if (cp != null && cp.getNodeType() == Node.DOCUMENT_NODE)
+          out.write(encodeText(eol));
+        break;
+      case Node.DOCUMENT_NODE:
+      case Node.DOCUMENT_FRAGMENT_NODE:
+        if (mode == Stylesheet.OUTPUT_XML)
+          {
+            if ("UTF-16".equalsIgnoreCase(encoding))
+              {
+                out.write(0xfe);
+                out.write(0xff);
+              }
+            if (!"yes".equals(node.getUserData("omit-xml-declaration")) &&
+                xmlDeclaration)
+              {
+                Document doc = (node instanceof Document) ?
+                  (Document) node : null;
+                String version = (doc != null) ? doc.getXmlVersion() : null;
+                if (version == null)
+                  version = (String) node.getUserData("version");
+                if (version == null)
+                  version = "1.0";
+                out.write(BRA);
+                out.write(0x3f);
+                out.write("xml version=\"".getBytes("US-ASCII"));
+                out.write(version.getBytes("US-ASCII"));
+                out.write(0x22);
+                if (!("UTF-8".equalsIgnoreCase(encoding)))
+                  {
+                    out.write(" encoding=\"".getBytes("US-ASCII"));
+                    out.write(encoding.getBytes("US-ASCII"));
+                    out.write(0x22);
+                  }
+                if ((doc != null && doc.getXmlStandalone()) ||
+                    "yes".equals(node.getUserData("standalone")))
+                  out.write(" standalone=\"yes\"".getBytes("US-ASCII"));
+                out.write(0x3f);
+                out.write(KET);
+                out.write(encodeText(eol));
+              }
+            // TODO warn if not outputting the declaration would be a
+            // problem
+          }
+        else if (mode == Stylesheet.OUTPUT_HTML)
+          {
+            // Ensure that encoding is accessible if head element is present
+            String mediaType = (String) node.getUserData("media-type");
+            if (mediaType == null)
+              mediaType = "text/html";
+            String contentType = mediaType + "; charset=" +
+              ((encoding.indexOf(' ') != -1) ?
+                "\"" + encoding + "\"" :
+                encoding);
+            Document doc = (node instanceof Document) ? (Document) node :
+              node.getOwnerDocument();
+            Node html = null;
+            for (Node ctx = node.getFirstChild(); ctx != null;
+                 ctx = ctx.getNextSibling())
+              {
+                if (ctx.getNodeType() == Node.ELEMENT_NODE &&
+                    isHTMLElement(ctx, "html"))
+                  {
+                    html = ctx;
+                    break;
+                  }
+              }
+            if (html != null)
+              {
+                Node head = null;
+                for (Node ctx = html.getFirstChild(); ctx != null;
+                     ctx = ctx.getNextSibling())
+                  {
+                    if (isHTMLElement(ctx, "head"))
+                      {
+                        head = ctx;
+                        break;
+                      }
+                  }
+                if (head != null)
+                  {
+                    Node meta = null;
+                    Node metaContent = null;
+                    for (Node ctx = head.getFirstChild(); ctx != null;
+                         ctx = ctx.getNextSibling())
+                      {
+                        if (isHTMLElement(ctx, "meta"))
+                          {
+                            NamedNodeMap metaAttrs = ctx.getAttributes();
+                            int len = metaAttrs.getLength();
+                            String httpEquiv = null;
+                            Node content = null;
+                            for (int i = 0; i < len; i++)
+                              {
+                                Node attr = metaAttrs.item(i);
+                                String attrName = attr.getNodeName();
+                                if ("http-equiv".equalsIgnoreCase(attrName))
+                                  httpEquiv = attr.getNodeValue();
+                                else if ("content".equalsIgnoreCase(attrName))
+                                  content = attr;
+                              }
+                            if ("Content-Type".equalsIgnoreCase(httpEquiv))
+                              {
+                                meta = ctx;
+                                metaContent = content;
+                                break;
+                              }
+                          }
+                      }
+                    if (meta == null)
+                      {
+                        meta = doc.createElement("meta");
+                        // Insert first
+                        Node first = head.getFirstChild();
+                        if (first == null)
+                          head.appendChild(meta);
+                        else
+                          head.insertBefore(meta, first);
+                        Node metaHttpEquiv = doc.createAttribute("http-equiv");
+                        meta.getAttributes().setNamedItem(metaHttpEquiv);
+                        metaHttpEquiv.setNodeValue("Content-Type");
+                      }
+                    if (metaContent == null)
+                      {
+                        metaContent = doc.createAttribute("content");
+                        meta.getAttributes().setNamedItem(metaContent);
+                      }
+                    metaContent.setNodeValue(contentType);
+                    htmlEncoded = true;
+                  }
+              }
+          }
+        children = node.getFirstChild();
+        if (children != null)
+          serialize(children, out, convertToCdata);
+        break;
+      case Node.DOCUMENT_TYPE_NODE:
+        DocumentType doctype = (DocumentType) node;
+        out.write(BRA);
+        out.write(BANG);
+        out.write(encodeText("DOCTYPE "));
+        value = doctype.getNodeName();
+        out.write(encodeText(value));
+        String publicId = doctype.getPublicId();
+        if (publicId != null)
+          {
+            out.write(encodeText(" PUBLIC "));
+            out.write(APOS);
+            out.write(encodeText(publicId));
+            out.write(APOS);
+          }
+        String systemId = doctype.getSystemId();
+        if (systemId != null)
+          {
+            out.write(encodeText(" SYSTEM "));
+            out.write(APOS);
+            out.write(encodeText(systemId));
+            out.write(APOS);
+          }
+        String internalSubset = doctype.getInternalSubset();
+        if (internalSubset != null)
+          {
+            out.write(encodeText(internalSubset));
+          }
+        out.write(KET);
+        out.write(eol.getBytes(encoding));
+        break;
+      case Node.ENTITY_REFERENCE_NODE:
+        value = "&" + node.getNodeValue() + ";";
+        out.write(encodeText(value));
+        break;
+      case Node.PROCESSING_INSTRUCTION_NODE:
+        value = "<?" + node.getNodeName() + " " + node.getNodeValue() + "?>";
+        out.write(encodeText(value));
+        Node pp = node.getParentNode();
+        if (pp != null && pp.getNodeType() == Node.DOCUMENT_NODE)
+          {
+            out.write(encodeText(eol));
+          }
+        break;
+      default:
+        System.err.println("Unhandled node type: "+nt);
+      }
+  }
+
+  boolean isHTMLElement(Node node, String name)
+  {
+    if (node.getNodeType() != Node.ELEMENT_NODE)
+      return false;
+    String localName = node.getLocalName();
+    if (localName == null)
+      localName = node.getNodeName();
+    if (!name.equalsIgnoreCase(localName))
+      return false;
+    String uri = node.getNamespaceURI();
+    return (uri == null || HTML_URIS.contains(uri));
+  }
+
+  boolean isDefined(String uri, String prefix)
+  {
+    if (XMLConstants.XML_NS_URI.equals(uri))
+      return "xml".equals(prefix);
+    if (XMLConstants.XMLNS_ATTRIBUTE_NS_URI.equals(uri))
+      return "xmlns".equals(prefix);
+    if (prefix == null)
+      prefix = "";
+    for (Iterator i = namespaces.iterator(); i.hasNext(); )
+      {
+        Map ctx = (Map) i.next();
+        String val = (String) ctx.get(uri);
+        if (val != null && val.equals(prefix))
+          return true;
+      }
+    return false;
+  }
+
+  void pushNamespaceContext()
+  {
+    namespaces.addFirst(new HashMap());
+  }
+
+  String define(String uri, String prefix)
+  {
+    if (namespaces.isEmpty())
+      return prefix;
+    HashMap ctx = (HashMap) namespaces.getFirst();
+    while (ctx.containsValue(prefix))
+      {
+        // Fabricate new prefix
+        prefix = prefix + "_";
+      }
+    ctx.put(uri, prefix);
+    return prefix;
+  }
+
+  void popNamespaceContext()
+  {
+    namespaces.removeFirst();
+  }
+
+  final byte[] encodeText(String text)
+    throws IOException
+  {
+    encoder.reset();
+    boolean htmlNeedingEncoding =
+      (mode == Stylesheet.OUTPUT_HTML && !htmlEncoded);
+    if (!encoder.canEncode(text) || htmlNeedingEncoding)
+      {
+        // Check each character
+        StringBuffer buf = new StringBuffer();
+        int len = text.length();
+        for (int i = 0; i < len; i++)
+          {
+            char c = text.charAt(i);
+            if (!encoder.canEncode(c))
+              {
+                // Replace with character entity reference
+                String hex = Integer.toHexString((int) c);
+                buf.append("&#x");
+                buf.append(hex);
+                buf.append(';');
+              }
+            else if (htmlNeedingEncoding)
+              {
+                String entityName = getHTMLCharacterEntity(c);
+                if (entityName != null)
+                  {
+                    buf.append('&');
+                    buf.append(entityName);
+                    buf.append(';');
+                  }
+                else
+                  buf.append(c);
+              }
+            else
+              buf.append(c);
+          }
+        text = buf.toString();
+      }
+    ByteBuffer encoded = encoder.encode(CharBuffer.wrap(text));
+    int len = encoded.limit() - encoded.position();
+    if (encoded.hasArray())
+      {
+        byte[] ret = encoded.array();
+        if (ret.length > len)
+          {
+            // Why?
+            byte[] ret2 = new byte[len];
+            System.arraycopy(ret, 0, ret2, 0, len);
+            ret = ret2;
+          }
+        return ret;
+      }
+    encoded.flip();
+    byte[] ret = new byte[len];
+    encoded.get(ret, 0, len);
+    return ret;
+  }
+
+  String encode(String text, boolean encodeCtl, boolean inAttr)
+  {
+    int len = text.length();
+    StringBuffer buf = null;
+    for (int i = 0; i < len; i++)
+      {
+        char c = text.charAt(i);
+        if (c == '<')
+          {
+            if (buf == null)
+              buf = new StringBuffer(text.substring(0, i));
+            buf.append("<");
+          }
+        else if (c == '>')
+          {
+            if (buf == null)
+              buf = new StringBuffer(text.substring(0, i));
+            buf.append(">");
+          }
+        else if (c == '&')
+          {
+            if (mode == Stylesheet.OUTPUT_HTML && (i + 1) < len &&
+                text.charAt(i + 1) == '{')
+              {
+                if (buf != null)
+                  buf.append(c);
+              }
+            else
+              {
+                if (buf == null)
+                  buf = new StringBuffer(text.substring(0, i));
+                buf.append("&");
+              }
+          }
+        else if (c == '\'' && inAttr)
+          {
+            if (buf == null)
+              buf = new StringBuffer(text.substring(0, i));
+            if (mode == Stylesheet.OUTPUT_HTML)
+              // HTML does not define ', use character entity ref
+              buf.append("&#x27;");
+            else
+              buf.append("'");
+          }
+        else if (c == '"' && inAttr)
+          {
+            if (buf == null)
+              buf = new StringBuffer(text.substring(0, i));
+            buf.append(""");
+          }
+        else if (encodeCtl)
+          {
+            if (c < 0x20)
+              {
+                if (buf == null)
+                  buf = new StringBuffer(text.substring(0, i));
+                buf.append('&');
+                buf.append('#');
+                buf.append((int) c);
+                buf.append(';');
+              }
+            else if (buf != null)
+              buf.append(c);
+          }
+        else if (buf != null)
+          buf.append(c);
+      }
+    return (buf == null) ? text : buf.toString();
+  }
+
+  String toString(Node node)
+  {
+    ByteArrayOutputStream out = new ByteArrayOutputStream();
+    try
+      {
+        serialize(node, out);
+        return new String(out.toByteArray(), encoding);
+      }
+    catch (IOException e)
+      {
+        throw new RuntimeException(e.getMessage());
+      }
+  }
+
+  boolean isHTMLBoolean(Attr attr, String attrName)
+  {
+    attrName = attrName.toLowerCase();
+    Node element = attr.getOwnerElement();
+    String elementName = element.getLocalName();
+    if (elementName == null)
+      {
+        elementName = element.getNodeName();
+      }
+    elementName = elementName.toLowerCase();
+    Collection attributes =
+      (Collection) HTML_BOOLEAN_ATTRIBUTES.get(elementName);
+    return (attributes != null && attributes.contains(attrName));
+  }
+
+  static String getHTMLCharacterEntity(char c)
+  {
+    // Hardcode these here to avoid loading the HTML DTD
+    switch (c)
+      {
+      case 160: return "nbsp";
+      case 161: return "iexcl";
+      case 162: return "cent";
+      case 163: return "pound";
+      case 164: return "curren";
+      case 165: return "yen";
+      case 166: return "brvbar";
+      case 167: return "sect";
+      case 168: return "uml";
+      case 169: return "copy";
+      case 170: return "ordf";
+      case 171: return "laquo";
+      case 172: return "not";
+      case 173: return "shy";
+      case 174: return "reg";
+      case 175: return "macr";
+      case 176: return "deg";
+      case 177: return "plusmn";
+      case 178: return "sup2";
+      case 179: return "sup3";
+      case 180: return "acute";
+      case 181: return "micro";
+      case 182: return "para";
+      case 183: return "middot";
+      case 184: return "cedil";
+      case 185: return "sup1";
+      case 186: return "ordm";
+      case 187: return "raquo";
+      case 188: return "frac14";
+      case 189: return "frac12";
+      case 190: return "frac34";
+      case 191: return "iquest";
+      case 192: return "Agrave";
+      case 193: return "Aacute";
+      case 194: return "Acirc";
+      case 195: return "Atilde";
+      case 196: return "Auml";
+      case 197: return "Aring";
+      case 198: return "AElig";
+      case 199: return "Ccedil";
+      case 200: return "Egrave";
+      case 201: return "Eacute";
+      case 202: return "Ecirc";
+      case 203: return "Euml";
+      case 204: return "Igrave";
+      case 205: return "Iacute";
+      case 206: return "Icirc";
+      case 207: return "Iuml";
+      case 208: return "ETH";
+      case 209: return "Ntilde";
+      case 210: return "Ograve";
+      case 211: return "Oacute";
+      case 212: return "Ocirc";
+      case 213: return "Otilde";
+      case 214: return "Ouml";
+      case 215: return "times";
+      case 216: return "Oslash";
+      case 217: return "Ugrave";
+      case 218: return "Uacute";
+      case 219: return "Ucirc";
+      case 220: return "Uuml";
+      case 221: return "Yacute";
+      case 222: return "THORN";
+      case 223: return "szlig";
+      case 224: return "agrave";
+      case 225: return "aacute";
+      case 226: return "acirc";
+      case 227: return "atilde";
+      case 228: return "auml";
+      case 229: return "aring";
+      case 230: return "aelig";
+      case 231: return "ccedil";
+      case 232: return "egrave";
+      case 233: return "eacute";
+      case 234: return "ecirc";
+      case 235: return "euml";
+      case 236: return "igrave";
+      case 237: return "iacute";
+      case 238: return "icirc";
+      case 239: return "iuml";
+      case 240: return "eth";
+      case 241: return "ntilde";
+      case 242: return "ograve";
+      case 243: return "oacute";
+      case 244: return "ocirc";
+      case 245: return "otilde";
+      case 246: return "ouml";
+      case 247: return "divide";
+      case 248: return "oslash";
+      case 249: return "ugrave";
+      case 250: return "uacute";
+      case 251: return "ucirc";
+      case 252: return "uuml";
+      case 253: return "yacute";
+      case 254: return "thorn";
+      case 255: return "yuml";
+      default: return null;
+      }
+  }
+
+}

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/StrippingInstruction.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/StrippingInstruction.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/StrippingInstruction.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/StrippingInstruction.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,73 @@
+/* StrippingInstruction.java -- 
+   Copyright (C) 2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.xml.transform;
+
+import gnu.xml.xpath.NameTest;
+
+/**
+ * An entry in a strip-space or preserve-space list.
+ *
+ * @author <a href='mailto:dog at gnu.org'>Chris Burdess</a>
+ */
+class StrippingInstruction
+{
+
+  final NameTest element;
+  final int precedence;
+  
+  StrippingInstruction(NameTest element, int precedence)
+  {
+    this.element = element;
+    this.precedence = precedence;
+  }
+
+  /**
+   * Returns the <i>default priority</i> of the element name test.
+   * @see http://www.w3.org/TR/xslt#dt-default-priority
+   */
+  float getPriority()
+  {
+    if (element.matchesAny())
+      return -0.5f;
+    else if (element.matchesAnyLocalName())
+      return -0.25f;
+    else
+      return 0.0f;
+  }
+  
+}

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/Stylesheet.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/Stylesheet.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/Stylesheet.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/Stylesheet.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,1773 @@
+/* Stylesheet.java -- 
+   Copyright (C) 2004,2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.xml.transform;
+
+import java.text.DecimalFormat;
+import java.text.DecimalFormatSymbols;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.StringTokenizer;
+import java.util.TreeSet;
+import javax.xml.XMLConstants;
+import javax.xml.namespace.NamespaceContext;
+import javax.xml.namespace.QName;
+import javax.xml.transform.Source;
+import javax.xml.transform.TransformerConfigurationException;
+import javax.xml.transform.TransformerException;
+import javax.xml.xpath.XPathFunction;
+import javax.xml.xpath.XPathFunctionResolver;
+import javax.xml.xpath.XPathExpressionException;
+import org.w3c.dom.Attr;
+import org.w3c.dom.Document;
+import org.w3c.dom.DOMException;
+import org.w3c.dom.Element;
+import org.w3c.dom.NamedNodeMap;
+import org.w3c.dom.Node;
+import org.w3c.dom.Text;
+import org.w3c.dom.UserDataHandler;
+import gnu.xml.xpath.Expr;
+import gnu.xml.xpath.NameTest;
+import gnu.xml.xpath.NodeTypeTest;
+import gnu.xml.xpath.Pattern;
+import gnu.xml.xpath.Selector;
+import gnu.xml.xpath.Root;
+import gnu.xml.xpath.Test;
+import gnu.xml.xpath.XPathImpl;
+
+/**
+ * An XSL stylesheet.
+ *
+ * @author <a href='mailto:dog at gnu.org'>Chris Burdess</a>
+ */
+class Stylesheet
+  implements NamespaceContext, XPathFunctionResolver, UserDataHandler, Cloneable
+{
+
+  static final String XSL_NS = "http://www.w3.org/1999/XSL/Transform";
+  private static final NameTest STYLESHEET_PRESERVE_TEXT =
+    new NameTest(new QName(XSL_NS, "text"), false, false);
+  
+  static final int OUTPUT_XML = 0;
+  static final int OUTPUT_HTML = 1;
+  static final int OUTPUT_TEXT = 2;
+
+  final TransformerFactoryImpl factory;
+  TransformerImpl transformer;
+  Stylesheet parent;
+  final XPathImpl xpath;
+  final String systemId;
+  final int precedence;
+
+  final boolean debug;
+
+  /**
+   * Version of XSLT.
+   */
+  String version;
+
+  Collection extensionElementPrefixes;
+  Collection excludeResultPrefixes;
+
+  /**
+   * Set of element names for which we should strip whitespace.
+   */
+  Set stripSpace;
+
+  /**
+   * Set of element names for which we should preserve whitespace.
+   */
+  Set preserveSpace;
+
+  /**
+   * Output options.
+   */
+  Node output;
+  int outputMethod;
+  String outputVersion;
+  String outputEncoding;
+  boolean outputOmitXmlDeclaration;
+  boolean outputStandalone;
+  String outputPublicId;
+  String outputSystemId;
+  Collection outputCdataSectionElements;
+  boolean outputIndent;
+  String outputMediaType;
+
+  /**
+   * Keys.
+   */
+  Collection keys;
+
+  /**
+   * Decimal formats.
+   */
+  Map decimalFormats;
+  
+  /**
+   * Namespace aliases.
+   */
+  Map namespaceAliases;
+
+  /**
+   * Attribute-sets.
+   */
+  List attributeSets;
+
+  /**
+   * Variables.
+   */
+  List variables;
+
+  /**
+   * Variable and parameter bindings.
+   */
+  Bindings bindings;
+
+  /**
+   * Templates.
+   */
+  LinkedList templates;
+
+  TemplateNode builtInNodeTemplate;
+  TemplateNode builtInTextTemplate;
+
+  /**
+   * Holds the current node while parsing.
+   * Necessary to associate the document function with its declaring node,
+   * to resolve namespaces, and to maintain the current node for the
+   * current() function.
+   */
+  Node current;
+
+  /**
+   * Set by a terminating message.
+   */
+  transient boolean terminated;
+
+  /**
+   * Current template in force.
+   */
+  transient Template currentTemplate;
+
+  Stylesheet(TransformerFactoryImpl factory,
+             Stylesheet parent,
+             Document doc,
+             String systemId,
+             int precedence)
+    throws TransformerConfigurationException
+  {
+    this.factory = factory;
+    this.systemId = systemId;
+    this.precedence = precedence;
+    this.parent = parent;
+    extensionElementPrefixes = new HashSet();
+    excludeResultPrefixes = new HashSet();
+    stripSpace = new LinkedHashSet();
+    preserveSpace = new LinkedHashSet();
+    outputCdataSectionElements = new LinkedHashSet();
+    xpath = (XPathImpl) factory.xpathFactory.newXPath();
+    xpath.setNamespaceContext(this);
+    if (parent == null)
+      {
+        bindings = new Bindings(this);
+        attributeSets = new LinkedList();
+        variables = new LinkedList();
+        namespaceAliases = new LinkedHashMap();
+        templates = new LinkedList();
+        keys = new LinkedList();
+        decimalFormats = new LinkedHashMap();
+        initDefaultDecimalFormat();
+        xpath.setXPathFunctionResolver(this);
+      }
+    else
+      {
+        /* Test for import circularity */
+        for (Stylesheet ctx = this; ctx.parent != null; ctx = ctx.parent)
+          {
+            if (systemId != null && systemId.equals(ctx.parent.systemId))
+              {
+                String msg = "circularity importing " + systemId;
+                throw new TransformerConfigurationException(msg);
+              }
+          }
+        /* OK */
+        Stylesheet root = getRootStylesheet();
+        bindings = root.bindings;
+        attributeSets = root.attributeSets;
+        variables = root.variables;
+        namespaceAliases = root.namespaceAliases;
+        templates = root.templates;
+        keys = root.keys;
+        decimalFormats = root.decimalFormats;
+        xpath.setXPathFunctionResolver(root);
+      }
+    xpath.setXPathVariableResolver(bindings);
+
+    Test anyNode = new NodeTypeTest((short) 0);
+    List tests = Collections.singletonList(anyNode);
+    builtInNodeTemplate =
+      new ApplyTemplatesNode(new Selector(Selector.CHILD, tests),
+                             null, null, null, true);
+    builtInTextTemplate =
+      new ValueOfNode(new Selector(Selector.SELF, tests),
+                      false);
+    
+    parse(doc.getDocumentElement(), true);
+    current = doc; // Alow namespace resolution during processing
+    
+    debug = ("yes".equals(System.getProperty("xsl.debug")));
+
+    if (debug)
+      {
+        System.err.println("Stylesheet: " + doc.getDocumentURI());
+        for (Iterator i = templates.iterator(); i.hasNext(); )
+          {
+            Template t = (Template) i.next();
+            t.list(System.err);
+            System.err.println("--------------------");
+          }
+      }
+  }
+
+  Stylesheet getRootStylesheet()
+  {
+    Stylesheet stylesheet = this;
+    while (stylesheet.parent != null)
+      stylesheet = stylesheet.parent;
+    return stylesheet;
+  }
+  
+  void initDefaultDecimalFormat()
+  {
+    DecimalFormat defaultDecimalFormat = new DecimalFormat();
+    DecimalFormatSymbols symbols = new DecimalFormatSymbols();
+    symbols.setDecimalSeparator('.');
+    symbols.setGroupingSeparator(',');
+    symbols.setPercent('%');
+    symbols.setPerMill('\u2030');
+    symbols.setZeroDigit('0');
+    symbols.setDigit('#');
+    symbols.setPatternSeparator(';');
+    symbols.setInfinity("Infinity");
+    symbols.setNaN("NaN");
+    symbols.setMinusSign('-');
+    defaultDecimalFormat.setDecimalFormatSymbols(symbols);
+    decimalFormats.put(null, defaultDecimalFormat);
+  }
+  
+  // -- Cloneable --
+
+  public Object clone()
+  {
+    try
+      {
+        Stylesheet clone = (Stylesheet) super.clone();
+        clone.bindings = (Bindings) bindings.clone();
+
+        LinkedList templates2 = new LinkedList();
+        for (Iterator i = templates.iterator(); i.hasNext(); )
+          {
+            Template t = (Template) i.next();
+            templates2.add(t.clone(clone));
+          }
+        clone.templates = templates2;
+
+        LinkedList attributeSets2 = new LinkedList();
+        for (Iterator i = attributeSets.iterator(); i.hasNext(); )
+          {
+            AttributeSet as = (AttributeSet) i.next();
+            attributeSets2.add(as.clone(clone));
+          }
+        clone.attributeSets = attributeSets2;
+
+        LinkedList variables2 = new LinkedList();
+        for (Iterator i = variables.iterator(); i.hasNext(); )
+          {
+            ParameterNode var = (ParameterNode) i.next();
+            variables2.add(var.clone(clone));
+          }
+        clone.variables = variables2;
+
+        LinkedList keys2 = new LinkedList();
+        for (Iterator i = keys.iterator(); i.hasNext(); )
+          {
+            Key k = (Key) i.next();
+            keys2.add(k.clone(clone));
+          }
+        clone.keys = keys2;
+        
+        return clone;
+      }
+    catch (CloneNotSupportedException e)
+      {
+        throw new Error(e.getMessage());
+      }
+  }
+
+  // -- Variable evaluation --
+
+  void initTopLevelVariables(Node context)
+    throws TransformerException
+  {
+    current = context;
+    // Sort the variables into order
+    // See XSLT 11.4: "If the template or expression specifying the value of
+    // a global variable x references a global variable y, then the value
+    // for y must be computed before the value of x."
+    List topLevel = new ArrayList(variables);
+    Collections.sort(topLevel);
+    for (Iterator i = topLevel.iterator(); i.hasNext(); )
+      {
+        ParameterNode var = (ParameterNode) i.next();
+        bindings.set(var.name,
+                     var.getValue(this, null, context, 1, 1),
+                     var.type);
+      }
+    current = null;
+  }
+
+  // -- NamespaceContext --
+
+  public String getNamespaceURI(String prefix)
+  {
+    return (current == null) ? null : current.lookupNamespaceURI(prefix);
+  }
+
+  public String getPrefix(String namespaceURI)
+  {
+    return (current == null) ? null : current.lookupPrefix(namespaceURI);
+  }
+
+  public Iterator getPrefixes(String namespaceURI)
+  {
+    // TODO
+    return Collections.singleton(getPrefix(namespaceURI)).iterator();
+  }
+
+  final QName getQName(String name)
+  {
+    String localName = name, uri = null, prefix = null;
+    int ci = name.indexOf(':');
+    if (ci != -1)
+      {
+        prefix = name.substring(0, ci);
+        localName = name.substring(ci + 1);
+        uri = getNamespaceURI(prefix);
+      }
+    return new QName(uri, localName, prefix);
+  }
+  
+  // -- Template selection --
+  
+  TemplateNode getTemplate(QName mode, Node context, boolean applyImports)
+    throws TransformerException
+  {
+    if (debug)
+      System.err.println("getTemplate: mode="+mode+" context="+context);
+    Template selected = null;
+    for (Iterator j = templates.iterator(); j.hasNext(); )
+      {
+        Template t = (Template) j.next();
+        boolean isMatch = t.matches(mode, context);
+        if (applyImports)
+          {
+            if (currentTemplate == null)
+              {
+                String msg = "current template may not be null " +
+                  "during apply-imports";
+                throw new TransformerException(msg);
+              }
+            if (!currentTemplate.imports(t))
+              isMatch = false;
+          }
+        //System.err.println("\t"+context+" "+t+"="+isMatch);
+        if (isMatch)
+          {
+            // Conflict resolution
+            // @see http://www.w3.org/TR/xslt#conflict
+            if (selected == null)
+              selected = t;
+            else
+              {
+                if (t.precedence < selected.precedence ||
+                    t.priority < selected.priority)
+                  continue;
+                selected = t;
+              }
+          }
+      }
+    if (selected == null)
+      {
+        // Apply built-in template
+        // Current template is unchanged
+        if (debug)
+          System.err.println("\tbuiltInTemplate context="+context);
+        switch (context.getNodeType())
+          {
+          case Node.ELEMENT_NODE:
+          case Node.DOCUMENT_NODE:
+          case Node.DOCUMENT_FRAGMENT_NODE:
+          case Node.PROCESSING_INSTRUCTION_NODE:
+          case Node.COMMENT_NODE:
+            return builtInNodeTemplate;
+          case Node.TEXT_NODE:
+          case Node.CDATA_SECTION_NODE:
+          case Node.ATTRIBUTE_NODE:
+            return builtInTextTemplate;
+          default:
+            return null;
+          }
+      }
+    // Set current template
+    currentTemplate = selected;
+    if (debug)
+      System.err.println("\ttemplate="+currentTemplate+" context="+context);
+    return currentTemplate.node;
+  }
+
+  TemplateNode getTemplate(QName mode, QName name)
+    throws TransformerException
+  {
+    Template selected = null;
+    for (Iterator j = templates.iterator(); j.hasNext(); )
+      {
+        Template t = (Template) j.next();
+        boolean isMatch = t.matches(name);
+        if (isMatch)
+          {
+            // Conflict resolution
+            // @see http://www.w3.org/TR/xslt#conflict
+            if (selected == null)
+              selected = t;
+            else
+              {
+                if (t.precedence < selected.precedence ||
+                    t.priority < selected.priority)
+                  continue;
+                selected = t;
+              }
+          }
+      }
+    if (selected == null)
+      return null;
+    return selected.node;
+  }
+
+  /**
+   * template
+   */
+  final Template parseTemplate(Node node, NamedNodeMap attrs)
+    throws TransformerConfigurationException, XPathExpressionException
+  {
+    String n = getAttribute(attrs, "name");
+    QName name = (n == null) ? null : getQName(n);
+    String m = getAttribute(attrs, "match");
+    Pattern match = null;
+    if (m != null)
+      {
+        try
+          {
+            match = (Pattern) xpath.compile(m);
+          }
+        catch (ClassCastException e)
+          {
+            String msg = "illegal pattern: " + m;
+            throw new TransformerConfigurationException(msg);
+          }
+      }
+    String p = getAttribute(attrs, "priority");
+    String mm = getAttribute(attrs, "mode");
+    QName mode = (mm == null) ? null : getQName(mm);
+    Node children = node.getFirstChild();
+    return new Template(this, name, match, parse(children),
+                        precedence, p, mode);
+  }
+
+  /**
+   * output
+   */
+  final void parseOutput(Node node, NamedNodeMap attrs)
+    throws TransformerConfigurationException
+  {
+    output = node;
+    String method = getAttribute(attrs, "method");
+    if ("xml".equals(method) || method == null)
+      outputMethod = OUTPUT_XML;
+    else if ("html".equals(method))
+      outputMethod = OUTPUT_HTML;
+    else if ("text".equals(method))
+      outputMethod = OUTPUT_TEXT;
+    else
+      {
+        String msg = "unsupported output method: " + method;
+        DOMSourceLocator l = new DOMSourceLocator(node);
+        throw new TransformerConfigurationException(msg, l);
+      }
+    outputPublicId = getAttribute(attrs, "doctype-public");
+    outputSystemId = getAttribute(attrs, "doctype-system");
+    outputEncoding = getAttribute(attrs, "encoding");
+    String indent = getAttribute(attrs, "indent");
+    if (indent != null)
+      outputIndent = "yes".equals(indent);
+    outputVersion = getAttribute(attrs, "version");
+    String omitXmlDecl = getAttribute(attrs, "omit-xml-declaration");
+    if (omitXmlDecl != null)
+      outputOmitXmlDeclaration = "yes".equals(omitXmlDecl);
+    String standalone = getAttribute(attrs, "standalone");
+    if (standalone != null)
+      outputStandalone = "yes".equals(standalone);
+    outputMediaType = getAttribute(attrs, "media-type");
+    String cdataSectionElements =
+      getAttribute(attrs, "cdata-section-elements");
+    if (cdataSectionElements != null)
+      {
+        StringTokenizer st = new StringTokenizer(cdataSectionElements, " ");
+        while (st.hasMoreTokens())
+          outputCdataSectionElements.add(st.nextToken());
+      }
+  }
+
+  /**
+   * key
+   */
+  final void parseKey(Node node, NamedNodeMap attrs)
+    throws TransformerConfigurationException, XPathExpressionException
+  {
+    String n = getRequiredAttribute(attrs, "name", node);
+    String m = getRequiredAttribute(attrs, "match", node);
+    String u = getRequiredAttribute(attrs, "use", node);
+    QName name = getQName(n);
+    Expr use = (Expr) xpath.compile(u);
+    try
+      {
+        Pattern match = (Pattern) xpath.compile(m);
+        Key key = new Key(name, match, use);
+        keys.add(key);
+      }
+    catch (ClassCastException e)
+      {
+        throw new TransformerConfigurationException("invalid pattern: " + m);
+      }
+  }
+
+  /**
+   * decimal-format
+   */
+  final void parseDecimalFormat(Node node, NamedNodeMap attrs)
+    throws TransformerConfigurationException
+  {
+    String dfName = getAttribute(attrs, "name");
+    DecimalFormat df = new DecimalFormat();
+    DecimalFormatSymbols symbols = new DecimalFormatSymbols();
+    symbols.setDecimalSeparator(parseDFChar(attrs, "decimal-separator", '.'));
+    symbols.setGroupingSeparator(parseDFChar(attrs, "grouping-separator", ','));
+    symbols.setInfinity(parseDFString(attrs, "infinity", "Infinity"));
+    symbols.setMinusSign(parseDFChar(attrs, "minus-sign", '-'));
+    symbols.setNaN(parseDFString(attrs, "NaN", "NaN"));
+    symbols.setPercent(parseDFChar(attrs, "percent", '%'));
+    symbols.setPerMill(parseDFChar(attrs, "per-mille", '\u2030'));
+    symbols.setZeroDigit(parseDFChar(attrs, "zero-digit", '0'));
+    symbols.setDigit(parseDFChar(attrs, "digit", '#'));
+    symbols.setPatternSeparator(parseDFChar(attrs, "pattern-separator", ';'));
+    df.setDecimalFormatSymbols(symbols);
+    decimalFormats.put(dfName, df);
+  }
+
+  private final char parseDFChar(NamedNodeMap attrs, String name, char def)
+    throws TransformerConfigurationException
+  {
+    Node attr = attrs.getNamedItem(name);
+    try
+      {
+        return (attr == null) ? def : attr.getNodeValue().charAt(0);
+      }
+    catch (StringIndexOutOfBoundsException e)
+      {
+        throw new TransformerConfigurationException("empty attribute '" +
+                                                    name +
+                                                    "' in decimal-format", e);
+      }
+  }
+
+  private final String parseDFString(NamedNodeMap attrs, String name,
+                                     String def)
+  {
+    Node attr = attrs.getNamedItem(name);
+    return (attr == null) ? def : attr.getNodeValue();
+  }
+  
+  /**
+   * namespace-alias
+   */
+  final void parseNamespaceAlias(Node node, NamedNodeMap attrs)
+    throws TransformerConfigurationException
+  {
+    String sp = getRequiredAttribute(attrs, "stylesheet-prefix", node);
+    String rp = getRequiredAttribute(attrs, "result-prefix", node);
+    namespaceAliases.put(sp, rp);
+  }
+
+  /**
+   * attribute-set
+   */
+  final void parseAttributeSet(Node node, NamedNodeMap attrs)
+    throws TransformerConfigurationException, XPathExpressionException
+  {
+    TemplateNode children = parse(node.getFirstChild());
+    String name = getRequiredAttribute(attrs, "name", node);
+    String uas = getAttribute(attrs, "use-attribute-sets");
+    attributeSets.add(new AttributeSet(children, name, uas));
+  }
+
+  /**
+   * Parse top-level elements.
+   */
+  void parse(Node node, boolean root)
+    throws TransformerConfigurationException
+  {
+    while (node != null)
+      {
+        current = node;
+        doParse(node, root);
+        node = node.getNextSibling();
+      }
+  }
+
+  void doParse(Node node, boolean root)
+    throws TransformerConfigurationException
+  {
+    try
+      {
+        String namespaceUri = node.getNamespaceURI();
+        if (XSL_NS.equals(namespaceUri) &&
+            node.getNodeType() == Node.ELEMENT_NODE)
+          {
+            String name = node.getLocalName();
+            NamedNodeMap attrs = node.getAttributes();
+            if ("stylesheet".equals(name))
+              {
+                version = getAttribute(attrs, "version");
+                String eep = getAttribute(attrs, "extension-element-prefixes");
+                if (eep != null)
+                  {
+                    StringTokenizer st = new StringTokenizer(eep);
+                    while (st.hasMoreTokens())
+                      {
+                        extensionElementPrefixes.add(st.nextToken());
+                      }
+                  }
+                String erp = getAttribute(attrs, "exclude-result-prefixes");
+                if (erp != null)
+                  {
+                    StringTokenizer st = new StringTokenizer(erp);
+                    while (st.hasMoreTokens())
+                      {
+                        excludeResultPrefixes.add(st.nextToken());
+                      }
+                  }
+                parse(node.getFirstChild(), false);
+              }
+            else if ("template".equals(name))
+              templates.add(parseTemplate(node, attrs));
+            else if ("param".equals(name) ||
+                     "variable".equals(name))
+              {
+                int type = "variable".equals(name) ?
+                  Bindings.VARIABLE : Bindings.PARAM;
+                TemplateNode content = parse(node.getFirstChild());
+                QName paramName =
+                  getQName(getRequiredAttribute(attrs, "name", node));
+                String select = getAttribute(attrs, "select");
+                ParameterNode param;
+                if (select != null && select.length() > 0)
+                  {
+                    if (content != null)
+                      {
+                        String msg = "parameter '" + paramName +
+                          "' has both select and content";
+                        DOMSourceLocator l = new DOMSourceLocator(node);
+                        throw new TransformerConfigurationException(msg, l);
+                      }
+                    Expr expr = (Expr) xpath.compile(select);
+                    param = new ParameterNode(paramName, expr, type);
+                  }
+                else
+                  {
+                    param = new ParameterNode(paramName, null, type);
+                    param.children = content;
+                  }
+                variables.add(param);
+              }
+            else if ("include".equals(name) || "import".equals(name))
+              {
+                int delta = "import".equals(name) ? -1 : 0;
+                String href = getRequiredAttribute(attrs, "href", node);
+                Source source;
+                synchronized (factory.resolver)
+                  {
+                    if (transformer != null)
+                      {
+                        factory.resolver
+                          .setUserResolver(transformer.getURIResolver());
+                        factory.resolver
+                          .setUserListener(transformer.getErrorListener());
+                      }
+                    source = factory.resolver.resolve(systemId, href);
+                  }
+                factory.newStylesheet(source, precedence + delta, this);
+              }
+            else if ("output".equals(name))
+              parseOutput(node, attrs);
+            else if ("preserve-space".equals(name))
+              {
+                String elements =
+                  getRequiredAttribute(attrs, "elements", node);
+                StringTokenizer st = new StringTokenizer(elements,
+                                                         " \t\n\r");
+                while (st.hasMoreTokens())
+                  {
+                    NameTest element = parseNameTest(st.nextToken());
+                    preserveSpace.add(new StrippingInstruction(element,
+                                                               precedence));
+                  }
+              }
+            else if ("strip-space".equals(name))
+              {
+                String elements =
+                  getRequiredAttribute(attrs, "elements", node);
+                StringTokenizer st = new StringTokenizer(elements,
+                                                         " \t\n\r");
+                while (st.hasMoreTokens())
+                  {
+                    NameTest element = parseNameTest(st.nextToken());
+                    stripSpace.add(new StrippingInstruction(element, 
+                                                            precedence));
+                  }
+              }
+            else if ("key".equals(name))
+              parseKey(node, attrs);
+            else if ("decimal-format".equals(name))
+              parseDecimalFormat(node, attrs);
+            else if ("namespace-alias".equals(name))
+              parseNamespaceAlias(node, attrs);
+            else if ("attribute-set".equals(name))
+              parseAttributeSet(node, attrs);
+          }
+        else if (root)
+          {
+            // Literal document element
+            Attr versionNode =
+              ((Element)node).getAttributeNodeNS(XSL_NS, "version");
+            if (versionNode == null)
+              {
+                String msg = "no xsl:version attribute on literal result node";
+                DOMSourceLocator l = new DOMSourceLocator(node);
+                throw new TransformerConfigurationException(msg, l);
+              }
+            version = versionNode.getValue();
+            Node rootClone = node.cloneNode(true);
+            NamedNodeMap attrs = rootClone.getAttributes();
+            attrs.removeNamedItemNS(XSL_NS, "version");
+            templates.add(new Template(this, null, new Root(),
+                                       parse(rootClone),
+                                       precedence,
+                                       null,
+                                       null));
+          }
+        else
+          {
+            // Skip unknown elements, text, comments, etc
+          }
+      }
+    catch (TransformerException e)
+      {
+        DOMSourceLocator l = new DOMSourceLocator(node);
+        throw new TransformerConfigurationException(e.getMessage(), l, e);
+      }
+    catch (DOMException e)
+      {
+        DOMSourceLocator l = new DOMSourceLocator(node);
+        throw new TransformerConfigurationException(e.getMessage(), l, e);
+      }
+    catch (XPathExpressionException e)
+      {
+        DOMSourceLocator l = new DOMSourceLocator(node);
+        throw new TransformerConfigurationException(e.getMessage(), l, e);
+      }
+  }
+
+  final NameTest parseNameTest(String token)
+  {
+    if ("*".equals(token))
+      return new NameTest(null, true, true);
+    else if (token.endsWith(":*"))
+      {
+        QName qName = getQName(token);
+        return new NameTest(qName, true, false);
+      }
+    else
+      {
+        QName qName = getQName(token);
+        return new NameTest(qName, false, false);
+      }
+  }
+
+  final TemplateNode parseAttributeValueTemplate(String value, Node source)
+    throws TransformerConfigurationException, XPathExpressionException
+  {
+    current = source;
+    // Tokenize
+    int len = value.length();
+    int off = 0;
+    List tokens = new ArrayList(); // text tokens
+    List types = new ArrayList(); // literal or expression
+    int depth = 0;
+    for (int i = 0; i < len; i++)
+      {
+        char c = value.charAt(i);
+        if (c == '{')
+          {
+            if (i < (len - 1) && value.charAt(i + 1) == '{')
+              {
+                tokens.add(value.substring(off, i + 1));
+                types.add(Boolean.FALSE);
+                i++;
+                off = i + 1;
+                continue;
+              }
+            if (depth == 0)
+              {
+                if (i - off > 0)
+                  {
+                    tokens.add(value.substring(off, i));
+                    types.add(Boolean.FALSE);
+                  }
+                off = i + 1;
+              }
+            depth++;
+          }
+        else if (c == '}')
+          {
+            if (i < (len - 1) && value.charAt(i + 1) == '}')
+              {
+                tokens.add(value.substring(off, i + 1));
+                types.add(Boolean.FALSE);
+                i++;
+                off = i + 1;
+                continue;
+              }
+            if (depth == 1)
+              {
+                if (i - off > 0)
+                  {
+                    tokens.add(value.substring(off, i));
+                    types.add(Boolean.TRUE);
+                  }
+                else
+                  {
+                    String msg = "attribute value template " +
+                      "must contain expression: " + value;
+                    DOMSourceLocator l = new DOMSourceLocator(source);
+                    throw new TransformerConfigurationException(msg, l);
+                  }
+                off = i + 1;
+              }
+            depth--;
+          }
+      }
+    if (depth > 0)
+      {
+        String msg = "invalid attribute value template: " + value;
+        throw new TransformerConfigurationException(msg);
+      }
+    if (len - off > 0)
+      {
+        // Trailing text
+        tokens.add(value.substring(off));
+        types.add(Boolean.FALSE);
+      }
+    
+    // Construct template node tree
+    TemplateNode ret = null;
+    Document doc = source.getOwnerDocument();
+    len = tokens.size();
+    for (int i = len - 1; i >= 0; i--)
+      {
+        String token = (String) tokens.get(i);
+        Boolean type = (Boolean) types.get(i);
+        if (type == Boolean.TRUE)
+          {
+            // Expression text
+            Expr select = (Expr) xpath.compile(token);
+            TemplateNode ret2 = new ValueOfNode(select, false);
+            ret2.next = ret;
+            ret = ret2;
+          }
+        else
+          {
+            // Verbatim text
+            TemplateNode ret2 = new LiteralNode(doc.createTextNode(token));
+            ret2.next = ret;
+            ret = ret2;
+          }
+      }
+    return ret;
+  }
+
+  /**
+   * Whitespace stripping.
+   * @param text the text node
+   * @param source true if a source node, false if a stylesheet text node
+   * @see http://www.w3.org/TR/xslt#strip
+   */
+  boolean isPreserved(Text text, boolean source)
+    throws TransformerConfigurationException
+  {
+    // Check characters in text
+    String value = text.getData();
+    if (value != null)
+      {
+        int len = value.length();
+        for (int i = 0; i < len; i++)
+          {
+            char c = value.charAt(i);
+            if (c != 0x20 && c != 0x09 && c != 0x0a && c != 0x0d)
+              return true;
+          }
+      }
+    // Check parent node
+    Node ctx = text.getParentNode();
+    if (source)
+      {
+        // Source document text node
+        boolean preserve = true;
+        float psPriority = 0.0f, ssPriority = 0.0f;
+        if (!stripSpace.isEmpty())
+          {
+            // Conflict resolution
+            StrippingInstruction ssi = null, psi = null;
+            for (Iterator i = stripSpace.iterator(); i.hasNext(); )
+              {
+                StrippingInstruction si = (StrippingInstruction) i.next();
+                if (si.element.matches(ctx, 1, 1))
+                  {
+                    if (ssi != null)
+                      {
+                        if (si.precedence < ssi.precedence)
+                          continue;
+                        float p = si.getPriority();
+                        if (p < ssPriority)
+                          continue;
+                      }
+                    ssi = si;
+                  }
+              }
+            for (Iterator i = preserveSpace.iterator(); i.hasNext(); )
+              {
+                StrippingInstruction si = (StrippingInstruction) i.next();
+                if (si.element.matches(ctx, 1, 1))
+                  {
+                    if (psi != null)
+                      {
+                        if (si.precedence < psi.precedence)
+                          continue;
+                        float p = si.getPriority();
+                        if (p < psPriority)
+                          continue;
+                      }
+                    psi = si;
+                  }
+              }
+            if (ssi != null)
+              {
+                if (psi != null)
+                  {
+                    if (psi.precedence < ssi.precedence)
+                      preserve = false;
+                    else if (psPriority < ssPriority)
+                      preserve = false;
+                  }
+                else
+                  preserve = false;
+              }
+          }
+        if (preserve)
+          return true;
+      }
+    else
+      {
+        // Stylesheet text node
+        if (STYLESHEET_PRESERVE_TEXT.matches(ctx, 1, 1))
+          return true;
+      }
+    // Check whether any ancestor specified xml:space
+    while (ctx != null)
+      {
+        if (ctx.getNodeType() == Node.ELEMENT_NODE)
+          {
+            Element element = (Element) ctx;
+            String xmlSpace = element.getAttribute("xml:space");
+            if ("default".equals(xmlSpace))
+              break;
+            else if ("preserve".equals(xmlSpace))
+              return true;
+            else if (xmlSpace.length() > 0)
+              {
+                String msg = "Illegal value for xml:space: " + xmlSpace;
+                throw new TransformerConfigurationException(msg);
+              }
+          }
+        ctx = ctx.getParentNode();
+      }
+    return false;
+  }
+
+  public XPathFunction resolveFunction(QName name, int arity)
+  {
+    String uri = name.getNamespaceURI();
+    if (XSL_NS.equals(uri) || uri == null || uri.length() == 0)
+      {
+        String localName = name.getLocalPart();
+        if ("document".equals(localName) && (arity == 1 || arity == 2))
+          {
+            if (current == null)
+                throw new RuntimeException("current is null");
+            return new DocumentFunction(getRootStylesheet(), current);
+          }
+        else if ("key".equals(localName) && (arity == 2))
+          return new KeyFunction(getRootStylesheet());
+        else if ("format-number".equals(localName) &&
+                 (arity == 2 || arity == 3))
+          return new FormatNumberFunction(getRootStylesheet());
+        else if ("current".equals(localName) && (arity == 0))
+          return new CurrentFunction(getRootStylesheet());
+        else if ("unparsed-entity-uri".equals(localName) && (arity == 1))
+          return new UnparsedEntityUriFunction();
+        else if ("generate-id".equals(localName) &&
+                 (arity == 1 || arity == 0))
+          return new GenerateIdFunction();
+        else if ("system-property".equals(localName) && (arity == 1))
+          return new SystemPropertyFunction();
+        else if ("element-available".equals(localName) && (arity == 1))
+          return new ElementAvailableFunction(new NamespaceProxy(current));
+        else if ("function-available".equals(localName) && (arity == 1))
+          return new FunctionAvailableFunction(new NamespaceProxy(current));
+      }
+    return null;
+  }
+  
+  // -- Parsing --
+
+  /**
+   * apply-templates
+   */
+  final TemplateNode parseApplyTemplates(Node node)
+    throws TransformerConfigurationException, XPathExpressionException
+  {
+    NamedNodeMap attrs = node.getAttributes();
+    String m = getAttribute(attrs, "mode");
+    QName mode = (m == null) ? null : getQName(m);
+    String s = getAttribute(attrs, "select");
+    if (s == null)
+      s = "child::node()";
+    Node children = node.getFirstChild();
+    List sortKeys = parseSortKeys(children);
+    List withParams = parseWithParams(children);
+    Expr select = (Expr) xpath.compile(s);
+    return new ApplyTemplatesNode(select, mode,
+                                  sortKeys, withParams, false);
+  }
+
+  /**
+   * call-template
+   */
+  final TemplateNode parseCallTemplate(Node node)
+    throws TransformerConfigurationException, XPathExpressionException
+  {
+    NamedNodeMap attrs = node.getAttributes();
+    String n = getRequiredAttribute(attrs, "name", node);
+    QName name = getQName(n);
+    Node children = node.getFirstChild();
+    List withParams = parseWithParams(children);
+    return new CallTemplateNode(name, withParams);
+  }
+  
+  /**
+   * value-of
+   */
+  final TemplateNode parseValueOf(Node node)
+    throws TransformerConfigurationException, XPathExpressionException
+  {
+    NamedNodeMap attrs = node.getAttributes();
+    String s = getRequiredAttribute(attrs, "select", node);
+    String doe = getAttribute(attrs, "disable-output-escaping");
+    boolean d = "yes".equals(doe);
+    Expr select = (Expr) xpath.compile(s);
+    return new ValueOfNode(select, d);
+  }
+  
+  /**
+   * for-each
+   */
+  final TemplateNode parseForEach(Node node)
+    throws TransformerConfigurationException, XPathExpressionException
+  {
+    NamedNodeMap attrs = node.getAttributes();
+    String s = getRequiredAttribute(attrs, "select", node);
+    Node children = node.getFirstChild();
+    List sortKeys = parseSortKeys(children);
+    Expr select = (Expr) xpath.compile(s);
+    ForEachNode ret = new ForEachNode(select, sortKeys);
+    ret.children = parse(children);
+    return ret;
+  }
+  
+  /**
+   * if
+   */
+  final TemplateNode parseIf(Node node)
+    throws TransformerConfigurationException, XPathExpressionException
+  {
+    NamedNodeMap attrs = node.getAttributes();
+    String t = getRequiredAttribute(attrs, "test", node);
+    Expr test = (Expr) xpath.compile(t);
+    Node children = node.getFirstChild();
+    IfNode ret = new IfNode(test);
+    ret.children = parse(children);
+    return ret;
+  }
+  
+  /**
+   * when
+   */
+  final TemplateNode parseWhen(Node node)
+    throws TransformerConfigurationException, XPathExpressionException
+  {
+    NamedNodeMap attrs = node.getAttributes();
+    String t = getRequiredAttribute(attrs, "test", node);
+    Expr test = (Expr) xpath.compile(t);
+    Node children = node.getFirstChild();
+    WhenNode ret = new WhenNode(test);
+    ret.children = parse(children);
+    return ret;
+  }
+  
+  /**
+   * element
+   */
+  final TemplateNode parseElement(Node node)
+    throws TransformerConfigurationException, XPathExpressionException
+  {
+    NamedNodeMap attrs = node.getAttributes();
+    String name = getRequiredAttribute(attrs, "name", node);
+    String namespace = getAttribute(attrs, "namespace");
+    String uas = getAttribute(attrs, "use-attribute-sets");
+    TemplateNode n = parseAttributeValueTemplate(name, node);
+    TemplateNode ns = (namespace == null) ? null :
+      parseAttributeValueTemplate(namespace, node);
+    Node children = node.getFirstChild();
+    ElementNode ret = new ElementNode(n, ns, uas, node);
+    ret.children = parse(children);
+    return ret;
+  }
+
+  /**
+   * attribute
+   */
+  final TemplateNode parseAttribute(Node node)
+    throws TransformerConfigurationException, XPathExpressionException
+  {
+    NamedNodeMap attrs = node.getAttributes();
+    String name = getRequiredAttribute(attrs, "name", node);
+    String namespace = getAttribute(attrs, "namespace");
+    TemplateNode n = parseAttributeValueTemplate(name, node);
+    TemplateNode ns = (namespace == null) ? null :
+      parseAttributeValueTemplate(namespace, node);
+    Node children = node.getFirstChild();
+    AttributeNode ret = new AttributeNode(n, ns, node);
+    ret.children = parse(children);
+    return ret;
+  }
+  
+  /**
+   * text
+   */
+  final TemplateNode parseText(Node node)
+    throws TransformerConfigurationException, XPathExpressionException
+  {
+    NamedNodeMap attrs = node.getAttributes();
+    String doe = getAttribute(attrs, "disable-output-escaping");
+    boolean d = "yes".equals(doe);
+    Node children = node.getFirstChild();
+    TextNode ret = new TextNode(d);
+    ret.children = parse(children);
+    return ret;
+  }
+  
+  /**
+   * copy
+   */
+  final TemplateNode parseCopy(Node node)
+    throws TransformerConfigurationException, XPathExpressionException
+  {
+    NamedNodeMap attrs = node.getAttributes();
+    String uas = getAttribute(attrs, "use-attribute-sets");
+    Node children = node.getFirstChild();
+    CopyNode ret = new CopyNode(uas);
+    ret.children = parse(children);
+    return ret;
+  }
+  
+  /**
+   * processing-instruction
+   */
+  final TemplateNode parseProcessingInstruction(Node node)
+    throws TransformerConfigurationException, XPathExpressionException
+  {
+    NamedNodeMap attrs = node.getAttributes();
+    String name = getRequiredAttribute(attrs, "name", node);
+    Node children = node.getFirstChild();
+    ProcessingInstructionNode ret = new ProcessingInstructionNode(name);
+    ret.children = parse(children);
+    return ret;
+  }
+  
+  /**
+   * number
+   */
+  final TemplateNode parseNumber(Node node)
+    throws TransformerConfigurationException, XPathExpressionException
+  {
+    NamedNodeMap attrs = node.getAttributes();
+    String v = getAttribute(attrs, "value");
+    String ff = getAttribute(attrs, "format");
+    if (ff == null)
+      {
+        ff = "1";
+      }
+    TemplateNode format = parseAttributeValueTemplate(ff, node);
+    String lang = getAttribute(attrs, "lang");
+    String lv = getAttribute(attrs, "letter-value");
+    int letterValue = "traditional".equals(lv) ?
+      AbstractNumberNode.TRADITIONAL :
+      AbstractNumberNode.ALPHABETIC;
+    String gs = getAttribute(attrs, "grouping-separator");
+    String gz = getAttribute(attrs, "grouping-size");
+    int gz2 = (gz != null && gz.length() > 0) ?
+      Integer.parseInt(gz) : 1;
+    Node children = node.getFirstChild();
+    TemplateNode ret;
+    if (v != null && v.length() > 0)
+      {
+        Expr value = (Expr) xpath.compile(v);
+        ret = new NumberNode(value, format, lang,
+                             letterValue, gs, gz2);
+      }
+    else
+      {
+        String l = getAttribute(attrs, "level");
+        int level =
+          "multiple".equals(l) ? NodeNumberNode.MULTIPLE :
+                      "any".equals(l) ? NodeNumberNode.ANY :
+                      NodeNumberNode.SINGLE;
+        String c = getAttribute(attrs, "count");
+        String f = getAttribute(attrs, "from");
+        Pattern count = null;
+        Pattern from = null;
+        if (c != null)
+          {
+            try
+              {
+                count = (Pattern) xpath.compile(c);
+              }
+            catch (ClassCastException e)
+              {
+                String msg = "invalid pattern: " + c;
+                throw new TransformerConfigurationException(msg);
+              }
+          }
+        if (f != null)
+          {
+            try
+              {
+                from = (Pattern) xpath.compile(f);
+              }
+            catch (ClassCastException e)
+              {
+                String msg = "invalid pattern: " + f;
+                throw new TransformerConfigurationException(msg);
+              }
+          }
+        ret = new NodeNumberNode(level, count, from,
+                                 format, lang,
+                                 letterValue, gs, gz2);
+      }
+    ret.children = parse(children);
+    return ret;
+  }
+  
+  /**
+   * copy-of
+   */
+  final TemplateNode parseCopyOf(Node node)
+    throws TransformerConfigurationException, XPathExpressionException
+  {
+    NamedNodeMap attrs = node.getAttributes();
+    String s = getRequiredAttribute(attrs, "select", node);
+    Expr select = (Expr) xpath.compile(s);
+    Node children = node.getFirstChild();
+    CopyOfNode ret = new CopyOfNode(select);
+    ret.children = parse(children);
+    return ret;
+  }
+  
+  /**
+   * message
+   */
+  final TemplateNode parseMessage(Node node)
+    throws TransformerConfigurationException, XPathExpressionException
+  {
+    NamedNodeMap attrs = node.getAttributes();
+    String t = getAttribute(attrs, "terminate");
+    boolean terminate = "yes".equals(t);
+    Node children = node.getFirstChild();
+    MessageNode ret = new MessageNode(terminate);
+    ret.children = parse(children);
+    return ret;
+  }
+  
+  /**
+   * Parse template-level elements.
+   */
+  final TemplateNode parse(Node node)
+    throws TransformerConfigurationException
+  {
+    TemplateNode first = null;
+    TemplateNode previous = null;
+    while (node != null)
+      {
+        Node next = node.getNextSibling();
+        TemplateNode tnode = doParse(node);
+        if (tnode != null)
+          {
+            if (first == null)
+              first = tnode;
+            if (previous != null)
+              previous.next = tnode;
+            previous = tnode;
+          }
+        node = next;
+      }
+    return first;
+  }
+
+  private final TemplateNode doParse(Node node)
+    throws TransformerConfigurationException
+  {
+    // Hack to associate the document function with its declaring node
+    current = node;
+    try
+      {
+        String namespaceUri = node.getNamespaceURI();
+        if (Stylesheet.XSL_NS.equals(namespaceUri) &&
+            Node.ELEMENT_NODE == node.getNodeType())
+          {
+            String name = node.getLocalName();
+            if ("apply-templates".equals(name))
+              return parseApplyTemplates(node);
+            else if ("call-template".equals(name))
+              return parseCallTemplate(node);
+            else if ("value-of".equals(name))
+              return parseValueOf(node);
+            else if ("for-each".equals(name))
+              return parseForEach(node);
+            else if ("if".equals(name))
+              return parseIf(node);
+            else if ("choose".equals(name))
+              {
+                Node children = node.getFirstChild();
+                ChooseNode ret = new ChooseNode();
+                ret.children = parse(children);
+                return ret;
+              }
+            else if ("when".equals(name))
+              return parseWhen(node);
+            else if ("otherwise".equals(name))
+              {
+                Node children = node.getFirstChild();
+                OtherwiseNode ret = new OtherwiseNode();
+                ret.children = parse(children);
+                return ret;
+              }
+            else if ("element".equals(name))
+              return parseElement(node);
+            else if ("attribute".equals(name))
+              return parseAttribute(node);
+            else if ("text".equals(name))
+              return parseText(node);
+            else if ("copy".equals(name))
+              return parseCopy(node);
+            else if ("processing-instruction".equals(name))
+              return parseProcessingInstruction(node);
+            else if ("comment".equals(name))
+              {
+                Node children = node.getFirstChild();
+                CommentNode ret = new CommentNode();
+                ret.children = parse(children);
+                return ret;
+              }
+            else if ("number".equals(name))
+              return parseNumber(node);
+            else if ("param".equals(name) ||
+                     "variable".equals(name))
+              {
+                int type = "variable".equals(name) ?
+                  Bindings.VARIABLE : Bindings.PARAM;
+                NamedNodeMap attrs = node.getAttributes();
+                Node children = node.getFirstChild();
+                TemplateNode content = parse(children);
+                QName paramName = 
+                  getQName(getRequiredAttribute(attrs, "name", node));
+                String select = getAttribute(attrs, "select");
+                ParameterNode ret;
+                if (select != null)
+                  {
+                    if (content != null)
+                      {
+                        String msg = "parameter '" + paramName +
+                          "' has both select and content";
+                        DOMSourceLocator l = new DOMSourceLocator(node);
+                        throw new TransformerConfigurationException(msg, l);
+                      }
+                    Expr expr = (Expr) xpath.compile(select);
+                    ret = new ParameterNode(paramName, expr, type);
+                  }
+                else
+                  {
+                    ret = new ParameterNode(paramName, null, type);
+                    ret.children = content;
+                  }
+                return ret;
+              }
+            else if ("copy-of".equals(name))
+              return parseCopyOf(node);
+            else if ("message".equals(name))
+              return parseMessage(node);
+            else if ("apply-imports".equals(name))
+              {
+                Node children = node.getFirstChild();
+                ApplyImportsNode ret = new ApplyImportsNode();
+                ret.children = parse(children);
+                return ret;
+              }
+            else
+              {
+                // xsl:fallback
+                // Pass over any other XSLT nodes
+                return null;
+              }
+          }
+        String prefix = node.getPrefix();
+        if (extensionElementPrefixes.contains(prefix))
+          {
+            // Check for xsl:fallback
+            for (Node ctx = node.getFirstChild(); ctx != null;
+                 ctx = ctx.getNextSibling())
+              {
+                String ctxUri = ctx.getNamespaceURI();
+                if (XSL_NS.equals(ctxUri) &&
+                    "fallback".equals(ctx.getLocalName()))
+                  {
+                    ctx = ctx.getFirstChild();
+                    return (ctx == null) ? null : parse(ctx);
+                  }
+              }
+            // Otherwise pass over extension element
+            return null;
+          }
+        switch (node.getNodeType())
+          {
+          case Node.TEXT_NODE:
+          case Node.CDATA_SECTION_NODE:
+            // Determine whether to strip whitespace
+            Text text = (Text) node;
+            if (!isPreserved(text, false))
+              {
+                // Strip
+                text.getParentNode().removeChild(text);
+                return null;
+              }
+            break;
+          case Node.COMMENT_NODE:
+            // Ignore comments
+            return null;
+          case Node.ELEMENT_NODE:
+            // Check for attribute value templates and use-attribute-sets
+            NamedNodeMap attrs = node.getAttributes();
+            boolean convert = false;
+            String useAttributeSets = null;
+            int len = attrs.getLength();
+            for (int i = 0; i < len; i++)
+              {
+                Node attr = attrs.item(i);
+                String value = attr.getNodeValue();
+                if (Stylesheet.XSL_NS.equals(attr.getNamespaceURI()) &&
+                    "use-attribute-sets".equals(attr.getLocalName()))
+                  {
+                    useAttributeSets = value;
+                    convert = true;
+                    break;
+                  }
+                int start = value.indexOf('{');
+                int end = value.indexOf('}');
+                if (start != -1 || end != -1)
+                  {
+                    convert = true;
+                    break;
+                  }
+              }
+            if (convert)
+              {
+                // Create an element-producing template node instead
+                // with appropriate attribute-producing child template nodes
+                Node children = node.getFirstChild();
+                TemplateNode child = parse(children);
+                for (int i = 0; i < len; i++)
+                  {
+                    Node attr = attrs.item(i);
+                    String ans = attr.getNamespaceURI();
+                    String aname = attr.getNodeName();
+                    if (Stylesheet.XSL_NS.equals(ans) &&
+                        "use-attribute-sets".equals(attr.getLocalName()))
+                      continue;
+                    String value = attr.getNodeValue();
+                    TemplateNode grandchild =
+                      parseAttributeValueTemplate(value, node);
+                    TemplateNode n =
+                      parseAttributeValueTemplate(aname, node);
+                    TemplateNode ns = (ans == null) ? null :
+                      parseAttributeValueTemplate(ans, node);
+                    TemplateNode newChild = new AttributeNode(n, ns, attr);
+                    newChild.children = grandchild;
+                    newChild.next = child;
+                    child = newChild;
+                  }
+                String ename = node.getNodeName();
+                TemplateNode n = parseAttributeValueTemplate(ename, node);
+                //TemplateNode ns = (namespaceUri == null) ? null :
+                //  parseAttributeValueTemplate(namespaceUri, node);
+                TemplateNode ns = null;
+                ElementNode ret = new ElementNode(n, ns, useAttributeSets,
+                                                  node);
+                ret.children = child;
+                return ret;
+              }
+            // Otherwise fall through
+            break;
+          }
+      }
+    catch (XPathExpressionException e)
+      {
+        DOMSourceLocator l = new DOMSourceLocator(node);
+        throw new TransformerConfigurationException(e.getMessage(), l, e);
+      }
+    Node children = node.getFirstChild();
+    LiteralNode ret = new LiteralNode(node);
+    ret.children = parse(children);
+    return ret;
+  }
+
+  final List parseSortKeys(Node node)
+    throws TransformerConfigurationException, XPathExpressionException
+  {
+    List ret = new LinkedList();
+    while (node != null)
+      {
+        String namespaceUri = node.getNamespaceURI();
+        if (Stylesheet.XSL_NS.equals(namespaceUri) &&
+            Node.ELEMENT_NODE == node.getNodeType() &&
+            "sort".equals(node.getLocalName()))
+          {
+            NamedNodeMap attrs = node.getAttributes();
+            String s = getAttribute(attrs, "select");
+            if (s == null)
+              s = ".";
+            Expr select = (Expr) xpath.compile(s);
+            String l = getAttribute(attrs, "lang");
+            TemplateNode lang = (l == null) ? null :
+              parseAttributeValueTemplate(l, node);
+            String dt = getAttribute(attrs, "data-type");
+            TemplateNode dataType = (dt == null) ? null :
+              parseAttributeValueTemplate(dt, node);
+            String o = getAttribute(attrs, "order");
+            TemplateNode order = (o == null) ? null :
+              parseAttributeValueTemplate(o, node);
+            String co = getAttribute(attrs, "case-order");
+            TemplateNode caseOrder = (co == null) ? null :
+              parseAttributeValueTemplate(co, node);
+            ret.add(new SortKey(select, lang, dataType, order, caseOrder));
+          }
+        node = node.getNextSibling();
+      }
+    return ret.isEmpty() ? null : ret;
+  }
+
+  final List parseWithParams(Node node)
+    throws TransformerConfigurationException, XPathExpressionException
+  {
+    List ret = new LinkedList();
+    while (node != null)
+      {
+        String namespaceUri = node.getNamespaceURI();
+        if (Stylesheet.XSL_NS.equals(namespaceUri) &&
+            Node.ELEMENT_NODE == node.getNodeType() &&
+            "with-param".equals(node.getLocalName()))
+          {
+            NamedNodeMap attrs = node.getAttributes();
+            TemplateNode content = parse(node.getFirstChild());
+            QName name =
+              getQName(getRequiredAttribute(attrs, "name", node));
+            String select = getAttribute(attrs, "select");
+            if (select != null)
+              {
+                if (content != null)
+                  {
+                    String msg = "parameter '" + name +
+                      "' has both select and content";
+                    DOMSourceLocator l = new DOMSourceLocator(node);
+                    throw new TransformerConfigurationException(msg, l);
+                  }
+                Expr expr = (Expr) xpath.compile(select);
+                ret.add(new WithParam(name, expr));
+              }
+            else
+              ret.add(new WithParam(name, content));
+          }
+        node = node.getNextSibling();
+      }
+    return ret.isEmpty() ? null : ret;
+  }
+
+  /**
+   * Created element nodes have a copy of the namespace nodes in the
+   * stylesheet, except the XSLT namespace, extension namespaces, and
+   * exclude-result-prefixes.
+   */
+  final void addNamespaceNodes(Node source, Node target, Document doc,
+                               Collection elementExcludeResultPrefixes)
+  {
+    NamedNodeMap attrs = source.getAttributes();
+    if (attrs != null)
+      {
+        int len = attrs.getLength();
+        for (int i = 0; i < len; i++)
+          {
+            Node attr = attrs.item(i);
+            String uri = attr.getNamespaceURI();
+            if (uri == XMLConstants.XMLNS_ATTRIBUTE_NS_URI)
+              {
+                String prefix = attr.getLocalName();
+                if (XMLConstants.XMLNS_ATTRIBUTE.equals(prefix))
+                  prefix = "#default";
+                String ns = attr.getNodeValue();
+                // Should the namespace be excluded?
+                if (XSL_NS.equals(ns) ||
+                    extensionElementPrefixes.contains(prefix) ||
+                    elementExcludeResultPrefixes.contains(prefix) ||
+                    excludeResultPrefixes.contains(prefix))
+                  continue;
+                // Is the namespace already defined on the target?
+                if (prefix == "#default")
+                  prefix = null;
+                if (target.lookupNamespaceURI(prefix) != null)
+                  continue;
+                attr = attr.cloneNode(true);
+                attr = doc.adoptNode(attr);
+                target.getAttributes().setNamedItemNS(attr);
+              }
+          }
+      }
+    Node parent = source.getParentNode();
+    if (parent != null)
+      addNamespaceNodes(parent, target, doc, elementExcludeResultPrefixes);
+  }
+
+  static final String getAttribute(NamedNodeMap attrs, String name)
+  {
+    Node attr = attrs.getNamedItem(name);
+    if (attr == null)
+      return null;
+    String ret = attr.getNodeValue();
+    if (ret.length() == 0)
+      return null;
+    return ret;
+  }
+
+  static final String getRequiredAttribute(NamedNodeMap attrs, String name,
+                                           Node source)
+    throws TransformerConfigurationException
+  {
+    String value = getAttribute(attrs, name);
+    if (value == null || value.length() == 0)
+      {
+        String msg =
+          name + " attribute is required on " + source.getNodeName();
+        DOMSourceLocator l = new DOMSourceLocator(source);
+        throw new TransformerConfigurationException(msg, l);
+      }
+    return value;
+  }
+
+  // Handle user data changes when nodes are cloned etc
+
+  public void handle(short op, String key, Object data, Node src, Node dst)
+  {
+    dst.setUserData(key, data, this);
+  }
+
+}
+

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/SystemPropertyFunction.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/SystemPropertyFunction.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/SystemPropertyFunction.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/SystemPropertyFunction.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,141 @@
+/* SystemPropertyFunction.java -- 
+   Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.xml.transform;
+
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import javax.xml.namespace.QName;
+import javax.xml.xpath.XPathFunction;
+import javax.xml.xpath.XPathFunctionException;
+import org.w3c.dom.Node;
+import gnu.xml.xpath.Expr;
+import gnu.xml.xpath.Function;
+
+/**
+ * The XSLT <code>system-property()</code>function.
+ *
+ * @author <a href='mailto:dog at gnu.org'>Chris Burdess</a>
+ */
+final class SystemPropertyFunction
+  extends Expr
+  implements XPathFunction, Function
+{
+
+  List args;
+
+  public Object evaluate(List args)
+    throws XPathFunctionException
+  {
+    String name = (String) args.get(0);
+    return systemProperty(QName.valueOf(name));
+  }
+
+  public void setArguments(List args)
+  {
+    this.args = args;
+  }
+
+  public Object evaluate(Node context, int pos, int len)
+  {
+    int arity = args.size();
+    List values = new ArrayList(arity);
+    for (int i = 0; i < arity; i++)
+      {
+        Expr arg = (Expr) args.get(i);
+        values.add(arg.evaluate(context, pos, len));
+      }
+    String name = _string(context, values.get(0));
+    return systemProperty(QName.valueOf(name));
+  }
+
+  Object systemProperty(QName name)
+  {
+    String localName = name.getLocalPart();
+    String prefix = name.getPrefix();
+    String uri = name.getNamespaceURI();
+    if (Stylesheet.XSL_NS.equals(uri) ||
+        "xsl".equals(prefix))
+      {
+        if ("version".equals(localName))
+          {
+            return new Double(1.0d);
+          }
+        else if ("vendor".equals(localName))
+          {
+            return "The Free Software Foundation";
+          }
+        else if ("vendor-url".equals(localName))
+          {
+            return "http://www.gnu.org/";
+          }
+        else
+          {
+            return "";
+          }
+      }
+    return System.getProperty(localName);
+  }
+
+  public Expr clone(Object context)
+  {
+    SystemPropertyFunction f = new SystemPropertyFunction();
+    int len = args.size();
+    List args2 = new ArrayList(len);
+    for (int i = 0; i < len; i++)
+      {
+        args2.add(((Expr) args.get(i)).clone(context));
+      }
+    f.setArguments(args2);
+    return f;
+  }
+
+  public boolean references(QName var)
+  {
+    for (Iterator i = args.iterator(); i.hasNext(); )
+      {
+        if (((Expr) i.next()).references(var))
+          {
+            return true;
+          }
+      }
+    return false;
+  }
+
+}
+

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/Template.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/Template.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/Template.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/Template.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,259 @@
+/* Template.java -- 
+   Copyright (C) 2004,2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.xml.transform;
+
+import java.io.PrintStream;
+import javax.xml.namespace.QName;
+import javax.xml.transform.TransformerException;
+import org.w3c.dom.Node;
+import gnu.xml.xpath.Expr;
+import gnu.xml.xpath.NameTest;
+import gnu.xml.xpath.NodeTypeTest;
+import gnu.xml.xpath.Pattern;
+import gnu.xml.xpath.Selector;
+import gnu.xml.xpath.Test;
+
+/**
+ * A template in an XSL stylesheet.
+ *
+ * @author <a href='mailto:dog at gnu.org'>Chris Burdess</a>
+ */
+class Template
+  implements Comparable
+{
+
+  static final double DEFAULT_PRIORITY = 0.5d;
+
+  final Stylesheet stylesheet;
+  final QName name;
+  final Pattern match;
+  final TemplateNode node;
+  final double priority;
+  final int precedence;
+  final QName mode;
+  final boolean isAnyNode; // is the match simply "node()"?
+
+  Template(Stylesheet stylesheet, 
+           QName name, Pattern match, TemplateNode node,
+           int precedence, String priorityAttr, QName mode)
+  {
+    this.stylesheet = stylesheet;
+    this.name = name;
+    this.match = match;
+    this.node = node;
+    this.precedence = precedence;
+    this.mode = mode;
+    
+    double p = DEFAULT_PRIORITY;
+    boolean a = false;
+    if (priorityAttr != null)
+      p = Double.parseDouble(priorityAttr);
+    else
+      {
+        // adjust priority if necessary
+        // see XSLT section 5.5
+        if (match instanceof Selector)
+          {
+            Selector selector = (Selector) match;
+            Test[] tests = selector.getTests();
+            if (tests.length > 0)
+              {
+                Test test = tests[0];
+                if (test instanceof NameTest)
+                  {
+                    NameTest nameTest = (NameTest) test;
+                    if (nameTest.matchesAny())
+                      p = -0.25d;
+                    else if (nameTest.matchesAnyLocalName())
+                      p = -0.20d;
+                    else
+                      p = 0.0d;
+                  }
+                else
+                  {
+                    NodeTypeTest nodeTypeTest = (NodeTypeTest) test;
+                    if (nodeTypeTest.getNodeType() ==
+                        Node.PROCESSING_INSTRUCTION_NODE &&
+                        nodeTypeTest.getData() != null)
+                      p = 0.0d;
+                    else
+                      p = -0.5d;
+                    a = (nodeTypeTest.getNodeType() == 0);
+                  }
+                // Add a small difference for predicates
+                if (tests.length > 1)
+                  p += ((double) tests.length - 1) * 0.001;
+              }
+          }
+      }
+    this.priority = p;
+    this.isAnyNode = a;
+  }
+  
+  private Template(Stylesheet stylesheet, 
+           QName name, Pattern match, TemplateNode node,
+           int precedence, double priority, QName mode, boolean isAnyNode)
+  {
+    this.stylesheet = stylesheet;
+    this.name = name;
+    this.match = match;
+    this.node = node;
+    this.precedence = precedence;
+    this.priority = priority;
+    this.mode = mode;
+    this.isAnyNode = isAnyNode;
+  }
+
+  Template clone(Stylesheet stylesheet)
+  {
+    // FIXME by cloning we lose the imports() functionality, so
+    // apply-imports will be broken.
+    return new Template(stylesheet,
+                        name,
+                        (match == null) ? null :
+                        (Pattern) match.clone(stylesheet),
+                        (node == null) ? null : node.clone(stylesheet),
+                        precedence,
+                        priority,
+                        mode,
+                        isAnyNode);
+  }
+  
+  public int compareTo(Object other)
+  {
+    if (other instanceof Template)
+      {
+        Template t = (Template) other;
+        int d = t.precedence - precedence;
+        if (d != 0)
+          return d;
+        double d2 = t.priority - priority;
+        if (d2 != 0.0d)
+          return (int) Math.round(d2 * 1000.0d);
+      }
+    return 0;
+  }
+
+  Test getNodeTest(Expr expr)
+  {
+    return null;
+  }
+
+  boolean matches(QName mode, Node node)
+  {
+    if ((mode == null && this.mode != null) ||
+        (mode != null && !mode.equals(this.mode)))
+      return false;
+    if (match == null)
+      return false;
+    if (isAnyNode && node.getNodeType() == Node.DOCUMENT_NODE)
+      return false; // don't match document node
+    return match.matches(node);
+  }
+
+  boolean matches(QName name)
+  {
+    return name.equals(this.name);
+  }
+
+  boolean imports(Template other)
+  {
+    for (Stylesheet ctx = other.stylesheet.parent;
+         ctx != null;
+         ctx = ctx.parent)
+      {
+        if (ctx == stylesheet)
+          return true;
+      }
+    return false;
+  }
+
+  /**
+   * @param stylesheet the stylesheet
+   * @param parent the parent of result nodes
+   * @param context the context node in the source document
+   * @param pos the context position
+   * @param len the context size
+   * @param nextSibling if non-null, add result nodes before this node
+   */
+  void apply(Stylesheet stylesheet, QName mode,
+             Node context, int pos, int len,
+             Node parent, Node nextSibling)
+    throws TransformerException
+  {
+    if (stylesheet.debug)
+      System.err.println("...applying " + toString() + " to " + context);
+    if (node != null)
+      node.apply(stylesheet, mode,
+                 context, pos, len,
+                 parent, nextSibling);
+  }
+
+  public String toString()
+  {
+    StringBuffer buf = new StringBuffer(getClass().getName());
+    buf.append('[');
+    if (name != null)
+      {
+        buf.append("name=");
+        buf.append(name);
+      }
+    else if (match != null)
+      {
+        buf.append("match=");
+        buf.append(match);
+      }
+    if (mode != null)
+      {
+        buf.append(",mode=");
+        buf.append(mode);
+      }
+    buf.append(']');
+    return buf.toString();
+    
+    //return (name != null) ? name.toString() : match.toString();
+  }
+
+  void list(PrintStream out)
+  {
+    out.println(toString());
+    if (node != null)
+      node.list(1, out, true);
+  }
+
+}

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/TemplateNode.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/TemplateNode.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/TemplateNode.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/TemplateNode.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,130 @@
+/* TemplateNode.java -- 
+   Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.xml.transform;
+
+import java.io.PrintStream;
+import java.util.Comparator;
+import javax.xml.namespace.QName;
+import javax.xml.transform.TransformerException;
+import org.w3c.dom.Node;
+import gnu.xml.xpath.DocumentOrderComparator;
+
+/**
+ * Wrapper for a source node in a template.
+ *
+ * @author <a href='mailto:dog at gnu.org'>Chris Burdess</a>
+ */
+abstract class TemplateNode
+{
+
+  static final Comparator documentOrderComparator =
+    new DocumentOrderComparator();
+
+  TemplateNode children;
+  TemplateNode next;
+
+  final void apply(Stylesheet stylesheet, QName mode,
+                   Node context, int pos, int len,
+                   Node parent, Node nextSibling)
+    throws TransformerException
+  {
+    if (stylesheet.terminated)
+      return;
+    if (Thread.currentThread().isInterrupted())
+      {
+        // Try to head off any infinite loops at the pass
+        return;
+      }
+    if (stylesheet.debug)
+      {
+        System.err.println("Applying " + toString());
+        System.err.println("\twith context=" + context + ", pos=" + pos +
+                           ", len=" + len);
+      }
+    doApply(stylesheet, mode, context, pos, len, parent, nextSibling);
+  }
+
+  abstract void doApply(Stylesheet stylesheet, QName mode,
+                        Node context, int pos, int len,
+                        Node parent, Node nextSibling)
+    throws TransformerException;
+
+  abstract TemplateNode clone(Stylesheet stylesheet);
+
+  public boolean references(QName var)
+  {
+    if (children != null && children.references(var))
+      return true;
+    if (next != null && next.references(var))
+      return true;
+    return false;
+  }
+
+  /**
+   * Debugging
+   */
+  void list(int depth, PrintStream out, boolean listNext)
+  {
+    for (int i = 0; i < depth; i++)
+      out.print("  ");
+    out.println(toString());
+    if (children != null)
+      children.list(depth + 1, out, true);
+    if (listNext && next != null)
+      next.list(depth, out, listNext);
+  }
+
+  /**
+   * Indicates whether the template for which this template node is the
+   * first node specifies the given parameter.
+   */
+  boolean hasParam(QName name)
+  {
+    for (TemplateNode ctx = this; ctx != null; ctx = ctx.next)
+      {
+        if (ctx instanceof ParameterNode)
+          {
+            ParameterNode param = (ParameterNode) ctx;
+            if (param.type == Bindings.PARAM && param.name.equals(name))
+              return true;
+          }
+      }
+    return false;
+  }
+
+}

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/TemplatesImpl.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/TemplatesImpl.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/TemplatesImpl.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/TemplatesImpl.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,80 @@
+/* TemplatesImpl.java -- 
+   Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.xml.transform;
+
+import java.util.Properties;
+import javax.xml.transform.Templates;
+import javax.xml.transform.Transformer;
+import javax.xml.transform.TransformerConfigurationException;
+
+/**
+ * GNU precompiled stylesheet implementation.
+ *
+ * @author <a href='mailto:dog at gnu.org'>Chris Burdess</a>
+ */
+class TemplatesImpl
+  implements Templates
+{
+
+  final TransformerFactoryImpl factory;
+  final Stylesheet stylesheet;
+  final Properties outputProperties;
+
+  TemplatesImpl(TransformerFactoryImpl factory, Stylesheet stylesheet)
+  {
+    this.factory = factory;
+    this.stylesheet = stylesheet;
+    outputProperties = new TransformerOutputProperties(stylesheet);
+  }
+
+  public Transformer newTransformer()
+    throws TransformerConfigurationException
+  {
+    Stylesheet stylesheet = (Stylesheet) this.stylesheet.clone();
+    TransformerImpl transformer =
+      new TransformerImpl(factory, stylesheet, outputProperties);
+    stylesheet.transformer = transformer;
+    return transformer;
+  }
+
+  public Properties getOutputProperties()
+  {
+    return (Properties) outputProperties.clone();
+  }
+  
+}

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/TextNode.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/TextNode.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/TextNode.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/TextNode.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,119 @@
+/* TextNode.java -- 
+   Copyright (C) 2004,2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.xml.transform;
+
+import javax.xml.namespace.QName;
+import javax.xml.transform.TransformerException;
+import org.w3c.dom.Document;
+import org.w3c.dom.DocumentFragment;
+import org.w3c.dom.Node;
+import org.w3c.dom.Text;
+import gnu.xml.xpath.Expr;
+
+/**
+ * A template node representing the XSL <code>text</code> instruction.
+ *
+ * @author <a href='mailto:dog at gnu.org'>Chris Burdess</a>
+ */
+final class TextNode
+  extends TemplateNode
+{
+
+  final boolean disableOutputEscaping;
+
+  TextNode(boolean disableOutputEscaping)
+  {
+    this.disableOutputEscaping = disableOutputEscaping;
+  }
+
+  TemplateNode clone(Stylesheet stylesheet)
+  {
+    TemplateNode ret = new TextNode(disableOutputEscaping);
+    if (children != null)
+      ret.children = children.clone(stylesheet);
+    if (next != null)
+      ret.next = next.clone(stylesheet);
+    return ret;
+  }
+
+  void doApply(Stylesheet stylesheet, QName mode,
+               Node context, int pos, int len,
+               Node parent, Node nextSibling)
+    throws TransformerException
+  {
+    String value = "";
+    Document doc = (parent instanceof Document) ? (Document) parent :
+      parent.getOwnerDocument();
+    if (children != null)
+      {
+        // Create a document fragment to hold the text
+        DocumentFragment fragment = doc.createDocumentFragment();
+        // Apply children to the fragment
+        children.apply(stylesheet, mode,
+                       context, pos, len,
+                       fragment, null);
+        // Use XPath string-value of fragment
+        value = Expr.stringValue(fragment);
+      }
+    Text text = doc.createTextNode(value);
+    if (disableOutputEscaping)
+      text.setUserData("disable-output-escaping", "yes", stylesheet);
+    // Insert into result tree
+    if (nextSibling != null)
+      parent.insertBefore(text, nextSibling);
+    else
+      parent.appendChild(text);
+    if (next != null)
+      next.apply(stylesheet, mode,
+                 context, pos, len,
+                 parent, nextSibling);
+  }
+
+  public String toString()
+  {
+    StringBuffer buf = new StringBuffer("text");
+    if (disableOutputEscaping)
+      {
+        buf.append('[');
+        buf.append("disable-output-escaping");
+        buf.append(']');
+      }
+    return buf.toString();
+  }
+  
+}

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/TransformerFactoryImpl.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/TransformerFactoryImpl.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/TransformerFactoryImpl.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/TransformerFactoryImpl.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,390 @@
+/* TransformerFactoryImpl.java -- 
+   Copyright (C) 2004,2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.xml.transform;
+
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.InputStream;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.net.URL;
+import java.util.Iterator;
+import java.util.LinkedHashMap;
+import java.util.LinkedList;
+import java.util.Map;
+import java.util.Properties;
+import javax.xml.transform.ErrorListener;
+import javax.xml.transform.Source;
+import javax.xml.transform.Templates;
+import javax.xml.transform.Transformer;
+import javax.xml.transform.TransformerConfigurationException;
+import javax.xml.transform.TransformerException;
+import javax.xml.transform.TransformerFactory;
+import javax.xml.transform.URIResolver;
+import javax.xml.transform.dom.DOMResult;
+import javax.xml.transform.dom.DOMSource;
+import javax.xml.transform.sax.SAXResult;
+import javax.xml.transform.sax.SAXSource;
+import javax.xml.transform.stream.StreamResult;
+import javax.xml.transform.stream.StreamSource;
+import javax.xml.xpath.XPathFactory;
+import org.w3c.dom.Document;
+import org.w3c.dom.Node;
+import gnu.xml.dom.DomDocument;
+
+/**
+ * GNU transformer factory implementation.
+ *
+ * @author <a href='mailto:dog at gnu.org'>Chris Burdess</a>
+ */
+public class TransformerFactoryImpl
+  extends TransformerFactory
+{
+
+  final XPathFactory xpathFactory;
+  final XSLURIResolver resolver;
+  ErrorListener userListener;
+  URIResolver userResolver;
+
+  public TransformerFactoryImpl()
+  {
+    xpathFactory = new gnu.xml.xpath.XPathFactoryImpl();
+    resolver = new XSLURIResolver();
+  }
+
+  public Transformer newTransformer(Source source)
+    throws TransformerConfigurationException
+  {
+    Stylesheet stylesheet = newStylesheet(source, 0, null);
+    Properties outputProperties =
+      new TransformerOutputProperties(stylesheet);
+    TransformerImpl transformer =
+      new TransformerImpl(this, stylesheet, outputProperties);
+    stylesheet.transformer = transformer;
+    return transformer;
+  }
+
+  public Transformer newTransformer()
+    throws TransformerConfigurationException
+  {
+    return new TransformerImpl(this, null, new Properties());
+  }
+
+  public Templates newTemplates(Source source)
+    throws TransformerConfigurationException
+  {
+    Stylesheet stylesheet = newStylesheet(source, 0, null);
+    return new TemplatesImpl(this, stylesheet);
+  }
+
+  Stylesheet newStylesheet(Source source, int precedence, Stylesheet parent)
+    throws TransformerConfigurationException
+  {
+    Document doc = null;
+    String systemId = null;
+    if (source != null)
+      {
+        try
+          {
+            DOMSource ds;
+            synchronized (resolver)
+              {
+                resolver.setUserResolver(userResolver);
+                resolver.setUserListener(userListener);
+                ds = resolver.resolveDOM(source, null, null);
+              }
+            Node node = ds.getNode();
+            if (node == null)
+              {
+                throw new TransformerConfigurationException("no source document");
+              }
+            doc = (node instanceof Document) ? (Document) node :
+              node.getOwnerDocument();
+            systemId = ds.getSystemId();
+          }
+        catch (TransformerException e)
+          {
+            throw new TransformerConfigurationException(e);
+          }
+      }
+    return new Stylesheet(this, parent, doc, systemId, precedence);
+  }
+  
+  public Source getAssociatedStylesheet(Source source,
+                                        String media,
+                                        String title,
+                                        String charset)
+    throws TransformerConfigurationException
+  {
+    try
+      {
+        DOMSource ds;
+        synchronized (resolver)
+          {
+            resolver.setUserResolver(userResolver);
+            resolver.setUserListener(userListener);
+            ds = resolver.resolveDOM(source, null, null);
+          }
+        Node node = ds.getNode();
+        if (node == null)
+          {
+            throw new TransformerConfigurationException("no source document");
+          }
+        Document doc = (node instanceof Document) ? (Document) node :
+          node.getOwnerDocument();
+        LinkedList matches = new LinkedList();
+        for (node = doc.getFirstChild();
+             node != null;
+             node = node.getNextSibling())
+          {
+            if (node.getNodeType() == Node.PROCESSING_INSTRUCTION_NODE &&
+                "xml-stylesheet".equals(node.getNodeName()))
+              {
+                Map params = parseParameters(node.getNodeValue());
+                if (media != null && !media.equals(params.get("media")))
+                  {
+                    continue;
+                  }
+                if (title != null && !title.equals(params.get("title")))
+                  {
+                    continue;
+                  }
+                if (charset != null && !charset.equals(params.get("charset")))
+                  {
+                    continue;
+                  }
+                String href = (String) params.get("href");
+                URL url = resolver.resolveURL(null, node.getBaseURI(), href);
+                matches.add(url);
+              }
+          }
+        switch (matches.size())
+          {
+          case 0:
+            return null;
+          case 1:
+            return new StreamSource(((URL) matches.getFirst()).toString());
+          default:
+            // Create a source representing a stylesheet with a list of
+            // imports
+            DomDocument ssDoc = new DomDocument();
+            ssDoc.setBuilding(true);
+            // Create document element
+            Node root =
+              ssDoc.createElementNS(Stylesheet.XSL_NS, "stylesheet");
+            Node version =
+              ssDoc.createAttributeNS(null, "version");
+            version.setNodeValue("1.0");
+            root.getAttributes().setNamedItemNS(version);
+            ssDoc.appendChild(root);
+            // Create xsl:import for each URL
+            for (Iterator i = matches.iterator(); i.hasNext(); )
+              {
+                URL url = (URL) i.next();
+                Node imp =
+                  ssDoc.createElementNS(Stylesheet.XSL_NS, "import");
+                Node href =
+                  ssDoc.createAttributeNS(null, "href");
+                href.setNodeValue(url.toString());
+                imp.getAttributes().setNamedItemNS(href);
+                root.appendChild(imp);
+              }
+            ssDoc.setBuilding(false);
+            return new DOMSource(ssDoc);
+          }
+      }
+    catch (IOException e)
+      {
+        throw new TransformerConfigurationException(e);
+      }
+    catch (TransformerException e)
+      {
+        throw new TransformerConfigurationException(e);
+      }
+  }
+
+  Map parseParameters(String data)
+  {
+    Map ret = new LinkedHashMap();
+    int len = data.length();
+    String key = null;
+    int start = 0;
+    char quoteChar = '\u0000';
+    for (int i = 0; i < len; i++)
+      {
+        char c = data.charAt(i);
+        if (quoteChar == '\u0000' && c == ' ')
+          {
+            if (key == null && start < i)
+              {
+                key = data.substring(start, i);
+              }
+            else
+              {
+                String val = unquote(data.substring(start, i).trim());
+                ret.put(key, val);
+                key = null;
+              }
+            start = i + 1;
+          }
+        else if (c == '"')
+          {
+            quoteChar = (quoteChar == c) ? '\u0000' : c;
+          }
+        else if (c == '\'')
+          {
+            quoteChar = (quoteChar == c) ? '\u0000' : c;
+          }
+      }
+    if (start < len && key != null)
+      {
+        String val = unquote(data.substring(start, len).trim());
+        ret.put(key, val);
+      }
+    return ret;
+  }
+
+  String unquote(String text)
+  {
+    int end = text.length() - 1;
+    if (text.charAt(0) == '\'' && text.charAt(end) == '\'')
+      {
+        return text.substring(1, end);
+      }
+    if (text.charAt(0) == '"' && text.charAt(end) == '"')
+      {
+        return text.substring(1, end);
+      }
+    return text;
+  }
+
+  public void setURIResolver(URIResolver resolver)
+  {
+    userResolver = resolver;
+  }
+
+  public URIResolver getURIResolver()
+  {
+    return userResolver;
+  }
+
+  public void setFeature(String name, boolean value)
+    throws TransformerConfigurationException
+  {
+    throw new TransformerConfigurationException("not supported");
+  }
+
+  public boolean getFeature(String name)
+  {
+    if (SAXSource.FEATURE.equals(name) ||
+        SAXResult.FEATURE.equals(name) ||
+        StreamSource.FEATURE.equals(name) ||
+        StreamResult.FEATURE.equals(name) ||
+        DOMSource.FEATURE.equals(name) ||
+        DOMResult.FEATURE.equals(name))
+      {
+        return true;
+      }
+    return false;
+  }
+
+  public void setAttribute(String name, Object value)
+    throws IllegalArgumentException
+  {
+    throw new IllegalArgumentException("not supported");
+  }
+
+  public Object getAttribute(String name)
+    throws IllegalArgumentException
+  {
+    throw new IllegalArgumentException("not supported");
+  }
+
+  public void setErrorListener(ErrorListener listener)
+    throws IllegalArgumentException
+  {
+    userListener = listener;
+  }
+
+  public ErrorListener getErrorListener()
+  {
+    return userListener;
+  }
+
+  /**
+   * Syntax: TransformerFactoryImpl [<stylesheet> [<input> [<output>]]]
+   */
+  public static void main(String[] args)
+    throws Exception
+  {
+    InputStream stylesheet = null, in = null;
+    OutputStream out = null;
+    try
+      {
+        if (args.length > 0)
+          {
+            stylesheet = new FileInputStream(args[0]);
+            if (args.length > 1)
+              {
+                in = new FileInputStream(args[1]);
+                if (args.length > 2)
+                  out = new FileOutputStream(args[2]);
+              }
+          }
+        if (in == null)
+          in = System.in;
+        if (out == null)
+          out = System.out;
+        TransformerFactory f = new TransformerFactoryImpl();
+        Transformer t = (stylesheet != null) ?
+          f.newTransformer(new StreamSource(stylesheet)) :
+          f.newTransformer();
+        t.transform(new StreamSource(in), new StreamResult(out));
+      }
+    finally
+      {
+        if (stylesheet != null)
+          stylesheet.close();
+        if (in != null && in instanceof FileInputStream)
+          in.close();
+        if (out != null && out instanceof FileOutputStream)
+          out.close();
+      }
+  }
+  
+}

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/TransformerImpl.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/TransformerImpl.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/TransformerImpl.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/TransformerImpl.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,803 @@
+/* TransformerImpl.java -- 
+   Copyright (C) 2004,2005,2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.xml.transform;
+
+import java.io.BufferedOutputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.io.UnsupportedEncodingException;
+import java.io.Writer;
+import java.net.MalformedURLException;
+import java.net.UnknownServiceException;
+import java.net.URL;
+import java.net.URLConnection;
+import java.util.Collection;
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Properties;
+import java.util.StringTokenizer;
+import javax.xml.namespace.QName;
+import javax.xml.transform.ErrorListener;
+import javax.xml.transform.OutputKeys;
+import javax.xml.transform.Result;
+import javax.xml.transform.Source;
+import javax.xml.transform.Transformer;
+import javax.xml.transform.TransformerConfigurationException;
+import javax.xml.transform.TransformerException;
+import javax.xml.transform.URIResolver;
+import javax.xml.transform.dom.DOMSource;
+import javax.xml.transform.dom.DOMResult;
+import javax.xml.transform.sax.SAXResult;
+import javax.xml.transform.stream.StreamResult;
+import org.w3c.dom.Document;
+import org.w3c.dom.DocumentType;
+import org.w3c.dom.DOMImplementation;
+import org.w3c.dom.Node;
+import org.w3c.dom.Text;
+import org.xml.sax.ContentHandler;
+import org.xml.sax.SAXException;
+import org.xml.sax.ext.LexicalHandler;
+import gnu.xml.dom.DomDoctype;
+import gnu.xml.dom.DomDocument;
+import gnu.xml.dom.ls.WriterOutputStream;
+
+/**
+ * The transformation process for a given stylesheet.
+ *
+ * @author <a href='mailto:dog at gnu.org'>Chris Burdess</a>
+ */
+class TransformerImpl
+  extends Transformer
+{
+
+  final TransformerFactoryImpl factory;
+  final Stylesheet stylesheet;
+  URIResolver uriResolver;
+  ErrorListener errorListener;
+  Properties outputProperties;
+
+  TransformerImpl(TransformerFactoryImpl factory,
+                  Stylesheet stylesheet,
+                  Properties outputProperties)
+    throws TransformerConfigurationException
+  {
+    this.factory = factory;
+    uriResolver = factory.userResolver;
+    errorListener = factory.userListener;
+    this.stylesheet = stylesheet;
+    this.outputProperties = outputProperties;
+    if (stylesheet != null)
+      {
+        // Set up parameter context for this transformer
+        stylesheet.bindings.push(Bindings.PARAM);
+      }
+  }
+
+  public void transform(Source xmlSource, Result outputTarget)
+    throws TransformerException
+  {
+    // Get the source tree
+    DOMSource source;
+    synchronized (factory.resolver)
+      {
+        factory.resolver.setUserResolver(uriResolver);
+        factory.resolver.setUserListener(errorListener);
+        source = factory.resolver.resolveDOM(xmlSource, null, null);
+      }
+    Node context = source.getNode();
+    Document doc = (context instanceof Document) ? (Document) context :
+      context.getOwnerDocument();
+    if (doc instanceof DomDocument)
+      {
+        // Suppress mutation events
+        ((DomDocument) doc).setBuilding(true);
+      }
+    // Get the result tree
+    Node parent = null, nextSibling = null;
+    if (outputTarget instanceof DOMResult)
+      {
+        DOMResult dr = (DOMResult) outputTarget;
+        parent = dr.getNode();
+        nextSibling = dr.getNextSibling();
+
+        Document rdoc = (parent instanceof Document) ? (Document) parent :
+          parent.getOwnerDocument();
+        if (rdoc instanceof DomDocument)
+          {
+            // Suppress mutation events and allow multiple root elements
+            DomDocument drdoc = (DomDocument) rdoc;
+            drdoc.setBuilding(true);
+            drdoc.setCheckWellformedness(false);
+          }
+      }
+    boolean created = false;
+    // Transformation
+    if (stylesheet != null)
+      {
+        if (parent == null)
+          {
+            // Create a new document to hold the result
+            DomDocument resultDoc = new DomDocument();
+            resultDoc.setBuilding(true);
+            resultDoc.setCheckWellformedness(false);
+            parent = resultDoc;
+            created = true;
+          }
+        // Make a copy of the source node, and strip it
+        context = context.cloneNode(true);
+        strip(stylesheet, context);
+        // XSLT transformation
+        try
+          {
+            // Set output properties in the underlying stylesheet
+            ((TransformerOutputProperties) outputProperties).apply();
+            stylesheet.initTopLevelVariables(context);
+            TemplateNode t = stylesheet.getTemplate(null, context, false);
+            if (t != null)
+              {
+                stylesheet.current = context;
+                t.apply(stylesheet, null, context, 1, 1, parent, nextSibling);
+              }
+          }
+        catch (TransformerException e)
+          {
+            // Done transforming, reset document
+            if (doc instanceof DomDocument)
+              ((DomDocument) doc).setBuilding(false);
+            throw e;
+          }
+      }
+    else
+      {
+        // Identity transform
+        Node clone = context.cloneNode(true);
+        if (context.getNodeType() != Node.DOCUMENT_NODE)
+          {
+            Document resultDoc;
+            if (parent == null)
+              {
+                // Create a new document to hold the result
+                DomDocument rd = new DomDocument();
+                rd.setBuilding(true);
+                rd.setCheckWellformedness(false);
+                parent = resultDoc = rd;
+                created = true;
+              }
+            else
+              {
+                resultDoc = (parent instanceof Document) ?
+                  (Document) parent :
+                  parent.getOwnerDocument();
+              }
+            Document sourceDoc = context.getOwnerDocument();
+            if (sourceDoc != resultDoc)
+              clone = resultDoc.adoptNode(clone);
+            if (nextSibling != null)
+              parent.insertBefore(clone, nextSibling);
+            else
+              parent.appendChild(clone);
+          }
+        else
+          {
+            // Cannot append document to another tree
+            parent = clone;
+            created = true;
+          }
+      }
+    String method = outputProperties.getProperty(OutputKeys.METHOD);
+    int outputMethod = "html".equals(method) ? Stylesheet.OUTPUT_HTML :
+      "text".equals(method) ? Stylesheet.OUTPUT_TEXT :
+      Stylesheet.OUTPUT_XML;
+    String encoding = outputProperties.getProperty(OutputKeys.ENCODING);
+    String publicId = outputProperties.getProperty(OutputKeys.DOCTYPE_PUBLIC);
+    String systemId = outputProperties.getProperty(OutputKeys.DOCTYPE_SYSTEM);
+    String version = outputProperties.getProperty(OutputKeys.VERSION);
+    boolean omitXmlDeclaration = 
+      "yes".equals(outputProperties.getProperty(OutputKeys.OMIT_XML_DECLARATION));
+    boolean standalone = 
+      "yes".equals(outputProperties.getProperty(OutputKeys.STANDALONE));
+    String mediaType = outputProperties.getProperty(OutputKeys.MEDIA_TYPE);
+    String cdataSectionElements =
+      outputProperties.getProperty(OutputKeys.CDATA_SECTION_ELEMENTS);
+    boolean indent =
+      "yes".equals(outputProperties.getProperty(OutputKeys.INDENT));
+    if (created && parent instanceof DomDocument)
+      {
+        // Discover document element
+        DomDocument resultDoc = (DomDocument) parent;
+        Node root = resultDoc.getDocumentElement();
+        // Add doctype if specified
+        if (publicId != null || systemId != null)
+          {
+            if (root != null)
+              {
+                // We must know the name of the root element to
+                // create the document type
+                DocumentType doctype = new DomDoctype(resultDoc,
+                                                      root.getNodeName(),
+                                                      publicId,
+                                                      systemId);
+                resultDoc.insertBefore(doctype, root);
+              }
+          }
+        resultDoc.setBuilding(false);
+        resultDoc.setCheckWellformedness(true);
+      }
+    else if (publicId != null || systemId != null)
+      {
+        switch (parent.getNodeType())
+          {
+          case Node.DOCUMENT_NODE:
+          case Node.DOCUMENT_FRAGMENT_NODE:
+            Document resultDoc = (parent instanceof Document) ?
+              (Document) parent :
+              parent.getOwnerDocument();
+            DOMImplementation impl = resultDoc.getImplementation();
+            Node root = resultDoc.getDocumentElement();
+            if (root != null)
+              {
+                DocumentType doctype =
+                  impl.createDocumentType(root.getNodeName(),
+                                          publicId,
+                                          systemId);
+                resultDoc.insertBefore(doctype, root);
+              }
+          }
+      }
+    if (version != null)
+      parent.setUserData("version", version, stylesheet);
+    if (omitXmlDeclaration)
+      parent.setUserData("omit-xml-declaration", "yes", stylesheet);
+    if (standalone)
+      parent.setUserData("standalone", "yes", stylesheet);
+    if (mediaType != null)
+      parent.setUserData("media-type", mediaType, stylesheet);
+    if (cdataSectionElements != null)
+      {
+        List list = new LinkedList();
+        StringTokenizer st = new StringTokenizer(cdataSectionElements);
+        while (st.hasMoreTokens())
+          {
+            String name = st.nextToken();
+            String localName = name;
+            String uri = null;
+            String prefix = null;
+            int ci = name.indexOf(':');
+            if (ci != -1)
+              {
+                // Use namespaces defined on xsl:output node to resolve
+                // namespaces for QName
+                prefix = name.substring(0, ci);
+                localName = name.substring(ci + 1);
+                uri = stylesheet.output.lookupNamespaceURI(prefix);
+              }
+            list.add(new QName(uri, localName, prefix));
+          }
+        if (!list.isEmpty())
+          {
+            Document resultDoc = (parent instanceof Document) ?
+              (Document) parent :
+              parent.getOwnerDocument();
+            convertCdataSectionElements(resultDoc, parent, list);
+          }
+      }
+    if (indent)
+      {
+        if (created && parent instanceof DomDocument)
+          {
+            DomDocument domDoc = (DomDocument) parent;
+            domDoc.setBuilding(true);
+            domDoc.setCheckWellformedness(false);
+          }
+        parent.normalize();
+        if (stylesheet != null)
+          strip(stylesheet, parent);
+        Document resultDoc = (parent instanceof Document) ?
+          (Document) parent :
+          parent.getOwnerDocument();
+        reindent(resultDoc, parent, 0);
+        if (created && parent instanceof DomDocument)
+          {
+            DomDocument domDoc = (DomDocument) parent;
+            domDoc.setBuilding(false);
+            domDoc.setCheckWellformedness(true);
+          }
+      }
+    // Render result to the target device
+    if (outputTarget instanceof DOMResult)
+      {
+        if (created)
+          {
+            DOMResult dr = (DOMResult) outputTarget;
+            dr.setNode(parent);
+            dr.setNextSibling(null);
+          }
+      }
+    else if (outputTarget instanceof StreamResult)
+      {
+        StreamResult sr = (StreamResult) outputTarget;
+        IOException ex = null;
+        try
+          {
+            writeStreamResult(parent, sr, outputMethod, encoding);
+          }
+        catch (UnsupportedEncodingException e)
+          {
+            try
+              {
+                writeStreamResult(parent, sr, outputMethod, "UTF-8");
+              }
+            catch (IOException e2)
+              {
+                ex = e2;
+              }
+          }
+        catch (IOException e)
+          {
+            ex = e;
+          }
+        if (ex != null)
+          {
+            if (errorListener != null)
+              errorListener.error(new TransformerException(ex));
+            else
+              ex.printStackTrace(System.err);
+          }
+      }
+    else if (outputTarget instanceof SAXResult)
+      {
+        SAXResult sr = (SAXResult) outputTarget;
+        try
+          {
+            ContentHandler ch = sr.getHandler();
+            LexicalHandler lh = sr.getLexicalHandler();
+            if (lh == null && ch instanceof LexicalHandler)
+              lh = (LexicalHandler) ch;
+            SAXSerializer serializer = new SAXSerializer();
+            serializer.serialize(parent, ch, lh);
+          }
+        catch (SAXException e)
+          {
+            if (errorListener != null)
+              errorListener.error(new TransformerException(e));
+            else
+              e.printStackTrace(System.err);
+          }
+      }
+  }
+
+  /**
+   * Strip whitespace from the source tree.
+   */
+  static boolean strip(Stylesheet stylesheet, Node node)
+    throws TransformerConfigurationException
+  {
+    short nt = node.getNodeType();
+    if (nt == Node.ENTITY_REFERENCE_NODE)
+      {
+        // Replace entity reference with its content
+        Node parent = node.getParentNode();
+        Node nextSibling = node.getNextSibling();
+        Node child = node.getFirstChild();
+        while (child != null)
+          {
+            Node next = child.getNextSibling();
+            node.removeChild(child);
+            if (nextSibling != null)
+              parent.insertBefore(child, nextSibling);
+            else
+              parent.appendChild(child);
+            child = next;
+          }
+        return true;
+      }
+    if (nt == Node.TEXT_NODE || nt == Node.CDATA_SECTION_NODE)
+      {
+        // Denormalize text into whitespace and non-whitespace nodes
+        String text = node.getNodeValue();
+        String[] tokens = tokenizeWhitespace(text);
+        if (tokens.length > 1)
+          {
+            node.setNodeValue(tokens[0]);
+            Node parent = node.getParentNode();
+            Node nextSibling = node.getNextSibling();
+            Document doc = node.getOwnerDocument();
+            for (int i = 1; i < tokens.length; i++)
+              {
+                Node newChild = (nt == Node.CDATA_SECTION_NODE) ?
+                  doc.createCDATASection(tokens[i]) :
+                  doc.createTextNode(tokens[i]);
+                if (nextSibling != null)
+                  parent.insertBefore(newChild, nextSibling);
+                else
+                  parent.appendChild(newChild);
+              }
+          }
+        return !stylesheet.isPreserved((Text) node, true);
+      }
+    else
+      {
+        Node child = node.getFirstChild();
+        while (child != null)
+          {
+            boolean remove = strip(stylesheet, child);
+            Node next = child.getNextSibling();
+            if (remove)
+              node.removeChild(child);
+            child = next;
+          }
+      }
+    return false;
+  }
+
+  /**
+   * Tokenize the specified text into contiguous whitespace-only and
+   * non-whitespace chunks.
+   */
+  private static String[] tokenizeWhitespace(String text)
+  {
+    int len = text.length();
+    int start = 0, end = len - 1;
+    // Find index of text start
+    for (int i = 0; i < len; i++)
+      {
+        char c = text.charAt(i);
+        boolean whitespace = (c == ' ' || c == '\n' || c == '\t' || c == '\r');
+        if (whitespace)
+          start++;
+        else
+          break;
+      }
+    if (start == end) // all whitespace
+      return new String[] { text };
+    // Find index of text end
+    for (int i = end; i > start; i--)
+      {
+        char c = text.charAt(i);
+        boolean whitespace = (c == ' ' || c == '\n' || c == '\t' || c == '\r');
+        if (whitespace)
+          end--;
+        else
+          break;
+      }
+    if (start == 0 && end == len - 1) // all non-whitespace
+      return new String[] { text };
+    // whitespace, then text, then whitespace
+    String[] ret = (start > 0 && end < len - 1) ?
+      new String[3] : new String[2];
+    int i = 0;
+    if (start > 0)
+      ret[i++] = text.substring(0, start);
+    ret[i++] = text.substring(start, end + 1);
+    if (end < len - 1)
+      ret[i++] = text.substring(end + 1);
+    return ret;
+  }
+
+  /**
+   * Obtain a suitable output stream for writing the result to,
+   * and use the StreamSerializer to write the result tree to the stream.
+   */
+  void writeStreamResult(Node node, StreamResult sr, int outputMethod,
+                         String encoding)
+    throws IOException
+  {
+    OutputStream out = null;
+    boolean created = false;
+    try
+      {
+        out = sr.getOutputStream();
+        if (out == null)
+          {
+            Writer writer = sr.getWriter();
+            if (writer != null)
+              out = new WriterOutputStream(writer);
+          }
+        if (out == null)
+          {
+            String systemId = sr.getSystemId();
+            try
+              {
+                URL url = new URL(systemId);
+                URLConnection connection = url.openConnection();
+                // We need to call setDoInput(false), because our
+                // implementation of the file protocol allows writing
+                // (unlike Sun), but it will fail with a FileNotFoundException
+                // if we also open the connection for input and the output
+                // file doesn't yet exist.
+                connection.setDoInput(false);
+                connection.setDoOutput(true);
+                out = connection.getOutputStream();
+              }
+            catch (MalformedURLException e)
+              {
+                out = new FileOutputStream(systemId);
+              }
+            catch (UnknownServiceException e)
+              {
+                URL url = new URL(systemId);
+                out = new FileOutputStream(url.getPath());
+              }
+            created = true;
+          }
+        out = new BufferedOutputStream(out);
+        StreamSerializer serializer =
+          new StreamSerializer(outputMethod, encoding, null);
+        if (stylesheet != null)
+          {
+            Collection celem = stylesheet.outputCdataSectionElements;
+            serializer.setCdataSectionElements(celem);
+          }
+        serializer.serialize(node, out);
+        out.flush();
+      }
+    finally
+      {
+        try
+          {
+            if (out != null && created)
+              out.close();
+          }
+        catch (IOException e)
+          {
+            if (errorListener != null)
+              {
+                try
+                  {
+                    errorListener.error(new TransformerException(e));
+                  }
+                catch (TransformerException e2)
+                  {
+                    e2.printStackTrace(System.err);
+                  }
+              }
+            else
+              e.printStackTrace(System.err);
+          }
+      }
+  }
+
+  void copyChildren(Document dstDoc, Node src, Node dst)
+  {
+    Node srcChild = src.getFirstChild();
+    while (srcChild != null)
+      {
+        Node dstChild = dstDoc.adoptNode(srcChild);
+        dst.appendChild(dstChild);
+        srcChild = srcChild.getNextSibling();
+      }
+  }
+
+  public void setParameter(String name, Object value)
+  {
+    if (stylesheet != null)
+      stylesheet.bindings.set(new QName(null, name), value, Bindings.PARAM);
+  }
+
+  public Object getParameter(String name)
+  {
+    if (stylesheet != null)
+      return stylesheet.bindings.get(new QName(null, name), null, 1, 1);
+    return null;
+  }
+
+  public void clearParameters()
+  {
+    if (stylesheet != null)
+      {
+        stylesheet.bindings.pop(Bindings.PARAM);
+        stylesheet.bindings.push(Bindings.PARAM);
+      }
+  }
+
+  public void setURIResolver(URIResolver resolver)
+  {
+    uriResolver = resolver;
+  }
+
+  public URIResolver getURIResolver()
+  {
+    return uriResolver;
+  }
+
+  public void setOutputProperties(Properties oformat)
+    throws IllegalArgumentException
+  {
+    if (oformat == null)
+      outputProperties.clear();
+    else
+      outputProperties.putAll(oformat);
+  }
+
+  public Properties getOutputProperties()
+  {
+    return (Properties) outputProperties.clone();
+  }
+
+  public void setOutputProperty(String name, String value)
+    throws IllegalArgumentException
+  {
+    outputProperties.put(name, value);
+  }
+
+  public String getOutputProperty(String name)
+    throws IllegalArgumentException
+  {
+    return outputProperties.getProperty(name);
+  }
+
+  public void setErrorListener(ErrorListener listener)
+  {
+    errorListener = listener;
+  }
+
+  public ErrorListener getErrorListener()
+  {
+    return errorListener;
+  }
+
+  static final String INDENT_WHITESPACE = "  ";
+
+  /*
+   * Apply indent formatting to the given tree.
+   */
+  void reindent(Document doc, Node node, int offset)
+  {
+    if (node.hasChildNodes())
+      {
+        boolean markupContent = false;
+        boolean textContent = false;
+        List children = new LinkedList();
+        Node ctx = node.getFirstChild();
+        while (ctx != null)
+          {
+            switch (ctx.getNodeType())
+              {
+              case Node.ELEMENT_NODE:
+              case Node.PROCESSING_INSTRUCTION_NODE:
+              case Node.DOCUMENT_TYPE_NODE:
+                markupContent = true;
+                break;
+              case Node.TEXT_NODE:
+              case Node.CDATA_SECTION_NODE:
+              case Node.ENTITY_REFERENCE_NODE:
+              case Node.COMMENT_NODE:
+                textContent = true;
+                break;
+              }
+            children.add(ctx);
+            ctx = ctx.getNextSibling();
+          }
+        if (markupContent)
+          {
+            if (textContent)
+              {
+                // XXX handle mixed content differently?
+              }
+            int nodeType = node.getNodeType();
+            if (nodeType == Node.DOCUMENT_NODE)
+              {
+                for (Iterator i = children.iterator(); i.hasNext(); )
+                  {
+                    ctx = (Node) i.next();
+                    reindent(doc, ctx, offset);
+                  }
+              }
+            else
+              {
+                StringBuffer buf = new StringBuffer();
+                buf.append('\n');
+                for (int i = 0; i < offset + 1; i++)
+                  buf.append(INDENT_WHITESPACE);
+                String ws = buf.toString();
+                for (Iterator i = children.iterator(); i.hasNext(); )
+                  {
+                    ctx = (Node) i.next();
+                    node.insertBefore(doc.createTextNode(ws), ctx);
+                    reindent(doc, ctx, offset + 1);
+                  }
+                buf = new StringBuffer();
+                buf.append('\n');
+                for (int i = 0; i < offset; i++)
+                  buf.append(INDENT_WHITESPACE);
+                ws = buf.toString();
+                node.appendChild(doc.createTextNode(ws));
+              }
+          }
+      }
+  }
+
+  /**
+   * Converts the text node children of any cdata-section-elements in the
+   * tree to CDATA section nodes.
+   */
+  void convertCdataSectionElements(Document doc, Node node, List list)
+  {
+    if (node.getNodeType() == Node.ELEMENT_NODE)
+      {
+        boolean match = false;
+        for (Iterator i = list.iterator(); i.hasNext(); )
+          {
+            QName qname = (QName) i.next();
+            if (match(qname, node))
+              {
+                match = true;
+                break;
+              }
+          }
+        if (match)
+          {
+            Node ctx = node.getFirstChild();
+            while (ctx != null)
+              {
+                if (ctx.getNodeType() == Node.TEXT_NODE)
+                  {
+                    Node cdata = doc.createCDATASection(ctx.getNodeValue());
+                    node.replaceChild(cdata, ctx);
+                    ctx = cdata;
+                  }
+                ctx = ctx.getNextSibling();
+              }
+          }
+      }
+    Node ctx = node.getFirstChild();
+    while (ctx != null)
+      {
+        if (ctx.hasChildNodes())
+          convertCdataSectionElements(doc, ctx, list);
+        ctx = ctx.getNextSibling();
+      }
+  }
+
+  boolean match(QName qname, Node node)
+  {
+    String ln1 = qname.getLocalPart();
+    String ln2 = node.getLocalName();
+    if (ln2 == null)
+      return ln1.equals(node.getNodeName());
+    else
+      {
+        String uri1 = qname.getNamespaceURI();
+        String uri2 = node.getNamespaceURI();
+        return (uri1.equals(uri2) && ln1.equals(ln2));
+      }
+  }
+
+}

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/TransformerOutputProperties.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/TransformerOutputProperties.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/TransformerOutputProperties.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/TransformerOutputProperties.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,185 @@
+/* TransformerOutputProperties.java -- 
+   Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.xml.transform;
+
+import java.util.Collection;
+import java.util.Iterator;
+import java.util.LinkedHashSet;
+import java.util.Properties;
+import java.util.StringTokenizer;
+import javax.xml.transform.OutputKeys;
+
+/**
+ * Helper class to manage JAXP user setting of output properties.
+ *
+ * @author <a href='mailto:dog at gnu.org'>Chris Burdess</a>
+ */
+class TransformerOutputProperties
+  extends Properties
+{
+  
+  final Properties defaultProperties;
+  final Stylesheet stylesheet;
+  boolean dirty;
+
+  TransformerOutputProperties(Stylesheet stylesheet)
+  {
+    this.stylesheet = stylesheet;
+    defaultProperties = new Properties();
+    switch (stylesheet.outputMethod)
+      {
+      case Stylesheet.OUTPUT_XML:
+        defaultProperties.put(OutputKeys.METHOD, "xml");
+        break;
+      case Stylesheet.OUTPUT_HTML:
+        defaultProperties.put(OutputKeys.METHOD, "html");
+        break;
+      case Stylesheet.OUTPUT_TEXT:
+        defaultProperties.put(OutputKeys.METHOD, "text");
+        break;
+      }
+    if (stylesheet.outputVersion != null)
+      {
+        defaultProperties.put(OutputKeys.VERSION, stylesheet.outputVersion);
+      }
+    if (stylesheet.outputEncoding != null)
+      {
+        defaultProperties.put(OutputKeys.ENCODING, stylesheet.outputEncoding);
+      }
+    defaultProperties.put(OutputKeys.OMIT_XML_DECLARATION,
+                          stylesheet.outputOmitXmlDeclaration ? "yes" : "no");
+    defaultProperties.put(OutputKeys.STANDALONE,
+                          stylesheet.outputStandalone ? "yes" : "no");
+    if (stylesheet.outputPublicId != null)
+      {
+        defaultProperties.put(OutputKeys.DOCTYPE_PUBLIC,
+                              stylesheet.outputPublicId);
+      }
+    if (stylesheet.outputSystemId != null)
+      {
+        defaultProperties.put(OutputKeys.DOCTYPE_SYSTEM,
+                              stylesheet.outputSystemId);
+      }
+    StringBuffer buf = new StringBuffer();
+    for (Iterator i = stylesheet.outputCdataSectionElements.iterator();
+         i.hasNext(); )
+      {
+        if (buf.length() > 0)
+          {
+            buf.append(' ');
+          }
+        buf.append((String) i.next());
+      }
+    defaultProperties.put(OutputKeys.CDATA_SECTION_ELEMENTS, buf.toString());
+    defaultProperties.put(OutputKeys.INDENT,
+                          stylesheet.outputIndent ? "yes" : "no");
+    if (stylesheet.outputMediaType != null)
+      {
+        defaultProperties.put(OutputKeys.MEDIA_TYPE,
+                              stylesheet.outputMediaType);
+      }
+  }
+
+  public String getProperty(String key)
+  {
+    String val = super.getProperty(key);
+    if (val == null)
+      {
+        val = defaultProperties.getProperty(key);
+      }
+    return val;
+  }
+
+  public Object put(Object key, Object value)
+  {
+    Object ret = super.put(key, value);
+    dirty = true;
+    return ret;
+  }
+
+  public void clear()
+  {
+    super.clear();
+    dirty = true;
+  }
+
+  /**
+   * Applies the current set of properties to the underlying stylesheet.
+   */
+  void apply()
+  {
+    if (!dirty)
+      {
+        return;
+      }
+    String method = getProperty(OutputKeys.METHOD);
+    if ("xml".equals(method))
+      {
+        stylesheet.outputMethod = Stylesheet.OUTPUT_XML;
+      }
+    else if ("html".equals(method))
+      {
+        stylesheet.outputMethod = Stylesheet.OUTPUT_HTML;
+      }
+    else if ("text".equals(method))
+      {
+        stylesheet.outputMethod = Stylesheet.OUTPUT_TEXT;
+      }
+    stylesheet.outputVersion = getProperty(OutputKeys.VERSION);
+    stylesheet.outputEncoding = getProperty(OutputKeys.ENCODING);
+    stylesheet.outputOmitXmlDeclaration =
+      "yes".equals(getProperty(OutputKeys.OMIT_XML_DECLARATION));
+    stylesheet.outputStandalone =
+      "yes".equals(getProperty(OutputKeys.STANDALONE));
+    stylesheet.outputPublicId = getProperty(OutputKeys.DOCTYPE_PUBLIC);
+    stylesheet.outputSystemId = getProperty(OutputKeys.DOCTYPE_SYSTEM);
+    StringTokenizer st = 
+      new StringTokenizer(getProperty(OutputKeys.CDATA_SECTION_ELEMENTS));
+    Collection acc = new LinkedHashSet();
+    while (st.hasMoreTokens())
+      {
+        acc.add(st.nextToken());
+      }
+    stylesheet.outputCdataSectionElements = acc;
+    stylesheet.outputIndent = "yes".equals(getProperty(OutputKeys.INDENT));
+    stylesheet.outputMediaType = getProperty(OutputKeys.MEDIA_TYPE);
+    dirty = false;
+  }
+
+}
+

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/URIResolverEntityResolver.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/URIResolverEntityResolver.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/URIResolverEntityResolver.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/URIResolverEntityResolver.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,83 @@
+/* URIResolverEntityResolver.java -- 
+   Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.xml.transform;
+
+import java.io.IOException;
+import javax.xml.transform.Source;
+import javax.xml.transform.TransformerException;
+import javax.xml.transform.URIResolver;
+import javax.xml.transform.sax.SAXSource;
+import org.xml.sax.EntityResolver;
+import org.xml.sax.InputSource;
+import org.xml.sax.SAXException;
+
+/**
+ * EntityResolver that wraps a URIResolver.
+ *
+ * @author <a href='mailto:dog at gnu.org'>Chris Burdess</a>
+ */
+class URIResolverEntityResolver
+  implements EntityResolver
+{
+
+  final URIResolver resolver;
+
+  URIResolverEntityResolver(URIResolver resolver)
+  {
+    this.resolver = resolver;
+  }
+
+  public InputSource resolveEntity(String publicId, String systemId)
+    throws SAXException, IOException
+  {
+    try
+      {
+        Source source = resolver.resolve(null, systemId);
+        if (source == null)
+          {
+            return null;
+          }
+        return SAXSource.sourceToInputSource(source);
+      }
+    catch (TransformerException e)
+      {
+        throw new SAXException(e);
+      }
+  }
+  
+}

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/UnparsedEntityUriFunction.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/UnparsedEntityUriFunction.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/UnparsedEntityUriFunction.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/UnparsedEntityUriFunction.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,132 @@
+/* UnparsedEntityUriFunction.java -- 
+   Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.xml.transform;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Iterator;
+import java.util.List;
+import javax.xml.namespace.QName;
+import javax.xml.xpath.XPathFunction;
+import javax.xml.xpath.XPathFunctionException;
+import org.w3c.dom.DocumentType;
+import org.w3c.dom.NamedNodeMap;
+import org.w3c.dom.Node;
+import org.w3c.dom.Notation;
+import gnu.xml.xpath.Expr;
+import gnu.xml.xpath.Function;
+
+/**
+ * The XSLT <code>unparsed-entity-uri()</code>function.
+ *
+ * @author <a href='mailto:dog at gnu.org'>Chris Burdess</a>
+ */
+final class UnparsedEntityUriFunction
+  extends Expr
+  implements XPathFunction, Function
+{
+
+  List args;
+
+  public Object evaluate(List args)
+    throws XPathFunctionException
+  {
+    // Useless...
+    return Collections.EMPTY_SET;
+  }
+
+  public void setArguments(List args)
+  {
+    this.args = args;
+  }
+
+  public Object evaluate(Node context, int pos, int len)
+  {
+    int arity = args.size();
+    List values = new ArrayList(arity);
+    for (int i = 0; i < arity; i++)
+      {
+        Expr arg = (Expr) args.get(i);
+        values.add(arg.evaluate(context, pos, len));
+      }
+    String name = _string(context, values.get(0));
+    DocumentType doctype = context.getOwnerDocument().getDoctype();
+    if (doctype != null)
+      {
+        NamedNodeMap notations = doctype.getNotations();
+        Notation notation = (Notation) notations.getNamedItem(name);
+        if (notation != null)
+          {
+            String systemId = notation.getSystemId();
+            // XXX absolutize?
+            if (systemId != null)
+              {
+                return systemId;
+              }
+          }
+      }
+    return "";
+  }
+
+  public Expr clone(Object context)
+  {
+    UnparsedEntityUriFunction f = new UnparsedEntityUriFunction();
+    int len = args.size();
+    List args2 = new ArrayList(len);
+    for (int i = 0; i < len; i++)
+      {
+        args2.add(((Expr) args.get(i)).clone(context));
+      }
+    f.setArguments(args2);
+    return f;
+  }
+
+  public boolean references(QName var)
+  {
+    for (Iterator i = args.iterator(); i.hasNext(); )
+      {
+        if (((Expr) i.next()).references(var))
+          {
+            return true;
+          }
+      }
+    return false;
+  }
+
+}
+

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/ValueOfNode.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/ValueOfNode.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/ValueOfNode.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/ValueOfNode.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,139 @@
+/* ValueOfNode.java -- 
+   Copyright (C) 2004,2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.xml.transform;
+
+import java.util.Collection;
+import java.util.Iterator;
+import javax.xml.namespace.QName;
+import javax.xml.transform.TransformerException;
+import org.w3c.dom.Document;
+import org.w3c.dom.Node;
+import org.w3c.dom.Text;
+import gnu.xml.xpath.Expr;
+
+/**
+ * A template node representing an XSLT <code>value-of</code> instruction.
+ *
+ * @author <a href='mailto:dog at gnu.org'>Chris Burdess</a>
+ */
+final class ValueOfNode
+  extends TemplateNode
+{
+
+  final Expr select;
+  final boolean disableOutputEscaping;
+
+  ValueOfNode(Expr select, boolean disableOutputEscaping)
+  {
+    this.select = select;
+    this.disableOutputEscaping = disableOutputEscaping;
+  }
+
+  TemplateNode clone(Stylesheet stylesheet)
+  {
+    TemplateNode ret = new ValueOfNode(select.clone(stylesheet),
+                                       disableOutputEscaping);
+    if (children != null)
+      ret.children = children.clone(stylesheet);
+    if (next != null)
+      ret.next = next.clone(stylesheet);
+    return ret;
+  }
+
+  void doApply(Stylesheet stylesheet, QName mode,
+               Node context, int pos, int len,
+               Node parent, Node nextSibling)
+    throws TransformerException
+  {
+    Object ret = select.evaluate(context, pos, len);
+    String value;
+    if (ret instanceof Collection)
+      {
+        StringBuffer buf = new StringBuffer();
+        for (Iterator i = ((Collection) ret).iterator(); i.hasNext(); )
+          {
+            Node node = (Node) i.next();
+            buf.append(Expr.stringValue(node));
+          }
+        value = buf.toString();
+      }
+    else if (ret == null)
+      value = "";
+    else
+      value = Expr._string(context, ret);
+    if (stylesheet.debug)
+      System.err.println("value-of: "+context+" "+ select + " -> "+ value);
+    if (value != null && value.length() > 0)
+      {
+        Document doc = (parent instanceof Document) ?
+          (Document) parent : parent.getOwnerDocument();
+        Text textNode = doc.createTextNode(value);
+        if (disableOutputEscaping)
+          textNode.setUserData("disable-output-escaping", "yes", stylesheet);
+        if (nextSibling != null)
+          parent.insertBefore(textNode, nextSibling);
+        else
+          parent.appendChild(textNode);
+      }
+    // value-of doesn't process children
+    if (next != null)
+      next.apply(stylesheet, mode,
+                 context, pos, len,
+                 parent, nextSibling);
+  }
+
+  public boolean references(QName var)
+  {
+    if (select != null && select.references(var))
+      return true;
+    return super.references(var);
+  }
+  
+  public String toString()
+  {
+    StringBuffer buf = new StringBuffer("value-of");
+    buf.append('[');
+    buf.append("select=");
+    buf.append(select);
+    if (disableOutputEscaping)
+      buf.append(",disableOutputEscaping");
+    buf.append(']');
+    return buf.toString();
+  }
+  
+}

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/WhenNode.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/WhenNode.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/WhenNode.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/WhenNode.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,113 @@
+/* WhenNode.java -- 
+   Copyright (C) 2004,2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.xml.transform;
+
+import javax.xml.namespace.QName;
+import javax.xml.transform.TransformerException;
+import org.w3c.dom.Node;
+import gnu.xml.xpath.Expr;
+
+/**
+ * A template node representing an XSL <code>when</code> instruction.
+ *
+ * @author <a href='mailto:dog at gnu.org'>Chris Burdess</a>
+ */
+final class WhenNode
+  extends TemplateNode
+{
+
+  final Expr test;
+
+  WhenNode(Expr test)
+  {
+    this.test = test;
+  }
+
+  TemplateNode clone(Stylesheet stylesheet)
+  {
+    TemplateNode ret = new WhenNode(test.clone(stylesheet));
+    if (children != null)
+      ret.children = children.clone(stylesheet);
+    if (next != null)
+      ret.next = next.clone(stylesheet);
+    return ret;
+  }
+
+  void doApply(Stylesheet stylesheet, QName mode,
+               Node context, int pos, int len,
+               Node parent, Node nextSibling)
+    throws TransformerException
+  {
+    Object ret = test.evaluate(context, pos, len);
+    boolean success = (ret instanceof Boolean) ?
+      ((Boolean) ret).booleanValue() :
+      Expr._boolean(context, ret);
+    if (success)
+      {
+        if (children != null)
+          children.apply(stylesheet, mode,
+                         context, pos, len,
+                         parent, nextSibling);
+      }
+    else
+      {
+        if (next != null)
+          next.apply(stylesheet, mode,
+                     context, pos, len,
+                     parent, nextSibling);
+      }
+  }
+  
+  public boolean references(QName var)
+  {
+    if (test != null && test.references(var))
+      return true;
+    return super.references(var);
+  }
+  
+  public String toString()
+  {
+    StringBuffer buf = new StringBuffer("when");
+    buf.append('[');
+    buf.append("test=");
+    buf.append(test);
+    buf.append(']');
+    return buf.toString();
+  }
+  
+}

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/WithParam.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/WithParam.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/WithParam.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/WithParam.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,123 @@
+/* WithParam.java -- 
+   Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.xml.transform;
+
+import java.util.Collections;
+import javax.xml.namespace.QName;
+import javax.xml.transform.TransformerException;
+import org.w3c.dom.Document;
+import org.w3c.dom.DocumentFragment;
+import org.w3c.dom.Node;
+import gnu.xml.xpath.Expr;
+
+/**
+ * A specification for setting a variable or parameter during template
+ * processing with <code>apply-templates</code> or
+ * <code>call-template</code>.
+ *
+ * @author <a href='mailto:dog at gnu.org'>Chris Burdess</a>
+ */
+final class WithParam
+{
+
+  final QName name;
+  final Expr select;
+  final TemplateNode content;
+
+  WithParam(QName name, Expr select)
+  {
+    this.name = name;
+    this.select = select;
+    content = null;
+  }
+
+  WithParam(QName name, TemplateNode content)
+  {
+    this.name = name;
+    this.content = content;
+    select = null;
+  }
+
+  Object getValue(Stylesheet stylesheet, QName mode,
+                  Node context, int pos, int len)
+    throws TransformerException
+  {
+    if (select != null)
+      {
+        return select.evaluate(context, pos, len);
+      }
+    else
+      {
+        Document doc = (context instanceof Document) ? (Document) context :
+          context.getOwnerDocument();
+        DocumentFragment fragment = doc.createDocumentFragment();
+        content.apply(stylesheet, mode,
+                      context, pos, len,
+                      fragment, null);
+        return Collections.singleton(fragment);
+      }
+  }
+
+  WithParam clone(Stylesheet stylesheet)
+  {
+    if (content == null)
+      {
+        return new WithParam(name,
+                             select.clone(stylesheet));
+      }
+    else
+      {
+        return new WithParam(name,
+                             content.clone(stylesheet));
+      }
+  }
+
+  boolean references(QName var)
+  {
+    if (select != null && select.references(var))
+      {
+        return true;
+      }
+    if (content != null && content.references(var))
+      {
+        return true;
+      }
+    return false;
+  }
+
+}

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/XSLComparator.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/XSLComparator.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/XSLComparator.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/XSLComparator.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,124 @@
+/* XSLComparator.java -- 
+   Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.xml.transform;
+
+import java.util.Comparator;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Locale;
+import java.text.Collator;
+import org.w3c.dom.Node;
+import gnu.xml.xpath.Expr;
+
+/**
+ * Comparator for sorting lists of nodes according to a list of sort keys.
+ *
+ * @author <a href='mailto:dog at gnu.org'>Chris Burdess</a>
+ */
+class XSLComparator
+  implements Comparator
+{
+
+  final List sortKeys;
+
+  XSLComparator(List sortKeys)
+  {
+    this.sortKeys = sortKeys;
+  }
+
+  public int compare(Object o1, Object o2)
+  {
+    if (o1 instanceof Node && o2 instanceof Node)
+      {
+        Node n1 = (Node) o1;
+        Node n2 = (Node) o2;
+        for (Iterator i = sortKeys.iterator(); i.hasNext(); )
+          {
+            SortKey sortKey = (SortKey) i.next();
+            String k1 = sortKey.key(n1);
+            String k2 = sortKey.key(n2);
+            if ("text".equals(sortKey.dataType))
+              {
+                Locale locale = (sortKey.lang == null) ? Locale.getDefault() :
+                  new Locale(sortKey.lang);
+                Collator collator = Collator.getInstance(locale);
+                int d = collator.compare(k1, k2);
+                if (d != 0)
+                  {
+                    switch (sortKey.caseOrder)
+                      {
+                      case SortKey.UPPER_FIRST:
+                        // TODO
+                        break;
+                      case SortKey.LOWER_FIRST:
+                        // TODO
+                        break;
+                      }
+                    if (sortKey.descending)
+                      {
+                        d = -d;
+                      }
+                    return d;
+                  }
+              }
+            else if ("number".equals(sortKey.dataType))
+              {
+                double kn1 = Expr._number(n1, k1);
+                double kn2 = Expr._number(n2, k2);
+                int d;
+                if (Double.isNaN(kn1) || Double.isInfinite(kn2))
+                  {
+                    d = -1;
+                  }
+                else if (Double.isNaN(kn2) || Double.isInfinite(kn1))
+                  {
+                    d = 1;
+                  }
+                else
+                  {
+                    // conversion to int may give 0 for small numbers
+                    d = (kn1 > kn2) ? 1 : (kn1 < kn2) ? -1 : 0;
+                  }
+                return (sortKey.descending) ? -d : d;
+              }
+          }
+      }
+    return 0;
+  }
+  
+}

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/XSLURIResolver.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/XSLURIResolver.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/XSLURIResolver.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/XSLURIResolver.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,282 @@
+/* XSLURIResolver.java -- 
+   Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.xml.transform;
+
+import java.io.File;
+import java.io.InputStream;
+import java.io.IOException;
+import java.io.Reader;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.net.URLConnection;
+import java.util.HashMap;
+import java.util.Map;
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.transform.ErrorListener;
+import javax.xml.transform.Source;
+import javax.xml.transform.TransformerException;
+import javax.xml.transform.URIResolver;
+import javax.xml.transform.dom.DOMSource;
+import javax.xml.transform.stream.StreamSource;
+import org.w3c.dom.Node;
+import org.xml.sax.InputSource;
+import org.xml.sax.SAXException;
+import gnu.xml.dom.ls.ReaderInputStream;
+
+/**
+ * URI resolver for XSLT.
+ * This resolver parses external entities into DOMSources. It
+ * maintains a cache of URIs to DOMSources to avoid expensive re-parsing.
+ *
+ * @author <a href='mailto:dog at gnu.org'>Chris Burdess</a>
+ */
+class XSLURIResolver
+  implements URIResolver
+{
+
+  Map lastModifiedCache = new HashMap();
+  Map nodeCache = new HashMap();
+  DocumentBuilder builder;
+  URIResolver userResolver;
+  ErrorListener userListener;
+
+  void setUserResolver(URIResolver userResolver)
+  {
+    this.userResolver = userResolver;
+  }
+
+  void setUserListener(ErrorListener userListener)
+  {
+    this.userListener = userListener;
+  }
+
+  /**
+   * Clear the cache.
+   */
+  void flush()
+  {
+    lastModifiedCache.clear();
+    nodeCache.clear();
+  }
+
+  public Source resolve(String href, String base)
+    throws TransformerException
+  {
+    Source source = null;
+    if (userResolver != null)
+      {
+        source = userResolver.resolve(base, href);
+      }
+    return resolveDOM(source, href, base);
+  }
+
+  DOMSource resolveDOM(Source source, String base, String href)
+    throws TransformerException
+  {
+    if (source != null && source instanceof DOMSource)
+      {
+        return (DOMSource) source;
+      }
+    String systemId = (source == null) ? null : source.getSystemId();
+    long lastModified = 0L, lastLastModified = 0L;
+
+    try
+      {
+        URL url = resolveURL(systemId, base, href);
+        Node node = null;
+        InputStream in = null;
+        if (source instanceof StreamSource)
+          {
+            StreamSource ss = (StreamSource) source;
+            in = ss.getInputStream();
+            if (in == null)
+              {
+                Reader reader = ss.getReader();
+                if (reader != null)
+                  {
+                    in = new ReaderInputStream(reader);
+                  }
+              }
+          }
+        if (in == null)
+          {
+            if (url != null)
+              {
+                systemId = url.toString();
+                node = (Node) nodeCache.get(systemId);
+                // Is the resource up to date?
+                URLConnection conn = url.openConnection();
+                Long llm = (Long) lastModifiedCache.get(systemId);
+                if (llm != null)
+                  {
+                    lastLastModified = llm.longValue();
+                    conn.setIfModifiedSince(lastLastModified);
+                  }
+                conn.connect();
+                lastModified = conn.getLastModified();
+                if (node != null && 
+                    lastModified > 0L &&
+                    lastModified <= lastLastModified)
+                  {
+                    // Resource unchanged
+                    return new DOMSource(node, systemId);
+                  }
+                else
+                  {
+                    // Resource new or modified
+                    in = conn.getInputStream();
+                    nodeCache.put(systemId, node);
+                    lastModifiedCache.put(systemId, new Long(lastModified));
+                  }
+              }
+            else
+              {
+                throw new TransformerException("can't resolve URL: " +
+                                               systemId);
+              }
+          }
+        InputSource input = new InputSource(in);
+        input.setSystemId(systemId);
+        DocumentBuilder builder = getDocumentBuilder();
+        node = builder.parse(input);
+        return new DOMSource(node, systemId);
+      }
+    catch (IOException e)
+      {
+        throw new TransformerException(e);
+      }
+    catch (SAXException e)
+      {
+        throw new TransformerException(e);
+      }
+  }
+
+  URL resolveURL(String systemId, String base, String href)
+    throws IOException
+  {
+    URL url = null;
+    try
+      {
+        if (systemId != null)
+          {
+            try
+              {
+                url = new URL(systemId);
+              }
+            catch (MalformedURLException e)
+              {
+                // Try building from base + href
+              }
+          }
+        if (url == null)
+          {
+            if (base != null)
+              {
+                URL baseURL = new URL(base);
+                url = new URL(baseURL, href);
+              }
+            else if (href != null)
+              {
+                url = new URL(href);
+              }
+            else
+              {
+                // See below
+                throw new MalformedURLException(systemId);
+              }
+          }
+        return url;
+      }
+    catch (MalformedURLException e)
+      {
+        // Fall back to local filesystem
+        File file = null;
+        if (href == null)
+          {
+            href = systemId;
+          }
+        if (base != null)
+          {
+            int lsi = base.lastIndexOf(File.separatorChar);
+            if (lsi != -1 && lsi < base.length() - 1)
+              {
+                base = base.substring(0, lsi);
+              }
+            File baseFile = new File(base);
+            file = new File(baseFile, href);
+          }
+        else if (href != null)
+          {
+            file = new File(href);
+          }
+        return (file == null) ? null : file.toURL();
+      }
+  }
+  
+  DocumentBuilder getDocumentBuilder()
+    throws TransformerException
+  {
+    try
+      {
+        if (builder == null)
+          {
+            DocumentBuilderFactory factory =
+              DocumentBuilderFactory.newInstance();
+            factory.setNamespaceAware(true);
+            factory.setExpandEntityReferences(true);
+            builder = factory.newDocumentBuilder();
+          }
+        if (userResolver != null)
+          {
+            builder.setEntityResolver(new URIResolverEntityResolver(userResolver));
+          }
+        if (userListener != null)
+          {
+            builder.setErrorHandler(new ErrorListenerErrorHandler(userListener));
+          }
+        return builder;
+      }
+    catch (Exception e)
+      {
+        throw new TransformerException(e);
+      }
+  }
+  
+}
+

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/package.html
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/package.html?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/package.html (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/transform/package.html Thu Nov  8 16:56:19 2007
@@ -0,0 +1,77 @@
+<html>
+<body>
+
+<h1>GNU JAXP XSL transformer</h1>
+
+<div>
+This package contains a Java XSL transformer compliant with the JAXP
+specification. It depends on the GNU DOM and XPath implementations, and
+will generate GNU DOM nodes unless a specific target from another
+implementation was given. It understands DOM, SAX, and stream sources
+and result sinks and supports these JAXP features.
+</div>
+
+<div>
+To use this transformer, set the system property
+<code>javax.xml.transform.TransformerFactory</code> to the value
+<code>gnu.xml.transform.TransformerFactoryImpl</code>. You can then
+instantiate <a href='TransformerFactory.html'>TransformerFactory</a>
+and transformers in the ordinary manner. Reuse of stylesheets is
+supported using the JAXP <a href='Templates.html'>Templates</a>
+mechanism.
+</div>
+
+<h3>Architecture</h3>
+
+<div>
+When given a stylesheet source, this implementation compiles it internally
+into a Stylesheet object, which is a container for templates and state.
+Each stylesheet instruction is represented by a subclass of TemplateNode,
+which is arranged in a directed graph: each TemplateNode has a reference
+to its first child and the next node.
+</div>
+
+<div>
+The transformation process consists of identifying the Template that matches
+the root of the source context, and calling <code>apply</code> on its
+corresponding TemplateNode. This in turn processes its children and next
+TemplateNode, depending on the semantics of each node type.
+</div>
+
+<div>
+Template nodes may reference XPath expressions or patterns. These are fully
+compiled to objects of type <a href='../xpath/Expr.html'>Expr</a> at the
+time the stylesheet is compiled.
+</div>
+
+<h3>Conformance</h3>
+
+<div>
+This implementation is feature complete, but the XSLT specification is
+large and there are still many bugs that need to be ironed out. It has
+been tested against the OASIS XSLT TC test suite, comprising unit tests
+from the Xalan project and Microsoft. Conformance to these unit tests
+is approximately 70% at the current time, although normal usage of the
+transformer should involve relatively few surprises (the test suite is
+designed to test very complex and obscure functionality).
+</div>
+
+<h3>Known bugs</h3>
+
+<ul>
+<li>When reusing stylesheets using the JAXP Templates mechanism, XSL
+<code>apply-imports</code> instructions will not work.</li>
+<li>XPath filter expressions do not always work as expected (this is a
+problem with the GNU XPath implementation rather than the transformer).
+This can result in problems with the <code>position()</code> function,
+as well as <code>select</code> expressions and numbering.</li>
+</ul>
+
+<div>
+Obviously we'd like to improve conformance and fix these bugs. If you're
+interested in working on any of these issues please
+<a href='mailto:classpathx-xml at gnu.org'>contact us</a>.
+</div>
+
+</body>
+</html>

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/util/DoParse.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/util/DoParse.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/util/DoParse.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/util/DoParse.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,300 @@
+/* DoParse.java -- 
+   Copyright (C) 1999,2000,2001 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.xml.util;
+
+import java.io.IOException;
+
+import org.xml.sax.ErrorHandler;
+import org.xml.sax.InputSource;
+import org.xml.sax.SAXException;
+import org.xml.sax.SAXParseException;
+import org.xml.sax.XMLReader;
+import org.xml.sax.helpers.XMLReaderFactory;
+
+import gnu.xml.pipeline.EventConsumer;
+import gnu.xml.pipeline.EventFilter;
+import gnu.xml.pipeline.NSFilter;
+import gnu.xml.pipeline.PipelineFactory;
+import gnu.xml.pipeline.TeeConsumer;
+import gnu.xml.pipeline.ValidationConsumer;
+import gnu.xml.pipeline.WellFormednessFilter;
+
+/**
+ * This class provides a driver which may be invoked from the command line
+ * to process a document using a SAX2 parser and a specified XML processing
+ * pipeline.
+ * This facilitates some common types of command line tools, such as parsing an
+ * XML document in order test it for well formedness or validity.
+ *
+ * <p>The SAX2 XMLReaderFactory should return a SAX2 XML parser which
+ * supports both of the standardized extension handlers (for declaration
+ * and lexical events).  That parser will be used to produce events.
+ *
+ * <p>The first parameter to the command gives the name of the document that
+ * will be given to that processor.  If it is a file name, it is converted
+ * to a URL first.
+ *
+ * <p>The second parameter describes a simple processing pipeline, and will
+ * be used as input to {@link gnu.xml.pipeline.PipelineFactory}
+ * methods which identify the processing to be done.  Examples of such a
+ * pipeline include <pre>
+ *
+ *    nsfix | validate                <em>to validate the input document </em>
+ *    nsfix | write ( stdout )        <em>to echo the file as XML text</em>
+ *    dom | nsfix | write ( stdout )  <em>parse into DOM, print the result</em>
+ * </pre>
+ *
+ * <p> Relatively complex pipelines can be described on the command line, but
+ * not all interesting ones will require as little configuration as can be done
+ * in that way.  Put filters like "nsfix", perhaps followed by "validate",
+ * at the front of the pipeline so they can be optimized out if a parser
+ * supports those modes natively.
+ *
+ * <p> If the parsing is aborted for any reason, the JVM will exit with a
+ * failure code.  If a validating parse was done then both validation and
+ * well formedness errors will cause a failure.  A non-validating parse
+ * will report failure on well formedness errors.
+ *
+ * @see gnu.xml.pipeline.PipelineFactory
+ *
+ * @author David Brownell
+ */
+final public class DoParse
+{
+    private DoParse () { /* no instances allowed */ }
+
+    // first reported nonrecoverable error
+    private static SAXParseException	fatal;
+
+    // error categories
+    private static int			errorCount;
+    private static int			fatalCount;
+
+    /**
+     * Command line invoker for this class; pass a filename or URL
+     * as the first argument, and a pipeline description as the second.
+     * Make sure to use filters to condition the input to stages that
+     * require it; an <em>nsfix</em> filter will be a common requirement,
+     * to restore syntax that SAX2 parsers delete by default.  Some
+     * conditioning filters may be eliminated by setting parser options.
+     * (For example, "nsfix" can set the "namespace-prefixes" feature to
+     * a non-default value of "true".  In the same way, "validate" can set
+     * the "validation" feature to "true".)
+     */
+    public static void main (String argv [])
+    throws IOException
+    {
+	int		exitStatus = 1;
+
+	if (argv.length != 2) {
+	    System.err.println ("Usage: DoParse [filename|URL] pipeline-spec");
+	    System.err.println ("Example pipeline specs:");
+	    System.err.println ("  'nsfix | validate'");
+	    System.err.println (
+		"       ... restore namespace syntax, validate");
+	    System.err.println ("  'nsfix | write ( stdout )'");
+	    System.err.println (
+		"       ... restore namespace syntax, write to stdout as XML"
+		);
+	    System.exit (1);
+	}
+
+	try {
+	    //
+	    // Get input source for specified document (or try ;-)
+	    //
+	    argv [0] = Resolver.getURL (argv [0]);
+	    InputSource input = new InputSource (argv [0]);
+
+	    //
+	    // Get the producer, using the system default parser (which
+	    // can be overridden for this particular invocation).
+	    //
+	    // And the pipeline, using commandline options.
+	    //
+	    XMLReader		producer;
+	    EventConsumer	consumer;
+
+	    producer = XMLReaderFactory.createXMLReader ();
+
+	    //
+	    // XXX pipeline factory now has a pre-tokenized input
+	    // method, use it ... that way at least some params
+	    // can be written using quotes (have spaces, ...)
+	    //
+	    consumer = PipelineFactory.createPipeline (argv [1]);
+
+	    //
+	    // XXX want commandline option for tweaking error handler.
+	    // Want to be able to present warnings.
+	    //
+	    producer.setErrorHandler (new MyErrorHandler ());
+
+	    // XXX need facility enabling resolving to local DTDs
+
+	    //
+	    // Parse.  The pipeline may get optimized a bit, so we
+	    // can't always fail cleanly for validation without taking
+	    // a look at the filter stages.
+	    //
+	    EventFilter.bind (producer, consumer);
+	    producer.parse (input);
+
+	    try {
+		if (producer.getFeature (
+			"http://org.xml/sax/features/validation"))
+		    exitStatus = ((errorCount + fatalCount) > 0) ? 1 : 0;
+		else if (fatalCount == 0)
+		    exitStatus = 0;
+	    } catch (SAXException e) {
+		if (hasValidator (consumer))
+		    exitStatus = ((errorCount + fatalCount) > 0) ? 1 : 0;
+		else if (fatalCount == 0)
+		    exitStatus = 0;
+	    }
+
+	} catch (java.net.MalformedURLException e) {
+	    System.err.println ("** Malformed URL: " + e.getMessage ());
+	    System.err.println ("Is '" + argv [0] + "' a non-existent file?");
+	    e.printStackTrace ();
+		// e.g. FNF
+
+	} catch (SAXParseException e) {
+	    if (e != fatal) {
+		System.err.print (printParseException ("Parsing Aborted", e));
+		e.printStackTrace ();
+		if (e.getException () != null) {
+		    System.err.println ("++ Wrapped exception:");
+		    e.getException ().printStackTrace ();
+		}
+	    }
+
+	} catch (SAXException e) {
+	    Exception	x = e;
+	    if (e.getException () != null)
+		x = e.getException ();
+	    x.printStackTrace ();
+
+	} catch (Throwable t) {
+	    t.printStackTrace ();
+	}
+
+	System.exit (exitStatus);
+    }
+
+    // returns true if saw a validator (before end or unrecognized node)
+    // false otherwise
+    private static boolean hasValidator (EventConsumer e)
+    {
+	if (e == null)
+	    return false;
+	if (e instanceof ValidationConsumer)
+	    return true;
+	if (e instanceof TeeConsumer) {
+	    TeeConsumer	t = (TeeConsumer) e;
+	    return hasValidator (t.getFirst ())
+		|| hasValidator (t.getRest ());
+	}
+	if (e instanceof WellFormednessFilter
+		|| e instanceof NSFilter
+		)
+	    return hasValidator (((EventFilter)e).getNext ());
+	
+	// else ... gee, we can't know.  Assume not.
+
+	return false;
+    }
+
+    static class MyErrorHandler implements ErrorHandler
+    {
+	// dump validation errors, but continue
+	public void error (SAXParseException e)
+	throws SAXParseException
+	{
+	    errorCount++;
+	    System.err.print (printParseException ("Error", e));
+	}
+
+	public void warning (SAXParseException e)
+	throws SAXParseException
+	{
+	    // System.err.print (printParseException ("Warning", e));
+	}
+
+	// try to continue fatal errors, in case a parser reports more
+	public void fatalError (SAXParseException e)
+	throws SAXParseException
+	{
+	    fatalCount++;
+	    if (fatal == null)
+		fatal = e;
+	    System.err.print (printParseException ("Nonrecoverable Error", e));
+	}
+    }
+
+    static private String printParseException (
+	String			label,
+	SAXParseException	e
+    ) {
+	StringBuffer	buf = new StringBuffer ();
+	int		temp;
+
+	buf.append ("** ");
+	buf.append (label);
+	buf.append (": ");
+	buf.append (e.getMessage ());
+	buf.append ('\n');
+	if (e.getSystemId () != null) {
+	    buf.append ("   URI:  ");
+	    buf.append (e.getSystemId ());
+	    buf.append ('\n');
+	}
+	if ((temp = e.getLineNumber ()) != -1) {
+	    buf.append ("   line: ");
+	    buf.append (temp);
+	    buf.append ('\n');
+	}
+	if ((temp = e.getColumnNumber ()) != -1) {
+	    buf.append ("   char: ");
+	    buf.append (temp);
+	    buf.append ('\n');
+	}
+
+	return buf.toString ();
+    }
+}

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/util/DomParser.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/util/DomParser.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/util/DomParser.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/util/DomParser.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,804 @@
+/* DomParser.java -- 
+   Copyright (C) 1999,2000,2001 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.xml.util;
+
+import java.util.Enumeration;
+import java.util.Locale;
+
+import org.xml.sax.*;
+import org.xml.sax.helpers.AttributesImpl;
+import org.xml.sax.helpers.NamespaceSupport;
+import org.xml.sax.ext.DeclHandler;
+import org.xml.sax.ext.DefaultHandler2;
+import org.xml.sax.ext.LexicalHandler;
+
+import org.w3c.dom.*;
+
+
+/**
+ * This parser emits SAX2 parsing events as it traverses a DOM tree, using
+ * any conformant implementation of DOM.  It exposes all SAX1 features,
+ * and the following SAX2 features and properties (as
+ * identified by standard URIs which are not fully provided here).  Note
+ * that if a Level 1 DOM implementation is given, then this behaves as if
+ * namespaces were disabled, and namespace prefixes were enabled.  </p>
+ *
+ * <table border="1" width='100%' cellpadding='3' cellspacing='0'>
+ * <tr bgcolor='#ccccff'>
+ *	<th><font size='+1'>Name</font></th>
+ *	<th><font size='+1'>Notes</font></th></tr>
+ *
+ * <tr><td colspan=2><center><em>Features ... URL prefix is
+ * <b>http://xml.org/sax/features/</b></em></center></td></tr>
+ *
+ * <tr><td>(URL)/external-general-entities</td>
+ *	<td>false (does no parsing)</td></tr>
+ * <tr><td>(URL)/external-parameter-entities</td>
+ *	<td>false (does no parsing)</td></tr>
+ * <tr><td>(URL)/namespaces</td>
+ *	<td>Value is fixed at <em>true</em></td></tr>
+ * <tr><td>(URL)/namespace-prefixes</td>
+ *	<td>Value is settable, defaulting to <em>false</em>
+ *	(<code>xmlns</code> attributes hidden, and names aren't prefixed)
+ *	</td></tr>
+ * <tr><td>(URL)/string-interning</td>
+ *	<td>Value is fixed at <em>false</em> (DOM provides no
+ *	guarantees as to interning)</td></tr>
+ * <tr><td>(URL)/validation</td>
+ *	<td>false (does no parsing)</td></tr>
+ * <tr><td>(URL)/lexical-handler/parameter-entities</td>
+ *	<td>false (DOM doesn't do parameter entities)</td></tr>
+ *
+ * <tr><td colspan=2><center><em>Properties ... URL prefix is
+ * <b>http://xml.org/sax/properties/</b></em></center></td></tr>
+ *
+ *
+ * <tr><td>(URL)/dom-node</td>
+ *	<td>This property may be set before parsing to hold a DOM
+ *	<em>Document</em> node; any arguments given to <em>parse</em>
+ *	methods are ignored.  When retrieved
+ *	during a parse, this value contains the "current" DOM node.
+ *	</td></tr>
+ * <tr><td>(URL)/declaration-handler</td>
+ *	<td>A declaration handler may be provided.  Declaration of external
+ *	general entities is exposed, but not parameter entities; none of the
+ *	entity names reported here will begin with "%". </td></tr>
+ * <tr><td>(URL)/lexical-handler</td>
+ *	<td>A lexical handler may be provided.  While the start and end of
+ *	any external subset are reported, expansion of other parameter
+ *	entities (e.g. inside attribute list declarations) is not exposed.
+ *	Expansion of general entities within attributes is also not exposed
+ *	(see below).</td></tr>
+ * </table>
+ *
+ * <P> The consequences of modifying a DOM document tree as it is being walked
+ * by this "parser" are unspecified; don't do it! </P>
+ *
+ * @author David Brownell
+ */
+final public class DomParser implements XMLReader
+{
+    // Stuff used internally to route events correctly
+    private DefaultHandler2	defaultHandler = new DefaultHandler2 ();
+
+    // per-parse SAX stuff
+    private ContentHandler	contentHandler = defaultHandler;
+    private DTDHandler		dtdHandler = defaultHandler;
+    private DeclHandler		declHandler = defaultHandler;
+    private LexicalHandler	lexicalHandler = defaultHandler;
+
+    // shared context
+    private ErrorHandler	errHandler = defaultHandler;
+    private EntityResolver	resolver = defaultHandler;
+    private Locale		locale = Locale.getDefault ();
+
+    // parser state
+    private Node		start;
+    private Node		current;
+    private boolean		isL2;
+    private boolean		showNamespaces = true;
+    private boolean		showXML1_0 = false;
+    private NamespaceSupport	prefixStack = new NamespaceSupport ();
+    private boolean		isDocument;
+
+
+    /**
+     * Constructs an unitialized <b>SAX2</b> parser.
+     */
+    public DomParser () {
+    } 
+
+    /**
+     * Constructs an <b>SAX2</b> parser initialized to traverse the specified
+     * DOM tree.  If the node is a document, the startDocument() and
+     * endDocument() calls bracket the calls exposing children.
+     */
+    public DomParser (Node node) {
+	setStart (node);
+    } 
+
+
+    // stuff that most components in an application should be sharing:
+    // resolver and error locale.
+
+    /**
+     * <b>SAX2</b>: Returns the object used when resolving external
+     * entities during parsing (both general and parameter entities).
+     */
+    public EntityResolver getEntityResolver ()
+    {
+	return resolver;
+    }
+
+    /**
+     * <b>SAX1</b>: Provides an object which may be used when resolving external
+     * entities during parsing (both general and parameter entities).
+     */
+    public void setEntityResolver (EntityResolver resolver)
+    {
+	if (resolver == null)
+	    resolver = defaultHandler;
+	this.resolver = resolver;
+    }
+
+    /**
+     * <b>SAX1</b>: Identifies the locale which the parser should use for the
+     * diagnostics it provides.
+     *
+     * @exception SAXException as defined in the specification for
+     *	<em>org.xml.sax.Parser.setLocale()</em>
+     */
+    public void setLocale (Locale locale)
+    throws SAXException
+    {
+	if (locale == null)
+	    locale = Locale.getDefault ();
+	this.locale = locale;
+    }
+
+    
+    // different modules will tend to handle error handling the same,
+    // but it may not be the same through the whole app
+
+    /**
+     * <b>SAX2</b>: Returns the object used to receive callbacks for XML
+     * errors of all levels (fatal, nonfatal, warning).
+     */
+    public ErrorHandler getErrorHandler ()
+    {
+	return errHandler;
+    }
+
+    /**
+     * <b>SAX1</b>: Provides an object which receives callbacks for XML errors
+     * of all levels (fatal, nonfatal, warning).
+     */
+    public void setErrorHandler (ErrorHandler handler)
+    {
+	if (handler == null)
+	    handler = defaultHandler;
+	errHandler = handler;
+    }
+
+
+    // stuff different parts of a module will handle differently
+
+    /**
+     * <b>SAX2</b>: Returns the object used to report the logical
+     * content of an XML document.
+     */
+    public ContentHandler getContentHandler ()
+    {
+	return contentHandler;
+    }
+
+    /**
+     * <b>SAX2</b>: Assigns the object used to report the logical
+     * content of an XML document.
+     */
+    public void setContentHandler (ContentHandler handler)
+    {
+	if (handler == null)
+	    handler = defaultHandler;
+	contentHandler = handler;
+    }
+
+    /**
+     * <b>SAX2</b>: Returns the object used to process declarations related
+     * to notations and unparsed entities.
+     */
+    public DTDHandler getDTDHandler ()
+    {
+	return dtdHandler;
+    }
+
+    /**
+     * <b>SAX1</b>: Provides an object which may be used to intercept
+     * declarations related to notations and unparsed entities.
+     */
+    public void setDTDHandler (DTDHandler handler)
+    {
+	if (handler == null)
+	    handler = defaultHandler;
+	dtdHandler = handler;
+    }
+
+
+    /**
+     * <b>SAX1</b>:  Parses the previously provided DOM document (the
+     * input parameter is ignored).  When this returns, that same
+     * document may be parsed again without needing a "reset".
+     *
+     * @param uri ignored (pass an empty string)
+     * @exception SAXException as defined in the specification for
+     *	<em>org.xml.sax.Parser.parse()</em>
+     */
+    public void parse (String uri) throws SAXException
+    {
+	parse ();
+    }
+
+    /**
+     * <b>SAX1</b>:  Parses the previously provided DOM document (the
+     * input parameter is ignored).  When this returns, that same
+     * document may be parsed again without needing a "reset".
+     *
+     * @param input ignored
+     * @exception SAXException as defined in the specification for
+     *	<em>org.xml.sax.Parser.parse()</em>
+     */
+    public void parse (InputSource input) throws SAXException
+    {
+	parse ();
+    }
+
+    private void parse () throws SAXException
+    {
+	try {
+	    walk ();
+	} finally {
+	    if (isDocument)
+		contentHandler.endDocument ();
+	    current = null;
+	    prefixStack.reset ();
+	}
+    }
+
+    private boolean getIsL2 (Node node)
+    {
+	DOMImplementation	impl;
+	Document		doc;
+
+	if (node instanceof Document)
+	    doc = (Document) node;
+	else
+	    doc = node.getOwnerDocument ();
+	if (doc == null)
+	    throw new RuntimeException ("? unowned node - L2 DTD ?");
+	impl = doc.getImplementation ();
+	return impl.hasFeature ("XML", "2.0");
+    }
+
+
+    private static final String FEATURES = "http://xml.org/sax/features/";
+    private static final String HANDLERS = "http://xml.org/sax/properties/";
+
+    /**
+     * <b>SAX2</b>: Tells whether this parser supports the specified feature.
+     */
+    public boolean getFeature (String name)
+    throws SAXNotRecognizedException, SAXNotSupportedException
+    {
+	// basically, none are relevant -- they relate more to
+	// parsing than to walking a "parse tree".
+
+		// FIXME: DOM feature to expose interning?
+
+	if ((FEATURES + "validation").equals (name)
+		|| (FEATURES + "external-general-entities")
+		    .equals (name)
+		|| (FEATURES + "external-parameter-entities")
+		    .equals (name)
+		|| (FEATURES + "string-interning").equals (name)
+		)
+	    return false;
+    
+	if ((FEATURES + "namespaces").equals (name))
+	    return showNamespaces;
+	if ((FEATURES + "namespace-prefixes").equals (name))
+	    return showXML1_0;
+
+	throw new SAXNotRecognizedException (name);
+    }
+
+    /**
+     * <b>SAX2</b>:  Returns the specified property.  At this time only
+     * the declaration and lexical handlers, and current the "DOM" node,
+     * are supported.
+     */
+    public Object getProperty (String name)
+    throws SAXNotRecognizedException, SAXNotSupportedException
+    {
+	if ((HANDLERS + "declaration-handler").equals (name))
+	    return declHandler == defaultHandler ? null : declHandler;
+	if ((HANDLERS + "lexical-handler").equals (name))
+	    return lexicalHandler == defaultHandler ? null : lexicalHandler;
+
+	if ((HANDLERS + "dom-node").equals (name))
+	    return current;
+
+	// unknown properties
+	throw new SAXNotRecognizedException (name);
+    }
+
+    /**
+     * <b>SAX2</b>:  Sets the state of features supported in this parser.
+     * Only the namespace support features are mutable.
+     */
+    public void setFeature (String name, boolean state)
+    throws SAXNotRecognizedException, SAXNotSupportedException
+    {
+	if (current != null)
+	    throw new IllegalStateException ("feature change midparse");
+
+	boolean value = getFeature (name);
+
+	if (value == state)
+	    return;
+
+	if ((FEATURES + "namespaces").equals (name)) {
+	    if (!showXML1_0 && state == false)
+		throw new SAXNotSupportedException ("Illegal namespace "
+			+ "processing configuration");
+	    showNamespaces = state;
+	    return;
+	}
+	if ((FEATURES + "namespace-prefixes").equals (name)) {
+	    if (!showNamespaces && state == false)
+		throw new SAXNotSupportedException ("Illegal namespace "
+			+ "processing configuration");
+	    showXML1_0 = state;
+	    return;
+	}
+
+	throw new SAXNotSupportedException (name);
+    }
+
+    /**
+     * <b>SAX2</b>:  Assigns the specified property.  At this time only
+     * declaration and lexical handlers, and the initial DOM document, are
+     * supported.  These must not be changed to values of the wrong type.
+     * Like SAX1 handlers, these handlers may be changed at any time.
+     * Like SAX1 input source or document URI, the initial DOM document
+     * may not be changed during a parse.
+     */
+    public void setProperty (String name, Object state)
+    throws SAXNotRecognizedException, SAXNotSupportedException
+    {
+	if ((HANDLERS + "declaration-handler").equals (name)) {
+	    if (!(state instanceof DeclHandler || state == null))
+		throw new SAXNotSupportedException (name);
+	    declHandler = (DeclHandler) state;
+	    return;
+	}
+
+	if ((HANDLERS + "lexical-handler").equals (name)) {
+	    if (!(state instanceof LexicalHandler || state == null))
+		throw new SAXNotSupportedException (name);
+	    lexicalHandler = (LexicalHandler) state;
+	    return;
+	}
+
+	if ((HANDLERS + "dom-node").equals (name)) {
+	    if (state == null || state instanceof Node) {
+		if (current != null)
+		    throw new SAXNotSupportedException (
+			"property is readonly during parse:  " + name);
+		setStart ((Node) state);
+		return;
+	    }
+	    throw new SAXNotSupportedException ("not a DOM Node");
+	}
+
+	// unknown properties
+	throw new SAXNotRecognizedException (name);
+    }
+
+    private void setStart (Node property)
+    {
+	start = property;
+	if (start != null) {
+	    isL2 = getIsL2 (start);
+	    isDocument = (start instanceof Document);
+	}
+    }
+
+    //
+    // Non-recursive walk, using DOM state when backtracking is needed
+    //
+    private void walk ()
+    throws SAXException
+    {
+	int			type;
+	NamedNodeMap		nodes;
+	int			length;
+	AttributesImpl		attrs = new AttributesImpl ();
+	char			chars [];
+	String			ns, local;
+
+	synchronized (this) {
+	    if (current != null)
+		throw new IllegalStateException ("already walking tree");
+
+	    // JVM guarantees assignments are atomic; so no other
+	    // thread could get this far till this walk's done.
+	    current = start;
+	}
+    
+	for (;;) {
+	    type = current.getNodeType ();
+
+	    //
+	    // First, visit the current node, including any "start" calls
+	    //
+	    switch (type) {
+
+	      case Node.DOCUMENT_NODE:
+	        contentHandler.startDocument ();
+		break;
+
+	      case Node.ELEMENT_NODE:
+		nodes = current.getAttributes ();
+		length = nodes.getLength ();
+		prefixStack.pushContext ();
+		for (int i = 0; i < length; i++) {
+		    Attr	attr = (Attr) nodes.item (i);
+		    String	name = attr.getNodeName ();
+
+		    if (showNamespaces && name.startsWith ("xmlns")) {
+			String	prefix;
+			String	uri;
+			
+			// NOTE: DOM L2 (CR2+ and REC) violate the
+			// Namespaces REC, treat "xmlns" like a strange
+			// attribute instead of a magic token
+			if ("xmlns".equals (name))
+			    prefix = "";
+			else
+			    prefix = name.substring (6);
+			uri = attr.getNodeValue ();
+
+			prefixStack.declarePrefix (prefix, uri);
+			contentHandler.startPrefixMapping (prefix, uri);
+			
+			if (!showXML1_0)
+			    continue;
+		    }
+
+		    //
+		    // NOTE:  DOM doesn't record the attribute type info
+		    // which SAX exposes; so this always reports CDATA.
+		    //
+		    // NOTE:  SAX doesn't expose the isSpecified info which
+		    // DOM exposes; that's discarded here.  Similarly with
+		    // the information DOM hides inside itself about what
+		    // the default values for an attribute are.
+		    //
+		    if (showNamespaces) {
+			if (isL2) {
+			    if ((ns = attr.getNamespaceURI ()) == null)
+				ns = "";
+			    // Note:  SAX2 and DOM handle "local" names
+			    // differently
+			    if ((local = attr.getLocalName ()) == null)
+				local = name;
+			} else {
+// XXX
+			    throw new RuntimeException (
+				"NYI, ns lookup when parsing L1 DOM");
+			}
+		    } else
+			ns = local = "";
+		    attrs.addAttribute (ns, local, name,
+			"CDATA", attr.getNodeValue ());
+		}
+		if (showNamespaces) {
+		    if (isL2) {
+			if ((ns = current.getNamespaceURI ()) == null)
+			    ns = "";
+			// Note:  SAX2 and DOM handle "local" names differently
+			if ((local = current.getLocalName ()) == null)
+			    local = current.getNodeName ();
+		    } else {
+// XXX
+			throw new RuntimeException (
+			    "NYI, ns lookup when parsing L1 DOM");
+		    }
+		} else
+		    ns = local = "";
+		contentHandler.startElement  (ns, local,
+		    current.getNodeName (), attrs);
+		if (length != 0)
+		    attrs.clear ();
+		break;
+
+	      case Node.CDATA_SECTION_NODE:
+		lexicalHandler.startCDATA ();
+		chars = current.getNodeValue ().toCharArray ();
+		contentHandler.characters (chars, 0, chars.length);
+		lexicalHandler.endCDATA ();
+		break;
+
+	      case Node.COMMENT_NODE:
+		chars = current.getNodeValue ().toCharArray ();
+		lexicalHandler.comment (chars, 0, chars.length);
+		break;
+
+	      case Node.DOCUMENT_TYPE_NODE:
+		{
+		    DocumentType	doctype = (DocumentType) current;
+
+		    //
+		    // Only DOM L2 supports recreating even some DTDs in full.
+		    //
+		    if (isL2) {
+			lexicalHandler.startDTD (doctype.getName (),
+				doctype.getPublicId (),
+				doctype.getSystemId ());
+		    } else
+			lexicalHandler.startDTD (doctype.getName (),
+				null, null);
+		    
+		    //
+		    // The only sure way to recreate is to provide both the
+		    // internal and external subsets.  Otherwise, only part
+		    // of the job can be done ... because from the DTD, DOM
+		    // discards both the critical data, like the attribute and
+		    // element declarations, as well as the PIs and comments
+		    // that are used to hold their documentation.
+		    //
+		    // Even the entity and notation declarations that it can
+		    // expose can't be recorded without proprietary extensions.
+		    //
+		    // We construct a comment to tell what we know about how
+		    // (in)complete this particular really DTD is.
+		    //
+		    {
+			String message;
+			char buf [];
+
+			//
+			// Though DOM L2 lets the whole doctype be recreated,
+			// SAX2 can't represent it (input or output).
+			// So this will be the typical case.
+			//
+			if (isL2 && doctype.getInternalSubset () != null)
+			    message =
+		    " Full DTD known; can't be shown using SAX2. ";
+
+			//
+			// Otherwise, we'll concoct a partial DTD.  If there's
+			// any more data here at all, it was provided using a
+			// (proprietary) extension to DOM.
+			//
+			else
+			    message =
+	    " This DTD was was recreated using incomplete DOM L2 records. ";
+
+			buf = message.toCharArray ();
+			lexicalHandler.comment (buf, 0, buf.length);
+		    }
+
+		    // report notations first
+		    nodes = doctype.getNotations ();
+		    length = nodes.getLength ();
+		    for (int i = 0; i < length; i++) {
+			Notation notation = (Notation) nodes.item (i);
+			    dtdHandler.notationDecl (
+				notation.getNodeName (),
+				notation.getPublicId (),
+				notation.getSystemId ());
+		    }
+
+		    // then parsed and unparsed external general entities
+		    nodes = doctype.getEntities ();
+		    length = nodes.getLength ();
+		    for (int i = 0; i < length; i++) {
+			Entity	entity = (Entity) nodes.item (i);
+			String	notation = entity.getNotationName ();
+
+			if (notation != null)
+			    dtdHandler.unparsedEntityDecl (
+				entity.getNodeName (),
+				entity.getPublicId (),
+				entity.getSystemId (),
+				notation);
+			else if (entity.getSystemId () != null)
+			    declHandler.externalEntityDecl (
+				entity.getNodeName (),
+				entity.getPublicId (),
+				entity.getSystemId ());
+			
+			//
+			// NOTE:  DOM doesn't clearly provide internal
+			// entity support; but in case someone tries to
+			// fudge such support, we defend ourselves above.
+			//
+			// NOTE:  DOM doesn't expose parameter entities
+			// (thank you thank you thank you thank you)
+			//
+		    }
+
+		    //
+		    // NOTE:  DOM (levels 1 and 2) doesn't expose real
+		    // typing information (element or attribute decls),
+		    // as exposed by SAX2 declaration handlers.
+		    //
+		    lexicalHandler.endDTD ();
+		}
+		break;
+
+	      case Node.ENTITY_REFERENCE_NODE:
+		// this isn't done except (a) in content, and
+		// (b) not within a start tag (att value)
+		lexicalHandler.startEntity (current.getNodeName ());
+		break;
+
+	      case Node.PROCESSING_INSTRUCTION_NODE:
+	        contentHandler.processingInstruction (
+		    current.getNodeName (), current.getNodeValue ());
+		break;
+
+	      case Node.TEXT_NODE:
+		chars = current.getNodeValue ().toCharArray ();
+		contentHandler.characters (chars, 0, chars.length);
+		break;
+
+	      default:
+		// e.g. fragments, entities, notations, attributes
+		throw new SAXException ("Illegal DOM Node type in Document:  "
+		    +  current.getNodeType ());
+	    }
+
+	    //
+	    // Then, pick the next node to visit.  If the next node isn't
+	    // a child, an "end" call may be needed before moving on.
+	    // If there's no next node, we're done.
+	    //
+	    Node		next;
+
+	    switch (type) {
+	      case Node.DOCUMENT_NODE:
+	      case Node.ELEMENT_NODE:
+	      case Node.ENTITY_REFERENCE_NODE:
+		//
+		// For elements that can have children, visit those
+		// children before any siblings (i.e. depth first)
+		// and after visiting this node (i.e. preorder)
+		//
+		next = current.getFirstChild ();
+		if (next != null) {
+		    current = next;
+		    break;
+		}
+		//
+		// Else treat this like other childless nodes, but
+		// handle this node's "end" immediately.
+		//
+		callEnd (current);
+
+		// FALLTHROUGH
+
+	      case Node.CDATA_SECTION_NODE:
+	      case Node.COMMENT_NODE:
+	      case Node.DOCUMENT_TYPE_NODE:
+	      case Node.ENTITY_NODE:
+	      case Node.PROCESSING_INSTRUCTION_NODE:
+	      case Node.TEXT_NODE:
+		//
+		// Use next sibling, if there is one.
+		// Else, climb up a level (calling "end")
+		//	until we find an ancestral sibling
+		//	or until we we climb off the top (FINISH)
+		//
+		for (;;) {
+		    if ((next = current.getNextSibling ()) != null)
+			break;
+		    current = current.getParentNode ();
+		    if (current == null || current == start)
+			return;
+		    callEnd (current);
+		}
+		current = next;
+		break;
+
+	      default:
+		throw new SAXException (
+		    "Illegal DOM Node type found:  " +  current.getNodeType ());
+	    }
+	}
+    }
+
+    private void callEnd (Node node) throws SAXException
+    {
+	switch (node.getNodeType ()) {
+	  // only these three container types may ever be found
+	  // directly inside a Document.
+	  case Node.DOCUMENT_NODE:
+	    // for SAX conformance, endDocument must always
+	    // be called ... it's done in a "finally" clause)
+	    return;
+
+	  case Node.ELEMENT_NODE:
+	    if (showNamespaces) {
+		if (isL2)
+		    contentHandler.endElement (
+			node.getNamespaceURI (),
+			node.getLocalName (),
+			node.getNodeName ());
+		else
+// XXX
+		    throw new RuntimeException (
+			"NYI, ns lookup when parsing L1 DOM");
+		for (Enumeration e = prefixStack.getDeclaredPrefixes ();
+			e.hasMoreElements ();
+			) {
+		    contentHandler.endPrefixMapping ((String) e.nextElement ());
+		}
+	    } else
+		contentHandler.endElement ("", "", node.getNodeName ());
+	    prefixStack.popContext ();
+	    return;
+
+	  case Node.ENTITY_REFERENCE_NODE:
+	    // see above -- in content, outside start tags.
+	    lexicalHandler.endEntity (node.getNodeName ());
+	    return;
+
+	  // these can be given at the top level
+	  case Node.DOCUMENT_FRAGMENT_NODE:
+	  case Node.ATTRIBUTE_NODE:
+	    return;
+
+	  default:
+	    throw new SAXException (
+		"Illegal DOM container type found:  "
+			+  current.getNodeType ());
+	}
+    }
+}

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/util/Resolver.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/util/Resolver.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/util/Resolver.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/util/Resolver.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,263 @@
+/* Resolver.java -- 
+   Copyright (C) 1999,2000,2001 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.xml.util;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.Dictionary;
+
+import org.xml.sax.EntityResolver;
+import org.xml.sax.InputSource;
+import org.xml.sax.SAXException;
+
+/**
+ * Utility implementation of a SAX resolver, which can be used to improve
+ * network utilization of SAX based XML components.  It does this by
+ * supporting local caches of external entities.
+ * SAX parsers <em>should</em> use such local caches when possible.
+ *
+ * @see XCat
+ */
+public class Resolver implements EntityResolver, Cloneable
+{
+    /**
+     * Updates a dictionary used to map PUBLIC identifiers to file names,
+     * so that it uses the mappings in a specified directory.
+     *
+     * @param mappings Array of string pairs, where the first member
+     *	of each pair is a PUBLIC identifier and the second is the
+     *	name of a file, relative to the specified directory.
+     * @param directory File holding the specified files.
+     */
+    public static void addDirectoryMapping (
+	Dictionary	table,
+	String		mappings [][],
+	File		directory
+    ) throws IOException
+    {
+	for (int i = 0; i < mappings.length; i++) {
+	    File	file = new File (directory, mappings [i][1]);
+	    String	temp;
+
+	    if (!file.exists ())	// ?? log a warning ??
+		continue;
+
+	    temp = fileToURL (file);
+	    table.put (mappings [i][0], temp);
+	}
+    }
+
+	// FIXME: these *URL routines don't quite belong here, except
+	// that they're all in the same spirit of making it easy to
+	// use local filesystem URIs with XML parsers.
+
+    /**
+     * Provides the URL for a named file, without relying on the JDK 1.2
+     * {@link java.io.File#toURL File.toURL}() utility method.
+     *
+     * @param filename the file name to convert.  Relative file names
+     *	are resolved the way the JVM resolves them (current to the
+     *	process-global current working directory).
+     *
+     * @exception IOException if the file does not exist
+     */
+    public static String fileNameToURL (String filename)
+    throws IOException
+    {
+	return fileToURL (new File (filename));
+    }
+
+    /**
+     * Provides the URL for a file, without relying on the JDK 1.2
+     * {@link java.io.File#toURL File.toURL}() utility method.
+     *
+     * @param f the file to convert.  Relative file names
+     *	are resolved the way the JVM resolves them (current to the
+     *	process-global current working directory).
+     *
+     * @exception IOException if the file does not exist
+     */
+    public static String fileToURL (File f)
+    throws IOException
+    {
+	String	temp;
+
+	// NOTE:  the javax.xml.parsers.DocumentBuilder and
+	// javax.xml.transform.stream.StreamSource versions
+	// of this don't have this test.  Some JVM versions
+	// don't report this error sanely through URL code. 
+	if (!f.exists ())
+	    throw new IOException ("no such file: " + f.getName ());
+
+	    // FIXME: getAbsolutePath() seems buggy; I'm seeing components
+	    // like "/foo/../" which are clearly not "absolute"
+	    // and should have been resolved with the filesystem.
+
+	    // Substituting "/" would be wrong, "foo" may have been
+	    // symlinked ... the URL code will make that change
+	    // later, so that things can get _really_ broken!
+
+	temp = f.getAbsolutePath ();
+
+	if (File.separatorChar != '/')
+	    temp = temp.replace (File.separatorChar, '/');
+	if (!temp.startsWith ("/"))
+	    temp = "/" + temp;
+	if (!temp.endsWith ("/") && f.isDirectory ())
+	    temp = temp + "/";
+	return "file:" + temp;
+    }
+
+
+    /**
+     * Returns a URL string.  Note that if a malformed URL is provided, or
+     * the parameter names a nonexistent file, the resulting URL may be
+     * malformed.
+     *
+     * @param fileOrURL If this is the name of a file which exists,
+     *	then its URL is returned.  Otherwise the argument is returned.
+     */
+    public static String getURL (String fileOrURL)
+    {
+	try {
+	    return fileNameToURL (fileOrURL);
+	} catch (Exception e) {
+	    return fileOrURL;
+	}
+    }
+
+
+
+    // note:  cloneable, this is just copied; unguarded against mods
+    private Dictionary		pubidMapping;
+
+    /**
+     * Constructs a resolver which understands how to map PUBLIC identifiers
+     * to other URIs, typically for local copies of standard DTD components.
+     * 
+     * @param dictionary maps PUBLIC identifiers to URIs.  This is not
+     *	copied; subsequent modifications will be reported through the
+     *	resolution operations.
+     */
+    public Resolver (Dictionary dict)
+	{ pubidMapping = dict; }
+
+    
+    // FIXME: want notion of a "system default" resolver, presumably
+    // loaded with all sorts of useful stuff.  At the same time need
+    // a notion of resolver chaining (failure --> next) so that subsystems
+    // can set up things that won't interfere with other ones.
+
+    /**
+     * This parses most MIME content type strings that have <em>charset=...</em>
+     * encoding declarations to and returns the specified encoding.  This
+     * conforms to RFC 3023, and is useful when constructing InputSource
+     * objects from URLConnection objects or other objects using MIME
+     * content typing.
+     *
+     * @param contentType the MIME content type that will be parsed; must
+     *	not be null.
+     * @return the appropriate encoding, or null if the content type is
+     *	not text and there's no <code>charset=...</code> attribute
+     */
+    static public String getEncoding (String contentType)
+    {
+	// currently a dumb parsing algorithm that works "mostly" and handles
+	//	..anything...charset=ABC
+	//	..anything...charset=ABC;otherAttr=DEF
+	//	..anything...charset=ABC (comment);otherAttr=DEF
+	//	..anything...charset= "ABC" (comment);otherAttr=DEF
+
+	int	temp;
+	String	encoding;
+	String	defValue = null;
+
+	if (contentType.startsWith ("text/"))
+	    defValue = contentType.startsWith ("text/html")
+		    ? "ISO-8859-1" : "US-ASCII";
+
+	// Assumes 'charset' is only an attribute name, not part
+	// of a value, comment, or other attribute name
+	// ALSO assumes no escaped values like "\;" or "\)"
+	if ((temp = contentType.indexOf ("charset")) != -1) {
+	    // strip out everything up to '=' ...
+	    temp = contentType.indexOf ('=', temp);
+	    if (temp == -1)
+		return defValue;
+	    encoding = contentType.substring (temp + 1);
+	    // ... and any subsequent attributes
+	    if ((temp = encoding.indexOf (';')) != -1)
+		encoding = encoding.substring (0, temp);
+	    // ... and any comments after value
+	    if ((temp = encoding.indexOf ('(')) != -1)
+		encoding = encoding.substring (0, temp);
+	    // ... then whitespace, and any (double) quotes
+	    encoding = encoding.trim ();
+	    if (encoding.charAt (0) == '"')
+		encoding = encoding.substring (1, encoding.length () - 1);
+	} else
+	    encoding = defValue;
+	return encoding;
+    }
+
+
+    /**
+     * Uses a local dictionary of public identifiers to resolve URIs,
+     * normally with the goal of minimizing network traffic or latencies.
+     */
+    public InputSource resolveEntity (String publicId, String systemId)
+    throws IOException, SAXException
+    {
+	InputSource	retval = null;
+	String		uri;
+
+	if (publicId != null
+		&& ((uri = (String) pubidMapping.get (publicId)) != null)) {
+	    retval = new InputSource (uri);
+	    retval.setPublicId (publicId);
+	}
+
+	// Could do URN resolution here
+
+	// URL resolution always done by parser
+
+	// FIXME: chain to "next" resolver
+
+	return retval;
+    }
+}

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/util/SAXNullTransformerFactory.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/util/SAXNullTransformerFactory.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/util/SAXNullTransformerFactory.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/util/SAXNullTransformerFactory.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,676 @@
+/* SAXNullTransformerFactory.java -- 
+   Copyright (C) 2001 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.xml.util;
+
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.net.URL;
+import java.net.URLConnection;
+import java.util.Hashtable;
+import java.util.Properties;
+
+import gnu.xml.dom.Consumer;
+import gnu.xml.dom.DomDocument;
+import gnu.xml.pipeline.DomConsumer;
+import gnu.xml.pipeline.EventFilter;
+
+import javax.xml.transform.*;
+import javax.xml.transform.dom.*;
+import javax.xml.transform.sax.*;
+import javax.xml.transform.stream.*;
+
+import org.xml.sax.*;
+import org.xml.sax.helpers.XMLReaderFactory;
+import org.xml.sax.helpers.LocatorImpl;
+
+
+/**
+ * Implements null transforms. XSLT stylesheets are not supported.
+ * This class provides a way to translate three representations of
+ * XML data (SAX event stream, DOM tree, and XML text) into each other.
+ * In essence it's a thinnish wrapper around basic SAX event
+ * <a href="../pipeline/package-summary.html">pipeline</a> facilities, which
+ * exposes only limited functionality.  The <em>javax.xml.transform</em>
+ * functionality is implemented as follows: <ul>
+ *
+ * <li>The {@link javax.xml.transform.sax.SAXSource SAXSource} class
+ * just wraps an {@link XMLReader} and {@link InputSource}, while the
+ * {@link javax.xml.transform.sax.SAXResult SAXResult} class is less
+ * functional than a {@link gnu.xml.pipeline.EventConsumer EventConsumer}.
+ * (Notably, it drops all but one declaration from any DTD.)</li>
+ *
+ * <li>The {@link javax.xml.transform.dom.DOMSource DOMSource} class
+ * corresponds to special SAX parsers like {@link DomParser}, and the
+ * {@link javax.xml.transform.dom.DOMResult DOMResult} class corresponds
+ * to a {@link gnu.xml.pipeline.DomConsumer DomConsumer}.</li>
+ *
+ * <li>The {@link javax.xml.transform.stream.StreamSource StreamSource}
+ * class corresponds to a SAX {@link InputSource}, and the
+ * {@link javax.xml.transform.stream.StreamResult StreamResult} class
+ * corresponds to a {@link gnu.xml.pipeline.TextConsumer TextConsumer}.</li>
+ *
+ * </ul>
+ *
+ * <p><em>This implementation is preliminary.</em>
+ *
+ * @see gnu.xml.pipeline.XsltFilter
+ *
+ * @author David Brownell
+ */
+public class SAXNullTransformerFactory extends SAXTransformerFactory
+{
+  
+  private ErrorListener	errListener;
+  private URIResolver		uriResolver;
+  
+  /** Default constructor */
+  public SAXNullTransformerFactory () { }
+  
+  //
+  // only has stuff that makes sense with null transforms
+  //
+  
+  /**
+   * Returns true if the requested feature is supported.
+   * All three kinds of input and output are accepted:
+   * XML text, SAX events, and DOM nodes.
+   */
+  public boolean getFeature (String feature)
+  {
+    return SAXTransformerFactory.FEATURE.equals (feature)
+      || SAXResult.FEATURE.equals (feature)
+      || SAXSource.FEATURE.equals (feature)
+      || DOMResult.FEATURE.equals (feature)
+      || DOMSource.FEATURE.equals (feature)
+      || StreamResult.FEATURE.equals (feature)
+      || StreamSource.FEATURE.equals (feature)
+      ;
+  }
+
+  public void setFeature(String name, boolean value)
+    throws TransformerConfigurationException
+  {
+    throw new TransformerConfigurationException(name);
+  }
+
+
+  /** Throws an exception (no implementation attributes are supported) */
+  public void setAttribute (String key, Object value)
+  {
+    throw new IllegalArgumentException ();
+  }
+
+  /** Throws an exception (no implementation attributes are supported) */
+  public Object getAttribute (String key)
+  {
+    throw new IllegalArgumentException ();
+  }
+
+  /** (not yet implemented) */
+  public Source getAssociatedStylesheet (Source source,
+                                         String media,
+                                         String title,
+                                         String charset)
+    throws TransformerConfigurationException
+  {
+    // parse, and find the appropriate xsl-stylesheet PI contents
+    throw new IllegalArgumentException ();
+  }
+
+  public Transformer newTransformer ()
+    throws TransformerConfigurationException
+  {
+    return new NullTransformer ();
+  }
+
+  /**
+   * Returns a TransformerHandler that knows how to generate output
+   * in all three standard formats.  Output text is generated using
+   * {@link XMLWriter}, and the GNU implementation of
+   * {@link DomDocument DOM} is used.
+   *
+   * @see SAXResult
+   * @see StreamResult
+   * @see DOMResult
+   */
+  public TransformerHandler newTransformerHandler ()
+    throws TransformerConfigurationException
+  {
+    NullTransformer	transformer = new NullTransformer ();
+    return transformer.handler;
+  }
+
+  //
+  // Stuff that depends on XSLT support, which we don't provide
+  //
+  private static final String		noXSLT = "No XSLT support";
+
+  /** Throws an exception (XSLT is not supported). */
+  public Transformer newTransformer (Source stylesheet)
+    throws TransformerConfigurationException
+  {
+    throw new TransformerConfigurationException (noXSLT);
+  }
+
+  /** Throws an exception (XSLT is not supported). */
+  public Templates newTemplates (Source stylesheet)
+    throws TransformerConfigurationException
+  {
+    throw new TransformerConfigurationException (noXSLT);
+  }
+
+  /** Throws an exception (XSLT is not supported). */
+  public TemplatesHandler newTemplatesHandler ()
+    throws TransformerConfigurationException
+  {
+    throw new TransformerConfigurationException (noXSLT);
+  }
+
+  /** Throws an exception (XSLT is not supported). */
+  public TransformerHandler newTransformerHandler (Source stylesheet)
+    throws TransformerConfigurationException
+  {
+    throw new TransformerConfigurationException (noXSLT);
+  }
+
+  /** Throws an exception (XSLT is not supported). */
+  public TransformerHandler newTransformerHandler (Templates stylesheet)
+    throws TransformerConfigurationException
+  {
+    throw new TransformerConfigurationException (noXSLT);
+  }
+
+  /** Throws an exception (XSLT is not supported). */
+  public XMLFilter newXMLFilter (Source stylesheet)
+    throws TransformerConfigurationException
+  {
+    throw new TransformerConfigurationException (noXSLT);
+  }
+
+  /** Throws an exception (XSLT is not supported). */
+  public XMLFilter newXMLFilter (Templates stylesheet)
+    throws TransformerConfigurationException
+  {
+    throw new TransformerConfigurationException (noXSLT);
+  }
+
+  /** Returns the value assigned by {@link #setErrorListener}.  */
+  public ErrorListener getErrorListener ()
+  {
+    return errListener;
+  }
+
+  /** Assigns a value that would be used when parsing stylesheets */
+  public void setErrorListener (ErrorListener e)
+  {
+    errListener = e;
+  }
+
+  /** Returns the value assigned by {@link #setURIResolver}.  */
+  public URIResolver getURIResolver ()
+  {
+    return uriResolver;
+  }
+
+  /** Assigns a value that would be used when parsing stylesheets */
+  public void setURIResolver (URIResolver u)
+  {
+    uriResolver = u;
+  }
+
+
+  //
+  // Helper classes.  These might in theory be subclassed
+  // by an XSLT implementation, if they were exported.
+  //
+
+  static class DomTerminus
+    extends DomConsumer
+  {
+
+    DomTerminus (DOMResult result)
+      throws SAXException
+    {
+      // won't really throw SAXException
+      super (DomDocument.class);
+      setHandler (new DomHandler (this, result));
+    }
+    
+  }
+
+  static class DomHandler
+    extends Consumer.Backdoor
+  {
+  
+    private DOMResult	result;
+    
+    DomHandler (DomConsumer c, DOMResult r)
+      throws SAXException
+    {
+      // won't really throw SAXException
+      super (c);
+      result = r;
+    }
+
+    public void endDocument ()
+      throws SAXException
+    {
+      super.endDocument ();
+      result.setNode (getDocument ());
+    }
+    
+  }
+
+  private static OutputStream getOutputStream (String uri)
+    throws IOException
+  {
+    // JDK stupidity:  file "protocol does not support output" ... 
+    if (uri.startsWith ("file:"))
+      return new FileOutputStream (uri.substring (5));
+    
+    // Otherwise ...
+    URL		url = new URL (uri);
+    URLConnection	conn = url.openConnection ();
+    
+    conn.setDoOutput (true);
+    return conn.getOutputStream ();
+  }
+  
+
+  static class NullHandler
+    extends EventFilter
+    implements TransformerHandler
+  {
+   
+    private String		systemId;
+    private Transformer	transformer;
+    
+    NullHandler (Transformer t)
+    {
+      transformer = t;
+    }
+
+    public Transformer getTransformer ()
+    {
+      return transformer;
+    }
+
+    public String getSystemId ()
+    {
+      return systemId;
+    }
+
+    public void setSystemId (String id)
+    {
+      systemId = id;
+    }
+
+    public void setResult (Result result)
+    {
+      if (result.getSystemId () != null)
+        systemId = result.getSystemId ();
+      
+      try
+        {
+          
+          // output to partial SAX event stream?
+          if (result instanceof SAXResult)
+            {
+              SAXResult 	r = (SAXResult) result;
+              
+              setContentHandler (r.getHandler ());
+              setProperty (LEXICAL_HANDLER, r.getLexicalHandler ());
+              // DTD info is filtered out by javax.transform
+              
+              // output to DOM tree?
+            }
+          else if (result instanceof DOMResult)
+            {
+              DomTerminus	out = new DomTerminus ((DOMResult) result);
+
+              setContentHandler (out.getContentHandler ());
+              setProperty (LEXICAL_HANDLER,
+                           out.getProperty (LEXICAL_HANDLER));
+              // save DTD-derived info, if any.
+              setDTDHandler (out.getDTDHandler ());
+              setProperty (DECL_HANDLER,
+                           out.getProperty (DECL_HANDLER));
+
+              // node is saved into result on endDocument()
+
+              // output to (XML) text?
+            }
+          else if (result instanceof StreamResult)
+            {
+              StreamResult	r = (StreamResult) result;
+              XMLWriter		out;
+
+              // FIXME:  when do output properties take effect?
+              // encoding, standalone decl, xml/xhtml/... ...
+
+              // FIXME:  maybe put nsfix filter up front
+
+              try
+                {
+                  if (r.getWriter () != null)
+                    out = new XMLWriter (r.getWriter ());
+                  else if (r.getOutputStream () != null)
+                    out = new XMLWriter (r.getOutputStream ());
+                  else if (r.getSystemId () != null)
+                    out = new XMLWriter (
+                                         getOutputStream (r.getSystemId ()));
+                  else
+                    throw new IllegalArgumentException (
+                                                        "bad StreamResult");
+                }
+              catch (IOException e)
+                {
+                  e.printStackTrace ();
+                  // on jdk 1.4, pass the root cause ...
+                  throw new IllegalArgumentException (e.getMessage ());
+                }
+
+              // out.setExpandingEntities (true);
+              // out.setPrettyPrinting (true);
+              // out.setXhtml (true);
+
+              setContentHandler (out);
+              setProperty (LEXICAL_HANDLER, out);
+              // save DTD info, if any; why not?
+              setDTDHandler (out);
+              setProperty (DECL_HANDLER, out);
+            }
+          
+        }
+      catch (SAXException e)
+        {
+          // SAXNotSupportedException or SAXNotRecognizedException:
+          // "can't happen" ... but SAXException for DOM build probs
+          // could happen, so ...
+          // on jdk 1.4, pass the root cause ...
+          throw new IllegalArgumentException (e.getMessage ());
+        }
+    }
+  }
+
+  // an interface that adds no value
+  static class LocatorAdapter
+    extends LocatorImpl
+    implements SourceLocator
+  {
+  
+    LocatorAdapter (SAXParseException e)
+    {
+      setSystemId (e.getSystemId ());
+      setPublicId (e.getPublicId ());
+      setLineNumber (e.getLineNumber ());
+      setColumnNumber (e.getColumnNumber ());
+    }
+    
+  }
+
+  // another interface that adds no value
+  static class ListenerAdapter
+    implements ErrorHandler
+  {
+    
+    NullTransformer	transformer;
+    
+    ListenerAdapter (NullTransformer t)
+    {
+      transformer = t;
+    }
+    
+    private TransformerException map (SAXParseException e)
+    {
+      return new TransformerException (
+                                       e.getMessage (),
+                                       new LocatorAdapter (e),
+                                       e);
+    }
+
+    public void error (SAXParseException e)
+      throws SAXParseException
+    {
+      try
+        {
+          if (transformer.errListener != null)
+            transformer.errListener.error (map (e));
+        }
+      catch (TransformerException ex)
+        {
+          transformer.ex = ex;
+          throw e;
+        }
+    }
+
+    public void fatalError (SAXParseException e)
+      throws SAXParseException
+    {
+      try
+        {
+          if (transformer.errListener != null)
+            transformer.errListener.fatalError (map (e));
+          else
+            throw map (e);
+        } catch (TransformerException ex) {
+          transformer.ex = ex;
+          throw e;
+        }
+    }
+
+    public void warning (SAXParseException e)
+      throws SAXParseException
+    {
+      try
+        {
+          if (transformer.errListener != null)
+            transformer.errListener.warning (map (e));
+        }
+      catch (TransformerException ex)
+        {
+          transformer.ex = ex;
+          throw e;
+        }
+    }
+  }
+
+  static class NullTransformer
+    extends Transformer
+  {
+  
+    private URIResolver		uriResolver;
+    private Properties		props = new Properties ();
+    private Hashtable		params = new Hashtable (7);
+    
+    ErrorListener			errListener = null;
+    TransformerException		ex = null;
+    NullHandler			handler;
+    
+    NullTransformer ()
+    {
+      super ();
+      handler = new NullHandler (this);
+    }
+    
+    public ErrorListener getErrorListener ()
+    {
+      return errListener;
+    }
+    
+    public void setErrorListener (ErrorListener e)
+    {
+      errListener = e;
+    }
+    
+    public URIResolver getURIResolver ()
+    {
+      return uriResolver;
+    }
+    
+    public void setURIResolver (URIResolver u)
+    {
+      uriResolver = u;
+    }
+
+    public void setOutputProperties (Properties p)
+    {
+      props = (Properties) p.clone ();
+    }
+    
+    public Properties getOutputProperties ()
+    {
+      return (Properties) props.clone ();
+    }
+
+    public void setOutputProperty (String name, String value)
+    {
+      props.setProperty (name, value);
+    }
+    
+    public String getOutputProperty (String name)
+    {
+      return props.getProperty (name);
+    }
+
+    public void clearParameters ()
+    {
+      params.clear ();
+    }
+    
+    public void setParameter (String name, Object value)
+    {
+      props.put (name, value);
+    }
+    
+    public Object getParameter (String name)
+    {
+      return props.get (name);
+    }
+
+    public void transform (Source in, Result out)
+      throws TransformerException
+    {
+      try
+        {
+          XMLReader		producer;
+          InputSource		input;
+          
+          // Input from DOM?
+          if (in instanceof DOMSource)
+            {
+              DOMSource	source = (DOMSource) in;
+              
+              if (source.getNode () == null)
+                throw new IllegalArgumentException ("no DOM node");
+              producer = new DomParser (source.getNode ());
+              input = null;
+              
+              // Input from SAX?
+            }
+          else if (in instanceof SAXSource)
+            {
+              SAXSource	source = (SAXSource) in;
+              
+              producer = source.getXMLReader ();
+              if (producer == null)
+                producer = XMLReaderFactory.createXMLReader ();
+              
+              input = source.getInputSource ();
+              if (input == null)
+                {
+                  if (source.getSystemId () != null)
+                    input = new InputSource (source.getSystemId ());
+                  else
+                    throw new IllegalArgumentException (
+                                                        "missing SAX input");
+                }
+              
+              // Input from a stream or something?
+            }
+          else
+            {
+              producer = XMLReaderFactory.createXMLReader ();
+              input = SAXSource.sourceToInputSource (in);
+              if (input == null)
+                throw new IllegalArgumentException ("missing input");
+            }
+          
+          // preserve original namespace prefixes
+          try
+            {
+              producer.setFeature(EventFilter.FEATURE_URI +
+                                  "namespace-prefixes",
+                                  true);
+            }
+          catch (Exception e)
+            {
+              /* ignore */
+              // FIXME if we couldn't, "NsFix" stage before the output ..
+            }
+          
+          // arrange the output
+          handler.setResult (out);
+          EventFilter.bind (producer, handler);
+          
+          // then parse ... single element pipeline
+          producer.parse (input);
+          
+        }
+      catch (IOException e)
+        {
+          throw new TransformerException ("transform failed", e);
+          
+        }
+      catch (SAXException e)
+        {
+          if (ex == null && ex.getCause () == e)
+            throw ex;
+          else
+            throw new TransformerException ("transform failed", e);
+          
+        }
+      finally
+        {
+          ex = null;
+        }
+    }
+  }
+
+}

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/util/XCat.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/util/XCat.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/util/XCat.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/util/XCat.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,1609 @@
+/* XCat.java -- 
+   Copyright (C) 2001 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package gnu.xml.util;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.net.URL;
+import java.util.Enumeration;
+import java.util.Hashtable;
+import java.util.StringTokenizer;
+import java.util.Stack;
+import java.util.Vector;
+
+import org.xml.sax.Attributes;
+import org.xml.sax.ErrorHandler;
+import org.xml.sax.InputSource;
+import org.xml.sax.Locator;
+import org.xml.sax.SAXException;
+import org.xml.sax.SAXNotRecognizedException;
+import org.xml.sax.SAXParseException;
+import org.xml.sax.XMLReader;
+
+import org.xml.sax.ext.DefaultHandler2;
+import org.xml.sax.ext.EntityResolver2;
+
+import org.xml.sax.helpers.XMLReaderFactory;
+
+/**
+ * Packages <a href=
+    "http://www.oasis-open.org/committees/entity/spec-2001-08-06.html"
+    >OASIS XML Catalogs</a>,
+ * primarily for entity resolution by parsers.
+ * That specification defines an XML syntax for mappings between
+ * identifiers declared in DTDs (particularly PUBLIC identifiers) and
+ * locations.  SAX has always supported such mappings, but conventions for
+ * an XML file syntax to maintain them have previously been lacking.
+ *
+ * <p> This has three main operational modes.  The primary intended mode is
+ * to create a resolver, then preloading it with one or more site-standard
+ * catalogs before using it with one or more SAX parsers: <pre>
+ *	XCat	catalog = new XCat ();
+ *	catalog.setErrorHandler (diagnosticErrorHandler);
+ *	catalog.loadCatalog ("file:/local/catalogs/catalog.cat");
+ *	catalog.loadCatalog ("http://shared/catalog.cat");
+ *	...
+ *	catalog.disableLoading ();
+ *	parser1.setEntityResolver (catalog);
+ *	parser2.setEntityResolver (catalog);
+ *	...</pre>
+ *
+ * <p>A second mode is to arrange that your application uses instances of
+ * this class as its entity resolver, and automatically loads catalogs
+ * referenced by <em><?oasis-xml-catalog...?></em> processing
+ * instructions found before the DTD in documents it parses.
+ * It would then discard the resolver after each parse.
+ *
+ * <p> A third mode applies catalogs in contexts other than entity
+ * resolution for parsers.
+ * The {@link #resolveURI resolveURI()} method supports resolving URIs
+ * stored in XML application data, rather than inside DTDs.
+ * Catalogs would be loaded as shown above, and the catalog could
+ * be used concurrently for parser entity resolution and for
+ * application URI resolution.
+ * </p>
+ *
+ * <center><hr width='70%'></center>
+ *
+ * <p>Errors in catalogs implicitly loaded (during resolution) are ignored
+ * beyond being reported through any <em>ErrorHandler</em> assigned using
+ * {@link #setErrorHandler setErrorHandler()}.  SAX exceptions
+ * thrown from such a handler won't abort resolution, although throwing a
+ * <em>RuntimeException</em> or <em>Error</em> will normally abort both
+ * resolution and parsing.  Useful diagnostic information is available to
+ * any <em>ErrorHandler</em> used to report problems, or from any exception
+ * thrown from an explicit {@link #loadCatalog loadCatalog()} invocation.
+ * Applications can use that information as troubleshooting aids.
+ *
+ * <p>While this class requires <em>SAX2 Extensions 1.1</em> classes in
+ * its class path, basic functionality does not require using a SAX2
+ * parser that supports the extended entity resolution functionality.
+ * See the original SAX1
+ * {@link #resolveEntity(java.lang.String,java.lang.String) resolveEntity()}
+ * method for a list of restrictions which apply when it is used with
+ * older SAX parsers.
+ *
+ * @see EntityResolver2
+ *
+ * @author David Brownell
+ */
+public class XCat implements EntityResolver2
+{
+    private Catalog		catalogs [];
+    private boolean		usingPublic = true;
+    private boolean		loadingPermitted = true;
+    private boolean		unified = true;
+    private String		parserClass;
+    private ErrorHandler	errorHandler;
+
+    // private EntityResolver	next;	// chain to next if we fail...
+
+    //
+    // NOTE:  This is a straightforward implementation, and if
+    // there are lots of "nextCatalog" or "delegate*" entries
+    // in use, two tweaks would be worth considering:
+    //
+    //	- Centralize some sort of cache (key by URI) for individual
+    //	  resolvers.  That'd avoid multiple copies of a given catalog.
+    //
+    //	- Have resolution track what catalogs (+modes) have been
+    //	  searched.  This would support loop detection.
+    //
+
+
+    /**
+     * Initializes without preloading a catalog.
+     * This API is convenient when you may want to arrange that catalogs
+     * are automatically loaded when explicitly referenced in documents,
+     * using the <em>oasis-xml-catalog</em> processing instruction.
+     * In such cases you won't usually be able to preload catalogs.
+     */
+    public XCat () { }
+
+    /**
+     * Initializes, and preloads a catalog using the default SAX parser.
+     * This API is convenient when you operate with one or more standard
+     * catalogs.
+     *
+     * <p> This just delegates to {@link #loadCatalog loadCatalog()};
+     * see it for exception information.
+     *
+     * @param uri absolute URI for the catalog file.
+     */
+    public XCat (String uri)
+    throws SAXException, IOException
+	{ loadCatalog (uri); }
+
+
+    /**
+     * Loads an OASIS XML Catalog.
+     * It is appended to the list of currently active catalogs, or
+     * reloaded if a catalog with the same URI was already loaded.
+     * Callers have control over what parser is used, how catalog parsing
+     * errors are reported, and whether URIs will be resolved consistently.
+     *
+     * <p> The OASIS specification says that errors detected when loading
+     * catalogs "must recover by ignoring the catalog entry file that
+     * failed, and proceeding."  In this API, that action can be the
+     * responsibility of applications, when they explicitly load any
+     * catalog using this method.
+     *
+     * <p>Note that catalogs referenced by this one will not be loaded
+     * at this time.  Catalogs referenced through <em>nextCatalog</em>
+     * or <em>delegate*</em> elements are normally loaded only if needed. 
+     *
+     * @see #setErrorHandler
+     * @see #setParserClass
+     * @see #setUnified
+     *
+     * @param uri absolute URI for the catalog file.
+     *
+     * @exception IOException As thrown by the parser, typically to
+     *	indicate problems reading data from that URI.
+     * @exception SAXException As thrown by the parser, typically to
+     *	indicate problems parsing data from that URI.  It may also
+     *  be thrown if the parser doesn't support necessary handlers. 
+     * @exception IllegalStateException When attempting to load a
+     *	catalog after loading has been {@link #disableLoading disabled},
+     *	such as after any entity or URI lookup has been performed.
+     */
+    public synchronized void loadCatalog (String uri)
+    throws SAXException, IOException
+    {
+	Catalog		catalog;
+	int		index = -1;
+
+	if (!loadingPermitted)
+	    throw new IllegalStateException ();
+	
+	uri = normalizeURI (uri);
+	if (catalogs != null) {
+	    // maybe just reload
+	    for (index = 0; index < catalogs.length; index++)
+		if (uri.equals (catalogs [index].catalogURI))
+		    break;
+	}
+	catalog = loadCatalog (parserClass, errorHandler, uri, unified);
+
+	// add to list of catalogs
+	if (catalogs == null) {
+	    index = 0;
+	    catalogs = new Catalog [1];
+	} else if (index == catalogs.length) {
+	    Catalog		tmp [];
+
+	    tmp = new Catalog [index + 1];
+	    System.arraycopy (catalogs, 0, tmp, 0, index);
+	    catalogs = tmp;
+	}
+	catalogs [index] = catalog;
+    }
+
+
+    /**
+     * "New Style" external entity resolution for parsers.
+     * Calls to this method prevent explicit loading of additional catalogs
+     * using {@link #loadCatalog loadCatalog()}.
+     *
+     * <p>This supports the full core catalog functionality for locating
+     * (and relocating) parsed entities that have been declared in a
+     * document's DTD.
+     *
+     * @param name Entity name, such as "dudley", "%nell", or "[dtd]".
+     * @param publicId Either a normalized public ID, or null.
+     * @param baseURI Absolute base URI associated with systemId.
+     * @param systemId URI found in entity declaration (may be
+     *	relative to baseURI).
+     *
+     * @return Input source for accessing the external entity, or null
+     *	if no mapping was found.  The input source may have opened
+     *	the stream, and will have a fully resolved URI.
+     *
+     * @see #getExternalSubset
+     */
+    public InputSource resolveEntity (
+	String name,		// UNUSED ... systemId is always non-null
+	String publicId,
+	String baseURI,		// UNUSED ... it just lets sysId be relative
+	String systemId
+    ) throws SAXException, IOException
+    {
+	if (loadingPermitted)
+	    disableLoading ();
+
+	try {
+	    // steps as found in OASIS XML catalog spec 7.1.2
+	    // steps 1, 8 involve looping over the list of catalogs
+	    for (int i = 0; i < catalogs.length; i++) {
+		InputSource	retval;
+		retval = catalogs [i].resolve (usingPublic, publicId, systemId);
+		if (retval != null)
+		    return retval;;
+	    }
+	} catch (DoneDelegation x) {
+	    // done!
+	}
+	// step 9 involves returning "no match" 
+	return null;
+    }
+
+
+    /**
+     * "New Style" parser callback to add an external subset.
+     * For documents that don't include an external subset, this may
+     * return one according to <em>doctype</em> catalog entries.
+     * (This functionality is not a core part of the OASIS XML Catalog
+     * specification, though it's presented in an appendix.)
+     * If no such entry is defined, this returns null to indicate that
+     * this document will not be modified to include such a subset.
+     * Calls to this method prevent explicit loading of additional catalogs
+     * using {@link #loadCatalog loadCatalog()}.
+     *
+     * <p><em>Warning:</em> That catalog functionality can be dangerous.
+     * It can provide definitions of general entities, and thereby mask
+     * certain well formedess errors.
+     *
+     * @param name Name of the document element, either as declared in
+     *	a DOCTYPE declaration or as observed in the text.
+     * @param baseURI Document's base URI (absolute).
+     *
+     * @return Input source for accessing the external subset, or null
+     *	if no mapping was found.  The input source may have opened
+     *	the stream, and will have a fully resolved URI.
+     */
+    public InputSource getExternalSubset (String name, String baseURI)
+    throws SAXException, IOException
+    {
+	if (loadingPermitted)
+	    disableLoading ();
+	try {
+	    for (int i = 0; i < catalogs.length; i++) {
+		InputSource retval = catalogs [i].getExternalSubset (name);
+		if (retval != null)
+		    return retval;
+	    }
+	} catch (DoneDelegation x) {
+	    // done!
+	}
+	return null;
+    }
+
+
+    /**
+     * "Old Style" external entity resolution for parsers.
+     * This API provides only core functionality.
+     * Calls to this method prevent explicit loading of additional catalogs
+     * using {@link #loadCatalog loadCatalog()}.
+     *
+     * <p>The functional limitations of this interface include:</p><ul>
+     *
+     *	<li>Since system IDs will be absolutized before the resolver
+     *	sees them, matching against relative URIs won't work.
+     *	This may affect <em>system</em>, <em>rewriteSystem</em>,
+     *	and <em>delegateSystem</em> catalog entries.
+     *
+     *	<li>Because of that absolutization, documents declaring entities
+     *	with system IDs using URI schemes that the JVM does not recognize
+     *	may be unparsable.  URI schemes such as <em>file:/</em>,
+     *	<em>http://</em>, <em>https://</em>, and <em>ftp://</em>
+     *	will usually work reliably.
+     *
+     *	<li>Because missing external subsets can't be provided, the
+     *	<em>doctype</em> catalog entries will be ignored.
+     *	(The {@link #getExternalSubset getExternalSubset()} method is
+     *	a "New Style" resolution option.)
+     *
+     *	</ul>
+     *
+     * <p>Applications can tell whether this limited functionality will be
+     * used: if the feature flag associated with the {@link EntityResolver2}
+     * interface is not <em>true</em>, the limitations apply.  Applications
+     * can't usually know whether a given document and catalog will trigger
+     * those limitations.  The issue can only be bypassed by operational
+     * procedures such as not using catalogs or documents which involve
+     * those features.
+     *
+     * @param publicId Either a normalized public ID, or null
+     * @param systemId Always an absolute URI.
+     *
+     * @return Input source for accessing the external entity, or null
+     *	if no mapping was found.  The input source may have opened
+     *	the stream, and will have a fully resolved URI.
+     */
+    final public InputSource resolveEntity (String publicId, String systemId)
+    throws SAXException, IOException
+    {
+	return resolveEntity (null, publicId, null, systemId);
+    }
+
+
+    /**
+     * Resolves a URI reference that's not defined to the DTD.
+     * This is intended for use with URIs found in document text, such as
+     * <em>xml-stylesheet</em> processing instructions and in attribute
+     * values, where they are not recognized as URIs by XML parsers.
+     * Calls to this method prevent explicit loading of additional catalogs
+     * using {@link #loadCatalog loadCatalog()}.
+     *
+     * <p>This functionality is supported by the OASIS XML Catalog
+     * specification, but will never be invoked by an XML parser.
+     * It corresponds closely to functionality for mapping system
+     * identifiers for entities declared in DTDs; closely enough that
+     * this implementation's default behavior is that they be
+     * identical, to minimize potential confusion.
+     *
+     * <p>This method could be useful when implementing the
+     * {@link javax.xml.transform.URIResolver} interface, wrapping the
+     * input source in a {@link javax.xml.transform.sax.SAXSource}.
+     *
+     * @see #isUnified
+     * @see #setUnified
+     *
+     * @param baseURI The relevant base URI as specified by the XML Base
+     *	specification.  This recognizes <em>xml:base</em> attributes
+     *	as overriding the actual (physical) base URI.
+     * @param uri Either an absolute URI, or one relative to baseURI
+     *
+     * @return Input source for accessing the mapped URI, or null
+     *	if no mapping was found.  The input source may have opened
+     *	the stream, and will have a fully resolved URI.
+     */
+    public InputSource resolveURI (String baseURI, String uri)
+    throws SAXException, IOException
+    {
+	if (loadingPermitted)
+	    disableLoading ();
+
+	// NOTE:  baseURI isn't used here, but caller MUST have it,
+	// and heuristics _might_ use it in the future ... plus,
+	// it's symmetric with resolveEntity ().
+
+	// steps 1, 6 involve looping
+	try {
+	    for (int i = 0; i < catalogs.length; i++) {
+		InputSource	tmp = catalogs [i].resolveURI (uri);
+		if (tmp != null)
+		    return tmp;
+	    }
+	} catch (DoneDelegation x) {
+	    // done
+	}
+	// step 7 reports no match
+	return null;
+    }
+
+
+    /** 
+     * Records that catalog loading is no longer permitted.
+     * Loading is automatically disabled when lookups are performed,
+     * and should be manually disabled when <em>startDTD()</em> (or
+     * any other DTD declaration callback) is invoked, or at the latest
+     * when the document root element is seen.
+     */
+    public synchronized void disableLoading ()
+    {
+	// NOTE:  this method and loadCatalog() are synchronized
+	// so that it's impossible to load (top level) catalogs
+	// after lookups start.  Likewise, deferred loading is also
+	// synchronized (for "next" and delegated catalogs) to
+	// ensure that parsers can share resolvers.
+	loadingPermitted = false;
+    }
+
+
+    /**
+     * Returns the error handler used to report catalog errors.
+     * Null is returned if the parser's default error handling
+     * will be used.
+     *
+     * @see #setErrorHandler
+     */
+    public ErrorHandler getErrorHandler ()
+	{ return errorHandler; }
+
+    /**
+     * Assigns the error handler used to report catalog errors.
+     * These errors may come either from the SAX2 parser or
+     * from the catalog parsing code driven by the parser. 
+     *
+     * <p> If you're sharing the resolver between parsers, don't
+     * change this once lookups have begun.
+     *
+     * @see #getErrorHandler
+     *
+     * @param parser The error handler, or null saying to use the default
+     *	(no diagnostics, and only fatal errors terminate loading).
+     */
+    public void setErrorHandler (ErrorHandler handler)
+	{ errorHandler = handler; }
+
+
+    /**
+     * Returns the name of the SAX2 parser class used to parse catalogs.
+     * Null is returned if the system default is used.
+     * @see #setParserClass
+     */
+    public String getParserClass ()
+	{ return parserClass; }
+
+    /**
+     * Names the SAX2 parser class used to parse catalogs.
+     *
+     * <p> If you're sharing the resolver between parsers, don't change
+     * this once lookups have begun.
+     *
+     * <p> Note that in order to properly support the <em>xml:base</em>
+     * attribute and relative URI resolution, the SAX parser used to parse
+     * the catalog must provide a {@link Locator} and support the optional
+     * declaration and lexical handlers.
+     *
+     * @see #getParserClass
+     *
+     * @param parser The parser class name, or null saying to use the
+     *	system default SAX2 parser.
+     */
+    public void setParserClass (String parser)
+	{ parserClass = parser; }
+
+
+    /**
+     * Returns true (the default) if all methods resolve
+     * a given URI in the same way.
+     * Returns false if calls resolving URIs as entities (such as
+     * {@link #resolveEntity resolveEntity()}) use different catalog entries
+     * than those resolving them as URIs ({@link #resolveURI resolveURI()}),
+     * which will generally produce different results.
+     *
+     * <p>The OASIS XML Catalog specification defines two related schemes
+     * to map URIs "as URIs" or "as system IDs".
+     * URIs use <em>uri</em>, <em>rewriteURI</em>, and <em>delegateURI</em>
+     * elements.  System IDs do the same things with <em>systemId</em>,
+     * <em>rewriteSystemId</em>, and <em>delegateSystemId</em>.
+     * It's confusing and error prone to maintain two parallel copies of
+     * such data.  Accordingly, this class makes that behavior optional.
+     * The <em>unified</em> interpretation of URI mappings is preferred,
+     * since it prevents surprises where one URI gets mapped to different
+     * contents depending on whether the reference happens to have come
+     * from a DTD (or not).
+     *
+     * @see #setUnified
+     */
+    public boolean isUnified ()
+	{ return unified; }
+
+    /**
+     * Assigns the value of the flag returned by {@link #isUnified}.
+     * Set it to false to be strictly conformant with the OASIS XML Catalog
+     * specification.  Set it to true to make all mappings for a given URI
+     * give the same result, regardless of the reason for the mapping.
+     *
+     * <p>Don't change this once you've loaded the first catalog.
+     *
+     * @param value new flag setting
+     */
+    public void setUnified (boolean value)
+	{ unified = value; }
+
+
+    /**
+     * Returns true (the default) if a catalog's public identifier
+     * mappings will be used.
+     * When false is returned, such mappings are ignored except when
+     * system IDs are discarded, such as for
+     * entities using the <em>urn:publicid:</em> URI scheme in their
+     * system identifiers.  (See RFC 3151 for information about that
+     * URI scheme.  Using it in system identifiers may not work well
+     * with many SAX parsers unless the <em>resolve-dtd-uris</em>
+     * feature flag is set to false.)
+     * @see #setUsingPublic
+     */
+    public boolean isUsingPublic ()
+	{ return usingPublic; }
+
+    /**
+     * Specifies which catalog search mode is used.
+     * By default, public identifier mappings are able to override system
+     * identifiers when both are available.
+     * Applications may choose to ignore public
+     * identifier mappings in such cases, so that system identifiers
+     * declared in DTDs will only be overridden by an explicit catalog
+     * match for that system ID.
+     *
+     * <p> If you're sharing the resolver between parsers, don't
+     * change this once lookups have begun.
+     * @see #isUsingPublic
+     *
+     * @param value true to always use public identifier mappings,
+     *	false to only use them for system ids using the <em>urn:publicid:</em>
+     *	URI scheme.
+     */
+    public void setUsingPublic (boolean value)
+	{ usingPublic = value; }
+
+
+
+    // hmm, what's this do? :)
+    private static Catalog loadCatalog (
+	String		parserClass,
+	ErrorHandler	eh,
+	String		uri,
+	boolean		unified
+    ) throws SAXException, IOException
+    {
+	XMLReader	parser;
+	Loader		loader;
+	boolean		doesIntern = false;
+
+	if (parserClass == null)
+	    parser = XMLReaderFactory.createXMLReader ();
+	else
+	    parser = XMLReaderFactory.createXMLReader (parserClass);
+	if (eh != null)
+	    parser.setErrorHandler (eh);
+	// resolve-dtd-entities is at default value (unrecognized == true)
+
+	try {
+	    doesIntern = parser.getFeature (
+		"http://xml.org/sax/features/string-interning");
+	} catch (SAXNotRecognizedException e) { }
+
+	loader = new Loader (doesIntern, eh, unified);
+	loader.cat.parserClass = parserClass;
+	loader.cat.catalogURI = uri;
+
+	parser.setContentHandler (loader);
+	parser.setProperty (
+	    "http://xml.org/sax/properties/declaration-handler",
+	    loader);
+	parser.setProperty (
+	    "http://xml.org/sax/properties/lexical-handler",
+	    loader);
+	parser.parse (uri);
+
+	return loader.cat;
+    }
+
+    // perform one or both the normalizations for public ids
+    private static String normalizePublicId (boolean full, String publicId)
+    {
+	if (publicId.startsWith ("urn:publicid:")) {
+	    StringBuffer	buf = new StringBuffer ();
+	    char		chars [] = publicId.toCharArray ();
+boolean hasbug = false;
+
+	    for (int i = 13; i < chars.length; i++) {
+		switch (chars [i]) {
+		case '+': 	buf.append (' '); continue;
+		case ':': 	buf.append ("//"); continue;
+		case ';': 	buf.append ("::"); continue;
+		case '%':
+// FIXME unhex that char!  meanwhile, warn and fallthrough ...
+		    hasbug = true;
+		default:	buf.append (chars [i]); continue;
+		}
+	    }
+	    publicId = buf.toString ();
+if (hasbug)
+System.err.println ("nyet unhexing public id: " + publicId);
+	    full = true;
+	}
+
+	// SAX parsers do everything except that URN mapping, but
+	// we can't trust other sources to normalize correctly
+	if (full) {
+	    StringTokenizer	tokens;
+	    String		token;
+
+	    tokens = new StringTokenizer (publicId, " \r\n");
+	    publicId = null;
+	    while (tokens.hasMoreTokens ()) {
+		if (publicId == null)
+		    publicId = tokens.nextToken ();
+		else
+		    publicId += " " + tokens.nextToken ();
+	    }
+	}
+	return publicId;
+    }
+
+    private static boolean isUriExcluded (int c)
+	{ return c <= 0x20 || c >= 0x7f || "\"<>^`{|}".indexOf (c) != -1; }
+
+    private static int hexNibble (int c)
+    {
+	if (c < 10)
+	    return c + '0';
+	return ('a' - 10) + c;
+    }
+
+    // handles URIs with "excluded" characters
+    private static String normalizeURI (String systemId)
+    {
+	int			length = systemId.length ();
+
+	for (int i = 0; i < length; i++) {
+	    char	c = systemId.charAt (i);
+
+	    // escape non-ASCII plus "excluded" characters
+	    if (isUriExcluded (c)) {
+		byte			buf [];
+		ByteArrayOutputStream	out;
+		int				b;
+
+		// a JVM that doesn't know UTF8 and 8859_1 is unusable!
+		try {
+		    buf = systemId.getBytes ("UTF8");
+		    out = new ByteArrayOutputStream (buf.length + 10);
+
+		    for (i = 0; i < buf.length; i++) {
+			b = buf [i] & 0x0ff;
+			if (isUriExcluded (b)) {
+			    out.write ((int) '%');
+			    out.write (hexNibble (b >> 4));
+			    out.write (hexNibble (b & 0x0f));
+			} else
+			    out.write (b);
+		    }
+		    return out.toString ("8859_1");
+		} catch (IOException e) {
+		    throw new RuntimeException (
+			"can't normalize URI: " + e.getMessage ());
+		}
+	    }
+	}
+	return systemId;
+    }
+
+    // thrown to mark authoritative end of a search
+    private static class DoneDelegation extends SAXException
+    {
+	DoneDelegation () { }
+    }
+
+
+    /**
+     * Represents a OASIS XML Catalog, and encapsulates much of
+     * the catalog functionality.
+     */
+    private static class Catalog
+    {
+	// loading infrastructure
+	String		catalogURI;
+	ErrorHandler	eh;
+	boolean		unified;
+	String		parserClass;
+
+	// catalog data
+	boolean		hasPreference;
+	boolean		usingPublic;
+
+	Hashtable	publicIds;
+	Hashtable	publicDelegations;
+
+	Hashtable	systemIds;
+	Hashtable	systemRewrites;
+	Hashtable	systemDelegations;
+
+	Hashtable	uris;
+	Hashtable	uriRewrites;
+	Hashtable	uriDelegations;
+
+	Hashtable	doctypes;
+
+	Vector		next;
+
+	// nonpublic!
+	Catalog () { }
+
+	
+	// steps as found in OASIS XML catalog spec 7.1.2
+	private InputSource locatePublicId (String publicId)
+	throws SAXException, IOException
+	{
+	    // 5. return (first) 'public' entry
+	    if (publicIds != null) {
+		String	retval = (String) publicIds.get (publicId);
+		if (retval != null) {
+		    // IF the URI is accessible ...
+		    return new InputSource (retval);
+		}
+	    }
+
+	    // 6. return delegatePublic catalog match [complex]
+	    if (publicDelegations != null)
+		return checkDelegations (publicDelegations, publicId,
+				publicId, null);
+	    
+	    return null;
+	}
+
+	// steps as found in OASIS XML catalog spec 7.1.2 or 7.2.2
+	private InputSource mapURI (
+	    String	uri,
+	    Hashtable	ids,
+	    Hashtable	rewrites,
+	    Hashtable	delegations
+	) throws SAXException, IOException
+	{
+	    // 7.1.2: 2. return (first) 'system' entry
+	    // 7.2.2: 2. return (first) 'uri' entry
+	    if (ids != null) {
+		String	retval = (String) ids.get (uri);
+		if (retval != null) {
+		    // IF the URI is accessible ...
+		    return new InputSource (retval);
+		}
+	    }
+
+	    // 7.1.2: 3. return 'rewriteSystem' entries
+	    // 7.2.2: 3. return 'rewriteURI' entries
+	    if (rewrites != null) {
+		String	prefix = null;
+		String	replace = null;
+		int	prefixLen = -1;
+
+		for (Enumeration e = rewrites.keys ();
+			e.hasMoreElements ();
+			/* NOP */) {
+		    String	temp = (String) e.nextElement ();
+		    int		len = -1;
+
+		    if (!uri.startsWith (temp))
+			continue;
+		    if (prefix != null
+			    && (len = temp.length ()) < prefixLen)
+			continue;
+		    prefix = temp;
+		    prefixLen = len;
+		    replace = (String) rewrites.get (temp);
+		}
+		if (prefix != null) {
+		    StringBuffer	buf = new StringBuffer (replace);
+		    buf.append (uri.substring (prefixLen));
+		    // IF the URI is accessible ...
+		    return new InputSource (buf.toString ());
+		}
+	    }
+
+	    // 7.1.2: 4. return 'delegateSystem' catalog match [complex]
+	    // 7.2.2: 4. return 'delegateURI' catalog match [complex]
+	    if (delegations != null)
+		return checkDelegations (delegations, uri, null, uri);
+
+	    return null;
+	}
+
+
+	/**
+	 * Returns a URI for an external entity.
+	 */
+	public InputSource resolve (
+	    boolean	usingPublic,
+	    String	publicId,
+	    String	systemId
+	) throws SAXException, IOException
+	{
+	    boolean	preferSystem;
+	    InputSource	retval;
+
+	    if (hasPreference)
+		preferSystem = !this.usingPublic;
+	    else
+		preferSystem = !usingPublic;
+	    
+	    if (publicId != null)
+		publicId = normalizePublicId (false, publicId);
+
+	    // behavior here matches section 7.1.1 of the oasis spec
+	    if (systemId != null) {
+		if (systemId.startsWith ("urn:publicid:")) {
+		    String	temp = normalizePublicId (true, systemId);
+		    if (publicId == null) {
+			publicId = temp;
+			systemId = null;
+		    } else if (!publicId.equals (temp)) {
+			// error; ok to recover by:
+			systemId = null;
+		    }
+		} else
+		    systemId = normalizeURI (systemId);
+	    }
+
+	    if (systemId == null && publicId == null)
+		return null;
+
+	    if (systemId != null) {
+		retval = mapURI (systemId, systemIds, systemRewrites,
+					systemDelegations);
+		if (retval != null) {
+		    retval.setPublicId (publicId);
+		    return retval;
+		}
+	    }
+
+	    if (publicId != null
+		    && !(systemId != null && preferSystem)) {
+		retval = locatePublicId (publicId);
+		if (retval != null) {
+		    retval.setPublicId (publicId);
+		    return retval;
+		}
+	    }
+
+	    // 7. apply nextCatalog entries
+	    if (next != null) {
+		int	length = next.size ();
+		for (int i = 0; i < length; i++) {
+		    Catalog	n = getNext (i);
+		    retval = n.resolve (usingPublic, publicId, systemId);
+		    if (retval != null)
+			return retval;
+		}
+	    }
+
+	    return null;
+	}
+
+	/**
+	 * Maps one URI into another, for resources that are not defined
+	 * using XML external entity or notation syntax.
+	 */
+	public InputSource resolveURI (String uri)
+	throws SAXException, IOException
+	{
+	    if (uri.startsWith ("urn:publicid:"))
+		return resolve (true, normalizePublicId (true, uri), null);
+
+	    InputSource	retval;
+
+	    uri = normalizeURI (uri);
+
+	    // 7.2.2 steps 2-4
+	    retval = mapURI (uri, uris, uriRewrites, uriDelegations);
+	    if (retval != null)
+		return retval;
+
+	    // 7.2.2 step 5. apply nextCatalog entries
+	    if (next != null) {
+		int	length = next.size ();
+		for (int i = 0; i < length; i++) {
+		    Catalog	n = getNext (i);
+		    retval = n.resolveURI (uri);
+		    if (retval != null)
+			return retval;
+		}
+	    }
+
+	    return null;
+	}
+
+
+	/**
+	 * Finds the external subset associated with a given root element.
+	 */
+	public InputSource getExternalSubset (String name)
+	throws SAXException, IOException
+	{
+	    if (doctypes != null) {
+		String	value = (String) doctypes.get (name);
+		if (value != null) {
+		    // IF the URI is accessible ...
+		    return new InputSource (value);
+		}
+	    }
+	    if (next != null) {
+		int	length = next.size ();
+		for (int i = 0; i < length; i++) {
+		    Catalog	n = getNext (i);
+		    if (n == null)
+			continue;
+		    InputSource	retval = n.getExternalSubset (name);
+		    if (retval != null)
+			return retval;
+		}
+	    }
+	    return null;
+	}
+
+	private synchronized Catalog getNext (int i)
+	throws SAXException, IOException
+	{
+	    Object	obj;
+
+	    if (next == null || i < 0 || i >= next.size ())
+		return null;
+	    obj = next.elementAt (i);
+	    if (obj instanceof Catalog)
+		return (Catalog) obj;
+	    
+	    // ok, we deferred reading that catalog till now.
+	    // load and cache it.
+	    Catalog	cat = null;
+
+	    try {
+		cat = loadCatalog (parserClass, eh, (String) obj, unified);
+		next.setElementAt (cat, i);
+	    } catch (SAXException e) {
+		// must fail quietly, says the OASIS spec
+	    } catch (IOException e) {
+		// same applies here
+	    }
+	    return cat;
+	}
+
+	private InputSource checkDelegations (
+	    Hashtable	delegations,
+	    String	id,
+	    String	publicId,	// only one of public/system
+	    String	systemId	// will be non-null...
+	) throws SAXException, IOException
+	{
+	    Vector	matches = null;
+	    int		length = 0;
+
+	    // first, see if any prefixes match.
+	    for (Enumeration e = delegations.keys ();
+		    e.hasMoreElements ();
+		    /* NOP */) {
+		String	prefix = (String) e.nextElement ();
+
+		if (!id.startsWith (prefix))
+		    continue;
+		if (matches == null)
+		    matches = new Vector ();
+		
+		// maintain in longer->shorter sorted order
+		// NOTE:  assumes not many matches will fire!
+		int	index;
+
+		for (index = 0; index < length; index++) {
+		    String	temp = (String) matches.elementAt (index);
+		    if (prefix.length () > temp.length ()) {
+			matches.insertElementAt (prefix, index);
+			break;
+		    }
+		}
+		if (index == length)
+		    matches.addElement (prefix);
+		length++;
+	    }
+	    if (matches == null)
+		return null;
+
+	    // now we know the list of catalogs to replace our "top level"
+	    // list ... we use it here, rather than somehow going back and
+	    // restarting, since this helps avoid reading most catalogs.
+	    // this assumes stackspace won't be a problem.
+	    for (int i = 0; i < length; i++) {
+		Catalog		catalog = null;
+		InputSource	result;
+
+		// get this catalog.  we may not have read it yet.
+		synchronized (delegations) {
+		    Object	prefix = matches.elementAt (i);
+		    Object	cat = delegations.get (prefix);
+
+		    if (cat instanceof Catalog)
+			catalog = (Catalog) cat;
+		    else {
+			try {
+			    // load and cache that catalog
+			    catalog = loadCatalog (parserClass, eh,
+				    (String) cat, unified);
+			    delegations.put (prefix, catalog);
+			} catch (SAXException e) {
+			    // must ignore, says the OASIS spec
+			} catch (IOException e) {
+			    // same applies here
+			}
+		    }
+		}
+
+		// ignore failed loads, and proceed
+		if (catalog == null)
+		    continue;
+		
+		// we have a catalog ... resolve!
+		// usingPublic value can't matter, there's no choice
+		result = catalog.resolve (true, publicId, systemId);
+		if (result != null)
+		    return result;
+	    }
+
+	    // if there were no successes, the entire
+	    // lookup failed (all the way to top level)
+	    throw new DoneDelegation ();
+	}
+    }
+
+
+    /** This is the namespace URI used for OASIS XML Catalogs.  */
+    private static final String	catalogNamespace =
+    	"urn:oasis:names:tc:entity:xmlns:xml:catalog";
+
+
+    /**
+     * Loads/unmarshals one catalog.
+     */
+    private static class Loader extends DefaultHandler2
+    {
+	private boolean		preInterned;
+	private ErrorHandler	handler;
+	private boolean		unified;
+	private int		ignoreDepth;
+	private Locator		locator;
+	private boolean		started;
+	private Hashtable	externals;
+	private Stack		bases;
+
+	Catalog			cat = new Catalog ();
+
+
+	/**
+	 * Constructor.
+	 * @param flag true iff the parser already interns strings.
+	 * @param eh Errors and warnings are delegated to this.
+	 * @param unified true keeps one table for URI mappings;
+	 *	false matches OASIS spec, storing mappings
+	 *	for URIs and SYSTEM ids in parallel tables.
+	 */
+	Loader (boolean flag, ErrorHandler eh, boolean unified)
+	{
+	    preInterned = flag;
+	    handler = eh;
+	    this.unified = unified;
+	    cat.unified = unified;
+	    cat.eh = eh;
+	}
+
+
+	// strips out fragments
+	private String nofrag (String uri)
+	throws SAXException
+	{
+	    if (uri.indexOf ('#') != -1) {
+		warn ("URI with fragment: " + uri);
+		uri = uri.substring (0, uri.indexOf ('#'));
+	    }
+	    return uri;
+	}
+
+	// absolutizes relative URIs
+	private String absolutize (String uri)
+	throws SAXException
+	{
+	    // avoid creating URLs if they're already absolutized,
+	    // or if the URI is already using a known scheme
+	    if (uri.startsWith ("file:/")
+		    || uri.startsWith ("http:/")
+		    || uri.startsWith ("https:/")
+		    || uri.startsWith ("ftp:/")
+		    || uri.startsWith ("urn:")
+		    )
+		return uri;
+
+	    // otherwise, let's hope the JDK handles this URI scheme.
+	    try {
+		URL	base = (URL) bases.peek ();
+		return new URL (base, uri).toString ();
+	    } catch (Exception e) {
+		fatal ("can't absolutize URI: " + uri);
+		return null;
+	    }
+	}
+
+	// recoverable error
+	private void error (String message)
+	throws SAXException
+	{
+	    if (handler == null)
+		return;
+	    handler.error (new SAXParseException (message, locator));
+	}
+
+	// nonrecoverable error
+	private void fatal (String message)
+	throws SAXException
+	{
+	    SAXParseException	spe;
+	    
+	    spe = new SAXParseException (message, locator);
+	    if (handler != null)
+		handler.fatalError (spe);
+	    throw spe;
+	}
+
+	// low severity problem
+	private void warn (String message)
+	throws SAXException
+	{
+	    if (handler == null)
+		return;
+	    handler.warning (new SAXParseException (message, locator));
+	}
+
+	// callbacks:
+
+	public void setDocumentLocator (Locator l)
+	    { locator = l; }
+
+	public void startDocument ()
+	throws SAXException
+	{
+	    if (locator == null)
+		error ("no locator!");
+	    bases = new Stack ();
+	    String	uri = locator.getSystemId ();
+	    try {
+		bases.push (new URL (uri));
+	    } catch (IOException e) {
+		fatal ("bad document base URI: " + uri);
+	    }
+	}
+
+	public void endDocument ()
+	throws SAXException
+	{
+	    try {
+		if (!started)
+		    error ("not a catalog!");
+	    } finally {
+		locator = null;
+		handler = null;
+		externals = null;
+		bases = null;
+	    }
+	}
+
+	// XML Base support for external entities.
+
+	// NOTE: expects parser is in default "resolve-dtd-uris" mode.
+	public void externalEntityDecl (String name, String pub, String sys)
+	throws SAXException
+	{
+	    if (externals == null)
+		externals = new Hashtable ();
+	    if (externals.get (name) == null)
+		externals.put (name, pub);
+	}
+
+	public void startEntity (String name)
+	throws SAXException
+	{
+	    if (externals == null)
+		return;
+	    String uri = (String) externals.get (name);
+
+	    // NOTE: breaks if an EntityResolver substitutes these URIs.
+	    // If toplevel loader supports one, must intercept calls...
+	    if (uri != null) {
+		try {
+		    bases.push (new URL (uri));
+		} catch (IOException e) {
+		    fatal ("entity '" + name + "', bad URI: " + uri);
+		}
+	    }
+	}
+
+	public void endEntity (String name)
+	{
+	    if (externals == null)
+		return;
+	    String value = (String) externals.get (name);
+
+	    if (value != null)
+		bases.pop ();
+	}
+
+	/**
+	 * Processes catalog elements, saving their data.
+	 */
+	public void startElement (String namespace, String local,
+	    String qName, Attributes atts)
+	throws SAXException
+	{
+	    // must ignore non-catalog elements, and their contents
+	    if (ignoreDepth != 0 || !catalogNamespace.equals (namespace)) {
+		ignoreDepth++;
+		return;
+	    }
+
+	    // basic sanity checks
+	    if (!preInterned)
+		local = local.intern ();
+	    if (!started) {
+		started = true;
+		if ("catalog" != local)
+		    fatal ("root element not 'catalog': " + local);
+	    }
+
+	    // Handle any xml:base attribute
+	    String	xmlbase = atts.getValue ("xml:base");
+
+	    if (xmlbase != null) {
+		URL	base = (URL) bases.peek ();
+		try {
+		    base = new URL (base, xmlbase);
+		} catch (IOException e) {
+		    fatal ("can't resolve xml:base attribute: " + xmlbase);
+		}
+		bases.push (base);
+	    } else
+		bases.push (bases.peek ());
+
+	    // fetch multi-element attributes, apply standard tweaks
+	    // values (uri, catalog, rewritePrefix) get normalized too,
+	    // as a precaution and since we may compare the values
+	    String	catalog = atts.getValue ("catalog");
+	    if (catalog != null)
+		catalog = normalizeURI (absolutize (catalog));
+
+	    String	rewritePrefix = atts.getValue ("rewritePrefix");
+	    if (rewritePrefix != null)
+		rewritePrefix = normalizeURI (absolutize (rewritePrefix));
+
+	    String	systemIdStartString;
+	    systemIdStartString = atts.getValue ("systemIdStartString");
+	    if (systemIdStartString != null) {
+		systemIdStartString = normalizeURI (systemIdStartString);
+		// unmatchable <rewriteSystemId>, <delegateSystemId> elements
+		if (systemIdStartString.startsWith ("urn:publicid:")) {
+		    error ("systemIdStartString is really a publicId!!");
+		    return;
+		}
+	    }
+
+	    String	uri = atts.getValue ("uri");
+	    if (uri != null)
+		uri = normalizeURI (absolutize (uri));
+
+	    String	uriStartString;
+	    uriStartString = atts.getValue ("uriStartString");
+	    if (uriStartString != null) {
+		uriStartString = normalizeURI (uriStartString);
+		// unmatchable <rewriteURI>, <delegateURI> elements
+		if (uriStartString.startsWith ("urn:publicid:")) {
+		    error ("uriStartString is really a publicId!!");
+		    return;
+		}
+	    }
+
+	    // strictly speaking "group" and "catalog" shouldn't nest
+	    // ... arbitrary restriction, no evident motivation
+
+// FIXME stack "prefer" settings (two elements only!) and use
+// them to populate different public mapping/delegation tables
+
+	    if ("catalog" == local || "group" == local) {
+		String	prefer = atts.getValue ("prefer");
+
+		if (prefer != null && !"public".equals (prefer)) {
+		    if (!"system".equals (prefer)) {
+			error ("in <" + local + " ... prefer='...'>, "
+			    + "assuming 'public'");
+			prefer = "public";
+		    }
+		}
+		if (prefer != null) {
+		    if ("catalog" == local) {
+			cat.hasPreference = true;
+			cat.usingPublic = "public".equals (prefer);
+		    } else {
+			if (!cat.hasPreference || cat.usingPublic
+				    != "public".equals (prefer)) {
+fatal ("<group prefer=...> case not handled");
+			}
+		    }
+		} else if ("group" == local && cat.hasPreference) {
+fatal ("<group prefer=...> case not handled");
+		}
+
+	    //
+	    // PUBLIC ids:  cleanly set up for id substitution
+	    //
+	    } else if ("public" == local) {
+		String	publicId = atts.getValue ("publicId");
+		String	value = null;
+
+		if (publicId == null || uri == null) {
+		    error ("expecting <public publicId=... uri=.../>");
+		    return;
+		}
+		publicId = normalizePublicId (true, publicId);
+		uri = nofrag (uri);
+		if (cat.publicIds == null)
+		    cat.publicIds = new Hashtable ();
+		else
+		    value = (String) cat.publicIds.get (publicId);
+		if (value != null) {
+		    if (!value.equals (uri))
+			warn ("ignoring <public...> entry for " + publicId);
+		} else
+		    cat.publicIds.put (publicId, uri);
+
+	    } else if ("delegatePublic" == local) {
+		String	publicIdStartString;
+		Object	value = null;
+
+		publicIdStartString = atts.getValue ("publicIdStartString");
+		if (publicIdStartString == null || catalog == null) {
+		    error ("expecting <delegatePublic "
+			+ "publicIdStartString=... catalog=.../>");
+		    return;
+		}
+		publicIdStartString = normalizePublicId (true,
+			publicIdStartString);
+		if (cat.publicDelegations == null)
+		    cat.publicDelegations = new Hashtable ();
+		else
+		    value = cat.publicDelegations.get (publicIdStartString);
+		if (value != null) {
+		    if (!value.equals (catalog))
+			warn ("ignoring <delegatePublic...> entry for "
+			    + uriStartString);
+		} else
+		    cat.publicDelegations.put (publicIdStartString, catalog);
+
+
+	    //
+	    // SYSTEM ids:  need substitution due to operational issues
+	    //
+	    } else if ("system" == local) {
+		String	systemId = atts.getValue ("systemId");
+		String	value = null;
+
+		if (systemId == null || uri == null) {
+		    error ("expecting <system systemId=... uri=.../>");
+		    return;
+		}
+		systemId = normalizeURI (systemId);
+		uri = nofrag (uri);
+		if (systemId.startsWith ("urn:publicid:")) {
+		    error ("systemId is really a publicId!!");
+		    return;
+		}
+		if (cat.systemIds == null) {
+		    cat.systemIds = new Hashtable ();
+		    if (unified)
+			cat.uris = cat.systemIds;
+		} else
+		    value = (String) cat.systemIds.get (systemId);
+		if (value != null) {
+		    if (!value.equals (uri))
+			warn ("ignoring <system...> entry for " + systemId);
+		} else
+		    cat.systemIds.put (systemId, uri);
+
+	    } else if ("rewriteSystem" == local) {
+		String	value = null;
+
+		if (systemIdStartString == null || rewritePrefix == null
+			|| systemIdStartString.length () == 0
+			|| rewritePrefix.length () == 0
+			) {
+		    error ("expecting <rewriteSystem "
+			+ "systemIdStartString=... rewritePrefix=.../>");
+		    return;
+		}
+		if (cat.systemRewrites == null) {
+		    cat.systemRewrites = new Hashtable ();
+		    if (unified)
+			cat.uriRewrites = cat.systemRewrites;
+		} else
+		    value = (String) cat.systemRewrites.get (
+		    				systemIdStartString);
+		if (value != null) {
+		    if (!value.equals (rewritePrefix))
+			warn ("ignoring <rewriteSystem...> entry for "
+			    + systemIdStartString);
+		} else
+		    cat.systemRewrites.put (systemIdStartString,
+		    		rewritePrefix);
+
+	    } else if ("delegateSystem" == local) {
+		Object	value = null;
+
+		if (systemIdStartString == null || catalog == null) {
+		    error ("expecting <delegateSystem "
+			+ "systemIdStartString=... catalog=.../>");
+		    return;
+		}
+		if (cat.systemDelegations == null) {
+		    cat.systemDelegations = new Hashtable ();
+		    if (unified)
+			cat.uriDelegations = cat.systemDelegations;
+		} else
+		    value = cat.systemDelegations.get (systemIdStartString);
+		if (value != null) {
+		    if (!value.equals (catalog))
+			warn ("ignoring <delegateSystem...> entry for "
+			    + uriStartString);
+		} else
+		    cat.systemDelegations.put (systemIdStartString, catalog);
+
+
+	    //
+	    // URI:  just like "system" ID support, except that
+	    // fragment IDs are disallowed in "system" elements.
+	    //
+	    } else if ("uri" == local) {
+		String	name = atts.getValue ("name");
+		String	value = null;
+
+		if (name == null || uri == null) {
+		    error ("expecting <uri name=... uri=.../>");
+		    return;
+		}
+		if (name.startsWith ("urn:publicid:")) {
+		    error ("name is really a publicId!!");
+		    return;
+		}
+		name = normalizeURI (name);
+		if (cat.uris == null) {
+		    cat.uris = new Hashtable ();
+		    if (unified)
+			cat.systemIds = cat.uris;
+		} else
+		    value = (String) cat.uris.get (name);
+		if (value != null) {
+		    if (!value.equals (uri))
+			warn ("ignoring <uri...> entry for " + name);
+		} else
+		    cat.uris.put (name, uri);
+
+	    } else if ("rewriteURI" == local) {
+		String value = null;
+
+		if (uriStartString == null || rewritePrefix == null
+			|| uriStartString.length () == 0
+			|| rewritePrefix.length () == 0
+			) {
+		    error ("expecting <rewriteURI "
+			+ "uriStartString=... rewritePrefix=.../>");
+		    return;
+		}
+		if (cat.uriRewrites == null) {
+		    cat.uriRewrites = new Hashtable ();
+		    if (unified)
+			cat.systemRewrites = cat.uriRewrites;
+		} else
+		    value = (String) cat.uriRewrites.get (uriStartString);
+		if (value != null) {
+		    if (!value.equals (rewritePrefix))
+			warn ("ignoring <rewriteURI...> entry for "
+			    + uriStartString);
+		} else
+		    cat.uriRewrites.put (uriStartString, rewritePrefix);
+
+	    } else if ("delegateURI" == local) {
+		Object	value = null;
+
+		if (uriStartString == null || catalog == null) {
+		    error ("expecting <delegateURI "
+			+ "uriStartString=... catalog=.../>");
+		    return;
+		}
+		if (cat.uriDelegations == null) {
+		    cat.uriDelegations = new Hashtable ();
+		    if (unified)
+			cat.systemDelegations = cat.uriDelegations;
+		} else
+		    value = cat.uriDelegations.get (uriStartString);
+		if (value != null) {
+		    if (!value.equals (catalog))
+			warn ("ignoring <delegateURI...> entry for "
+			    + uriStartString);
+		} else
+		    cat.uriDelegations.put (uriStartString, catalog);
+
+	    //
+	    // NON-DELEGATING approach to modularity
+	    //
+	    } else if ("nextCatalog" == local) {
+		if (catalog == null) {
+		    error ("expecting <nextCatalog catalog=.../>");
+		    return;
+		}
+		if (cat.next == null)
+		    cat.next = new Vector ();
+		cat.next.addElement (catalog);
+
+	    //
+	    // EXTENSIONS from appendix E
+	    //
+	    } else if ("doctype" == local) {
+		String	name = atts.getValue ("name");
+		String	value = null;
+
+		if (name == null || uri == null) {
+		    error ("expecting <doctype name=... uri=.../>");
+		    return;
+		}
+		name = normalizeURI (name);
+		if (cat.doctypes == null)
+		    cat.doctypes = new Hashtable ();
+		else
+		    value = (String) cat.doctypes.get (name);
+		if (value != null) {
+		    if (!value.equals (uri))
+			warn ("ignoring <doctype...> entry for "
+			    + uriStartString);
+		} else
+		    cat.doctypes.put (name, uri);
+	    
+
+	    //
+	    // RESERVED ... ignore (like reserved attributes) but warn
+	    //
+	    } else {
+		warn ("ignoring unknown catalog element: " + local);
+		ignoreDepth++;
+	    }
+	}
+
+	public void endElement (String uri, String local, String qName)
+	throws SAXException
+	{
+	    if (ignoreDepth != 0)
+		ignoreDepth--;
+	    else
+		bases.pop ();
+	}
+    }
+}

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/util/XHTMLWriter.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/util/XHTMLWriter.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/util/XHTMLWriter.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/util/XHTMLWriter.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,114 @@
+/* XHTMLWriter.java -- 
+   Copyright (C) 1999,2000,2001 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.xml.util;
+
+import java.io.IOException;
+import java.io.OutputStream;
+import java.io.OutputStreamWriter;
+import java.io.Writer;
+
+
+/**
+ * This extends XMLWriter to create a class which defaults to writing
+ * XHTML text, preferring the US-ASCII encoding.  It adds no unique
+ * functionality, only changing the defaults slightly to simplify writing
+ * XHTML processing components by providing a bean class whose properties
+ * have more convenient defaults.  An artifact of using the US-ASCII
+ * encoding is that no XML declaration is written, so that HTML tools
+ * that can't accept them will not become confused.  Components can treat
+ * the output as UTF-8, ISO-8859-1, or US-ASCII without incurring any
+ * data loss.
+ *
+ * @author David Brownell
+ *
+ * @deprecated Please use the javax.xml.stream APIs instead
+ */
+public class XHTMLWriter extends XMLWriter
+{
+    /**
+     * Constructs this handler with System.out used to write
+     * SAX events using the US-ASCII encoding, as XHTML.
+     */
+    public XHTMLWriter ()
+    throws IOException
+    {
+	this (System.out);
+    }
+
+    /**
+     * Constructs this handler such that the specified output stream
+     * is used to write SAX events in the US-ASCII encoding, as XHTML.
+     *
+     * @param out Where US-ASCII encoding of the stream of SAX
+     *	events will be sent.
+     */
+    public XHTMLWriter (OutputStream out)
+    throws IOException
+    {
+	// not all JVMs understand "ASCII" as an encoding name, so
+	// we use 8859_1 (they all seem to handle that one) and
+	// make the echo handler filter out non-ASCII characters
+	this (new OutputStreamWriter (out, "8859_1"), "US-ASCII");
+    }
+
+    /**
+     * Constructs this handler such that the specified output stream
+     * is used to write SAX events as XHTML.
+     *
+     * @param out Where the stream of SAX events will be written.
+     */
+    public XHTMLWriter (Writer out)
+    {
+	this (out, null);
+    }
+
+    /**
+     * Constructs this handler such that the specified output stream
+     * is used to write SAX events as XHTML, labeled with the specified
+     * encoding.
+     *
+     * @param out Where the stream of SAX events will be written.
+     * @param encoding If non-null, this names the encoding to be
+     *	placed in the encoding declaration.
+     */
+    public XHTMLWriter (Writer out, String encoding)
+    {
+	super (out, encoding);
+	setXhtml (true);
+    }
+}

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/util/XMLWriter.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/util/XMLWriter.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/util/XMLWriter.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/util/XMLWriter.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,1929 @@
+/* XMLWriter.java -- 
+   Copyright (C) 1999,2000,2001 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.xml.util;
+
+import java.io.BufferedWriter;
+import java.io.CharConversionException;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.io.OutputStreamWriter;
+import java.io.Writer;
+import java.util.Stack;
+
+import org.xml.sax.*;
+import org.xml.sax.ext.*;
+import org.xml.sax.helpers.*;
+
+
+/**
+ * This class is a SAX handler which writes all its input as a well formed
+ * XML or XHTML document.  If driven using SAX2 events, this output may
+ * include a recreated document type declaration, subject to limitations
+ * of SAX (no internal subset exposed) or DOM (the important declarations,
+ * with their documentation, are discarded).
+ *
+ * <p> By default, text is generated "as-is", but some optional modes
+ * are supported.  Pretty-printing is supported, to make life easier
+ * for people reading the output.  XHTML (1.0) output has can be made
+ * particularly pretty; all the built-in character entities are known.
+ * Canonical XML can also be generated, assuming the input is properly
+ * formed.
+ *
+ * <hr>
+ *
+ * <p> Some of the methods on this class are intended for applications to
+ * use directly, rather than as pure SAX2 event callbacks.  Some of those
+ * methods access the JavaBeans properties (used to tweak output formats,
+ * for example canonicalization and pretty printing).  Subclasses
+ * are expected to add new behaviors, not to modify current behavior, so
+ * many such methods are final.</p>
+ *
+ * <p> The <em>write*()</em> methods may be slightly simpler for some
+ * applications to use than direct callbacks.  For example, they support
+ * a simple policy for encoding data items as the content of a single element.
+ *
+ * <p> To reuse an XMLWriter you must provide it with a new Writer, since
+ * this handler closes the writer it was given as part of its endDocument()
+ * handling.  (XML documents have an end of input, and the way to encode
+ * that on a stream is to close it.) </p>
+ *
+ * <hr>
+ *
+ * <p> Note that any relative URIs in the source document, as found in
+ * entity and notation declarations, ought to have been fully resolved by
+ * the parser providing events to this handler.  This means that the
+ * output text should only have fully resolved URIs, which may not be
+ * the desired behavior in cases where later binding is desired. </p>
+ *
+ * <p> <em>Note that due to SAX2 defaults, you may need to manually
+ * ensure that the input events are XML-conformant with respect to namespace
+ * prefixes and declarations.  {@link gnu.xml.pipeline.NSFilter} is
+ * one solution to this problem, in the context of processing pipelines.</em>
+ * Something as simple as connecting this handler to a parser might not
+ * generate the correct output.  Another workaround is to ensure that the
+ * <em>namespace-prefixes</em> feature is always set to true, if you're
+ * hooking this directly up to some XMLReader implementation.
+ *
+ * @see gnu.xml.pipeline.TextConsumer
+ *
+ * @author David Brownell
+ *
+ * @deprecated Please use the javax.xml.stream APIs instead
+ */
+public class XMLWriter
+    implements ContentHandler, LexicalHandler, DTDHandler, DeclHandler
+{
+    // text prints/escapes differently depending on context
+    //	CTX_ENTITY ... entity literal value
+    //	CTX_ATTRIBUTE ... attribute literal value
+    //	CTX_CONTENT ... content of an element
+    //	CTX_UNPARSED ... CDATA, comment, PI, names, etc
+    //  CTX_NAME ... name or nmtoken, no escapes possible
+    private static final int	CTX_ENTITY = 1;
+    private static final int	CTX_ATTRIBUTE = 2;
+    private static final int	CTX_CONTENT = 3;
+    private static final int	CTX_UNPARSED = 4;
+    private static final int	CTX_NAME = 5;
+
+// FIXME: names (element, attribute, PI, notation, etc) are not
+// currently written out with range checks (escapeChars).
+// In non-XHTML, some names can't be directly written; panic!
+
+    private static String	sysEOL;
+
+    static {
+	try {
+	    sysEOL = System.getProperty ("line.separator", "\n");
+
+	    // don't use the system's EOL if it's illegal XML.
+	    if (!isLineEnd (sysEOL))
+		sysEOL = "\n";
+
+	} catch (SecurityException e) {
+	    sysEOL = "\n";
+	}
+    }
+
+    private static boolean isLineEnd (String eol)
+    {
+	return "\n".equals (eol)
+		    || "\r".equals (eol)
+		    || "\r\n".equals (eol);
+    }
+
+    private Writer		out;
+    private boolean		inCDATA;
+    private int			elementNestLevel;
+    private String		eol = sysEOL;
+
+    private short		dangerMask;
+    private StringBuffer	stringBuf;
+    private Locator		locator;
+    private ErrorHandler	errHandler;
+
+    private boolean		expandingEntities = false;
+    private int			entityNestLevel;
+    private boolean		xhtml;
+    private boolean		startedDoctype;
+    private String		encoding;
+
+    private boolean		canonical;
+    private boolean		inDoctype;
+    private boolean		inEpilogue;
+
+    // pretty printing controls
+    private boolean		prettyPrinting;
+    private int			column;
+    private boolean		noWrap;
+    private Stack		space = new Stack ();
+
+    // this is not a hard'n'fast rule -- longer lines are OK,
+    // but are to be avoided.  Here, prettyprinting is more to
+    // show structure "cleanly" than to be precise about it.
+    // better to have ragged layout than one line 24Kb long.
+    private static final int	lineLength = 75;
+
+
+    /**
+     * Constructs this handler with System.out used to write SAX events
+     * using the UTF-8 encoding.  Avoid using this except when you know
+     * it's safe to close System.out at the end of the document.
+     */
+    public XMLWriter () throws IOException
+	{ this (System.out); }
+
+    /**
+     * Constructs a handler which writes all input to the output stream
+     * in the UTF-8 encoding, and closes it when endDocument is called.
+     * (Yes it's annoying that this throws an exception -- but there's
+     * really no way around it, since it's barely possible a JDK may
+     * exist somewhere that doesn't know how to emit UTF-8.)
+     */
+    public XMLWriter (OutputStream out) throws IOException
+    {
+	this (new OutputStreamWriter (out, "UTF8"));
+    }
+
+    /**
+     * Constructs a handler which writes all input to the writer, and then
+     * closes the writer when the document ends.  If an XML declaration is
+     * written onto the output, and this class can determine the name of
+     * the character encoding for this writer, that encoding name will be
+     * included in the XML declaration.
+     *
+     * <P> See the description of the constructor which takes an encoding
+     * name for imporant information about selection of encodings.
+     *
+     * @param writer XML text is written to this writer.
+     */
+    public XMLWriter (Writer writer)
+    {
+	this (writer, null);
+    }
+
+    /**
+     * Constructs a handler which writes all input to the writer, and then
+     * closes the writer when the document ends.  If an XML declaration is
+     * written onto the output, this class will use the specified encoding
+     * name in that declaration.  If no encoding name is specified, no
+     * encoding name will be declared unless this class can otherwise
+     * determine the name of the character encoding for this writer.
+     *
+     * <P> At this time, only the UTF-8 ("UTF8") and UTF-16 ("Unicode")
+     * output encodings are fully lossless with respect to XML data.  If you
+     * use any other encoding you risk having your data be silently mangled
+     * on output, as the standard Java character encoding subsystem silently
+     * maps non-encodable characters to a question mark ("?") and will not
+     * report such errors to applications.
+     *
+     * <p> For a few other encodings the risk can be reduced. If the writer is
+     * a java.io.OutputStreamWriter, and uses either the ISO-8859-1 ("8859_1",
+     * "ISO8859_1", etc) or US-ASCII ("ASCII") encodings, content which
+     * can't be encoded in those encodings will be written safely.  Where
+     * relevant, the XHTML entity names will be used; otherwise, numeric
+     * character references will be emitted.
+     *
+     * <P> However, there remain a number of cases where substituting such
+     * entity or character references is not an option.  Such references are
+     * not usable within a DTD, comment, PI, or CDATA section.  Neither may
+     * they be used when element, attribute, entity, or notation names have
+     * the problematic characters.
+     *
+     * @param writer XML text is written to this writer.
+     * @param encoding if non-null, and an XML declaration is written,
+     *	this is the name that will be used for the character encoding.
+     */
+    public XMLWriter (Writer writer, String encoding)
+    {
+	setWriter (writer, encoding);
+    }
+    
+    private void setEncoding (String encoding)
+    {
+	if (encoding == null && out instanceof OutputStreamWriter)
+	    encoding = ((OutputStreamWriter)out).getEncoding ();
+
+	if (encoding != null) {
+	    encoding = encoding.toUpperCase ();
+
+	    // Use official encoding names where we know them,
+	    // avoiding the Java-only names.  When using common
+	    // encodings where we can easily tell if characters
+	    // are out of range, we'll escape out-of-range
+	    // characters using character refs for safety.
+
+	    // I _think_ these are all the main synonyms for these!
+	    if ("UTF8".equals (encoding)) {
+		encoding = "UTF-8";
+	    } else if ("US-ASCII".equals (encoding)
+		    || "ASCII".equals (encoding)) {
+		dangerMask = (short) 0xff80;
+		encoding = "US-ASCII";
+	    } else if ("ISO-8859-1".equals (encoding)
+		    || "8859_1".equals (encoding)
+		    || "ISO8859_1".equals (encoding)) {
+		dangerMask = (short) 0xff00;
+		encoding = "ISO-8859-1";
+	    } else if ("UNICODE".equals (encoding)
+		    || "UNICODE-BIG".equals (encoding)
+		    || "UNICODE-LITTLE".equals (encoding)) {
+		encoding = "UTF-16";
+
+		// TODO: UTF-16BE, UTF-16LE ... no BOM; what
+		// release of JDK supports those Unicode names?
+	    }
+
+	    if (dangerMask != 0)
+		stringBuf = new StringBuffer ();
+	}
+
+	this.encoding = encoding;
+    }
+
+
+    /**
+     * Resets the handler to write a new text document.
+     *
+     * @param writer XML text is written to this writer.
+     * @param encoding if non-null, and an XML declaration is written,
+     *	this is the name that will be used for the character encoding.
+     *
+     * @exception IllegalStateException if the current
+     *	document hasn't yet ended (with {@link #endDocument})
+     */
+    final public void setWriter (Writer writer, String encoding)
+    {
+	if (out != null)
+	    throw new IllegalStateException (
+		"can't change stream in mid course");
+	out = writer;
+	if (out != null)
+	    setEncoding (encoding);
+	if (!(out instanceof BufferedWriter))
+	    out = new BufferedWriter (out);
+	space.push ("default");
+    }
+
+    /**
+     * Assigns the line ending style to be used on output.
+     * @param eolString null to use the system default; else
+     *	"\n", "\r", or "\r\n".
+     */
+    final public void setEOL (String eolString)
+    {
+	if (eolString == null)
+	    eol = sysEOL;
+	else if (!isLineEnd (eolString))
+	    eol = eolString;
+	else
+	    throw new IllegalArgumentException (eolString);
+    }
+
+    /**
+     * Assigns the error handler to be used to present most fatal
+     * errors.
+     */
+    public void setErrorHandler (ErrorHandler handler)
+    {
+	errHandler = handler;
+    }
+
+    /**
+     * Used internally and by subclasses, this encapsulates the logic
+     * involved in reporting fatal errors.  It uses locator information
+     * for good diagnostics, if available, and gives the application's
+     * ErrorHandler the opportunity to handle the error before throwing
+     * an exception.
+     */
+    protected void fatal (String message, Exception e)
+    throws SAXException
+    {
+	SAXParseException	x;
+
+	if (locator == null)
+	    x = new SAXParseException (message, null, null, -1, -1, e);
+	else
+	    x = new SAXParseException (message, locator, e);
+	if (errHandler != null)
+	    errHandler.fatalError (x);
+	throw x;
+    }
+
+
+    // JavaBeans properties
+
+    /**
+     * Controls whether the output should attempt to follow the "transitional"
+     * XHTML rules so that it meets the "HTML Compatibility Guidelines"
+     * appendix in the XHTML specification.  A "transitional" Document Type
+     * Declaration (DTD) is placed near the beginning of the output document,
+     * instead of whatever DTD would otherwise have been placed there, and
+     * XHTML empty elements are printed specially.  When writing text in
+     * US-ASCII or ISO-8859-1 encodings, the predefined XHTML internal
+     * entity names are used (in preference to character references) when
+     * writing content characters which can't be expressed in those encodings.
+     *
+     * <p> When this option is enabled, it is the caller's responsibility
+     * to ensure that the input is otherwise valid as XHTML.  Things to
+     * be careful of in all cases, as described in the appendix referenced
+     * above, include:  <ul>
+     *
+     *	<li> Element and attribute names must be in lower case, both
+     *		in the document and in any CSS style sheet.
+     *	<li> All XML constructs must be valid as defined by the XHTML
+     *		"transitional" DTD (including all familiar constructs,
+     *		even deprecated ones).
+     *	<li> The root element must be "html".
+     *	<li> Elements that must be empty (such as <em><br></em>
+     *		must have no content.
+     *	<li> Use both <em>lang</em> and <em>xml:lang</em> attributes
+     *		when specifying language.
+     *	<li> Similarly, use both <em>id</em> and <em>name</em> attributes
+     *		when defining elements that may be referred to through
+     *		URI fragment identifiers ... and make sure that the
+     *		value is a legal NMTOKEN, since not all such HTML 4.0
+     *		identifiers are valid in XML.
+     *	<li> Be careful with character encodings; make sure you provide
+     *		a <em><meta http-equiv="Content-type"
+     *		content="text/xml;charset=..." /></em> element in
+     *		the HTML "head" element, naming the same encoding
+     *		used to create this handler.  Also, if that encoding
+     *		is anything other than US-ASCII, make sure that if
+     *		the document is given a MIME content type, it has
+     *		a <em>charset=...</em> attribute with that encoding.
+     *	</ul>
+     *
+     * <p> Additionally, some of the oldest browsers have additional
+     * quirks, to address with guidelines such as: <ul>
+     *
+     *	<li> Processing instructions may be rendered, so avoid them.
+     *		(Similarly for an XML declaration.)
+     *	<li> Embedded style sheets and scripts should not contain XML
+     *		markup delimiters:  &, <, and ]]> are trouble.
+     *	<li> Attribute values should not have line breaks or multiple
+     *		consecutive white space characters.
+     *	<li> Use no more than one of the deprecated (transitional)
+     *		<em><isindex></em> elements.
+     *	<li> Some boolean attributes (such as <em>compact, checked,
+     *		disabled, readonly, selected,</em> and more) confuse
+     *		some browsers, since they only understand minimized
+     *		versions which are illegal in XML.
+     *	</ul>
+     *
+     * <p> Also, some characteristics of the resulting output may be
+     * a function of whether the document is later given a MIME
+     * content type of <em>text/html</em> rather than one indicating
+     * XML (<em>application/xml</em> or <em>text/xml</em>).  Worse,
+     * some browsers ignore MIME content types and prefer to rely URI
+     * name suffixes -- so an "index.xml" could always be XML, never
+     * XHTML, no matter its MIME type.
+     */
+    final public void setXhtml (boolean value)
+    {
+	if (locator != null)
+	    throw new IllegalStateException ("started parsing");
+	xhtml = value;
+	if (xhtml)
+	    canonical = false;
+    }
+
+    /**
+     * Returns true if the output attempts to echo the input following
+     * "transitional" XHTML rules and matching the "HTML Compatibility
+     * Guidelines" so that an HTML version 3 browser can read the output
+     * as HTML; returns false (the default) othewise.
+     */
+    final public boolean isXhtml ()
+    {
+	return xhtml;
+    }
+
+    /**
+     * Controls whether the output text contains references to
+     * entities (the default), or instead contains the expanded
+     * values of those entities.
+     */
+    final public void setExpandingEntities (boolean value)
+    {
+	if (locator != null)
+	    throw new IllegalStateException ("started parsing");
+	expandingEntities = value;
+	if (!expandingEntities)
+	    canonical = false;
+    }
+
+    /**
+     * Returns true if the output will have no entity references;
+     * returns false (the default) otherwise.
+     */
+    final public boolean isExpandingEntities ()
+    {
+	return expandingEntities;
+    }
+
+    /**
+     * Controls pretty-printing, which by default is not enabled
+     * (and currently is most useful for XHTML output).
+     * Pretty printing enables structural indentation, sorting of attributes
+     * by name, line wrapping, and potentially other mechanisms for making
+     * output more or less readable.
+     *
+     * <p> At this writing, structural indentation and line wrapping are
+     * enabled when pretty printing is enabled and the <em>xml:space</em>
+     * attribute has the value <em>default</em> (its other legal value is
+     * <em>preserve</em>, as defined in the XML specification).  The three
+     * XHTML element types which use another value are recognized by their
+     * names (namespaces are ignored).
+     *
+     * <p> Also, for the record, the "pretty" aspect of printing here
+     * is more to provide basic structure on outputs that would otherwise
+     * risk being a single long line of text.  For now, expect the
+     * structure to be ragged ... unless you'd like to submit a patch
+     * to make this be more strictly formatted!
+     *
+     * @exception IllegalStateException thrown if this method is invoked
+     *	after output has begun.
+     */
+    final public void setPrettyPrinting (boolean value)
+    {
+	if (locator != null)
+	    throw new IllegalStateException ("started parsing");
+	prettyPrinting = value;
+	if (prettyPrinting)
+	    canonical = false;
+    }
+
+    /**
+     * Returns value of flag controlling pretty printing.
+     */
+    final public boolean isPrettyPrinting ()
+    {
+	return prettyPrinting;
+    }
+
+
+    /**
+     * Sets the output style to be canonicalized.  Input events must
+     * meet requirements that are slightly more stringent than the
+     * basic well-formedness ones, and include:  <ul>
+     *
+     *	<li> Namespace prefixes must not have been changed from those
+     *	in the original document.  (This may only be ensured by setting
+     *	the SAX2 XMLReader <em>namespace-prefixes</em> feature flag;
+     *	by default, it is cleared.)
+     *
+     *	<li> Redundant namespace declaration attributes have been
+     *	removed.  (If an ancestor element defines a namespace prefix
+     *	and that declaration hasn't been overriden, an element must
+     *	not redeclare it.)
+     *
+     *	<li> If comments are not to be included in the canonical output,
+     *	they must first be removed from the input event stream; this
+     *	<em>Canonical XML with comments</em> by default.
+     *
+     *	<li> If the input character encoding was not UCS-based, the
+     *	character data must have been normalized using Unicode
+     *	Normalization Form C.  (UTF-8 and UTF-16 are UCS-based.)
+     *
+     *	<li> Attribute values must have been normalized, as is done
+     *	by any conformant XML processor which processes all external
+     *	parameter entities.
+     *
+     *	<li> Similarly, attribute value defaulting has been performed.
+     *
+     *	</ul>
+     *
+     * <p> Note that fragments of XML documents, as specified by an XPath
+     * node set, may be canonicalized.  In such cases, elements may need
+     * some fixup (for <em>xml:*</em> attributes and application-specific
+     * context).
+     *
+     * @exception IllegalArgumentException if the output encoding
+     *	is anything other than UTF-8.
+     */
+    final public void setCanonical (boolean value)
+    {
+	if (value && !"UTF-8".equals (encoding))
+	    throw new IllegalArgumentException ("encoding != UTF-8");
+	canonical = value;
+	if (canonical) {
+	    prettyPrinting = xhtml = false;
+	    expandingEntities = true;
+	    eol = "\n";
+	}
+    }
+
+
+    /**
+     * Returns value of flag controlling canonical output.
+     */
+    final public boolean isCanonical ()
+    {
+	return canonical;
+    }
+
+
+    /**
+     * Flushes the output stream.  When this handler is used in long lived
+     * pipelines, it can be important to flush buffered state, for example
+     * so that it can reach the disk as part of a state checkpoint.
+     */
+    final public void flush ()
+    throws IOException
+    {
+	if (out != null)
+	    out.flush ();
+    }
+
+
+    // convenience routines
+
+// FIXME:  probably want a subclass that holds a lot of these...
+// and maybe more!
+    
+    /**
+     * Writes the string as if characters() had been called on the contents
+     * of the string.  This is particularly useful when applications act as
+     * producers and write data directly to event consumers.
+     */
+    final public void write (String data)
+    throws SAXException
+    {
+	char	buf [] = data.toCharArray ();
+	characters (buf, 0, buf.length);
+    }
+
+
+    /**
+     * Writes an element that has content consisting of a single string.
+     * @see #writeEmptyElement
+     * @see #startElement
+     */
+    public void writeElement (
+	String uri,
+	String localName,
+	String qName,
+	Attributes atts,
+	String content
+    ) throws SAXException
+    {
+	if (content == null || content.length () == 0) {
+	    writeEmptyElement (uri, localName, qName, atts);
+	    return;
+	}
+	startElement (uri, localName, qName, atts);
+	char chars [] = content.toCharArray ();
+	characters (chars, 0, chars.length);
+	endElement (uri, localName, qName);
+    }
+
+
+    /**
+     * Writes an element that has content consisting of a single integer,
+     * encoded as a decimal string.
+     * @see #writeEmptyElement
+     * @see #startElement
+     */
+    public void writeElement (
+	String uri,
+	String localName,
+	String qName,
+	Attributes atts,
+	int content
+    ) throws SAXException
+    {
+	writeElement (uri, localName, qName, atts, Integer.toString (content));
+    }
+
+
+    // SAX1 ContentHandler
+    /** <b>SAX1</b>:  provides parser status information */
+    final public void setDocumentLocator (Locator l)
+    {
+	locator = l;
+    }
+
+
+    // URL for dtd that validates against all normal HTML constructs
+    private static final String xhtmlFullDTD =
+    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd";
+
+    
+    /**
+     * <b>SAX1</b>:  indicates the beginning of a document parse.
+     * If you're writing (well formed) fragments of XML, neither
+     * this nor endDocument should be called.
+     */
+    // NOT final
+    public void startDocument ()
+    throws SAXException
+    {
+	try {
+	    if (out == null)
+		throw new IllegalStateException (
+		    "null Writer given to XMLWriter");
+
+	    // Not all parsers provide the locator we want; this also
+	    // flags whether events are being sent to this object yet.
+	    // We could only have this one call if we only printed whole
+	    // documents ... but we also print fragments, so most of the
+	    // callbacks here replicate this test.
+
+	    if (locator == null)
+		locator = new LocatorImpl ();
+	    
+	    // Unless the data is in US-ASCII or we're canonicalizing, write
+	    // the XML declaration if we know the encoding.  US-ASCII won't
+	    // normally get mangled by web server confusion about the
+	    // character encodings used.  Plus, it's an easy way to
+	    // ensure we can write ASCII that's unlikely to confuse
+	    // elderly HTML parsers.
+
+	    if (!canonical
+		    && dangerMask != (short) 0xff80
+		    && encoding != null) {
+		rawWrite ("<?xml version='1.0'");
+		rawWrite (" encoding='" + encoding + "'");
+		rawWrite ("?>");
+		newline ();
+	    }
+
+	    if (xhtml) {
+
+		rawWrite ("<!DOCTYPE html PUBLIC");
+		newline ();
+		rawWrite ("  '-//W3C//DTD XHTML 1.0 Transitional//EN'");
+		newline ();
+		rawWrite ("  '");
+		    // NOTE:  URL (above) matches the REC
+		rawWrite (xhtmlFullDTD);
+		rawWrite ("'>");
+		newline ();
+		newline ();
+
+		// fake the rest of the handler into ignoring
+		// everything until the root element, so any
+		// XHTML DTD comments, PIs, etc are ignored
+		startedDoctype = true;
+	    }
+
+	    entityNestLevel = 0;
+
+	} catch (IOException e) {
+	    fatal ("can't write", e);
+	}
+    }
+
+    /**
+     * <b>SAX1</b>:  indicates the completion of a parse.
+     * Note that all complete SAX event streams make this call, even
+     * if an error is reported during a parse.
+     */
+    // NOT final
+    public void endDocument ()
+    throws SAXException
+    {
+	try {
+	    if (!canonical) {
+		newline ();
+		newline ();
+	    }
+	    out.close ();
+	    out = null;
+	    locator = null;
+	} catch (IOException e) {
+	    fatal ("can't write", e);
+	}
+    }
+
+    // XHTML elements declared as EMPTY print differently
+    final private static boolean isEmptyElementTag (String tag)
+    {
+	switch (tag.charAt (0)) {
+	  case 'a':	return "area".equals (tag);
+	  case 'b':	return "base".equals (tag)
+			    || "basefont".equals (tag)
+			    || "br".equals (tag);
+	  case 'c':	return "col".equals (tag);
+	  case 'f':	return "frame".equals (tag);
+	  case 'h':	return "hr".equals (tag);
+	  case 'i':	return "img".equals (tag)
+			    || "input".equals (tag)
+			    || "isindex".equals (tag);
+	  case 'l':	return "link".equals (tag);
+	  case 'm':	return "meta".equals (tag);
+	  case 'p':	return "param".equals (tag);
+	}
+	return false;
+    }
+
+    private static boolean indentBefore (String tag)
+    {
+	// basically indent before block content
+	// and within structure like tables, lists
+	switch (tag.charAt (0)) {
+	  case 'a':	return "applet".equals (tag);
+	  case 'b':	return "body".equals (tag)
+			    || "blockquote".equals (tag);
+	  case 'c':	return "center".equals (tag);
+	  case 'f':	return "frame".equals (tag)
+			    || "frameset".equals (tag);
+	  case 'h':	return "head".equals (tag);
+	  case 'm':	return "meta".equals (tag);
+	  case 'o':	return "object".equals (tag);
+	  case 'p':	return "param".equals (tag)
+			    || "pre".equals (tag);
+	  case 's':	return "style".equals (tag);
+	  case 't':	return "title".equals (tag)
+			    || "td".equals (tag)
+			    || "th".equals (tag);
+	}
+	// ... but not inline elements like "em", "b", "font"
+	return false;
+    }
+
+    private static boolean spaceBefore (String tag)
+    {
+	// blank line AND INDENT before certain structural content
+	switch (tag.charAt (0)) {
+	  case 'h':	return "h1".equals (tag)
+			    || "h2".equals (tag)
+			    || "h3".equals (tag)
+			    || "h4".equals (tag)
+			    || "h5".equals (tag)
+			    || "h6".equals (tag)
+			    || "hr".equals (tag);
+	  case 'l':	return "li".equals (tag);
+	  case 'o':	return "ol".equals (tag);
+	  case 'p':	return "p".equals (tag);
+	  case 't':	return "table".equals (tag)
+			    || "tr".equals (tag);
+	  case 'u':	return "ul".equals (tag);
+	}
+	return false;
+    }
+
+    // XHTML DTDs say these three have xml:space="preserve"
+    private static boolean spacePreserve (String tag)
+    {
+	return "pre".equals (tag)
+		|| "style".equals (tag)
+		|| "script".equals (tag);
+    }
+
+    /**
+     * <b>SAX2</b>:  ignored.
+     */
+    final public void startPrefixMapping (String prefix, String uri)
+	{}
+
+    /**
+     * <b>SAX2</b>:  ignored.
+     */
+    final public void endPrefixMapping (String prefix)
+	{}
+
+    private void writeStartTag (
+	String name,
+	Attributes atts,
+	boolean isEmpty
+    ) throws SAXException, IOException
+    {
+	rawWrite ('<');
+	rawWrite (name);
+
+	// write out attributes ... sorting is particularly useful
+	// with output that's been heavily defaulted.
+	if (atts != null && atts.getLength () != 0) {
+
+	    // Set up to write, with optional sorting
+	    int 	indices [] = new int [atts.getLength ()];
+
+	    for (int i= 0; i < indices.length; i++)
+		indices [i] = i;
+	    
+	    // optionally sort
+
+// FIXME:  canon xml demands xmlns nodes go first,
+// and sorting by URI first (empty first) then localname
+// it should maybe use a different sort
+
+	    if (canonical || prettyPrinting) {
+
+		// insertion sort by attribute name
+		for (int i = 1; i < indices.length; i++) {
+		    int	n = indices [i], j;
+		    String	s = atts.getQName (n);
+
+		    for (j = i - 1; j >= 0; j--) {
+			if (s.compareTo (atts.getQName (indices [j]))
+				>= 0)
+			    break;
+			indices [j + 1] = indices [j];
+		    }
+		    indices [j + 1] = n;
+		}
+	    }
+
+	    // write, sorted or no
+	    for (int i= 0; i < indices.length; i++) {
+		String	s = atts.getQName (indices [i]);
+
+		    if (s == null || "".equals (s))
+			throw new IllegalArgumentException ("no XML name");
+		rawWrite (" ");
+		rawWrite (s);
+		rawWrite ("=");
+		writeQuotedValue (atts.getValue (indices [i]),
+		    CTX_ATTRIBUTE);
+	    }
+	}
+	if (isEmpty)
+	    rawWrite (" /");
+	rawWrite ('>');
+    }
+
+    /**
+     * <b>SAX2</b>:  indicates the start of an element.
+     * When XHTML is in use, avoid attribute values with
+     * line breaks or multiple whitespace characters, since
+     * not all user agents handle them correctly.
+     */
+    final public void startElement (
+	String uri,
+	String localName,
+	String qName,
+	Attributes atts
+    ) throws SAXException
+    {
+	startedDoctype = false;
+
+	if (locator == null)
+	    locator = new LocatorImpl ();
+	    
+	if (qName == null || "".equals (qName))
+	    throw new IllegalArgumentException ("no XML name");
+
+	try {
+	    if (entityNestLevel != 0)
+		return;
+	    if (prettyPrinting) {
+		String whitespace = null;
+
+		if (xhtml && spacePreserve (qName))
+		    whitespace = "preserve";
+		else if (atts != null)
+		    whitespace = atts.getValue ("xml:space");
+		if (whitespace == null)
+		    whitespace = (String) space.peek ();
+		space.push (whitespace);
+
+		if ("default".equals (whitespace)) {
+		    if (xhtml) {
+			if (spaceBefore (qName)) {
+			    newline ();
+			    doIndent ();
+			} else if (indentBefore (qName))
+			    doIndent ();
+			// else it's inlined, modulo line length
+			// FIXME: incrementing element nest level
+			// for inlined elements causes ugliness
+		    } else
+			doIndent ();
+		}
+	    }
+	    elementNestLevel++;
+	    writeStartTag (qName, atts, xhtml && isEmptyElementTag (qName));
+
+	    if (xhtml) {
+// FIXME: if this is an XHTML "pre" element, turn
+// off automatic wrapping.
+	    }
+
+	} catch (IOException e) {
+	    fatal ("can't write", e);
+	}
+    }
+
+    /**
+     * Writes an empty element.
+     * @see #startElement
+     */
+    public void writeEmptyElement (
+	String uri,
+	String localName,
+	String qName,
+	Attributes atts
+    ) throws SAXException
+    {
+	if (canonical) {
+	    startElement (uri, localName, qName, atts);
+	    endElement (uri, localName, qName);
+	} else {
+	    try {
+		writeStartTag (qName, atts, true);
+	    } catch (IOException e) {
+		fatal ("can't write", e);
+	    }
+	}
+    }
+
+
+    /** <b>SAX2</b>:  indicates the end of an element */
+    final public void endElement (String uri, String localName, String qName)
+    throws SAXException
+    {
+	if (qName == null || "".equals (qName))
+	    throw new IllegalArgumentException ("no XML name");
+
+	try {
+	    elementNestLevel--;
+	    if (entityNestLevel != 0)
+		return;
+	    if (xhtml && isEmptyElementTag (qName))
+		return;
+	    rawWrite ("</");
+	    rawWrite (qName);
+	    rawWrite ('>');
+
+	    if (prettyPrinting) {
+		if (!space.empty ())
+		    space.pop ();
+		else
+		    fatal ("stack discipline", null);
+	    }
+	    if (elementNestLevel == 0)
+		inEpilogue = true;
+
+	} catch (IOException e) {
+	    fatal ("can't write", e);
+	}
+    }
+
+    /** <b>SAX1</b>:  reports content characters */
+    final public void characters (char ch [], int start, int length)
+    throws SAXException
+    {
+	if (locator == null)
+	    locator = new LocatorImpl ();
+
+	try {
+	    if (entityNestLevel != 0)
+		return;
+	    if (inCDATA) {
+		escapeChars (ch, start, length, CTX_UNPARSED);
+	    } else {
+		escapeChars (ch, start, length, CTX_CONTENT);
+	    }
+	} catch (IOException e) {
+	    fatal ("can't write", e);
+	}
+    }
+
+    /** <b>SAX1</b>:  reports ignorable whitespace */
+    final public void ignorableWhitespace (char ch [], int start, int length)
+    throws SAXException
+    {
+	if (locator == null)
+	    locator = new LocatorImpl ();
+
+	try {
+	    if (entityNestLevel != 0)
+		return;
+	    // don't forget to map NL to CRLF, CR, etc
+	    escapeChars (ch, start, length, CTX_CONTENT);
+	} catch (IOException e) {
+	    fatal ("can't write", e);
+	}
+    }
+
+    /**
+     * <b>SAX1</b>:  reports a PI.
+     * This doesn't check for illegal target names, such as "xml" or "XML",
+     * or namespace-incompatible ones like "big:dog"; the caller is
+     * responsible for ensuring those names are legal.
+     */
+    final public void processingInstruction (String target, String data)
+    throws SAXException
+    {
+	if (locator == null)
+	    locator = new LocatorImpl ();
+
+	// don't print internal subset for XHTML
+	if (xhtml && startedDoctype)
+	    return;
+
+	// ancient HTML browsers might render these ... their loss.
+	// to prevent:  "if (xhtml) return;".
+
+	try {
+	    if (entityNestLevel != 0)
+		return;
+	    if (canonical && inEpilogue)
+		newline ();
+	    rawWrite ("<?");
+	    rawWrite (target);
+	    rawWrite (' ');
+	    escapeChars (data.toCharArray (), -1, -1, CTX_UNPARSED);
+	    rawWrite ("?>");
+	    if (elementNestLevel == 0 && !(canonical && inEpilogue))
+		newline ();
+	} catch (IOException e) {
+	    fatal ("can't write", e);
+	}
+    }
+
+    /** <b>SAX1</b>: indicates a non-expanded entity reference */
+    public void skippedEntity (String name)
+    throws SAXException
+    {
+	try {
+	    rawWrite ("&");
+	    rawWrite (name);
+	    rawWrite (";");
+	} catch (IOException e) {
+	    fatal ("can't write", e);
+	}
+    }
+
+    // SAX2 LexicalHandler
+
+    /** <b>SAX2</b>:  called before parsing CDATA characters */
+    final public void startCDATA ()
+    throws SAXException
+    {
+	if (locator == null)
+	    locator = new LocatorImpl ();
+	
+	if (canonical)
+	    return;
+
+	try {
+	    inCDATA = true;
+	    if (entityNestLevel == 0)
+		rawWrite ("<![CDATA[");
+	} catch (IOException e) {
+	    fatal ("can't write", e);
+	}
+    }
+
+    /** <b>SAX2</b>:  called after parsing CDATA characters */
+    final public void endCDATA ()
+    throws SAXException
+    {
+	if (canonical)
+	    return;
+
+	try {
+	    inCDATA = false;
+	    if (entityNestLevel == 0)
+		rawWrite ("]]>");
+	} catch (IOException e) {
+	    fatal ("can't write", e);
+	}
+    }
+
+    /**
+     * <b>SAX2</b>:  called when the doctype is partially parsed
+     * Note that this, like other doctype related calls, is ignored
+     * when XHTML is in use.
+     */
+    final public void startDTD (String name, String publicId, String systemId)
+    throws SAXException
+    {
+	if (locator == null)
+	    locator = new LocatorImpl ();
+	if (xhtml)
+	    return;
+	try {
+	    inDoctype = startedDoctype = true;
+	    if (canonical)
+		return;
+	    rawWrite ("<!DOCTYPE ");
+	    rawWrite (name);
+	    rawWrite (' ');
+
+	    if (!expandingEntities) {
+		if (publicId != null)
+		    rawWrite ("PUBLIC '" + publicId + "' '" + systemId + "' ");
+		else if (systemId != null)
+		    rawWrite ("SYSTEM '" + systemId + "' ");
+	    }
+
+	    rawWrite ('[');
+	    newline ();
+	} catch (IOException e) {
+	    fatal ("can't write", e);
+	}
+    }
+
+    /** <b>SAX2</b>:  called after the doctype is parsed */
+    final public void endDTD ()
+    throws SAXException
+    {
+	inDoctype = false;
+	if (canonical || xhtml)
+	    return;
+	try {
+	    rawWrite ("]>");
+	    newline ();
+	} catch (IOException e) {
+	    fatal ("can't write", e);
+	}
+    }
+
+    /**
+     * <b>SAX2</b>:  called before parsing a general entity in content
+     */
+    final public void startEntity (String name)
+    throws SAXException
+    {
+	try {
+	    boolean	writeEOL = true;
+
+	    // Predefined XHTML entities (for characters) will get
+	    // mapped back later.
+	    if (xhtml || expandingEntities)
+		return;
+
+	    entityNestLevel++;
+	    if (name.equals ("[dtd]"))
+		return;
+	    if (entityNestLevel != 1)
+		return;
+	    if (!name.startsWith ("%")) {
+		writeEOL = false;
+		rawWrite ('&');
+	    }
+	    rawWrite (name);
+	    rawWrite (';');
+	    if (writeEOL)
+		newline ();
+	} catch (IOException e) {
+	    fatal ("can't write", e);
+	}
+    }
+
+    /**
+     * <b>SAX2</b>:  called after parsing a general entity in content
+     */
+    final public void endEntity (String name)
+    throws SAXException
+    {
+	if (xhtml || expandingEntities)
+	    return;
+	entityNestLevel--;
+    }
+
+    /**
+     * <b>SAX2</b>:  called when comments are parsed.
+     * When XHTML is used, the old HTML tradition of using comments
+     * to for inline CSS, or for JavaScript code is  discouraged.
+     * This is because XML processors are encouraged to discard, on
+     * the grounds that comments are for users (and perhaps text
+     * editors) not programs.  Instead, use external scripts
+     */
+    final public void comment (char ch [], int start, int length)
+    throws SAXException
+    {
+	if (locator == null)
+	    locator = new LocatorImpl ();
+
+	// don't print internal subset for XHTML
+	if (xhtml && startedDoctype)
+	    return;
+	// don't print comment in doctype for canon xml
+	if (canonical && inDoctype)
+	    return;
+
+	try {
+	    boolean indent;
+
+	    if (prettyPrinting && space.empty ())
+		fatal ("stack discipline", null);
+	    indent = prettyPrinting && "default".equals (space.peek ());
+	    if (entityNestLevel != 0)
+		return;
+	    if (indent)
+		doIndent ();
+	    if (canonical && inEpilogue)
+		newline ();
+	    rawWrite ("<!--");
+	    escapeChars (ch, start, length, CTX_UNPARSED);
+	    rawWrite ("-->");
+	    if (indent)
+		doIndent ();
+	    if (elementNestLevel == 0 && !(canonical && inEpilogue))
+		newline ();
+	} catch (IOException e) {
+	    fatal ("can't write", e);
+	}
+    }
+
+    // SAX1 DTDHandler
+
+    /** <b>SAX1</b>:  called on notation declarations */
+    final public void notationDecl (String name,
+    	String publicId, String systemId)
+    throws SAXException
+    {
+	if (xhtml)
+	    return;
+	try {
+	    // At this time, only SAX2 callbacks start these.
+	    if (!startedDoctype)
+		return;
+
+	    if (entityNestLevel != 0)
+		return;
+	    rawWrite ("<!NOTATION " + name + " ");
+	    if (publicId != null)
+		rawWrite ("PUBLIC \"" + publicId + '"');
+	    else
+		rawWrite ("SYSTEM ");
+	    if (systemId != null)
+		rawWrite ('"' + systemId + '"');
+	    rawWrite (">");
+	    newline ();
+	} catch (IOException e) {
+	    fatal ("can't write", e);
+	}
+    }
+
+    /** <b>SAX1</b>:  called on unparsed entity declarations */
+    final public void unparsedEntityDecl (String name,
+	String publicId, String systemId,
+	String notationName)
+    throws SAXException
+    {
+	if (xhtml)
+	    return;
+	try {
+	    // At this time, only SAX2 callbacks start these.
+	    if (!startedDoctype)  {
+		// FIXME: write to temporary buffer, and make the start
+		// of the root element write these declarations.
+		return;
+	    }
+
+	    if (entityNestLevel != 0)
+		return;
+	    rawWrite ("<!ENTITY " + name + " ");
+	    if (publicId != null)
+		rawWrite ("PUBLIC \"" + publicId + '"');
+	    else
+		rawWrite ("SYSTEM ");
+	    rawWrite ('"' + systemId + '"');
+	    rawWrite (" NDATA " + notationName + ">");
+	    newline ();
+	} catch (IOException e) {
+	    fatal ("can't write", e);
+	}
+    }
+
+    // SAX2 DeclHandler
+
+    /** <b>SAX2</b>:  called on attribute declarations */
+    final public void attributeDecl (String eName, String aName,
+	    String type, String mode, String value)
+    throws SAXException
+    {
+	if (xhtml)
+	    return;
+	try {
+	    // At this time, only SAX2 callbacks start these.
+	    if (!startedDoctype)
+		return;
+	    if (entityNestLevel != 0)
+		return;
+	    rawWrite ("<!ATTLIST " + eName + ' ' + aName + ' ');
+	    rawWrite (type);
+	    rawWrite (' ');
+	    if (mode != null)
+		rawWrite (mode + ' ');
+	    if (value != null) 
+		writeQuotedValue (value, CTX_ATTRIBUTE);
+	    rawWrite ('>');
+	    newline ();
+	} catch (IOException e) {
+	    fatal ("can't write", e);
+	}
+    }
+
+    /** <b>SAX2</b>:  called on element declarations */
+    final public void elementDecl (String name, String model)
+    throws SAXException
+    {
+	if (xhtml)
+	    return;
+	try {
+	    // At this time, only SAX2 callbacks start these.
+	    if (!startedDoctype)
+		return;
+	    if (entityNestLevel != 0)
+		return;
+	    rawWrite ("<!ELEMENT " + name + ' ' + model + '>');
+	    newline ();
+	} catch (IOException e) {
+	    fatal ("can't write", e);
+	}
+    }
+
+    /** <b>SAX2</b>:  called on external entity declarations */
+    final public void externalEntityDecl (
+	String name,
+	String publicId,
+	String systemId)
+    throws SAXException
+    {
+	if (xhtml)
+	    return;
+	try {
+	    // At this time, only SAX2 callbacks start these.
+	    if (!startedDoctype)
+		return;
+	    if (entityNestLevel != 0)
+		return;
+	    rawWrite ("<!ENTITY ");
+	    if (name.startsWith ("%")) {
+		rawWrite ("% ");
+		rawWrite (name.substring (1));
+	    } else
+		rawWrite (name);
+	    if (publicId != null)
+		rawWrite (" PUBLIC \"" + publicId + '"');
+	    else
+		rawWrite (" SYSTEM ");
+	    rawWrite ('"' + systemId + "\">");
+	    newline ();
+	} catch (IOException e) {
+	    fatal ("can't write", e);
+	}
+    }
+
+    /** <b>SAX2</b>:  called on internal entity declarations */
+    final public void internalEntityDecl (String name, String value)
+    throws SAXException
+    {
+	if (xhtml)
+	    return;
+	try {
+	    // At this time, only SAX2 callbacks start these.
+	    if (!startedDoctype)
+		return;
+	    if (entityNestLevel != 0)
+		return;
+	    rawWrite ("<!ENTITY ");
+	    if (name.startsWith ("%")) {
+		rawWrite ("% ");
+		rawWrite (name.substring (1));
+	    } else
+		rawWrite (name);
+	    rawWrite (' ');
+	    writeQuotedValue (value, CTX_ENTITY);
+	    rawWrite ('>');
+	    newline ();
+	} catch (IOException e) {
+	    fatal ("can't write", e);
+	}
+    }
+
+    private void writeQuotedValue (String value, int code)
+    throws SAXException, IOException
+    {
+	char	buf [] = value.toCharArray ();
+	int	off = 0, len = buf.length;
+
+	// we can't add line breaks to attribute/entity/... values
+	noWrap = true;
+	rawWrite ('"');
+	escapeChars (buf, off, len, code);
+	rawWrite ('"');
+	noWrap = false;
+    }
+    
+    // From "HTMLlat1x.ent" ... names of entities for ISO-8859-1
+    // (Latin/1) characters, all codes:  160-255 (0xA0-0xFF).
+    // Codes 128-159 have no assigned values.
+    private static final String HTMLlat1x [] = {
+	// 160
+	"nbsp", "iexcl", "cent", "pound", "curren",
+	"yen", "brvbar", "sect", "uml", "copy",
+
+	// 170
+	"ordf", "laquo", "not", "shy", "reg",
+	"macr", "deg", "plusmn", "sup2", "sup3",
+
+	// 180
+	"acute", "micro", "para", "middot", "cedil",
+	"sup1", "ordm", "raquo", "frac14", "frac12",
+
+	// 190
+	"frac34", "iquest", "Agrave", "Aacute", "Acirc",
+	"Atilde", "Auml", "Aring", "AElig", "Ccedil",
+
+	// 200
+	"Egrave", "Eacute", "Ecirc", "Euml", "Igrave",
+	"Iacute", "Icirc", "Iuml", "ETH", "Ntilde",
+
+	// 210
+	"Ograve", "Oacute", "Ocirc", "Otilde", "Ouml",
+	"times", "Oslash", "Ugrave", "Uacute", "Ucirc",
+
+	// 220
+	"Uuml", "Yacute", "THORN", "szlig", "agrave",
+	"aacute", "acirc", "atilde", "auml", "aring",
+
+	// 230
+	"aelig", "ccedil", "egrave", "eacute", "ecirc",
+	"euml", "igrave", "iacute", "icirc", "iuml",
+
+	// 240
+	"eth", "ntilde", "ograve", "oacute", "ocirc",
+	"otilde", "ouml", "divide", "oslash", "ugrave",
+
+	// 250
+	"uacute", "ucirc", "uuml", "yacute", "thorn",
+	"yuml"
+    };
+
+    // From "HTMLsymbolx.ent" ... some of the symbols that
+    // we can conveniently handle.  Entities for the Greek.
+    // alphabet (upper and lower cases) are compact.
+    private static final String HTMLsymbolx_GR [] = {
+	// 913
+	"Alpha", "Beta", "Gamma", "Delta", "Epsilon",
+	"Zeta", "Eta", "Theta", "Iota", "Kappa",
+
+	// 923
+	"Lambda", "Mu", "Nu", "Xi", "Omicron",
+	"Pi", "Rho", null, "Sigma", "Tau",
+
+	// 933
+	"Upsilon", "Phi", "Chi", "Psi", "Omega"
+    };
+
+    private static final String HTMLsymbolx_gr [] = {
+	// 945
+	"alpha", "beta", "gamma", "delta", "epsilon",
+	"zeta", "eta", "theta", "iota", "kappa",
+
+	// 955
+	"lambda", "mu", "nu", "xi", "omicron",
+	"pi", "rho", "sigmaf", "sigma", "tau",
+
+	// 965
+	"upsilon", "phi", "chi", "psi", "omega"
+    };
+
+
+    // General routine to write text and substitute predefined
+    // entities (XML, and a special case for XHTML) as needed.
+    private void escapeChars (char buf [], int off, int len, int code)
+    throws SAXException, IOException
+    {
+	int	first = 0;
+
+	if (off < 0) {
+	    off = 0;
+	    len = buf.length;
+	}
+	for (int i = 0; i < len; i++) {
+	    String	esc;
+	    char 	c = buf [off + i];
+
+	    switch (c) {
+	      // Note that CTX_ATTRIBUTE isn't explicitly tested here;
+	      // all syntax delimiters are escaped in CTX_ATTRIBUTE,
+	      // otherwise it's similar to CTX_CONTENT
+
+	      // ampersand flags entity references; entity replacement
+	      // text has unexpanded references, other text doesn't.
+	      case '&':
+		if (code == CTX_ENTITY || code == CTX_UNPARSED)
+		    continue;
+		esc = "amp";
+		break;
+
+	      // attributes and text may NOT have literal '<', but
+	      // entities may have markup constructs
+	      case '<':
+		if (code == CTX_ENTITY || code == CTX_UNPARSED)
+		    continue;
+		esc = "lt";
+		break;
+
+	      // as above re markup constructs; but otherwise
+	      // except when canonicalizing, this is for consistency
+	      case '>':
+		if (code == CTX_ENTITY || code == CTX_UNPARSED)
+		    continue;
+	        esc = "gt";
+		break;
+	      case '\'':
+		if (code == CTX_CONTENT || code == CTX_UNPARSED)
+		    continue;
+		if (canonical)
+		    continue;
+		esc = "apos";
+		break;
+
+	      // needed when printing quoted attribute/entity values
+	      case '"':
+		if (code == CTX_CONTENT || code == CTX_UNPARSED)
+		    continue;
+		esc = "quot";
+		break;
+
+	      // make line ends work per host OS convention
+	      case '\n':
+		esc = eol;
+		break;
+
+	      //
+	      // No other characters NEED special treatment ... except
+	      // for encoding-specific issues, like whether the character
+	      // can really be represented in that encoding.
+	      //
+	      default:
+		//
+		// There are characters we can never write safely; getting
+		// them is an error.
+		//
+		//   (a) They're never legal in XML ... detected by range 
+		//	checks, and (eventually) by remerging surrogate
+		//	pairs on output.  (Easy error for apps to prevent.)
+		//
+		//   (b) This encoding can't represent them, and we
+		//	can't make reference substitution (e.g. inside
+		//	CDATA sections, names, PI data, etc).  (Hard for
+		//	apps to prevent, except by using UTF-8 or UTF-16
+		//	as their output encoding.)
+		//
+		// We know a very little bit about what characters
+		// the US-ASCII and ISO-8859-1 encodings support.  For
+		// other encodings we can't detect the second type of
+		// error at all.  (Never an issue for UTF-8 or UTF-16.)
+		//
+
+// FIXME:  CR in CDATA is an error; in text, turn to a char ref
+
+// FIXME:  CR/LF/TAB in attributes should become char refs
+
+		if ((c > 0xfffd)
+			|| ((c < 0x0020) && !((c == 0x0009)
+				|| (c == 0x000A) || (c == 0x000D)))
+			|| (((c & dangerMask) != 0)
+			    && (code == CTX_UNPARSED))) {
+
+		    // if case (b) in CDATA, we might end the section,
+		    // write a reference, then restart ... possible
+		    // in one DOM L3 draft.
+
+		    throw new CharConversionException (
+			    "Illegal or non-writable character: U+"
+			    + Integer.toHexString (c));
+		}
+
+		//
+		// If the output encoding represents the character
+		// directly, let it do so!  Else we'll escape it.
+		//
+		if ((c & dangerMask) == 0)
+		    continue;
+		esc = null;
+
+		// Avoid numeric refs where symbolic ones exist, as
+		// symbolic ones make more sense to humans reading!
+		if (xhtml) {
+		    // all the HTMLlat1x.ent entities
+		    // (all the "ISO-8859-1" characters)
+		    if (c >= 160 && c <= 255)
+			esc = HTMLlat1x [c - 160];
+
+		    // not quite half the HTMLsymbolx.ent entities
+		    else if (c >= 913 && c <= 937)
+			esc = HTMLsymbolx_GR [c - 913];
+		    else if (c >= 945 && c <= 969)
+			esc = HTMLsymbolx_gr [c - 945];
+
+		    else switch (c) {
+			// all of the HTMLspecialx.ent entities
+			case  338: esc = "OElig";	break;
+			case  339: esc = "oelig";	break;
+			case  352: esc = "Scaron";	break;
+			case  353: esc = "scaron";	break;
+			case  376: esc = "Yuml";	break;
+			case  710: esc = "circ";	break;
+			case  732: esc = "tilde";	break;
+			case 8194: esc = "ensp";	break;
+			case 8195: esc = "emsp";	break;
+			case 8201: esc = "thinsp";	break;
+			case 8204: esc = "zwnj";	break;
+			case 8205: esc = "zwj";		break;
+			case 8206: esc = "lrm";		break;
+			case 8207: esc = "rlm";		break;
+			case 8211: esc = "ndash";	break;
+			case 8212: esc = "mdash";	break;
+			case 8216: esc = "lsquo";	break;
+			case 8217: esc = "rsquo";	break;
+			case 8218: esc = "sbquo";	break;
+			case 8220: esc = "ldquo";	break;
+			case 8221: esc = "rdquo";	break;
+			case 8222: esc = "bdquo";	break;
+			case 8224: esc = "dagger";	break;
+			case 8225: esc = "Dagger";	break;
+			case 8240: esc = "permil";	break;
+			case 8249: esc = "lsaquo";	break;
+			case 8250: esc = "rsaquo";	break;
+			case 8364: esc = "euro";	break;
+
+			// the other HTMLsymbox.ent entities
+			case  402: esc = "fnof";	break;
+			case  977: esc = "thetasym";	break;
+			case  978: esc = "upsih";	break;
+			case  982: esc = "piv";		break;
+			case 8226: esc = "bull";	break;
+			case 8230: esc = "hellip";	break;
+			case 8242: esc = "prime";	break;
+			case 8243: esc = "Prime";	break;
+			case 8254: esc = "oline";	break;
+			case 8260: esc = "frasl";	break;
+			case 8472: esc = "weierp";	break;
+			case 8465: esc = "image";	break;
+			case 8476: esc = "real";	break;
+			case 8482: esc = "trade";	break;
+			case 8501: esc = "alefsym";	break;
+			case 8592: esc = "larr";	break;
+			case 8593: esc = "uarr";	break;
+			case 8594: esc = "rarr";	break;
+			case 8595: esc = "darr";	break;
+			case 8596: esc = "harr";	break;
+			case 8629: esc = "crarr";	break;
+			case 8656: esc = "lArr";	break;
+			case 8657: esc = "uArr";	break;
+			case 8658: esc = "rArr";	break;
+			case 8659: esc = "dArr";	break;
+			case 8660: esc = "hArr";	break;
+			case 8704: esc = "forall";	break;
+			case 8706: esc = "part";	break;
+			case 8707: esc = "exist";	break;
+			case 8709: esc = "empty";	break;
+			case 8711: esc = "nabla";	break;
+			case 8712: esc = "isin";	break;
+			case 8713: esc = "notin";	break;
+			case 8715: esc = "ni";		break;
+			case 8719: esc = "prod";	break;
+			case 8721: esc = "sum";		break;
+			case 8722: esc = "minus";	break;
+			case 8727: esc = "lowast";	break;
+			case 8730: esc = "radic";	break;
+			case 8733: esc = "prop";	break;
+			case 8734: esc = "infin";	break;
+			case 8736: esc = "ang";		break;
+			case 8743: esc = "and";		break;
+			case 8744: esc = "or";		break;
+			case 8745: esc = "cap";		break;
+			case 8746: esc = "cup";		break;
+			case 8747: esc = "int";		break;
+			case 8756: esc = "there4";	break;
+			case 8764: esc = "sim";		break;
+			case 8773: esc = "cong";	break;
+			case 8776: esc = "asymp";	break;
+			case 8800: esc = "ne";		break;
+			case 8801: esc = "equiv";	break;
+			case 8804: esc = "le";		break;
+			case 8805: esc = "ge";		break;
+			case 8834: esc = "sub";		break;
+			case 8835: esc = "sup";		break;
+			case 8836: esc = "nsub";	break;
+			case 8838: esc = "sube";	break;
+			case 8839: esc = "supe";	break;
+			case 8853: esc = "oplus";	break;
+			case 8855: esc = "otimes";	break;
+			case 8869: esc = "perp";	break;
+			case 8901: esc = "sdot";	break;
+			case 8968: esc = "lceil";	break;
+			case 8969: esc = "rceil";	break;
+			case 8970: esc = "lfloor";	break;
+			case 8971: esc = "rfloor";	break;
+			case 9001: esc = "lang";	break;
+			case 9002: esc = "rang";	break;
+			case 9674: esc = "loz";		break;
+			case 9824: esc = "spades";	break;
+			case 9827: esc = "clubs";	break;
+			case 9829: esc = "hearts";	break;
+			case 9830: esc = "diams";	break;
+		    }
+		}
+
+		// else escape with numeric char refs
+		if (esc == null) {
+		    stringBuf.setLength (0);
+		    stringBuf.append ("#x");
+		    stringBuf.append (Integer.toHexString (c).toUpperCase ());
+		    esc = stringBuf.toString ();
+
+		    // FIXME:  We don't write surrogate pairs correctly.
+		    // They should work as one ref per character, since
+		    // each pair is one character.  For reading back into
+		    // Unicode, it matters beginning in Unicode 3.1 ...
+		}
+		break;
+	    }
+	    if (i != first)
+		rawWrite (buf, off + first, i - first);
+	    first = i + 1;
+	    if (esc == eol)
+		newline ();
+	    else {
+		rawWrite ('&');
+		rawWrite (esc);
+		rawWrite (';');
+	    }
+	}
+	if (first < len)
+	    rawWrite (buf, off + first, len - first);
+    }
+
+
+
+    private void newline ()
+    throws SAXException, IOException
+    {
+	out.write (eol);
+	column = 0;
+    }
+
+    private void doIndent ()
+    throws SAXException, IOException
+    {
+	int	space = elementNestLevel * 2;
+
+	newline ();
+	column = space;
+	// track tabs only at line starts
+	while (space > 8) {
+	    out.write ("\t");
+	    space -= 8;
+	}
+	while (space > 0) {
+	    out.write ("  ");
+	    space -= 2;
+	}
+    }
+
+    private void rawWrite (char c)
+    throws IOException
+    {
+	out.write (c);
+	column++;
+    }
+
+    private void rawWrite (String s)
+    throws SAXException, IOException
+    {
+	if (prettyPrinting && "default".equals (space.peek ())) {
+	    char data [] = s.toCharArray ();
+	    rawWrite (data, 0, data.length);
+	} else {
+	    out.write (s);
+	    column += s.length ();
+	}
+    }
+
+    // NOTE:  if xhtml, the REC gives some rules about whitespace
+    // which we could follow ... notably, many places where conformant
+    // agents "must" consolidate/normalize whitespace.  Line ends can
+    // be removed there, etc.  This may not be the right place to do
+    // such mappings though.
+
+    // Line buffering may help clarify algorithms and improve results.
+
+    // It's likely xml:space needs more attention.
+
+    private void rawWrite (char buf [], int offset, int length)
+    throws SAXException, IOException
+    {
+	boolean		wrap;
+
+	if (prettyPrinting && space.empty ())
+	    fatal ("stack discipline", null);
+
+	wrap = prettyPrinting && "default".equals (space.peek ());
+	if (!wrap) {
+	    out.write (buf, offset, length);
+	    column += length;
+	    return;
+	}
+
+	// we're pretty printing and want to fill lines out only
+	// to the desired line length.
+	while (length > 0) {
+	    int		target = lineLength - column;
+	    boolean	wrote = false;
+
+	    // Do we even have a problem?
+	    if (target > length || noWrap) {
+		out.write (buf, offset, length);
+		column += length;
+		return;
+	    }
+
+	    // break the line at a space character, trying to fill
+	    // as much of the line as possible.
+	    char	c;
+
+	    for (int i = target - 1; i >= 0; i--) {
+		if ((c = buf [offset + i]) == ' ' || c == '\t') {
+		    i++;
+		    out.write (buf, offset, i);
+		    doIndent ();
+		    offset += i;
+		    length -= i;
+		    wrote = true;
+		    break;
+		}
+	    }
+	    if (wrote)
+		continue;
+	    
+	    // no space character permitting break before target
+	    // line length is filled.  So, take the next one.
+	    if (target < 0)
+		target = 0;
+	    for (int i = target; i < length; i++)
+		if ((c = buf [offset + i]) == ' ' || c == '\t') {
+		    i++;
+		    out.write (buf, offset, i);
+		    doIndent ();
+		    offset += i;
+		    length -= i;
+		    wrote = true;
+		    break;
+		}
+	    if (wrote)
+		continue;
+	    
+	    // no such luck.
+	    out.write (buf, offset, length);
+	    column += length;
+	    break;
+	}
+    }
+}

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/util/package.html
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/util/package.html?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/util/package.html (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/util/package.html Thu Nov  8 16:56:19 2007
@@ -0,0 +1,20 @@
+<!DOCTYPE html PUBLIC
+    "-//W3C//DTD XHTML 1.0 Transitional//EN"
+    "http://www.w3.org/TR/1999/PR-xhtml1-19991210/DTD/xhtml1-transitional.dtd">
+
+<html><head><title> org.brownell.xml package </title> </head>
+<!--
+/*
+ * Copyright (C) 1999,2000 The Free Software Foundation, Inc.
+ */
+-->
+<body>
+    <p> This package contains XML utilities, including SAX2 XML writers
+    and a parser of DOM trees, plus a command line driver.
+    That <a href="DoParse.html">driver</a>
+    connects parsers simple processing pipelines.
+    It can be handy for command line validation or
+    transformation tasks, possibly in batch mode,
+    or within Makefiles. </p>
+
+</body></html>

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/Annotation.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/Annotation.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/Annotation.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/Annotation.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,61 @@
+/* Annotation.java -- 
+   Copyright (C) 2006  Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.xml.validation.datatype;
+
+/**
+ * A schema component annotation.
+ *
+ * @author <a href='mailto:dog at gnu.org'>Chris Burdess</a>
+ */
+public class Annotation
+{
+
+  public final String documentation;
+
+  public Annotation(String documentation)
+  {
+    this.documentation = documentation;
+  }
+
+  public String toString()
+  {
+    return documentation;
+  }
+  
+}
+

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/AnySimpleType.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/AnySimpleType.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/AnySimpleType.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/AnySimpleType.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,59 @@
+/* AnySimpleType.java -- 
+   Copyright (C) 2006  Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.xml.validation.datatype;
+
+import java.util.Set;
+import javax.xml.XMLConstants;
+import javax.xml.namespace.QName;
+
+final class AnySimpleType
+  extends SimpleType
+{
+  
+  AnySimpleType()
+  {
+    super(new QName(XMLConstants.W3C_XML_SCHEMA_NS_URI, "anySimpleType"),
+          ANY, /* variety */
+          (Set) null, /* facets */
+          0, /* fundametalFacets */
+          (SimpleType) Type.ANY_TYPE, /* baseType */
+          null);
+  }
+
+}
+

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/AnyType.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/AnyType.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/AnyType.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/AnyType.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,58 @@
+/* AnyType.java -- 
+   Copyright (C) 2006  Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.xml.validation.datatype;
+
+import javax.xml.XMLConstants;
+import javax.xml.namespace.QName;
+
+final class AnyType
+  extends SimpleType
+{
+  
+  AnyType()
+  {
+    super(new QName(XMLConstants.W3C_XML_SCHEMA_NS_URI, "anyType"),
+          ANY, /* variety */
+          null, /* facets */
+          0, /* fundamentalFacets */
+          null, /* baseType */
+          null);
+  }
+
+}
+

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/AnyURIType.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/AnyURIType.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/AnyURIType.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/AnyURIType.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,94 @@
+/* AnyURIType.java -- 
+   Copyright (C) 2006  Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.xml.validation.datatype;
+
+import java.net.URI;
+import java.net.URISyntaxException;
+import javax.xml.XMLConstants;
+import javax.xml.namespace.QName;
+import org.relaxng.datatype.DatatypeException;
+import org.relaxng.datatype.ValidationContext;
+
+/**
+ * The XML Schema anyURI type.
+ *
+ * @author <a href='mailto:dog at gnu.org'>Chris Burdess</a>
+ */
+final class AnyURIType
+  extends AtomicSimpleType
+{
+
+  static final int[] CONSTRAINING_FACETS = {
+    Facet.LENGTH,
+    Facet.MIN_LENGTH,
+    Facet.MAX_LENGTH,
+    Facet.PATTERN,
+    Facet.ENUMERATION,
+    Facet.WHITESPACE
+  };
+
+  AnyURIType()
+  {
+    super(new QName(XMLConstants.W3C_XML_SCHEMA_NS_URI, "anyURI"),
+          TypeLibrary.ANY_SIMPLE_TYPE);
+  }
+
+  public int[] getConstrainingFacets()
+  {
+    return CONSTRAINING_FACETS;
+  }
+
+  public void checkValid(String value, ValidationContext context)
+    throws DatatypeException
+  {
+    super.checkValid(value, context);
+    try
+      {
+        new URI(value);
+      }
+    catch (URISyntaxException e)
+      {
+        DatatypeException e2 = new DatatypeException(e.getIndex(),
+                                                     e.getReason());
+        e2.initCause(e);
+        throw e2;
+      }
+  }
+  
+}
+

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/AtomicSimpleType.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/AtomicSimpleType.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/AtomicSimpleType.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/AtomicSimpleType.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,78 @@
+/* AtomicSimpleType.java -- 
+   Copyright (C) 2006  Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.xml.validation.datatype;
+
+import java.util.Set;
+import javax.xml.namespace.QName;
+import org.relaxng.datatype.DatatypeException;
+import org.relaxng.datatype.ValidationContext;
+
+/**
+ * An XML Schema atomic simple type.
+ *
+ * @author <a href='mailto:dog at gnu.org'>Chris Burdess</a>
+ */
+public class AtomicSimpleType
+  extends SimpleType
+{
+  
+  public AtomicSimpleType(QName name,
+                          Set facets,
+                          int fundamentalFacets,
+                          SimpleType baseType,
+                          Annotation annotation)
+  {
+    super(name, ATOMIC, facets, fundamentalFacets, baseType, annotation);
+  }
+
+  // Only for use by built-in types
+  AtomicSimpleType(QName name, SimpleType baseType)
+  {
+    super(name, ATOMIC, null, 0, baseType, null);
+  }
+
+  public void checkValid(String value, ValidationContext context)
+    throws DatatypeException
+  {
+    super.checkValid(value, context);
+    if (baseType != null)
+      baseType.checkValid(value, context);
+  }
+  
+}
+

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/Base64BinaryType.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/Base64BinaryType.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/Base64BinaryType.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/Base64BinaryType.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,131 @@
+/* Base64BinaryType.java -- 
+   Copyright (C) 2006  Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.xml.validation.datatype;
+
+import java.util.Collections;
+import java.util.Set;
+import javax.xml.XMLConstants;
+import javax.xml.namespace.QName;
+import org.relaxng.datatype.DatatypeException;
+import org.relaxng.datatype.ValidationContext;
+
+/**
+ * The XML Schema base64Binary type.
+ *
+ * @author <a href='mailto:dog at gnu.org'>Chris Burdess</a>
+ */
+final class Base64BinaryType
+  extends AtomicSimpleType
+{
+
+  static final String B64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" +
+    "abcdefghijklmnopqrstuvwxyz0123456789+/";
+  static final String B16 = "AEIMQUYcgkosw048";
+  static final String B04 = "AQgw";
+
+  static final int[] CONSTRAINING_FACETS = {
+    Facet.LENGTH,
+    Facet.MIN_LENGTH,
+    Facet.MAX_LENGTH,
+    Facet.PATTERN,
+    Facet.ENUMERATION,
+    Facet.WHITESPACE
+  };
+
+  Base64BinaryType()
+  {
+    super(new QName(XMLConstants.W3C_XML_SCHEMA_NS_URI, "base64Binary"),
+          TypeLibrary.ANY_SIMPLE_TYPE);
+  }
+
+  public int[] getConstrainingFacets()
+  {
+    return CONSTRAINING_FACETS;
+  }
+
+  public void checkValid(String value, ValidationContext context)
+    throws DatatypeException
+  {
+    super.checkValid(value, context);
+    // TODO value = collapseWhitespace(value);
+    int len = value.length();
+    try
+      {
+        for (int i = len - 1; i >= 0; )
+          {
+            char c4 = value.charAt(i--);
+            if (c4 == ' ')
+              c4 = value.charAt(i--);
+            char c3 = value.charAt(i--);
+            if (c3 == ' ')
+              c3 = value.charAt(i--);
+            char c2 = value.charAt(i--);
+            if (c2 == ' ')
+              c2 = value.charAt(i--);
+            char c1 = value.charAt(i--);
+            if (c1 == ' ')
+              c1 = value.charAt(i--);
+            
+            if (c4 == '=')
+              {
+                if (c3 == '=')
+                  {
+                    if (B04.indexOf(c2) != -1 &&
+                        B64.indexOf(c1) != -1)
+                      continue;
+                  }
+                else if (B16.indexOf(c3) != -1)
+                  {
+                    if (B64.indexOf(c2) != -1 &&
+                        B64.indexOf(c1) != -1)
+                      continue;
+                  }
+              }
+            else if (B64.indexOf(c4) != -1)
+              continue;
+            throw new DatatypeException(i, "illegal BASE64");
+          }
+      }
+    catch (IndexOutOfBoundsException e)
+      {
+        throw new DatatypeException("illegal BASE64");
+      }
+  }
+  
+}
+

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/BooleanType.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/BooleanType.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/BooleanType.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/BooleanType.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,91 @@
+/* BooleanType.java -- 
+   Copyright (C) 2006  Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.xml.validation.datatype;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Set;
+import java.util.TreeSet;
+import javax.xml.XMLConstants;
+import javax.xml.namespace.QName;
+import org.relaxng.datatype.DatatypeException;
+import org.relaxng.datatype.ValidationContext;
+
+/**
+ * The XML Schema boolean type.
+ *
+ * @author <a href='mailto:dog at gnu.org'>Chris Burdess</a>
+ */
+final class BooleanType
+  extends AtomicSimpleType
+{
+
+  static final int[] CONSTRAINING_FACETS = {
+    Facet.PATTERN,
+    Facet.WHITESPACE
+  };
+
+  static final Set VALUE_SPACE =
+    new TreeSet(Arrays.asList(new String[] {"true", "false", "1", "0"}));
+
+  BooleanType()
+  {
+    super(new QName(XMLConstants.W3C_XML_SCHEMA_NS_URI, "boolean"),
+          TypeLibrary.ANY_SIMPLE_TYPE);
+  }
+
+  public int[] getConstrainingFacets()
+  {
+    return CONSTRAINING_FACETS;
+  }
+
+  public void checkValid(String value, ValidationContext context)
+    throws DatatypeException
+  {
+    super.checkValid(value, context);
+    if (!VALUE_SPACE.contains(value))
+      throw new DatatypeException("invalid boolean value");
+  }
+  
+  public Object createValue(String literal, ValidationContext context) {
+    return ("1".equals(literal) || "true".equals(literal)) ? Boolean.TRUE :
+      Boolean.FALSE;
+  }
+  
+}
+

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/ByteType.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/ByteType.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/ByteType.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/ByteType.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,133 @@
+/* ByteType.java -- 
+   Copyright (C) 2006  Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.xml.validation.datatype;
+
+import javax.xml.XMLConstants;
+import javax.xml.namespace.QName;
+import org.relaxng.datatype.DatatypeException;
+import org.relaxng.datatype.ValidationContext;
+
+/**
+ * The XML Schema byte type.
+ *
+ * @author <a href='mailto:dog at gnu.org'>Chris Burdess</a>
+ */
+final class ByteType
+  extends AtomicSimpleType
+{
+
+  static final int[] CONSTRAINING_FACETS = {
+    Facet.TOTAL_DIGITS,
+    Facet.FRACTION_DIGITS,
+    Facet.PATTERN,
+    Facet.WHITESPACE,
+    Facet.ENUMERATION,
+    Facet.MAX_INCLUSIVE,
+    Facet.MAX_EXCLUSIVE,
+    Facet.MIN_INCLUSIVE,
+    Facet.MIN_EXCLUSIVE
+  };
+
+  static final String MAX_VALUE = "127";
+  static final String MIN_VALUE = "128";
+  static final int LENGTH = MAX_VALUE.length();
+
+  ByteType()
+  {
+    super(new QName(XMLConstants.W3C_XML_SCHEMA_NS_URI, "byte"),
+          TypeLibrary.SHORT);
+  }
+
+  public int[] getConstrainingFacets()
+  {
+    return CONSTRAINING_FACETS;
+  }
+
+  public void checkValue(String value, ValidationContext context)
+    throws DatatypeException
+  {
+    super.checkValid(value, context);
+    int len = value.length();
+    if (len == 0)
+      throw new DatatypeException(0, "invalid byte value");
+    int i = 0, off = 0;
+    boolean compare = false;
+    String compareTo = MAX_VALUE;
+    char c = value.charAt(0);
+    if (c == '+')
+      i++;
+    else if (c == '-')
+      {
+        compareTo = MIN_VALUE;
+        i++;
+      }
+    if (len - i > LENGTH)
+      throw new DatatypeException(0, "invalid byte value");
+    else if (len - i == LENGTH)
+      compare = true;
+    for (; i < len; i++)
+      {
+        c = value.charAt(i);
+        if (c >= 0x30 && c <= 0x39)
+          {
+            if (compare)
+              {
+                char d = compareTo.charAt(off);
+                if (Character.digit(c, 10) > Character.digit(d, 10))
+                  throw new DatatypeException(i, "invalid byte value");
+              }
+            off++;
+            continue;
+          }
+        throw new DatatypeException(i, "invalid byte value");
+      }
+  }
+  
+  public Object createValue(String literal, ValidationContext context) {
+    try
+      {
+        return new Byte(literal);
+      }
+    catch (NumberFormatException e)
+      {
+        return null;
+      }
+  }
+  
+}
+

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/DateTimeType.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/DateTimeType.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/DateTimeType.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/DateTimeType.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,335 @@
+/* DateTimeType.java -- 
+   Copyright (C) 2006  Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.xml.validation.datatype;
+
+import java.util.Calendar;
+import java.util.GregorianCalendar;
+import java.util.TimeZone;
+import javax.xml.XMLConstants;
+import javax.xml.namespace.QName;
+import org.relaxng.datatype.DatatypeException;
+import org.relaxng.datatype.ValidationContext;
+
+/**
+ * The XML Schema dateTime type.
+ *
+ * @author <a href='mailto:dog at gnu.org'>Chris Burdess</a>
+ */
+final class DateTimeType
+  extends AtomicSimpleType
+{
+
+  static final int[] CONSTRAINING_FACETS = {
+    Facet.PATTERN,
+    Facet.ENUMERATION,
+    Facet.WHITESPACE,
+    Facet.MAX_INCLUSIVE,
+    Facet.MAX_EXCLUSIVE,
+    Facet.MIN_INCLUSIVE,
+    Facet.MIN_EXCLUSIVE
+  };
+
+  DateTimeType()
+  {
+    super(new QName(XMLConstants.W3C_XML_SCHEMA_NS_URI, "dateTime"),
+          TypeLibrary.ANY_SIMPLE_TYPE);
+  }
+
+  public int[] getConstrainingFacets()
+  {
+    return CONSTRAINING_FACETS;
+  }
+
+  public void checkValue(String value, ValidationContext context)
+    throws DatatypeException
+  {
+    super.checkValid(value, context);
+    int len = value.length();
+    int state = 0;
+    int start = 0;
+    for (int i = 0; i < len; i++)
+      {
+        char c = value.charAt(i);
+        if (c == '-' && i == 0)
+          {
+            start++;
+            continue;
+          }
+        if (c >= 0x30 && c <= 0x39)
+          continue;
+        switch (state)
+          {
+          case 0: // year
+            if (c == '-')
+              {
+                String year = value.substring(start, i);
+                if ("0000".equals(year) || year.length() < 4)
+                  throw new DatatypeException(i, "invalid dateTime value");
+                state = 1;
+                start = i + 1;
+                continue;
+              }
+            break;
+          case 1: // month
+            if (c == '-')
+              {
+                if (i - start != 2)
+                  throw new DatatypeException(i, "invalid dateTime value");
+                state = 2;
+                start = i + 1;
+                continue;
+              }
+            break;
+          case 2: // day
+            if (c == 'T')
+              {
+                if (i - start != 2)
+                  throw new DatatypeException(i, "invalid dateTime value");
+                state = 3;
+                start = i + 1;
+                continue;
+              }
+            break;
+          case 3: // hour
+            if (c == ':')
+              {
+                if (i - start != 2)
+                  throw new DatatypeException(i, "invalid dateTime value");
+                state = 4;
+                start = i + 1;
+                continue;
+              }
+            break;
+          case 4: // minute
+            if (c == ':')
+              {
+                if (i - start != 2)
+                  throw new DatatypeException(i, "invalid dateTime value");
+                state = 5;
+                start = i + 1;
+                continue;
+              }
+            break;
+          case 5: // second
+            if (c == '.')
+              {
+                if (i - start != 2)
+                  throw new DatatypeException(i, "invalid dateTime value");
+                state = 6;
+                start = i + 1;
+                continue;
+              }
+            else if (c == ' ')
+              {
+                if (i - start != 2)
+                  throw new DatatypeException(i, "invalid dateTime value");
+                state = 7;
+                start = i + 1;
+                continue;
+              }
+            break;
+          case 6: // second fraction
+            if (c == ' ')
+              {
+                state = 7;
+                start = i + 1;
+                continue;
+              }
+            break;
+          case 7: // timezone 1
+            if (start == i)
+              {
+                if (c == '+' || c == '-')
+                    continue;
+                else if (c == 'Z')
+                  {
+                    state = 9;
+                    start = i + 1;
+                    continue;
+                  }
+              }
+            if (c == ':')
+              {
+                if (i - start != 2)
+                  throw new DatatypeException(i, "invalid dateTime value");
+                state = 8;
+                start = i + 1;
+                continue;
+              }
+            break;
+          }
+        throw new DatatypeException(i, "invalid dateTime value");
+      }
+    switch (state)
+      {
+      case 5: // second
+        if (len - start != 2)
+          throw new DatatypeException(len, "invalid dateTime value");
+        break;
+      case 6: // second fraction
+        break;
+      case 8: // timezone 2
+        if (len - start != 2)
+          throw new DatatypeException(len, "invalid dateTime value");
+        break;
+      case 9: // post Z
+        break;
+      default:
+        throw new DatatypeException(len, "invalid dateTime value");
+      }
+  }
+  
+  public Object createValue(String value, ValidationContext context) {
+    int len = value.length();
+    int state = 0;
+    int start = 0;
+    Calendar cal = new GregorianCalendar();
+    try
+      {
+        for (int i = 0; i < len; i++)
+          {
+            char c = value.charAt(i);
+            if (c == '-' && i == 0)
+              {
+                start++;
+                continue;
+              }
+            if (c >= 0x30 && c <= 0x39)
+              continue;
+            switch (state)
+              {
+              case 0: // year
+                if (c == '-')
+                  {
+                    cal.set(Calendar.YEAR,
+                            Integer.parseInt(value.substring(0, i)));
+                    state = 1;
+                    start = i + 1;
+                    continue;
+                  }
+                break;
+              case 1: // month
+                if (c == '-')
+                  {
+                    cal.set(Calendar.MONTH,
+                            Integer.parseInt(value.substring(start, i)));
+                    state = 2;
+                    start = i + 1;
+                    continue;
+                  }
+                break;
+              case 2: // day
+                if (c == 'T')
+                  {
+                    cal.set(Calendar.DATE,
+                            Integer.parseInt(value.substring(start, i)));
+                    state = 3;
+                    start = i + 1;
+                    continue;
+                  }
+                break;
+              case 3: // hour
+                if (c == ':')
+                  {
+                    cal.set(Calendar.HOUR,
+                            Integer.parseInt(value.substring(start, i)));
+                    state = 4;
+                    start = i + 1;
+                    continue;
+                  }
+                break;
+              case 4: // minute
+                if (c == ':')
+                  {
+                    cal.set(Calendar.MINUTE,
+                            Integer.parseInt(value.substring(start, i)));
+                    state = 5;
+                    start = i + 1;
+                    continue;
+                  }
+                break;
+              case 5: // second
+                if (c == ' ')
+                  {
+                    float second = Float.parseFloat(value.substring(start, i));
+                    // TODO adjust non-integer values
+                    cal.set(Calendar.SECOND, (int) second);
+                    state = 7;
+                    start = i + 1;
+                    continue;
+                  }
+                break;
+              }
+          }
+        // end of input
+        if (len - start > 0 && state == 7)
+          {
+            // Timezone
+            String timezone = value.substring(len - start);
+            int i = timezone.indexOf(':');
+            if (i == -1)
+              {
+                if ("Z".equals(timezone))
+                  timezone = "UTC";
+                TimeZone tz = TimeZone.getTimeZone(timezone);
+                if (tz == null)
+                  return null;
+                cal.set(Calendar.ZONE_OFFSET, tz.getRawOffset());
+              }
+            else
+              {
+                String tzh = timezone.substring(0, i);
+                String tzm = timezone.substring(i + 1);
+                int offset = Integer.parseInt(tzh) * 360000;
+                if (offset < 0)
+                  offset -= Integer.parseInt(tzm) * 60000;
+                else
+                  offset += Integer.parseInt(tzm) * 60000;
+                cal.set(Calendar.ZONE_OFFSET, offset);
+              }
+          }
+        return cal.getTime();
+      }
+    catch (NumberFormatException e)
+      {
+        return null;
+      }
+  }
+  
+}
+

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/DateType.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/DateType.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/DateType.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/DateType.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,222 @@
+/* DateType.java -- 
+   Copyright (C) 2006  Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.xml.validation.datatype;
+
+import java.util.Calendar;
+import java.util.GregorianCalendar;
+import java.util.TimeZone;
+import javax.xml.XMLConstants;
+import javax.xml.namespace.QName;
+import org.relaxng.datatype.DatatypeException;
+import org.relaxng.datatype.ValidationContext;
+
+/**
+ * The XML Schema date type.
+ *
+ * @author <a href='mailto:dog at gnu.org'>Chris Burdess</a>
+ */
+final class DateType
+  extends AtomicSimpleType
+{
+
+  static final int[] CONSTRAINING_FACETS = {
+    Facet.PATTERN,
+    Facet.ENUMERATION,
+    Facet.WHITESPACE,
+    Facet.MAX_INCLUSIVE,
+    Facet.MAX_EXCLUSIVE,
+    Facet.MIN_INCLUSIVE,
+    Facet.MIN_EXCLUSIVE
+  };
+
+  DateType()
+  {
+    super(new QName(XMLConstants.W3C_XML_SCHEMA_NS_URI, "date"),
+          TypeLibrary.ANY_SIMPLE_TYPE);
+  }
+
+  public int[] getConstrainingFacets()
+  {
+    return CONSTRAINING_FACETS;
+  }
+
+  public void checkValid(String value, ValidationContext context)
+    throws DatatypeException
+  {
+    super.checkValid(value, context);
+    int len = value.length();
+    int state = 0;
+    int start = 0;
+    for (int i = 0; i < len; i++)
+      {
+        char c = value.charAt(i);
+        if (c == '-' && i == 0)
+          {
+            start++;
+            continue;
+          }
+        if (c >= 0x30 && c <= 0x39)
+          continue;
+        switch (state)
+          {
+          case 0: // year
+            if (c == '-')
+              {
+                String year = value.substring(start, i);
+                if ("0000".equals(year) || year.length() < 4)
+                  throw new DatatypeException(i, "invalid date value");
+                state = 1;
+                start = i + 1;
+                continue;
+              }
+            break;
+          case 1: // month
+            if (c == '-')
+              {
+                if (i - start != 2)
+                  throw new DatatypeException(i, "invalid date value");
+                state = 2;
+                start = i + 1;
+                continue;
+              }
+            break;
+          }
+                  throw new DatatypeException(i, "invalid date value");
+      }
+    switch (state)
+      {
+      case 2: // day
+        if (len - start != 2)
+          throw new DatatypeException("invalid date value");
+        break;
+      default:
+        throw new DatatypeException("invalid date value");
+      }
+  }
+  
+  public Object createValue(String value, ValidationContext context) {
+    int len = value.length();
+    int state = 0;
+    int start = 0;
+    Calendar cal = new GregorianCalendar();
+    cal.set(Calendar.HOUR, 0);
+    cal.set(Calendar.MINUTE, 0);
+    cal.set(Calendar.SECOND, 0);
+    try
+      {
+        for (int i = 0; i < len; i++)
+          {
+            char c = value.charAt(i);
+            if (c == '-' && i == 0)
+              {
+                start++;
+                continue;
+              }
+            if (c >= 0x30 && c <= 0x39)
+              continue;
+            switch (state)
+              {
+              case 0: // year
+                if (c == '-')
+                  {
+                    cal.set(Calendar.YEAR,
+                            Integer.parseInt(value.substring(0, i)));
+                    state = 1;
+                    start = i + 1;
+                    continue;
+                  }
+                break;
+              case 1: // month
+                if (c == '-')
+                  {
+                    cal.set(Calendar.MONTH,
+                            Integer.parseInt(value.substring(start, i)));
+                    state = 2;
+                    start = i + 1;
+                    continue;
+                  }
+                break;
+              case 2: // day
+                if (c == 'T')
+                  {
+                    cal.set(Calendar.DATE,
+                            Integer.parseInt(value.substring(start, i)));
+                    state = 7;
+                    start = i + 1;
+                    continue;
+                  }
+                break;
+              }
+          }
+        // end of input
+        if (len - start > 0 && state == 7)
+          {
+            // Timezone
+            String timezone = value.substring(len - start);
+            int i = timezone.indexOf(':');
+            if (i == -1)
+              {
+                if ("Z".equals(timezone))
+                  timezone = "UTC";
+                TimeZone tz = TimeZone.getTimeZone(timezone);
+                if (tz == null)
+                  return null;
+                cal.set(Calendar.ZONE_OFFSET, tz.getRawOffset());
+              }
+            else
+              {
+                String tzh = timezone.substring(0, i);
+                String tzm = timezone.substring(i + 1);
+                int offset = Integer.parseInt(tzh) * 360000;
+                if (offset < 0)
+                  offset -= Integer.parseInt(tzm) * 60000;
+                else
+                  offset += Integer.parseInt(tzm) * 60000;
+                cal.set(Calendar.ZONE_OFFSET, offset);
+              }
+          }
+        return cal.getTime();
+      }
+    catch (NumberFormatException e)
+      {
+        return null;
+      }
+  }
+  
+}
+

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/DecimalType.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/DecimalType.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/DecimalType.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/DecimalType.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,121 @@
+/* DecimalType.java -- 
+   Copyright (C) 2006  Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.xml.validation.datatype;
+
+import java.math.BigDecimal;
+import java.util.Collections;
+import java.util.Set;
+import javax.xml.XMLConstants;
+import javax.xml.namespace.QName;
+import org.relaxng.datatype.DatatypeException;
+import org.relaxng.datatype.ValidationContext;
+
+/**
+ * The XML Schema decimal type.
+ *
+ * @author <a href='mailto:dog at gnu.org'>Chris Burdess</a>
+ */
+final class DecimalType
+  extends AtomicSimpleType
+{
+
+  static final int[] CONSTRAINING_FACETS = {
+    Facet.TOTAL_DIGITS,
+    Facet.FRACTION_DIGITS,
+    Facet.PATTERN,
+    Facet.WHITESPACE,
+    Facet.ENUMERATION,
+    Facet.MAX_INCLUSIVE,
+    Facet.MAX_EXCLUSIVE,
+    Facet.MIN_INCLUSIVE,
+    Facet.MIN_EXCLUSIVE
+  };
+
+  DecimalType()
+  {
+    super(new QName(XMLConstants.W3C_XML_SCHEMA_NS_URI, "decimal"),
+          TypeLibrary.ANY_SIMPLE_TYPE);
+  }
+
+  public int[] getConstrainingFacets()
+  {
+    return CONSTRAINING_FACETS;
+  }
+
+  public void checkValid(String value, ValidationContext context)
+    throws DatatypeException
+  {
+    super.checkValid(value, context);
+    int len = value.length();
+    if (len == 0)
+      throw new DatatypeException("invalid decimal value");
+    boolean seenDot = false;
+    for (int i = 0; i < len; i++)
+      {
+        char c = value.charAt(i);
+        if (c >= 0x30 && c <= 0x39)
+          continue;
+        else if (c == '.')
+          {
+            if (seenDot)
+              throw new DatatypeException(i, "invalid decimal value");
+            seenDot = true;
+            continue;
+          }
+        else if (c == '+' && i == 0)
+          continue;
+        else if (c == '-' && i == 0)
+          continue;
+        else
+          throw new DatatypeException(i, "invalid decimal value");
+      }
+  }
+  
+  public Object createValue(String literal, ValidationContext context) {
+    try
+      {
+        return new BigDecimal(literal);
+      }
+    catch (NumberFormatException e)
+      {
+        return null;
+      }
+  }
+  
+}
+

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/DoubleType.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/DoubleType.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/DoubleType.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/DoubleType.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,112 @@
+/* DoubleType.java -- 
+   Copyright (C) 2006  Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.xml.validation.datatype;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Set;
+import java.util.TreeSet;
+import javax.xml.XMLConstants;
+import javax.xml.namespace.QName;
+import org.relaxng.datatype.DatatypeException;
+import org.relaxng.datatype.ValidationContext;
+
+/**
+ * The XML Schema double type.
+ *
+ * @author <a href='mailto:dog at gnu.org'>Chris Burdess</a>
+ */
+final class DoubleType
+  extends AtomicSimpleType
+{
+
+  static final int[] CONSTRAINING_FACETS = {
+    Facet.PATTERN,
+    Facet.ENUMERATION,
+    Facet.WHITESPACE,
+    Facet.MAX_INCLUSIVE,
+    Facet.MAX_EXCLUSIVE,
+    Facet.MIN_INCLUSIVE,
+    Facet.MIN_EXCLUSIVE
+  };
+
+  static final Set SPECIAL =
+    new TreeSet(Arrays.asList(new String[] {"INF", "-INF", "NaN"}));
+
+  DoubleType()
+  {
+    super(new QName(XMLConstants.W3C_XML_SCHEMA_NS_URI, "double"),
+          TypeLibrary.ANY_SIMPLE_TYPE);
+  }
+
+  public int[] getConstrainingFacets()
+  {
+    return CONSTRAINING_FACETS;
+  }
+
+  public void checkValid(String value, ValidationContext context)
+    throws DatatypeException
+  {
+    super.checkValid(value, context);
+    if (SPECIAL.contains(value))
+      return;
+    try
+      {
+        Double.parseDouble(value);
+      }
+    catch (NumberFormatException e)
+      {
+        DatatypeException e2 = new DatatypeException("invalid double value");
+        e2.initCause(e);
+        throw e2;
+      }
+  }
+  
+  public Object createValue(String literal, ValidationContext context) {
+    try
+      {
+        return new Double(literal);
+      }
+    catch (NumberFormatException e)
+      {
+        return null;
+      }
+  }
+  
+}
+

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/DurationType.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/DurationType.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/DurationType.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/DurationType.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,239 @@
+/* DurationType.java -- 
+   Copyright (C) 2006  Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.xml.validation.datatype;
+
+import javax.xml.XMLConstants;
+import javax.xml.namespace.QName;
+import org.relaxng.datatype.DatatypeException;
+import org.relaxng.datatype.ValidationContext;
+
+/**
+ * The XML Schema duration type.
+ *
+ * @author <a href='mailto:dog at gnu.org'>Chris Burdess</a>
+ */
+final class DurationType
+  extends AtomicSimpleType
+{
+
+  static class Duration
+    implements Comparable
+  {
+    int years;
+    int months;
+    int days;
+    int minutes;
+    float seconds;
+
+    public int hashCode()
+    {
+      int hc = years;
+      hc = hc * 31 + months;
+      hc = hc * 31 + days;
+      hc = hc * 31 + minutes;
+      hc = hc * 31 + new Float(seconds).hashCode();
+      return hc;
+    }
+
+    public boolean equals(Object other)
+    {
+      if (other instanceof Duration)
+        {
+          Duration duration = (Duration) other;
+          return duration.years ==years &&
+            duration.months == months &&
+            duration.days == days &&
+            duration.minutes == minutes &&
+            duration.seconds == seconds;
+        }
+      return false;
+    }
+
+    public int compareTo(Object other)
+    {
+      if (other instanceof Duration)
+        {
+          Duration duration = (Duration) other;
+          if (duration.years != years)
+            return years - duration.years;
+          if (duration.months != months)
+            return months - duration.months;
+          if (duration.days != days)
+            return days - duration.days;
+          if (duration.minutes != minutes)
+            return minutes = duration.minutes;
+          if (duration.seconds == seconds)
+            return 0;
+          return (seconds < duration.seconds) ? -1 : 1;
+        }
+      return 0;
+    }
+    
+  }
+
+  static final int[] CONSTRAINING_FACETS = {
+    Facet.PATTERN,
+    Facet.ENUMERATION,
+    Facet.WHITESPACE,
+    Facet.MAX_INCLUSIVE,
+    Facet.MAX_EXCLUSIVE,
+    Facet.MIN_INCLUSIVE,
+    Facet.MIN_EXCLUSIVE
+  };
+
+  DurationType()
+  {
+    super(new QName(XMLConstants.W3C_XML_SCHEMA_NS_URI, "duration"),
+          TypeLibrary.ANY_SIMPLE_TYPE);
+  }
+
+  public int[] getConstrainingFacets()
+  {
+    return CONSTRAINING_FACETS;
+  }
+
+  public void checkValid(String value, ValidationContext context)
+    throws DatatypeException
+  {
+    super.checkValid(value, context);
+    int len = value.length();
+    char expect = 'P';
+    boolean seenT = false;
+    for (int i = 0; i < len; i++)
+      {
+        char c = value.charAt(i);
+        if (c == '-' && expect == 'P')
+          continue;
+        if (c == expect)
+          {
+            if (c == 'P')
+              expect = 'Y';
+            else if (c == 'Y')
+              expect = 'M';
+            else if (c == 'M' && !seenT)
+              expect = 'D';
+            else if (c == 'D')
+              expect = 'T';
+            else if (c == 'T')
+              {
+                expect = 'H';
+                seenT = true;
+              }
+            else if (c == 'H')
+              expect = 'M';
+            else if (c == 'M' && seenT)
+              expect = 'S';
+            else if (c == 'S')
+              {
+                if (i + 1 != len)
+                  throw new DatatypeException(i, "illegal duration value");
+              }
+            continue;
+          }
+        if (c >= 0x30 && c <= 0x39 && expect != 'P' && expect != 'T')
+          continue;
+        throw new DatatypeException(i, "illegal duration value");
+      }
+  }
+  
+  public Object createValue(String value, ValidationContext context) {
+    boolean negative = false;
+    int days = 0, months = 0, years = 0;
+    int minutes = 0;
+    float seconds = 0.0f;
+    int len = value.length();
+    char expect = 'P';
+    boolean seenT = false;
+    int start = 0;
+    for (int i = 0; i < len; i++)
+      {
+        char c = value.charAt(i);
+        if (c == '-' && expect == 'P')
+          {
+            negative = true;
+            continue;
+          }
+        if (c == expect)
+          {
+            if (c == 'P')
+              expect = 'Y';
+            else if (c == 'Y')
+              {
+                expect = 'M';
+                years = Integer.parseInt(value.substring(start, i));
+              }
+            else if (c == 'M' && !seenT)
+              expect = 'D';
+            else if (c == 'D')
+              expect = 'T';
+            else if (c == 'T')
+              {
+                expect = 'H';
+                seenT = true;
+              }
+            else if (c == 'H')
+              expect = 'M';
+            else if (c == 'M' && seenT)
+              expect = 'S';
+            else if (c == 'S')
+              {
+                if (i + 1 != len)
+                  return null;
+              }
+            start = i + 1;
+            continue;
+          }
+        if (c >= 0x30 && c <= 0x39 && expect != 'P' && expect != 'T')
+          continue;
+        return null;
+      }
+    if (negative)
+      {
+        days = days * -1;
+        minutes = minutes * -1;
+        seconds = seconds * -1.0f;
+      }
+    Duration duration = new Duration();
+    duration.days = days;
+    duration.minutes = minutes;
+    duration.seconds = seconds;
+    return duration;
+  }
+
+}
+

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/EntitiesType.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/EntitiesType.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/EntitiesType.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/EntitiesType.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,107 @@
+/* EntitiesType.java -- 
+   Copyright (C) 2006  Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.xml.validation.datatype;
+
+import javax.xml.XMLConstants;
+import javax.xml.namespace.QName;
+import org.relaxng.datatype.DatatypeException;
+import org.relaxng.datatype.ValidationContext;
+
+/**
+ * The XML Schema ENTITIES type.
+ *
+ * @author <a href='mailto:dog at gnu.org'>Chris Burdess</a>
+ */
+final class EntitiesType
+  extends AtomicSimpleType
+{
+
+  static final int[] CONSTRAINING_FACETS = {
+    Facet.LENGTH,
+    Facet.MIN_LENGTH,
+    Facet.MAX_LENGTH,
+    Facet.PATTERN,
+    Facet.ENUMERATION,
+    Facet.WHITESPACE
+  };
+
+  EntitiesType()
+  {
+    super(new QName(XMLConstants.W3C_XML_SCHEMA_NS_URI, "ENTITIES"),
+          TypeLibrary.ENTITY);
+  }
+
+  public int[] getConstrainingFacets()
+  {
+    return CONSTRAINING_FACETS;
+  }
+
+  public void checkValid(String value, ValidationContext context)
+    throws DatatypeException
+  {
+    super.checkValid(value, context);
+    StringBuffer buf = new StringBuffer();
+    int len = value.length();
+    for (int i = 0; i < len; i++)
+      {
+        char c = value.charAt(i);
+        if (c == ' ')
+          {
+            String token = buf.toString();
+            if (token.length() > 0)
+              {
+                if (!context.isUnparsedEntity(token))
+                  throw new DatatypeException(i, "invalid ENTITIES value");
+              }
+            buf.setLength(0);
+          }
+        else
+          buf.append(c);
+      }
+    String token = buf.toString();
+    if (token.length() == 0 || !context.isUnparsedEntity(token))
+      throw new DatatypeException("invalid ENTITIES value");
+  }
+
+  public boolean isContextDependent()
+  {
+    return true;
+  }
+  
+}
+

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/EntityType.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/EntityType.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/EntityType.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/EntityType.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,88 @@
+/* EntityType.java -- 
+   Copyright (C) 2006  Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.xml.validation.datatype;
+
+import javax.xml.XMLConstants;
+import javax.xml.namespace.QName;
+import org.relaxng.datatype.DatatypeException;
+import org.relaxng.datatype.ValidationContext;
+
+/**
+ * The XML Schema ENTITY type.
+ *
+ * @author <a href='mailto:dog at gnu.org'>Chris Burdess</a>
+ */
+final class EntityType
+  extends AtomicSimpleType
+{
+
+  static final int[] CONSTRAINING_FACETS = {
+    Facet.LENGTH,
+    Facet.MIN_LENGTH,
+    Facet.MAX_LENGTH,
+    Facet.PATTERN,
+    Facet.ENUMERATION,
+    Facet.WHITESPACE
+  };
+
+  EntityType()
+  {
+    super(new QName(XMLConstants.W3C_XML_SCHEMA_NS_URI, "ENTITY"),
+          TypeLibrary.NCNAME);
+  }
+
+  public int[] getConstrainingFacets()
+  {
+    return CONSTRAINING_FACETS;
+  }
+
+  public void checkValid(String value, ValidationContext context)
+    throws DatatypeException
+  {
+    super.checkValid(value, context);
+    if (value.length() == 0 || !context.isUnparsedEntity(value))
+      throw new DatatypeException("invalid ENTITY value");
+  }
+
+  public boolean isContextDependent()
+  {
+    return true;
+  }
+  
+}
+

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/EnumerationFacet.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/EnumerationFacet.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/EnumerationFacet.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/EnumerationFacet.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,69 @@
+/* EnumerationFacet.java -- 
+   Copyright (C) 2006  Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.xml.validation.datatype;
+
+/**
+ * The <code>enumeration</code> facet.
+ *
+ * @author <a href='mailto:dog at gnu.org'>Chris Burdess</a>
+ */
+public final class EnumerationFacet
+  extends Facet
+{
+  
+  public final String value;
+
+  public EnumerationFacet(String value, Annotation annotation)
+  {
+    super(ENUMERATION, annotation);
+    this.value = value;
+  }
+
+  public int hashCode()
+  {
+    return value.hashCode();
+  }
+
+  public boolean equals(Object other)
+  {
+    return (other instanceof EnumerationFacet &&
+            ((EnumerationFacet) other).value.equals(value));
+  }
+  
+}
+

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/Facet.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/Facet.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/Facet.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/Facet.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,78 @@
+/* Facet.java -- 
+   Copyright (C) 2006  Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.xml.validation.datatype;
+
+/**
+ * An XML Schema constraining facet.
+ *
+ * @author <a href='mailto:dog at gnu.org'>Chris Burdess</a>
+ */
+public abstract class Facet
+{
+
+  public static final int LENGTH = 1;
+  public static final int MIN_LENGTH = 2;
+  public static final int MAX_LENGTH = 3;
+  public static final int PATTERN = 4;
+  public static final int ENUMERATION = 5;
+  public static final int WHITESPACE = 6;
+  public static final int MAX_INCLUSIVE = 7;
+  public static final int MAX_EXCLUSIVE = 8;
+  public static final int MIN_EXCLUSIVE = 9;
+  public static final int MIN_INCLUSIVE = 10;
+  public static final int TOTAL_DIGITS = 11;
+  public static final int FRACTION_DIGITS = 12;
+
+  /**
+   * The type of this facet.
+   */
+  public final int type;
+
+  /**
+   * Optional annotation.
+   */
+  public Annotation annotation;
+
+  protected Facet(int type, Annotation annotation)
+  {
+    this.type = type;
+    this.annotation = annotation;
+  }
+  
+}
+

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/FloatType.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/FloatType.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/FloatType.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/FloatType.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,112 @@
+/* FloatType.java -- 
+   Copyright (C) 2006  Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.xml.validation.datatype;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Set;
+import java.util.TreeSet;
+import javax.xml.XMLConstants;
+import javax.xml.namespace.QName;
+import org.relaxng.datatype.DatatypeException;
+import org.relaxng.datatype.ValidationContext;
+
+/**
+ * The XML Schema float type.
+ *
+ * @author <a href='mailto:dog at gnu.org'>Chris Burdess</a>
+ */
+final class FloatType
+  extends AtomicSimpleType
+{
+
+  static final int[] CONSTRAINING_FACETS = {
+    Facet.PATTERN,
+    Facet.ENUMERATION,
+    Facet.WHITESPACE,
+    Facet.MAX_INCLUSIVE,
+    Facet.MAX_EXCLUSIVE,
+    Facet.MIN_INCLUSIVE,
+    Facet.MIN_EXCLUSIVE
+  };
+
+  static final Set SPECIAL =
+    new TreeSet(Arrays.asList(new String[] {"INF", "-INF", "NaN"}));
+
+  FloatType()
+  {
+    super(new QName(XMLConstants.W3C_XML_SCHEMA_NS_URI, "float"),
+          TypeLibrary.ANY_SIMPLE_TYPE);
+  }
+
+  public int[] getConstrainingFacets()
+  {
+    return CONSTRAINING_FACETS;
+  }
+
+  public void checkValid(String value, ValidationContext context)
+    throws DatatypeException
+  {
+    super.checkValid(value, context);
+    if (SPECIAL.contains(value))
+      return;
+    try
+      {
+        Float.parseFloat(value);
+      }
+    catch (NumberFormatException e)
+      {
+        DatatypeException e2 = new DatatypeException("invalid float value");
+        e2.initCause(e);
+        throw e2;
+      }
+  }
+  
+  public Object createValue(String literal, ValidationContext context) {
+    try
+      {
+        return new Float(literal);
+      }
+    catch (NumberFormatException e)
+      {
+        return null;
+      }
+  }
+  
+}
+

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/FractionDigitsFacet.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/FractionDigitsFacet.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/FractionDigitsFacet.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/FractionDigitsFacet.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,72 @@
+/* FractionDigitsFacet.java -- 
+   Copyright (C) 2006  Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.xml.validation.datatype;
+
+/**
+ * The <code>fractionDigits</code> facet.
+ *
+ * @author <a href='mailto:dog at gnu.org'>Chris Burdess</a>
+ */
+public final class FractionDigitsFacet
+  extends Facet
+{
+  
+  public final int value;
+
+  public final boolean fixed;
+
+  public FractionDigitsFacet(int value, boolean fixed, Annotation annotation)
+  {
+    super(FRACTION_DIGITS, annotation);
+    this.value = value;
+    this.fixed = fixed;
+  }
+  
+  public int hashCode()
+  {
+    return value;
+  }
+
+  public boolean equals(Object other)
+  {
+    return (other instanceof FractionDigitsFacet &&
+            ((FractionDigitsFacet) other).value == value);
+  }
+  
+}
+

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/GDayType.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/GDayType.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/GDayType.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/GDayType.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,175 @@
+/* GDayType.java -- 
+   Copyright (C) 2006  Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.xml.validation.datatype;
+
+import javax.xml.XMLConstants;
+import javax.xml.namespace.QName;
+import org.relaxng.datatype.DatatypeException;
+import org.relaxng.datatype.ValidationContext;
+
+/**
+ * The XML Schema gDay type.
+ *
+ * @author <a href='mailto:dog at gnu.org'>Chris Burdess</a>
+ */
+final class GDayType
+  extends AtomicSimpleType
+{
+
+  static class GDay
+    implements Comparable
+  {
+
+    int day;
+
+    public int hashCode()
+    {
+      return day;
+    }
+
+    public boolean equals(Object other)
+    {
+      if (other instanceof GDay)
+        return ((GDay) other).day == day;
+      return false;
+    }
+
+    public int compareTo(Object other)
+    {
+      if (other instanceof GDay)
+        {
+          GDay gd = (GDay) other;
+          if (gd.day == day)
+            return 0;
+          return (day < gd.day) ? -1 : 1;
+        }
+      return 0;
+    }
+    
+  }
+
+  static final int[] CONSTRAINING_FACETS = {
+    Facet.PATTERN,
+    Facet.ENUMERATION,
+    Facet.WHITESPACE,
+    Facet.MAX_INCLUSIVE,
+    Facet.MAX_EXCLUSIVE,
+    Facet.MIN_INCLUSIVE,
+    Facet.MIN_EXCLUSIVE
+  };
+
+  GDayType()
+  {
+    super(new QName(XMLConstants.W3C_XML_SCHEMA_NS_URI, "gDay"),
+          TypeLibrary.ANY_SIMPLE_TYPE);
+  }
+
+  public int[] getConstrainingFacets()
+  {
+    return CONSTRAINING_FACETS;
+  }
+
+  public void checkValid(String value, ValidationContext context)
+    throws DatatypeException
+  {
+    super.checkValid(value, context);
+    int len = value.length();
+    int state = 0;
+    int start = 0;
+    for (int i = 0; i < len; i++)
+      {
+        char c = value.charAt(i);
+        if (c >= 0x30 && c <= 0x39)
+          continue;
+        switch (state)
+          {
+          case 0: // year
+            if (c == '-')
+              {
+                switch (i)
+                  {
+                  case 0:
+                    continue;
+                  case 1:
+                    state = 1;
+                    start = i + 1;
+                    continue;
+                  default:
+                    throw new DatatypeException(i, "invalid GDay value");
+                  }
+              }
+            break;
+          case 1: // month
+            if (c == '-')
+              {
+                if (i - start != 0)
+                  throw new DatatypeException(i, "invalid GDay value");
+                state = 2;
+                start = i + 1;
+                continue;
+              }
+            break;
+          }
+        throw new DatatypeException(i, "invalid GDay value");
+      }
+    switch (state)
+      {
+      case 2: // day
+        if (len - start != 2)
+          throw new DatatypeException("invalid GDay value");
+        break;
+      default:
+        throw new DatatypeException("invalid GDay value");
+      }
+  }
+  
+  public Object createValue(String literal, ValidationContext context) {
+    try
+      {
+        GDay ret = new GDay();
+        ret.day = Integer.parseInt(literal.substring(3));
+        return ret;
+      }
+    catch (Exception e)
+      {
+        return null;
+      }
+  }
+  
+}
+

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/GMonthDayType.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/GMonthDayType.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/GMonthDayType.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/GMonthDayType.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,184 @@
+/* GMonthDayType.java -- 
+   Copyright (C) 2006  Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.xml.validation.datatype;
+
+import javax.xml.XMLConstants;
+import javax.xml.namespace.QName;
+import org.relaxng.datatype.DatatypeException;
+import org.relaxng.datatype.ValidationContext;
+
+/**
+ * The XML Schema gMonthDay type.
+ *
+ * @author <a href='mailto:dog at gnu.org'>Chris Burdess</a>
+ */
+final class GMonthDayType
+  extends AtomicSimpleType
+{
+
+  static class GMonthDay
+    implements Comparable
+  {
+
+    int month;
+    int day;
+
+    public int hashCode()
+    {
+      return month * 31 + day;
+    }
+
+    public boolean equals(Object other)
+    {
+      if (other instanceof GMonthDay)
+        {
+          GMonthDay gmd = (GMonthDay) other;
+          return gmd.month == month && gmd.day == day;
+        }
+      return false;
+    }
+
+    public int compareTo(Object other)
+    {
+      if (other instanceof GMonthDay)
+        {
+          GMonthDay gmd = (GMonthDay) other;
+          if (gmd.month == month)
+            {
+              if (gmd.day == day)
+                return 0;
+              return (day < gmd.day) ? -1 : 1;
+            }
+          return (month < gmd.month) ? -1 : 1;
+        }
+      return 0;
+    }
+    
+  }
+
+  static final int[] CONSTRAINING_FACETS = {
+    Facet.PATTERN,
+    Facet.ENUMERATION,
+    Facet.WHITESPACE,
+    Facet.MAX_INCLUSIVE,
+    Facet.MAX_EXCLUSIVE,
+    Facet.MIN_INCLUSIVE,
+    Facet.MIN_EXCLUSIVE
+  };
+
+  GMonthDayType()
+  {
+    super(new QName(XMLConstants.W3C_XML_SCHEMA_NS_URI, "gMonthDay"),
+          TypeLibrary.ANY_SIMPLE_TYPE);
+  }
+
+  public int[] getConstrainingFacets()
+  {
+    return CONSTRAINING_FACETS;
+  }
+
+  public void checkValid(String value, ValidationContext context)
+    throws DatatypeException
+  {
+    super.checkValid(value, context);
+    int len = value.length();
+    int state = 0;
+    int start = 0;
+    for (int i = 0; i < len; i++)
+      {
+        char c = value.charAt(i);
+        if (c >= 0x30 && c <= 0x39)
+          continue;
+        switch (state)
+          {
+          case 0: // year
+            if (c == '-')
+              {
+                switch (i)
+                  {
+                  case 0:
+                    continue;
+                  case 1:
+                    state = 1;
+                    start = i + 1;
+                    continue;
+                  default:
+                    throw new DatatypeException(i, "illegal GMonthDay type");
+                  }
+              }
+            break;
+          case 1: // month
+            if (c == '-')
+              {
+                if (i - start != 2)
+                  throw new DatatypeException(i, "illegal GMonthDay type");
+                state = 2;
+                start = i + 1;
+                continue;
+              }
+            break;
+          }
+        throw new DatatypeException(i, "illegal GMonthDay type");
+      }
+    switch (state)
+      {
+      case 2: // day
+        if (len - start != 2)
+          throw new DatatypeException("illegal GMonthDay type");
+        break;
+      default:
+        throw new DatatypeException("illegal GMonthDay type");
+      }
+  }
+  
+  public Object createValue(String literal, ValidationContext context) {
+    try
+      {
+        GMonthDay ret = new GMonthDay();
+        ret.month = Integer.parseInt(literal.substring(2, 5));
+        ret.day = Integer.parseInt(literal.substring(6));
+        return ret;
+      }
+    catch (Exception e)
+      {
+        return null;
+      }
+  }
+  
+}
+

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/GMonthType.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/GMonthType.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/GMonthType.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/GMonthType.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,164 @@
+/* GMonthType.java -- 
+   Copyright (C) 2006  Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.xml.validation.datatype;
+
+import javax.xml.XMLConstants;
+import javax.xml.namespace.QName;
+import org.relaxng.datatype.DatatypeException;
+import org.relaxng.datatype.ValidationContext;
+
+/**
+ * The XML Schema gMonth type.
+ *
+ * @author <a href='mailto:dog at gnu.org'>Chris Burdess</a>
+ */
+final class GMonthType
+  extends AtomicSimpleType
+{
+
+  static class GMonth
+    implements Comparable
+  {
+
+    int month;
+
+    public int hashCode()
+    {
+      return month;
+    }
+
+    public boolean equals(Object other)
+    {
+      if (other instanceof GMonth)
+        return ((GMonth) other).month == month;
+      return false;
+    }
+
+    public int compareTo(Object other)
+    {
+      if (other instanceof GMonth)
+        {
+          GMonth gm = (GMonth) other;
+          if (gm.month == month)
+            return 0;
+          return (month < gm.month) ? -1 : 1;
+        }
+      return 0;
+    }
+    
+  }
+
+  static final int[] CONSTRAINING_FACETS = {
+    Facet.PATTERN,
+    Facet.ENUMERATION,
+    Facet.WHITESPACE,
+    Facet.MAX_INCLUSIVE,
+    Facet.MAX_EXCLUSIVE,
+    Facet.MIN_INCLUSIVE,
+    Facet.MIN_EXCLUSIVE
+  };
+
+  GMonthType()
+  {
+    super(new QName(XMLConstants.W3C_XML_SCHEMA_NS_URI, "gMonth"),
+          TypeLibrary.ANY_SIMPLE_TYPE);
+  }
+
+  public int[] getConstrainingFacets()
+  {
+    return CONSTRAINING_FACETS;
+  }
+
+  public void checkValid(String value, ValidationContext context)
+    throws DatatypeException
+  {
+    int len = value.length();
+    int state = 0;
+    int start = 0;
+    for (int i = 0; i < len; i++)
+      {
+        char c = value.charAt(i);
+        if (c >= 0x30 && c <= 0x39)
+          continue;
+        switch (state)
+          {
+          case 0: // year
+            if (c == '-')
+              {
+                switch (i)
+                  {
+                  case 0:
+                    continue;
+                  case 1:
+                    state = 1;
+                    start = i + 1;
+                    continue;
+                  default:
+                    throw new DatatypeException(i, "illegal GMonth value");
+                  }
+              }
+            break;
+          }
+        throw new DatatypeException(i, "illegal GMonth value");
+      }
+    switch (state)
+      {
+      case 1: // month
+        if (len - start != 2)
+          throw new DatatypeException("illegal GMonth value");
+        break;
+      default:
+        throw new DatatypeException("illegal GMonth value");
+      }
+  }
+  
+  public Object createValue(String literal, ValidationContext context) {
+    try
+      {
+        GMonth ret = new GMonth();
+        ret.month = Integer.parseInt(literal.substring(2));
+        return ret;
+      }
+    catch (Exception e)
+      {
+        return null;
+      }
+  }
+  
+}
+

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/GYearMonthType.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/GYearMonthType.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/GYearMonthType.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/GYearMonthType.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,177 @@
+/* GYearMonthType.java -- 
+   Copyright (C) 2006  Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.xml.validation.datatype;
+
+import javax.xml.XMLConstants;
+import javax.xml.namespace.QName;
+import org.relaxng.datatype.DatatypeException;
+import org.relaxng.datatype.ValidationContext;
+
+/**
+ * The XML Schema gYearMonth type.
+ *
+ * @author <a href='mailto:dog at gnu.org'>Chris Burdess</a>
+ */
+final class GYearMonthType
+  extends AtomicSimpleType
+{
+
+  static class GYearMonth
+    implements Comparable
+  {
+
+    int year;
+    int month;
+
+    public int hashCode()
+    {
+      return year * 31 + month;
+    }
+
+    public boolean equals(Object other)
+    {
+      if (other instanceof GYearMonth)
+        {
+          GYearMonth gmy = (GYearMonth) other;
+          return gmy.year == year && gmy.month == month;
+        }
+      return false;
+    }
+
+    public int compareTo(Object other)
+    {
+      if (other instanceof GYearMonth)
+        {
+          GYearMonth gmy = (GYearMonth) other;
+          if (gmy.year == year)
+            {
+              if (gmy.month == month)
+                return 0;
+              return (month < gmy.month) ? -1 : 1;
+            }
+          return (year < gmy.year) ? -1 : 1;
+        }
+      return 0;
+    }
+    
+  }
+
+  static final int[] CONSTRAINING_FACETS = {
+    Facet.PATTERN,
+    Facet.ENUMERATION,
+    Facet.WHITESPACE,
+    Facet.MAX_INCLUSIVE,
+    Facet.MAX_EXCLUSIVE,
+    Facet.MIN_INCLUSIVE,
+    Facet.MIN_EXCLUSIVE
+  };
+
+  GYearMonthType()
+  {
+    super(new QName(XMLConstants.W3C_XML_SCHEMA_NS_URI, "gYearMonth"),
+          TypeLibrary.ANY_SIMPLE_TYPE);
+  }
+
+  public int[] getConstrainingFacets()
+  {
+    return CONSTRAINING_FACETS;
+  }
+
+  public void checkValid(String value, ValidationContext context)
+    throws DatatypeException
+  {
+    super.checkValid(value, context);
+    int len = value.length();
+    int state = 0;
+    int start = 0;
+    for (int i = 0; i < len; i++)
+      {
+        char c = value.charAt(i);
+        if (c == '-' && i == 0)
+          {
+            start++;
+            continue;
+          }
+        if (c >= 0x30 && c <= 0x39)
+          continue;
+        switch (state)
+          {
+          case 0: // year
+            if (c == '-')
+              {
+                String year = value.substring(start, i);
+                if (year.length() < 4 || Integer.parseInt(year) == 0)
+                  throw new DatatypeException(i, "illegal GYear value");
+                state = 1;
+                start = i + 1;
+                continue;
+              }
+            break;
+          }
+        throw new DatatypeException(i, "illegal GYear value");
+      }
+    switch (state)
+      {
+      case 1: // month
+        if (len - start != 2)
+          throw new DatatypeException("illegal GYear value");
+        break;
+      default:
+        throw new DatatypeException("illegal GYear value");
+      }
+  }
+  
+  public Object createValue(String literal, ValidationContext context) {
+    try
+      {
+        int offset = 5;
+        if (literal.charAt(0) == '-')
+          offset++;
+        GYearMonth ret = new GYearMonth();
+        ret.year = Integer.parseInt(literal.substring(0, offset));
+        ret.month = Integer.parseInt(literal.substring(offset + 1));
+        return ret;
+      }
+    catch (Exception e)
+      {
+        return null;
+      }
+  }
+  
+}
+

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/GYearType.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/GYearType.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/GYearType.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/GYearType.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,152 @@
+/* GYearType.java -- 
+   Copyright (C) 2006  Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.xml.validation.datatype;
+
+import javax.xml.XMLConstants;
+import javax.xml.namespace.QName;
+import org.relaxng.datatype.DatatypeException;
+import org.relaxng.datatype.ValidationContext;
+
+/**
+ * The XML Schema gYear type.
+ *
+ * @author <a href='mailto:dog at gnu.org'>Chris Burdess</a>
+ */
+final class GYearType
+  extends AtomicSimpleType
+{
+
+  static class GYear
+    implements Comparable
+  {
+
+    int year;
+
+    public int hashCode()
+    {
+      return year;
+    }
+
+    public boolean equals(Object other)
+    {
+      if (other instanceof GYear)
+        return ((GYear) other).year == year;
+      return false;
+    }
+
+    public int compareTo(Object other)
+    {
+      if (other instanceof GYear)
+        {
+          GYear gy = (GYear) other;
+          if (gy.year == year)
+            return 0;
+          return (year < gy.year) ? -1 : 1;
+        }
+      return 0;
+    }
+    
+  }
+
+  static final int[] CONSTRAINING_FACETS = {
+    Facet.PATTERN,
+    Facet.ENUMERATION,
+    Facet.WHITESPACE,
+    Facet.MAX_INCLUSIVE,
+    Facet.MAX_EXCLUSIVE,
+    Facet.MIN_INCLUSIVE,
+    Facet.MIN_EXCLUSIVE
+  };
+
+  GYearType()
+  {
+    super(new QName(XMLConstants.W3C_XML_SCHEMA_NS_URI, "gYear"),
+          TypeLibrary.ANY_SIMPLE_TYPE);
+  }
+
+  public int[] getConstrainingFacets()
+  {
+    return CONSTRAINING_FACETS;
+  }
+
+  public void checkValid(String value, ValidationContext context)
+    throws DatatypeException
+  {
+    super.checkValid(value, context);
+    int len = value.length();
+    int state = 0;
+    int start = 0;
+    for (int i = 0; i < len; i++)
+      {
+        char c = value.charAt(i);
+        if (c == '-' && i == 0)
+          {
+            start++;
+            continue;
+          }
+        if (c >= 0x30 && c <= 0x39)
+          continue;
+        throw new DatatypeException(i, "invalid GYear value");
+      }
+    switch (state)
+      {
+      case 0: // year
+        String year = value.substring(start, len);
+        if (year.length() < 4 || Integer.parseInt(year) == 0)
+          throw new DatatypeException("invalid GYear value");
+        break;
+      default:
+        throw new DatatypeException("invalid GYear value");
+      }
+  }
+  
+  public Object createValue(String literal, ValidationContext context) {
+    try
+      {
+        GYear ret = new GYear();
+        ret.year = Integer.parseInt(literal);
+        return ret;
+      }
+    catch (Exception e)
+      {
+        return null;
+      }
+  }
+  
+}
+

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/HexBinaryType.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/HexBinaryType.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/HexBinaryType.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/HexBinaryType.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,92 @@
+/* HexBinaryType.java -- 
+   Copyright (C) 2006  Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.xml.validation.datatype;
+
+import java.util.Collections;
+import java.util.Set;
+import javax.xml.XMLConstants;
+import javax.xml.namespace.QName;
+import org.relaxng.datatype.DatatypeException;
+import org.relaxng.datatype.ValidationContext;
+
+/**
+ * The XML Schema hexBinary type.
+ *
+ * @author <a href='mailto:dog at gnu.org'>Chris Burdess</a>
+ */
+final class HexBinaryType
+  extends AtomicSimpleType
+{
+
+  static final String HEX = "0123456789ABCDEF";
+
+  static final int[] CONSTRAINING_FACETS = {
+    Facet.LENGTH,
+    Facet.MIN_LENGTH,
+    Facet.MAX_LENGTH,
+    Facet.PATTERN,
+    Facet.ENUMERATION,
+    Facet.WHITESPACE
+  };
+
+  HexBinaryType()
+  {
+    super(new QName(XMLConstants.W3C_XML_SCHEMA_NS_URI, "hexBinary"),
+          TypeLibrary.ANY_SIMPLE_TYPE);
+  }
+
+  public int[] getConstrainingFacets()
+  {
+    return CONSTRAINING_FACETS;
+  }
+
+  public void checkValid(String value, ValidationContext context)
+    throws DatatypeException
+  {
+    super.checkValid(value, context);
+    int len = value.length();
+    for (int i = 0; i < len; i++)
+      {
+        char c = value.charAt(i);
+        if (HEX.indexOf(c) == -1)
+          throw new DatatypeException(i, "invalid hexBinary value");
+      }
+  }
+  
+}
+

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/IDRefType.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/IDRefType.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/IDRefType.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/IDRefType.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,87 @@
+/* IDRefType.java -- 
+   Copyright (C) 2006  Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.xml.validation.datatype;
+
+import javax.xml.XMLConstants;
+import javax.xml.namespace.QName;
+import org.relaxng.datatype.DatatypeException;
+import org.relaxng.datatype.ValidationContext;
+
+/**
+ * The XML Schema IDREF type.
+ *
+ * @author <a href='mailto:dog at gnu.org'>Chris Burdess</a>
+ */
+final class IDRefType
+  extends AtomicSimpleType
+{
+
+  static final int[] CONSTRAINING_FACETS = {
+    Facet.LENGTH,
+    Facet.MIN_LENGTH,
+    Facet.MAX_LENGTH,
+    Facet.PATTERN,
+    Facet.ENUMERATION,
+    Facet.WHITESPACE
+  };
+
+  IDRefType()
+  {
+    super(new QName(XMLConstants.W3C_XML_SCHEMA_NS_URI, "IDREF"),
+          TypeLibrary.NCNAME);
+  }
+
+  public int[] getConstrainingFacets()
+  {
+    return CONSTRAINING_FACETS;
+  }
+
+  public void checkValid(String value, ValidationContext context)
+    throws DatatypeException
+  {
+    super.checkValid(value, context);
+    // TODO
+  }
+
+  public int getIdType()
+  {
+    return ID_TYPE_IDREF;
+  }
+  
+}
+

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/IDRefsType.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/IDRefsType.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/IDRefsType.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/IDRefsType.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,87 @@
+/* IDRefsType.java -- 
+   Copyright (C) 2006  Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.xml.validation.datatype;
+
+import javax.xml.XMLConstants;
+import javax.xml.namespace.QName;
+import org.relaxng.datatype.DatatypeException;
+import org.relaxng.datatype.ValidationContext;
+
+/**
+ * The XML Schema IDREFS type.
+ *
+ * @author <a href='mailto:dog at gnu.org'>Chris Burdess</a>
+ */
+final class IDRefsType
+  extends AtomicSimpleType
+{
+
+  static final int[] CONSTRAINING_FACETS = {
+    Facet.LENGTH,
+    Facet.MIN_LENGTH,
+    Facet.MAX_LENGTH,
+    Facet.PATTERN,
+    Facet.ENUMERATION,
+    Facet.WHITESPACE
+  };
+
+  IDRefsType()
+  {
+    super(new QName(XMLConstants.W3C_XML_SCHEMA_NS_URI, "IDREFS"),
+          TypeLibrary.IDREF);
+  }
+
+  public int[] getConstrainingFacets()
+  {
+    return CONSTRAINING_FACETS;
+  }
+
+  public void checkValid(String value, ValidationContext context)
+    throws DatatypeException
+  {
+    super.checkValid(value, context);
+    // TODO
+  }
+
+  public int getIdType()
+  {
+    return ID_TYPE_IDREFS;
+  }
+  
+}
+

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/IDType.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/IDType.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/IDType.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/IDType.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,87 @@
+/* IDType.java -- 
+   Copyright (C) 2006  Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.xml.validation.datatype;
+
+import javax.xml.XMLConstants;
+import javax.xml.namespace.QName;
+import org.relaxng.datatype.DatatypeException;
+import org.relaxng.datatype.ValidationContext;
+
+/**
+ * The XML Schema ID type.
+ *
+ * @author <a href='mailto:dog at gnu.org'>Chris Burdess</a>
+ */
+final class IDType
+  extends AtomicSimpleType
+{
+
+  static final int[] CONSTRAINING_FACETS = {
+    Facet.LENGTH,
+    Facet.MIN_LENGTH,
+    Facet.MAX_LENGTH,
+    Facet.PATTERN,
+    Facet.ENUMERATION,
+    Facet.WHITESPACE
+  };
+
+  IDType()
+  {
+    super(new QName(XMLConstants.W3C_XML_SCHEMA_NS_URI, "ID"),
+          TypeLibrary.NCNAME);
+  }
+
+  public int[] getConstrainingFacets()
+  {
+    return CONSTRAINING_FACETS;
+  }
+
+  public void checkValid(String value, ValidationContext context)
+    throws DatatypeException
+  {
+    super.checkValid(value, context);
+    // TODO
+  }
+
+  public int getIdType()
+  {
+    return ID_TYPE_ID;
+  }
+  
+}
+

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/IntType.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/IntType.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/IntType.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/IntType.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,133 @@
+/* IntType.java -- 
+   Copyright (C) 2006  Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.xml.validation.datatype;
+
+import javax.xml.XMLConstants;
+import javax.xml.namespace.QName;
+import org.relaxng.datatype.DatatypeException;
+import org.relaxng.datatype.ValidationContext;
+
+/**
+ * The XML Schema int type.
+ *
+ * @author <a href='mailto:dog at gnu.org'>Chris Burdess</a>
+ */
+final class IntType
+  extends AtomicSimpleType
+{
+
+  static final int[] CONSTRAINING_FACETS = {
+    Facet.TOTAL_DIGITS,
+    Facet.FRACTION_DIGITS,
+    Facet.PATTERN,
+    Facet.WHITESPACE,
+    Facet.ENUMERATION,
+    Facet.MAX_INCLUSIVE,
+    Facet.MAX_EXCLUSIVE,
+    Facet.MIN_INCLUSIVE,
+    Facet.MIN_EXCLUSIVE
+  };
+
+  static final String MAX_VALUE = "2147483647";
+  static final String MIN_VALUE = "2147483648";
+  static final int LENGTH = MAX_VALUE.length();
+
+  IntType()
+  {
+    super(new QName(XMLConstants.W3C_XML_SCHEMA_NS_URI, "int"),
+          TypeLibrary.LONG);
+  }
+
+  public int[] getConstrainingFacets()
+  {
+    return CONSTRAINING_FACETS;
+  }
+
+  public void checkValid(String value, ValidationContext context)
+    throws DatatypeException
+  {
+    super.checkValid(value, context);
+    int len = value.length();
+    if (len == 0)
+      throw new DatatypeException(0, "invalid int value");
+    int i = 0, off = 0;
+    boolean compare = false;
+    String compareTo = MAX_VALUE;
+    char c = value.charAt(0);
+    if (c == '+')
+      i++;
+    else if (c == '-')
+      {
+        compareTo = MIN_VALUE;
+        i++;
+      }
+    if (len - i > LENGTH)
+      throw new DatatypeException("invalid int value");
+    else if (len - i == LENGTH)
+      compare = true;
+    for (; i < len; i++)
+      {
+        c = value.charAt(i);
+        if (c >= 0x30 && c <= 0x39)
+          {
+            if (compare)
+              {
+                char d = compareTo.charAt(off);
+                if (Character.digit(c, 10) > Character.digit(d, 10))
+                  throw new DatatypeException(i, "invalid int value");
+              }
+            off++;
+            continue;
+          }
+        throw new DatatypeException(i, "invalid int value");
+      }
+  }
+  
+  public Object createValue(String literal, ValidationContext context) {
+    try
+      {
+        return new Integer(literal);
+      }
+    catch (NumberFormatException e)
+      {
+        return null;
+      }
+  }
+  
+}
+

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/IntegerType.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/IntegerType.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/IntegerType.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/IntegerType.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,110 @@
+/* IntegerType.java -- 
+   Copyright (C) 2006  Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.xml.validation.datatype;
+
+import java.math.BigInteger;
+import javax.xml.XMLConstants;
+import javax.xml.namespace.QName;
+import org.relaxng.datatype.DatatypeException;
+import org.relaxng.datatype.ValidationContext;
+
+/**
+ * The XML Schema integer type.
+ *
+ * @author <a href='mailto:dog at gnu.org'>Chris Burdess</a>
+ */
+final class IntegerType
+  extends AtomicSimpleType
+{
+
+  static final int[] CONSTRAINING_FACETS = {
+    Facet.TOTAL_DIGITS,
+    Facet.FRACTION_DIGITS,
+    Facet.PATTERN,
+    Facet.WHITESPACE,
+    Facet.ENUMERATION,
+    Facet.MAX_INCLUSIVE,
+    Facet.MAX_EXCLUSIVE,
+    Facet.MIN_INCLUSIVE,
+    Facet.MIN_EXCLUSIVE
+  };
+
+  IntegerType()
+  {
+    super(new QName(XMLConstants.W3C_XML_SCHEMA_NS_URI, "integer"),
+          TypeLibrary.DECIMAL);
+  }
+
+  public int[] getConstrainingFacets()
+  {
+    return CONSTRAINING_FACETS;
+  }
+
+  public void checkValid(String value, ValidationContext context)
+    throws DatatypeException
+  {
+    super.checkValid(value, context);
+    int len = value.length();
+    if (len == 0)
+      throw new DatatypeException(0, "invalid integer value");
+    for (int i = 0; i < len; i++)
+      {
+        char c = value.charAt(i);
+        if (c >= 0x30 && c <= 0x39)
+          continue;
+        else if (c == '+' && i == 0)
+          continue;
+        else if (c == '-' && i == 0)
+          continue;
+        throw new DatatypeException(i, "invalid integer value");
+      }
+  }
+  
+  public Object createValue(String literal, ValidationContext context) {
+    try
+      {
+        return new BigInteger(literal);
+      }
+    catch (NumberFormatException e)
+      {
+        return null;
+      }
+  }
+  
+}
+

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/LanguageType.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/LanguageType.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/LanguageType.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/LanguageType.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,87 @@
+/* LanguageType.java -- 
+   Copyright (C) 2006  Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.xml.validation.datatype;
+
+import java.util.regex.Pattern;
+import javax.xml.XMLConstants;
+import javax.xml.namespace.QName;
+import org.relaxng.datatype.DatatypeException;
+import org.relaxng.datatype.ValidationContext;
+
+/**
+ * The XML Schema language type.
+ *
+ * @author <a href='mailto:dog at gnu.org'>Chris Burdess</a>
+ */
+final class LanguageType
+  extends AtomicSimpleType
+{
+
+  static final int[] CONSTRAINING_FACETS = {
+    Facet.LENGTH,
+    Facet.MIN_LENGTH,
+    Facet.MAX_LENGTH,
+    Facet.PATTERN,
+    Facet.ENUMERATION,
+    Facet.WHITESPACE
+  };
+
+  static final Pattern PATTERN =
+    Pattern.compile("[a-zA-Z]{1,8}(-[a-zA-Z0-9]{1,8})*");
+
+  LanguageType()
+  {
+    super(new QName(XMLConstants.W3C_XML_SCHEMA_NS_URI, "language"),
+          TypeLibrary.TOKEN);
+  }
+
+  public int[] getConstrainingFacets()
+  {
+    return CONSTRAINING_FACETS;
+  }
+
+  public void checkValid(String value, ValidationContext context)
+    throws DatatypeException
+  {
+    super.checkValid(value, context);
+    if (!PATTERN.matcher(value).matches())
+      throw new DatatypeException("invalid language value");
+  }
+  
+}
+

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/LengthFacet.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/LengthFacet.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/LengthFacet.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/LengthFacet.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,72 @@
+/* LengthFacet.java -- 
+   Copyright (C) 2006  Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.xml.validation.datatype;
+
+/**
+ * The <code>length</code> facet.
+ *
+ * @author <a href='mailto:dog at gnu.org'>Chris Burdess</a>
+ */
+public final class LengthFacet
+  extends Facet
+{
+  
+  public final int value;
+
+  public final boolean fixed;
+
+  public LengthFacet(int value, boolean fixed, Annotation annotation)
+  {
+    super(LENGTH, annotation);
+    this.value = value;
+    this.fixed = fixed;
+  }
+  
+  public int hashCode()
+  {
+    return value;
+  }
+
+  public boolean equals(Object other)
+  {
+    return (other instanceof LengthFacet &&
+            ((LengthFacet) other).value == value);
+  }
+  
+}
+

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/ListSimpleType.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/ListSimpleType.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/ListSimpleType.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/ListSimpleType.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,83 @@
+/* ListSimpleType.java -- 
+   Copyright (C) 2006  Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.xml.validation.datatype;
+
+import java.util.Set;
+import java.util.StringTokenizer;
+import javax.xml.namespace.QName;
+import org.relaxng.datatype.DatatypeException;
+import org.relaxng.datatype.ValidationContext;
+
+/**
+ * An XML Schema list simple type.
+ *
+ * @author <a href='mailto:dog at gnu.org'>Chris Burdess</a>
+ */
+public class ListSimpleType
+  extends SimpleType
+{
+
+  /**
+   * The type of the items in this list (atomic or union).
+   */
+  public final SimpleType itemType;
+  
+  public ListSimpleType(QName name, Set facets,
+                        int fundamentalFacets, SimpleType baseType,
+                        Annotation annotation, SimpleType itemType)
+  {
+    super(name, LIST, facets, fundamentalFacets, baseType, annotation);
+    this.itemType = itemType;
+  }
+  
+  public void checkValid(String value, ValidationContext context)
+    throws DatatypeException
+  {
+    super.checkValid(value, context);
+    StringTokenizer st = new StringTokenizer(value, " ");
+    if (!st.hasMoreTokens())
+      throw new DatatypeException("invalid list value");
+    while (st.hasMoreTokens())
+      {
+        String token = st.nextToken();
+        itemType.checkValid(token, context);
+      }
+  }
+  
+}
+

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/LongType.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/LongType.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/LongType.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/LongType.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,133 @@
+/* LongType.java -- 
+   Copyright (C) 2006  Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.xml.validation.datatype;
+
+import javax.xml.XMLConstants;
+import javax.xml.namespace.QName;
+import org.relaxng.datatype.DatatypeException;
+import org.relaxng.datatype.ValidationContext;
+
+/**
+ * The XML Schema long type.
+ *
+ * @author <a href='mailto:dog at gnu.org'>Chris Burdess</a>
+ */
+final class LongType
+  extends AtomicSimpleType
+{
+
+  static final int[] CONSTRAINING_FACETS = {
+    Facet.TOTAL_DIGITS,
+    Facet.FRACTION_DIGITS,
+    Facet.PATTERN,
+    Facet.WHITESPACE,
+    Facet.ENUMERATION,
+    Facet.MAX_INCLUSIVE,
+    Facet.MAX_EXCLUSIVE,
+    Facet.MIN_INCLUSIVE,
+    Facet.MIN_EXCLUSIVE
+  };
+
+  static final String MAX_VALUE = "9223372036854775807";
+  static final String MIN_VALUE = "9223372036854775808";
+  static final int LENGTH = MAX_VALUE.length();
+
+  LongType()
+  {
+    super(new QName(XMLConstants.W3C_XML_SCHEMA_NS_URI, "long"),
+          TypeLibrary.INTEGER);
+  }
+
+  public int[] getConstrainingFacets()
+  {
+    return CONSTRAINING_FACETS;
+  }
+
+  public void checkValid(String value, ValidationContext context)
+    throws DatatypeException
+  {
+    super.checkValid(value, context);
+    int len = value.length();
+    if (len == 0)
+      throw new DatatypeException(0, "invalid long value");
+    int i = 0, off = 0;
+    boolean compare = false;
+    String compareTo = MAX_VALUE;
+    char c = value.charAt(0);
+    if (c == '+')
+      i++;
+    else if (c == '-')
+      {
+        compareTo = MIN_VALUE;
+        i++;
+      }
+    if (len - i > LENGTH)
+      throw new DatatypeException(i, "invalid long value");
+    else if (len - i == LENGTH)
+      compare = true;
+    for (; i < len; i++)
+      {
+        c = value.charAt(i);
+        if (c >= 0x30 && c <= 0x39)
+          {
+            if (compare)
+              {
+                char d = compareTo.charAt(off);
+                if (Character.digit(c, 10) > Character.digit(d, 10))
+                  throw new DatatypeException(i, "invalid long value");
+              }
+            off++;
+            continue;
+          }
+        throw new DatatypeException(i, "invalid long value");
+      }
+  }
+  
+  public Object createValue(String literal, ValidationContext context) {
+    try
+      {
+        return new Long(literal);
+      }
+    catch (NumberFormatException e)
+      {
+        return null;
+      }
+  }
+  
+}
+

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/MaxExclusiveFacet.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/MaxExclusiveFacet.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/MaxExclusiveFacet.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/MaxExclusiveFacet.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,111 @@
+/* MaxExclusiveFacet.java -- 
+   Copyright (C) 2006  Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.xml.validation.datatype;
+
+import java.math.BigDecimal;
+import java.math.BigInteger;
+import java.util.Date;
+
+/**
+ * The <code>maxExclusive</code> facet.
+ *
+ * @author <a href='mailto:dog at gnu.org'>Chris Burdess</a>
+ */
+public final class MaxExclusiveFacet
+  extends Facet
+{
+  
+  public final Object value; // date or number
+
+  public final boolean fixed;
+
+  public MaxExclusiveFacet(Object value, boolean fixed, Annotation annotation)
+  {
+    super(MAX_EXCLUSIVE, annotation);
+    this.value = value;
+    this.fixed = fixed;
+  }
+  
+  public int hashCode()
+  {
+    return value.hashCode();
+  }
+
+  public boolean equals(Object other)
+  {
+    return (other instanceof MaxExclusiveFacet &&
+            ((MaxExclusiveFacet) other).value.equals(value));
+  }
+
+  boolean matches(Object test)
+  {
+    if (value instanceof Date)
+      {
+        Date dvalue = (Date) value;
+        if (!(test instanceof Date))
+          return false;
+        return ((Date) test).before(dvalue);
+      }
+    else if (value instanceof BigInteger)
+      {
+        BigInteger ivalue = (BigInteger) value;
+        if (!(test instanceof BigInteger))
+          return false;
+        return ((BigInteger) test).compareTo(ivalue) < 0;
+      }
+    else if (value instanceof BigDecimal)
+      {
+        BigDecimal dvalue = (BigDecimal) value;
+        if (!(test instanceof BigDecimal))
+          return false;
+        return ((BigDecimal) test).compareTo(dvalue) < 0;
+      }
+    else if (value instanceof Comparable)
+      {
+        if (!(test.getClass().equals(value.getClass())))
+          return false;
+        return ((Comparable) test).compareTo(value) < 0;
+      }
+    Number nvalue = (Number) value;
+    if (!(test instanceof Number))
+      return false;
+    return ((Number) test).doubleValue() < nvalue.doubleValue();
+  }
+  
+}
+

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/MaxInclusiveFacet.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/MaxInclusiveFacet.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/MaxInclusiveFacet.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/MaxInclusiveFacet.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,112 @@
+/* MaxInclusiveFacet.java -- 
+   Copyright (C) 2006  Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.xml.validation.datatype;
+
+import java.math.BigDecimal;
+import java.math.BigInteger;
+import java.util.Date;
+
+/**
+ * The <code>maxInclusive</code> facet.
+ *
+ * @author <a href='mailto:dog at gnu.org'>Chris Burdess</a>
+ */
+public final class MaxInclusiveFacet
+  extends Facet
+{
+  
+  public final Object value;
+
+  public final boolean fixed;
+
+  public MaxInclusiveFacet(Object value, boolean fixed, Annotation annotation)
+  {
+    super(MAX_INCLUSIVE, annotation);
+    this.value = value;
+    this.fixed = fixed;
+  }
+  
+  public int hashCode()
+  {
+    return value.hashCode();
+  }
+
+  public boolean equals(Object other)
+  {
+    return (other instanceof MaxInclusiveFacet &&
+            ((MaxInclusiveFacet) other).value.equals(value));
+  }
+  
+  boolean matches(Object test)
+  {
+    if (value instanceof Date)
+      {
+        Date dvalue = (Date) value;
+        if (!(test instanceof Date))
+          return false;
+        Date dtest = (Date) test;
+        return dtest.equals(dvalue) || dtest.before(dvalue);
+      }
+    else if (value instanceof BigInteger)
+      {
+        BigInteger ivalue = (BigInteger) value;
+        if (!(test instanceof BigInteger))
+          return false;
+        return ((BigInteger) test).compareTo(ivalue) <= 0;
+      }
+    else if (value instanceof BigDecimal)
+      {
+        BigDecimal dvalue = (BigDecimal) value;
+        if (!(test instanceof BigDecimal))
+          return false;
+        return ((BigDecimal) test).compareTo(dvalue) <= 0;
+      }
+    else if (value instanceof Comparable)
+      {
+        if (!(test.getClass().equals(value.getClass())))
+          return false;
+        return ((Comparable) test).compareTo(value) <= 0;
+      }
+    Number nvalue = (Number) value;
+    if (!(test instanceof Number))
+      return false;
+    return ((Number) test).doubleValue() <= nvalue.doubleValue();
+  }
+  
+}
+

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/MaxLengthFacet.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/MaxLengthFacet.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/MaxLengthFacet.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/MaxLengthFacet.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,72 @@
+/* MaxLengthFacet.java -- 
+   Copyright (C) 2006  Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.xml.validation.datatype;
+
+/**
+ * The <code>maxLength</code> facet.
+ *
+ * @author <a href='mailto:dog at gnu.org'>Chris Burdess</a>
+ */
+public final class MaxLengthFacet
+  extends Facet
+{
+
+  public final int value;
+
+  public final boolean fixed;
+
+  public MaxLengthFacet(int value, boolean fixed, Annotation annotation)
+  {
+    super(MAX_LENGTH, annotation);
+    this.value = value;
+    this.fixed = fixed;
+  }
+
+  public int hashCode()
+  {
+    return value;
+  }
+
+  public boolean equals(Object other)
+  {
+    return (other instanceof MaxLengthFacet &&
+            ((MaxLengthFacet) other).value == value);
+  }
+  
+}
+

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/MinExclusiveFacet.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/MinExclusiveFacet.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/MinExclusiveFacet.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/MinExclusiveFacet.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,111 @@
+/* MinExclusiveFacet.java -- 
+   Copyright (C) 2006  Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.xml.validation.datatype;
+
+import java.math.BigDecimal;
+import java.math.BigInteger;
+import java.util.Date;
+
+/**
+ * The <code>minExclusive</code> facet.
+ *
+ * @author <a href='mailto:dog at gnu.org'>Chris Burdess</a>
+ */
+public final class MinExclusiveFacet
+  extends Facet
+{
+  
+  public final Object value;
+
+  public final boolean fixed;
+
+  public MinExclusiveFacet(Object value, boolean fixed, Annotation annotation)
+  {
+    super(MIN_EXCLUSIVE, annotation);
+    this.value = value;
+    this.fixed = fixed;
+  }
+  
+  public int hashCode()
+  {
+    return value.hashCode();
+  }
+
+  public boolean equals(Object other)
+  {
+    return (other instanceof MinExclusiveFacet &&
+            ((MinExclusiveFacet) other).value.equals(value));
+  }
+  
+  boolean matches(Object test)
+  {
+    if (value instanceof Date)
+      {
+        Date dvalue = (Date) value;
+        if (!(test instanceof Date))
+          return false;
+        return ((Date) test).after(dvalue);
+      }
+    else if (value instanceof BigInteger)
+      {
+        BigInteger ivalue = (BigInteger) value;
+        if (!(test instanceof BigInteger))
+          return false;
+        return ((BigInteger) test).compareTo(ivalue) > 0;
+      }
+    else if (value instanceof BigDecimal)
+      {
+        BigDecimal dvalue = (BigDecimal) value;
+        if (!(test instanceof BigDecimal))
+          return false;
+        return ((BigDecimal) test).compareTo(dvalue) > 0;
+      }
+    else if (value instanceof Comparable)
+      {
+        if (!(test.getClass().equals(value.getClass())))
+          return false;
+        return ((Comparable) test).compareTo(value) > 0;
+      }
+    Number nvalue = (Number) value;
+    if (!(test instanceof Number))
+      return false;
+    return ((Number) test).doubleValue() > nvalue.doubleValue();
+  }
+  
+}
+

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/MinInclusiveFacet.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/MinInclusiveFacet.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/MinInclusiveFacet.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/MinInclusiveFacet.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,112 @@
+/* MinInclusiveFacet.java -- 
+   Copyright (C) 2006  Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.xml.validation.datatype;
+
+import java.math.BigDecimal;
+import java.math.BigInteger;
+import java.util.Date;
+
+/**
+ * The <code>minInclusive</code> facet.
+ *
+ * @author <a href='mailto:dog at gnu.org'>Chris Burdess</a>
+ */
+public final class MinInclusiveFacet
+  extends Facet
+{
+  
+  public final Object value;
+
+  public final boolean fixed;
+
+  public MinInclusiveFacet(Object value, boolean fixed, Annotation annotation)
+  {
+    super(MIN_INCLUSIVE, annotation);
+    this.value = value;
+    this.fixed = fixed;
+  }
+  
+  public int hashCode()
+  {
+    return value.hashCode();
+  }
+
+  public boolean equals(Object other)
+  {
+    return (other instanceof MinInclusiveFacet &&
+            ((MinInclusiveFacet) other).value.equals(value));
+  }
+  
+  boolean matches(Object test)
+  {
+    if (value instanceof Date)
+      {
+        Date dvalue = (Date) value;
+        if (!(test instanceof Date))
+          return false;
+        Date dtest = (Date) test;
+        return dtest.equals(dvalue) || dtest.after(dvalue);
+      }
+    else if (value instanceof BigInteger)
+      {
+        BigInteger ivalue = (BigInteger) value;
+        if (!(test instanceof BigInteger))
+          return false;
+        return ((BigInteger) test).compareTo(ivalue) >= 0;
+      }
+    else if (value instanceof BigDecimal)
+      {
+        BigDecimal dvalue = (BigDecimal) value;
+        if (!(test instanceof BigDecimal))
+          return false;
+        return ((BigDecimal) test).compareTo(dvalue) >= 0;
+      }
+    else if (value instanceof Comparable)
+      {
+        if (!(test.getClass().equals(value.getClass())))
+          return false;
+        return ((Comparable) test).compareTo(value) >= 0;
+      }
+    Number nvalue = (Number) value;
+    if (!(test instanceof Number))
+      return false;
+    return ((Number) test).doubleValue() >= nvalue.doubleValue();
+  }
+  
+}
+

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/MinLengthFacet.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/MinLengthFacet.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/MinLengthFacet.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/MinLengthFacet.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,72 @@
+/* MinLengthFacet.java -- 
+   Copyright (C) 2006  Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.xml.validation.datatype;
+
+/**
+ * The <code>minLength</code> facet.
+ *
+ * @author <a href='mailto:dog at gnu.org'>Chris Burdess</a>
+ */
+public final class MinLengthFacet
+  extends Facet
+{
+
+  public final int value;
+
+  public final boolean fixed;
+
+  public MinLengthFacet(int value, boolean fixed, Annotation annotation)
+  {
+    super(MIN_LENGTH, annotation);
+    this.value = value;
+    this.fixed = fixed;
+  }
+
+  public int hashCode()
+  {
+    return value;
+  }
+
+  public boolean equals(Object other)
+  {
+    return (other instanceof MinLengthFacet &&
+            ((MinLengthFacet) other).value == value);
+  }
+  
+}
+

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/NCNameType.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/NCNameType.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/NCNameType.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/NCNameType.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,111 @@
+/* NCNameType.java -- 
+   Copyright (C) 2006  Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.xml.validation.datatype;
+
+import java.io.IOException;
+import javax.xml.XMLConstants;
+import javax.xml.namespace.QName;
+import org.relaxng.datatype.DatatypeException;
+import org.relaxng.datatype.ValidationContext;
+import gnu.xml.stream.UnicodeReader;
+import gnu.xml.stream.XMLParser;
+
+/**
+ * The XML Schema NCName type.
+ *
+ * @author <a href='mailto:dog at gnu.org'>Chris Burdess</a>
+ */
+final class NCNameType
+  extends AtomicSimpleType
+{
+
+  static final int[] CONSTRAINING_FACETS = {
+    Facet.LENGTH,
+    Facet.MIN_LENGTH,
+    Facet.MAX_LENGTH,
+    Facet.PATTERN,
+    Facet.ENUMERATION,
+    Facet.WHITESPACE
+  };
+
+  NCNameType()
+  {
+    super(new QName(XMLConstants.W3C_XML_SCHEMA_NS_URI, "NCName"),
+          TypeLibrary.NAME);
+  }
+
+  public int[] getConstrainingFacets()
+  {
+    return CONSTRAINING_FACETS;
+  }
+
+  public void checkValid(String value, ValidationContext context)
+    throws DatatypeException
+  {
+    super.checkValid(value, context);
+    try
+      {
+        int[] cp = UnicodeReader.toCodePointArray(value);
+        if (cp.length == 0)
+          throw new DatatypeException("invalid NCName value");
+        // XXX XML 1.1 documents?
+        if (cp[0] == ':' || !XMLParser.isNameStartCharacter(cp[0], false))
+          throw new DatatypeException(0, "invalid NCName value");
+        boolean seenColon = false;
+        for (int i = 1; i < cp.length; i++)
+          {
+            if (cp[i] == ':')
+              {
+                if (seenColon || (i + 1 == cp.length))
+                  throw new DatatypeException(i, "invalid NCName value");
+                seenColon = true;
+              }
+            else if (!XMLParser.isNameCharacter(cp[i], false))
+              throw new DatatypeException(i, "invalid NCName value");
+          }
+      }
+    catch (IOException e)
+      {
+        DatatypeException e2 = new DatatypeException("invalid NCName value");
+        e2.initCause(e);
+        throw e2;
+      }
+  }
+  
+}
+

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/NMTokenType.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/NMTokenType.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/NMTokenType.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/NMTokenType.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,102 @@
+/* NMTokenType.java -- 
+   Copyright (C) 2006  Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.xml.validation.datatype;
+
+import java.io.IOException;
+import javax.xml.XMLConstants;
+import javax.xml.namespace.QName;
+import org.relaxng.datatype.DatatypeException;
+import org.relaxng.datatype.ValidationContext;
+import gnu.xml.stream.UnicodeReader;
+import gnu.xml.stream.XMLParser;
+
+/**
+ * The XML Schema NMTOKEN type.
+ *
+ * @author <a href='mailto:dog at gnu.org'>Chris Burdess</a>
+ */
+final class NMTokenType
+  extends AtomicSimpleType
+{
+
+  static final int[] CONSTRAINING_FACETS = {
+    Facet.LENGTH,
+    Facet.MIN_LENGTH,
+    Facet.MAX_LENGTH,
+    Facet.PATTERN,
+    Facet.ENUMERATION,
+    Facet.WHITESPACE
+  };
+
+  NMTokenType()
+  {
+    super(new QName(XMLConstants.W3C_XML_SCHEMA_NS_URI, "NMTOKEN"),
+          TypeLibrary.TOKEN);
+  }
+
+  public int[] getConstrainingFacets()
+  {
+    return CONSTRAINING_FACETS;
+  }
+
+  public void checkValid(String value, ValidationContext context)
+    throws DatatypeException
+  {
+    super.checkValid(value, context);
+    try
+      {
+        int[] cp = UnicodeReader.toCodePointArray(value);
+        if (cp.length == 0)
+          throw new DatatypeException("invalid NMTOKEN value");
+        for (int i = 0; i < cp.length; i++)
+          {
+            // XXX XML 1.1 documents?
+            if (!XMLParser.isNameCharacter(cp[i], false))
+              throw new DatatypeException(i, "invalid NMTOKEN value");
+          }
+      }
+    catch (IOException e)
+      {
+        DatatypeException e2 = new DatatypeException("invalid NMTOKEN value");
+        e2.initCause(e);
+        throw e2;
+      }
+  }
+  
+}
+

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/NMTokensType.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/NMTokensType.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/NMTokensType.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/NMTokensType.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,124 @@
+/* NMTokensType.java -- 
+   Copyright (C) 2006  Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.xml.validation.datatype;
+
+import java.io.IOException;
+import javax.xml.XMLConstants;
+import javax.xml.namespace.QName;
+import org.relaxng.datatype.DatatypeException;
+import org.relaxng.datatype.ValidationContext;
+import gnu.xml.stream.UnicodeReader;
+import gnu.xml.stream.XMLParser;
+
+/**
+ * The XML Schema NMTOKENS type.
+ *
+ * @author <a href='mailto:dog at gnu.org'>Chris Burdess</a>
+ */
+final class NMTokensType
+  extends AtomicSimpleType
+{
+
+  static final int[] CONSTRAINING_FACETS = {
+    Facet.LENGTH,
+    Facet.MIN_LENGTH,
+    Facet.MAX_LENGTH,
+    Facet.PATTERN,
+    Facet.ENUMERATION,
+    Facet.WHITESPACE
+  };
+
+  NMTokensType()
+  {
+    super(new QName(XMLConstants.W3C_XML_SCHEMA_NS_URI, "NMTOKENS"),
+          TypeLibrary.NMTOKEN);
+  }
+
+  public int[] getConstrainingFacets()
+  {
+    return CONSTRAINING_FACETS;
+  }
+
+  public void checkValid(String value, ValidationContext context)
+    throws DatatypeException
+  {
+    super.checkValid(value, context);
+    int len = value.length();
+    StringBuffer buf = new StringBuffer();
+    for (int i = 0; i < len; i++)
+      {
+        char c = value.charAt(i);
+        if (c == ' ')
+          {
+            String token = buf.toString();
+            if (token.length() > 0)
+              checkNmtoken(token, i);
+            buf.setLength(0);
+          }
+        else
+          buf.append(c);
+      }
+    checkNmtoken(buf.toString(), len);
+  }
+
+  private void checkNmtoken(String text, int i)
+    throws DatatypeException
+  {
+    try
+      {
+        int[] cp = UnicodeReader.toCodePointArray(text);
+        if (cp.length == 0)
+          throw new DatatypeException("invalid NMTOKEN value");
+        for (int j = 0; j < cp.length; j++)
+          {
+            // XXX XML 1.1 documents?
+            if (!XMLParser.isNameCharacter(cp[j], false))
+              throw new DatatypeException(i, "invalid NMTOKEN value");
+          }
+      }
+    catch (IOException e)
+      {
+        DatatypeException e2 = new DatatypeException("invalid NMTOKEN value");
+        e2.initCause(e);
+        throw e2;
+      }
+  }
+  
+  
+}
+

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/NameType.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/NameType.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/NameType.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/NameType.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,104 @@
+/* NameType.java -- 
+   Copyright (C) 2006  Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.xml.validation.datatype;
+
+import java.io.IOException;
+import javax.xml.XMLConstants;
+import javax.xml.namespace.QName;
+import org.relaxng.datatype.DatatypeException;
+import org.relaxng.datatype.ValidationContext;
+import gnu.xml.stream.UnicodeReader;
+import gnu.xml.stream.XMLParser;
+
+/**
+ * The XML Schema Name type.
+ *
+ * @author <a href='mailto:dog at gnu.org'>Chris Burdess</a>
+ */
+final class NameType
+  extends AtomicSimpleType
+{
+
+  static final int[] CONSTRAINING_FACETS = {
+    Facet.LENGTH,
+    Facet.MIN_LENGTH,
+    Facet.MAX_LENGTH,
+    Facet.PATTERN,
+    Facet.ENUMERATION,
+    Facet.WHITESPACE
+  };
+
+  NameType()
+  {
+    super(new QName(XMLConstants.W3C_XML_SCHEMA_NS_URI, "Name"),
+          TypeLibrary.TOKEN);
+  }
+
+  public int[] getConstrainingFacets()
+  {
+    return CONSTRAINING_FACETS;
+  }
+
+  public void checkValid(String value, ValidationContext context)
+    throws DatatypeException
+  {
+    super.checkValid(value, context);
+    try
+      {
+        int[] cp = UnicodeReader.toCodePointArray(value);
+        if (cp.length == 0)
+          throw new DatatypeException("invalid Name value");
+        // XXX XML 1.1 documents?
+        if (!XMLParser.isNameStartCharacter(cp[0], false))
+          throw new DatatypeException(0, "invalid Name value");
+        for (int i = 1; i < cp.length; i++)
+          {
+            if (!XMLParser.isNameCharacter(cp[i], false))
+              throw new DatatypeException(i, "invalid Name value");
+          }
+      }
+    catch (IOException e)
+      {
+        DatatypeException e2 = new DatatypeException("invalid Name value");
+        e2.initCause(e);
+        throw e2;
+      }
+  }
+  
+}
+

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/NegativeIntegerType.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/NegativeIntegerType.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/NegativeIntegerType.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/NegativeIntegerType.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,111 @@
+/* NegativeIntegerType.java -- 
+   Copyright (C) 2006  Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.xml.validation.datatype;
+
+import java.math.BigInteger;
+import javax.xml.XMLConstants;
+import javax.xml.namespace.QName;
+import org.relaxng.datatype.DatatypeException;
+import org.relaxng.datatype.ValidationContext;
+
+/**
+ * The XML Schema negativeInteger type.
+ *
+ * @author <a href='mailto:dog at gnu.org'>Chris Burdess</a>
+ */
+final class NegativeIntegerType
+  extends AtomicSimpleType
+{
+
+  static final int[] CONSTRAINING_FACETS = {
+    Facet.TOTAL_DIGITS,
+    Facet.FRACTION_DIGITS,
+    Facet.PATTERN,
+    Facet.WHITESPACE,
+    Facet.ENUMERATION,
+    Facet.MAX_INCLUSIVE,
+    Facet.MAX_EXCLUSIVE,
+    Facet.MIN_INCLUSIVE,
+    Facet.MIN_EXCLUSIVE
+  };
+
+  NegativeIntegerType()
+  {
+    super(new QName(XMLConstants.W3C_XML_SCHEMA_NS_URI, "negativeInteger"),
+          TypeLibrary.NON_POSITIVE_INTEGER);
+  }
+
+  public int[] getConstrainingFacets()
+  {
+    return CONSTRAINING_FACETS;
+  }
+
+  public void checkValue(String value, ValidationContext context)
+    throws DatatypeException
+  {
+    super.checkValid(value, context);
+    int len = value.length();
+    if (len == 0)
+      throw new DatatypeException(0, "invalid negative integer value");
+    for (int i = 0; i < len; i++)
+      {
+        char c = value.charAt(i);
+        if (c == '-')
+          {
+            if (i == 0)
+              continue;
+          }
+        else if (c >= 0x30 && c <= 0x39)
+            continue;
+        throw new DatatypeException(i, "invalid negative integer value");
+      }
+  }
+  
+  public Object createValue(String literal, ValidationContext context) {
+    try
+      {
+        return new BigInteger(literal);
+      }
+    catch (NumberFormatException e)
+      {
+        return null;
+      }
+  }
+  
+}
+

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/NonNegativeIntegerType.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/NonNegativeIntegerType.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/NonNegativeIntegerType.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/NonNegativeIntegerType.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,121 @@
+/* NonNegativeIntegerType.java -- 
+   Copyright (C) 2006  Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.xml.validation.datatype;
+
+import java.math.BigInteger;
+import javax.xml.XMLConstants;
+import javax.xml.namespace.QName;
+import org.relaxng.datatype.DatatypeException;
+import org.relaxng.datatype.ValidationContext;
+
+/**
+ * The XML Schema nonNegativeInteger type.
+ *
+ * @author <a href='mailto:dog at gnu.org'>Chris Burdess</a>
+ */
+final class NonNegativeIntegerType
+  extends AtomicSimpleType
+{
+
+  static final int[] CONSTRAINING_FACETS = {
+    Facet.TOTAL_DIGITS,
+    Facet.FRACTION_DIGITS,
+    Facet.PATTERN,
+    Facet.WHITESPACE,
+    Facet.ENUMERATION,
+    Facet.MAX_INCLUSIVE,
+    Facet.MAX_EXCLUSIVE,
+    Facet.MIN_INCLUSIVE,
+    Facet.MIN_EXCLUSIVE
+  };
+
+  NonNegativeIntegerType()
+  {
+    super(new QName(XMLConstants.W3C_XML_SCHEMA_NS_URI, "nonNegativeInteger"),
+          TypeLibrary.INTEGER);
+  }
+
+  public int[] getConstrainingFacets()
+  {
+    return CONSTRAINING_FACETS;
+  }
+
+  public void checkValid(String value, ValidationContext context)
+    throws DatatypeException
+  {
+    super.checkValid(value, context);
+    int len = value.length();
+    if (len == 0)
+      throw new DatatypeException(0, "invalid non-negative integer value");
+    boolean negative = false;
+    for (int i = 0; i < len; i++)
+      {
+        char c = value.charAt(i);
+        if (c == 0x30)
+          continue;
+        else if (c >= 0x31 && c <= 0x39)
+          {
+            if (negative)
+              throw new DatatypeException(i,
+                                          "invalid non-negative integer value");
+            continue;
+          }
+        else if (c == '+' && i == 0)
+          continue;
+        else if (c == '-' && i == 0)
+          {
+            negative = true;
+            continue;
+          }
+        throw new DatatypeException(i, "invalid non-negative integer value");
+      }
+  }
+  
+  public Object createValue(String literal, ValidationContext context) {
+    try
+      {
+        return new BigInteger(literal);
+      }
+    catch (NumberFormatException e)
+      {
+        return null;
+      }
+  }
+  
+}
+

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/NonPositiveIntegerType.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/NonPositiveIntegerType.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/NonPositiveIntegerType.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/NonPositiveIntegerType.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,121 @@
+/* NonPositiveIntegerType.java -- 
+   Copyright (C) 2006  Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.xml.validation.datatype;
+
+import java.math.BigInteger;
+import javax.xml.XMLConstants;
+import javax.xml.namespace.QName;
+import org.relaxng.datatype.DatatypeException;
+import org.relaxng.datatype.ValidationContext;
+
+/**
+ * The XML Schema nonPositiveInteger type.
+ *
+ * @author <a href='mailto:dog at gnu.org'>Chris Burdess</a>
+ */
+final class NonPositiveIntegerType
+  extends AtomicSimpleType
+{
+
+  static final int[] CONSTRAINING_FACETS = {
+    Facet.TOTAL_DIGITS,
+    Facet.FRACTION_DIGITS,
+    Facet.PATTERN,
+    Facet.WHITESPACE,
+    Facet.ENUMERATION,
+    Facet.MAX_INCLUSIVE,
+    Facet.MAX_EXCLUSIVE,
+    Facet.MIN_INCLUSIVE,
+    Facet.MIN_EXCLUSIVE
+  };
+
+  NonPositiveIntegerType()
+  {
+    super(new QName(XMLConstants.W3C_XML_SCHEMA_NS_URI, "nonPositiveInteger"),
+          TypeLibrary.INTEGER);
+  }
+
+  public int[] getConstrainingFacets()
+  {
+    return CONSTRAINING_FACETS;
+  }
+
+  public void checkValid(String value, ValidationContext context)
+    throws DatatypeException
+  {
+    super.checkValid(value, context);
+    int len = value.length();
+    if (len == 0)
+      throw new DatatypeException(0, "invalid non-positive integer value");
+    boolean positive = true;
+    for (int i = 0; i < len; i++)
+      {
+        char c = value.charAt(i);
+        if (c == 0x30)
+          continue;
+        else if (c >= 0x31 && c <= 0x39)
+          {
+            if (positive)
+              throw new DatatypeException(i,
+                                          "invalid non-positive integer value");
+            continue;
+          }
+        else if (c == '+' && i == 0)
+          continue;
+        else if (c == '-' && i == 0)
+          {
+            positive = false;
+            continue;
+          }
+        throw new DatatypeException(i, "invalid non-positive integer value");
+      }
+  }
+  
+  public Object createValue(String literal, ValidationContext context) {
+    try
+      {
+        return new BigInteger(literal);
+      }
+    catch (NumberFormatException e)
+      {
+        return null;
+      }
+  }
+  
+}
+

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/NormalizedStringType.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/NormalizedStringType.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/NormalizedStringType.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/NormalizedStringType.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,88 @@
+/* NormalizedStringType.java -- 
+   Copyright (C) 2006  Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.xml.validation.datatype;
+
+import javax.xml.XMLConstants;
+import javax.xml.namespace.QName;
+import org.relaxng.datatype.DatatypeException;
+import org.relaxng.datatype.ValidationContext;
+
+/**
+ * The XML Schema normalizedString type.
+ *
+ * @author <a href='mailto:dog at gnu.org'>Chris Burdess</a>
+ */
+final class NormalizedStringType
+  extends AtomicSimpleType
+{
+
+  static final int[] CONSTRAINING_FACETS = {
+    Facet.LENGTH,
+    Facet.MIN_LENGTH,
+    Facet.MAX_LENGTH,
+    Facet.PATTERN,
+    Facet.ENUMERATION,
+    Facet.WHITESPACE
+  };
+
+  NormalizedStringType()
+  {
+    super(new QName(XMLConstants.W3C_XML_SCHEMA_NS_URI, "normalizedString"),
+          TypeLibrary.STRING);
+  }
+
+  public int[] getConstrainingFacets()
+  {
+    return CONSTRAINING_FACETS;
+  }
+
+  public void checkValid(String value, ValidationContext context)
+    throws DatatypeException
+  {
+    super.checkValid(value, context);
+    int len = value.length();
+    for (int i = 0; i < len; i++)
+      {
+        char c = value.charAt(i);
+        if (c == 0x0a || c == 0x0d || c == 0x09)
+          throw new DatatypeException(i, "invalid normalized-string value");
+      }
+  }
+  
+}
+

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/NotationType.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/NotationType.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/NotationType.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/NotationType.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,90 @@
+/* NotationType.java -- 
+   Copyright (C) 2006  Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.xml.validation.datatype;
+
+import java.util.Collections;
+import java.util.Set;
+import javax.xml.XMLConstants;
+import javax.xml.namespace.QName;
+import org.relaxng.datatype.DatatypeException;
+import org.relaxng.datatype.ValidationContext;
+
+/**
+ * The XML Schema NOTATION type.
+ *
+ * @author <a href='mailto:dog at gnu.org'>Chris Burdess</a>
+ */
+final class NotationType
+  extends AtomicSimpleType
+{
+
+  static final int[] CONSTRAINING_FACETS = {
+    Facet.LENGTH,
+    Facet.MIN_LENGTH,
+    Facet.MAX_LENGTH,
+    Facet.PATTERN,
+    Facet.ENUMERATION,
+    Facet.WHITESPACE
+  };
+
+  NotationType()
+  {
+    super(new QName(XMLConstants.W3C_XML_SCHEMA_NS_URI, "NOTATION"),
+          TypeLibrary.ANY_SIMPLE_TYPE);
+  }
+
+  public int[] getConstrainingFacets()
+  {
+    return CONSTRAINING_FACETS;
+  }
+
+  public void checkValid(String value, ValidationContext context)
+    throws DatatypeException
+  {
+    super.checkValid(value, context);
+    if (!context.isNotation(value))
+      throw new DatatypeException("invalid NOTATION value");
+  }
+
+  public boolean isContextDependent()
+  {
+    return true;
+  }
+  
+}
+

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/PatternFacet.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/PatternFacet.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/PatternFacet.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/PatternFacet.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,71 @@
+/* PatternFacet.java -- 
+   Copyright (C) 2006  Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.xml.validation.datatype;
+
+import java.util.regex.Pattern;
+
+/**
+ * The <code>pattern</code> facet.
+ *
+ * @author <a href='mailto:dog at gnu.org'>Chris Burdess</a>
+ */
+public final class PatternFacet
+  extends Facet
+{
+
+  public final Pattern value;
+
+  public PatternFacet(Pattern value, Annotation annotation)
+  {
+    super(PATTERN, annotation);
+    this.value = value;
+  }
+
+  public int hashCode()
+  {
+    return value.hashCode();
+  }
+
+  public boolean equals(Object other)
+  {
+    return (other instanceof PatternFacet &&
+            ((PatternFacet) other).value.equals(value));
+  }
+  
+}
+

Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/PositiveIntegerType.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/PositiveIntegerType.java?rev=43913&view=auto

==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/PositiveIntegerType.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/xml/validation/datatype/PositiveIntegerType.java Thu Nov  8 16:56:19 2007
@@ -0,0 +1,111 @@
+/* PositiveIntegerType.java -- 
+   Copyright (C) 2006  Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath 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
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING.  If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library.  Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module.  An independent module is a module which is not derived from
+or based on this library.  If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so.  If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.xml.validation.datatype;
+
+import java.math.BigInteger;
+import javax.xml.XMLConstants;
+import javax.xml.namespace.QName;
+import org.relaxng.datatype.DatatypeException;
+import org.relaxng.datatype.ValidationContext;
+
+/**
+ * The XML Schema positiveInteger type.
+ *
+ * @author <a href='mailto:dog at gnu.org'>Chris Burdess</a>
+ */
+final class PositiveIntegerType
+  extends AtomicSimpleType
+{
+
+  static final int[] CONSTRAINING_FACETS = {
+    Facet.TOTAL_DIGITS,
+    Facet.FRACTION_DIGITS,
+    Facet.PATTERN,
+    Facet.WHITESPACE,
+    Facet.ENUMERATION,
+    Facet.MAX_INCLUSIVE,
+    Facet.MAX_EXCLUSIVE,
+    Facet.MIN_INCLUSIVE,
+    Facet.MIN_EXCLUSIVE
+  };
+
+  PositiveIntegerType()
+  {
+    super(new QName(XMLConstants.W3C_XML_SCHEMA_NS_URI, "positiveInteger"),
+          TypeLibrary.NON_NEGATIVE_INTEGER);
+  }
+
+  public int[] getConstrainingFacets()
+  {
+    return CONSTRAINING_FACETS;
+  }
+
+  public void checkValid(String value, ValidationContext context)
+    throws DatatypeException
+  {
+    super.checkValid(value, context);
+    int len = value.length();
+    if (len == 0)
+      throw new DatatypeException(0, "invalid positive integer value");
+    for (int i = 0; i < len; i++)
+      {
+        char c = value.charAt(i);
+        if (c == '+')
+          {
+            if (i == 0)
+              continue;
+          }
+        else if (c >= 0x30 && c <= 0x39)
+          continue;
+        throw new DatatypeException(i, "invalid positive integer value");
+      }
+  }
+  
+  public Object createValue(String literal, ValidationContext context) {
+    try
+      {
+        return new BigInteger(literal);
+      }
+    catch (NumberFormatException e)
+      {
+        return null;
+      }
+  }
+  
+}
+





More information about the llvm-commits mailing list