diff options
author | Mark Wielaard <mark@gcc.gnu.org> | 2006-03-10 21:46:48 +0000 |
---|---|---|
committer | Mark Wielaard <mark@gcc.gnu.org> | 2006-03-10 21:46:48 +0000 |
commit | 8aa540d2f783474d1d2e06f16744bf67b9c1facc (patch) | |
tree | ea38c56431c5d4528fb54254c3f8e50f517bede3 /libjava/classpath/gnu/xml | |
parent | 27079765d00123f8e53d0e1ef7f9d46559266e6d (diff) | |
download | gcc-8aa540d2f783474d1d2e06f16744bf67b9c1facc.zip gcc-8aa540d2f783474d1d2e06f16744bf67b9c1facc.tar.gz gcc-8aa540d2f783474d1d2e06f16744bf67b9c1facc.tar.bz2 |
Imported GNU Classpath 0.90
Imported GNU Classpath 0.90
* scripts/makemake.tcl: Set gnu/java/awt/peer/swing to ignore.
* gnu/classpath/jdwp/VMFrame.java (SIZE): New constant.
* java/lang/VMCompiler.java: Use gnu.java.security.hash.MD5.
* java/lang/Math.java: New override file.
* java/lang/Character.java: Merged from Classpath.
(start, end): Now 'int's.
(canonicalName): New field.
(CANONICAL_NAME, NO_SPACES_NAME, CONSTANT_NAME): New constants.
(UnicodeBlock): Added argument.
(of): New overload.
(forName): New method.
Updated unicode blocks.
(sets): Updated.
* sources.am: Regenerated.
* Makefile.in: Likewise.
From-SVN: r111942
Diffstat (limited to 'libjava/classpath/gnu/xml')
162 files changed, 14842 insertions, 1974 deletions
diff --git a/libjava/classpath/gnu/xml/aelfred2/XmlParser.java b/libjava/classpath/gnu/xml/aelfred2/XmlParser.java index ab2ed16..37466ca 100644 --- a/libjava/classpath/gnu/xml/aelfred2/XmlParser.java +++ b/libjava/classpath/gnu/xml/aelfred2/XmlParser.java @@ -2182,6 +2182,7 @@ loop: { nest++; } + break; case ']': if (tryRead("]>")) { diff --git a/libjava/classpath/gnu/xml/dom/DomCharacterData.java b/libjava/classpath/gnu/xml/dom/DomCharacterData.java index e94dcc4..1eec5be 100644 --- a/libjava/classpath/gnu/xml/dom/DomCharacterData.java +++ b/libjava/classpath/gnu/xml/dom/DomCharacterData.java @@ -1,5 +1,5 @@ /* DomCharacterData.java -- - Copyright (C) 1999,2000,2001,2004 Free Software Foundation, Inc. + Copyright (C) 1999,2000,2001,2004,2006 Free Software Foundation, Inc. This file is part of GNU Classpath. @@ -39,6 +39,8 @@ package gnu.xml.dom; import org.w3c.dom.CharacterData; import org.w3c.dom.DOMException; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; import org.w3c.dom.events.MutationEvent; @@ -55,6 +57,30 @@ public abstract class DomCharacterData implements CharacterData { + /** + * Empty node list representing the children of character data nodes. + */ + static class EmptyNodeList + implements NodeList + { + + public int getLength() + { + return 0; + } + + public Node item(int index) + { + return null; + } + + } + + /** + * Singleton empty node list for character data nodes. + */ + static final NodeList CHILD_NODES = new EmptyNodeList(); + private String text; // package private @@ -280,6 +306,15 @@ public abstract class DomCharacterData } /** + * Returns an empty node list. + * Character data nodes do not have children. + */ + public NodeList getChildNodes() + { + return CHILD_NODES; + } + + /** * The base URI for character data is <code>null</code>. * @since DOM Level 3 Core */ diff --git a/libjava/classpath/gnu/xml/dom/DomDocumentBuilder.java b/libjava/classpath/gnu/xml/dom/DomDocumentBuilder.java index 42444e8..343f48c 100644 --- a/libjava/classpath/gnu/xml/dom/DomDocumentBuilder.java +++ b/libjava/classpath/gnu/xml/dom/DomDocumentBuilder.java @@ -1,5 +1,5 @@ /* DomDocumentBuilder.java -- - Copyright (C) 2004 Free Software Foundation, Inc. + Copyright (C) 2004,2006 Free Software Foundation, Inc. This file is part of GNU Classpath. @@ -37,9 +37,11 @@ exception statement from your version. */ package gnu.xml.dom; +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 javax.xml.parsers.DocumentBuilder; import org.w3c.dom.Document; @@ -157,8 +159,18 @@ class DomDocumentBuilder } else { - URL url = new URL(systemId); - input.setByteStream(url.openStream()); + try + { + URL url = new URL(systemId); + input.setByteStream(url.openStream()); + } + catch (MalformedURLException e) + { + // Maybe this is a relative file URL + File cwd = new File(System.getProperty("user.dir")); + URL url = new URL(cwd.toURL(), systemId); + input.setByteStream(url.openStream()); + } } } input.setPublicId(is.getPublicId()); diff --git a/libjava/classpath/gnu/xml/dom/DomDocumentBuilderFactory.java b/libjava/classpath/gnu/xml/dom/DomDocumentBuilderFactory.java index 814141c..0234785 100644 --- a/libjava/classpath/gnu/xml/dom/DomDocumentBuilderFactory.java +++ b/libjava/classpath/gnu/xml/dom/DomDocumentBuilderFactory.java @@ -37,6 +37,7 @@ exception statement from your version. */ package gnu.xml.dom; +import javax.xml.XMLConstants; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.FactoryConfigurationError; @@ -59,6 +60,7 @@ public class DomDocumentBuilderFactory final DOMImplementation impl; final DOMImplementationLS ls; + private boolean secureProcessing; public DomDocumentBuilderFactory() { @@ -124,5 +126,26 @@ public class DomDocumentBuilderFactory // TODO } + public void setFeature(String name, boolean value) + throws ParserConfigurationException + { + if (name == null) + throw new NullPointerException(); + if (XMLConstants.FEATURE_SECURE_PROCESSING.equals(name)) + { + secureProcessing = true; + return; + } + throw new ParserConfigurationException(name); + } + + public boolean getFeature(String name) + throws ParserConfigurationException + { + if (XMLConstants.FEATURE_SECURE_PROCESSING.equals(name)) + return secureProcessing; + throw new ParserConfigurationException(name); + } + } diff --git a/libjava/classpath/gnu/xml/dom/JAXPFactory.java b/libjava/classpath/gnu/xml/dom/JAXPFactory.java index 8f481fad..ca14a8e 100644 --- a/libjava/classpath/gnu/xml/dom/JAXPFactory.java +++ b/libjava/classpath/gnu/xml/dom/JAXPFactory.java @@ -49,6 +49,7 @@ import org.xml.sax.XMLReader; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; +import javax.xml.XMLConstants; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; @@ -70,6 +71,7 @@ public final class JAXPFactory private static final String FEATURE = "http://xml.org/sax/features/"; private SAXParserFactory pf; + private boolean secureProcessing; /** * Default constructor. @@ -138,6 +140,27 @@ public final class JAXPFactory throw new IllegalArgumentException(name); } + public void setFeature(String name, boolean value) + throws ParserConfigurationException + { + if (name == null) + throw new NullPointerException(); + if (XMLConstants.FEATURE_SECURE_PROCESSING.equals(name)) + { + secureProcessing = true; + return; + } + throw new ParserConfigurationException(name); + } + + public boolean getFeature(String name) + throws ParserConfigurationException + { + if (XMLConstants.FEATURE_SECURE_PROCESSING.equals(name)) + return secureProcessing; + throw new ParserConfigurationException(name); + } + static final class JAXPBuilder extends DocumentBuilder implements ErrorHandler diff --git a/libjava/classpath/gnu/xml/libxmlj/dom/GnomeDocumentBuilderFactory.java b/libjava/classpath/gnu/xml/libxmlj/dom/GnomeDocumentBuilderFactory.java index c4f0ce2..c8918aa 100644 --- a/libjava/classpath/gnu/xml/libxmlj/dom/GnomeDocumentBuilderFactory.java +++ b/libjava/classpath/gnu/xml/libxmlj/dom/GnomeDocumentBuilderFactory.java @@ -37,6 +37,7 @@ exception statement from your version. */ package gnu.xml.libxmlj.dom; +import javax.xml.XMLConstants; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; @@ -47,9 +48,11 @@ import javax.xml.parsers.ParserConfigurationException; * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> */ public class GnomeDocumentBuilderFactory -extends DocumentBuilderFactory + extends DocumentBuilderFactory { + private boolean secureProcessing; + public GnomeDocumentBuilderFactory () { setNamespaceAware (true); @@ -91,4 +94,25 @@ extends DocumentBuilderFactory // TODO } + public void setFeature(String name, boolean value) + throws ParserConfigurationException + { + if (name == null) + throw new NullPointerException(); + if (XMLConstants.FEATURE_SECURE_PROCESSING.equals(name)) + { + secureProcessing = true; + return; + } + throw new ParserConfigurationException(name); + } + + public boolean getFeature(String name) + throws ParserConfigurationException + { + if (XMLConstants.FEATURE_SECURE_PROCESSING.equals(name)) + return secureProcessing; + throw new ParserConfigurationException(name); + } + } diff --git a/libjava/classpath/gnu/xml/stream/CRLFReader.java b/libjava/classpath/gnu/xml/stream/CRLFReader.java index 1d214ce..dad02b9 100644 --- a/libjava/classpath/gnu/xml/stream/CRLFReader.java +++ b/libjava/classpath/gnu/xml/stream/CRLFReader.java @@ -1,5 +1,5 @@ /* CRLFReader.java -- - Copyright (C) 2005 Free Software Foundation, Inc. + Copyright (C) 2005,2006 Free Software Foundation, Inc. This file is part of GNU Classpath. @@ -153,13 +153,14 @@ class CRLFReader throws IOException { doReset = false; - int lm1 = len - 1; - for (int i = off; i < len; i++) + int end = off + len; + int em1 = end - 1; + for (int i = off; i < end; i++) { if (b[i] == '\r') // CR { int d; - if (i == lm1) + if (i == em1) { d = in.read(); doReset = true; diff --git a/libjava/classpath/gnu/xml/stream/EntityReferenceImpl.java b/libjava/classpath/gnu/xml/stream/EntityReferenceImpl.java index 4b40bfa..38e1f00 100644 --- a/libjava/classpath/gnu/xml/stream/EntityReferenceImpl.java +++ b/libjava/classpath/gnu/xml/stream/EntityReferenceImpl.java @@ -1,5 +1,5 @@ /* EntityReferenceImpl.java -- - Copyright (C) 2005 Free Software Foundation, Inc. + Copyright (C) 2005,2006 Free Software Foundation, Inc. This file is part of GNU Classpath. @@ -41,7 +41,7 @@ import java.io.IOException; import java.io.Writer; import javax.xml.stream.Location; import javax.xml.stream.XMLStreamException; -//import javax.xml.stream.events.EntityDeclaration; +import javax.xml.stream.events.EntityDeclaration; import javax.xml.stream.events.EntityReference; /** @@ -54,26 +54,16 @@ public class EntityReferenceImpl implements EntityReference { - //protected final EntityDeclaration decl; + protected final EntityDeclaration decl; protected final String name; - protected final String baseUri; - protected final String publicId; - protected final String systemId; - protected final String replacementText; protected EntityReferenceImpl(Location location, - //EntityDeclaration decl, - String name, - String baseUri, String publicId, - String systemId, String replacementText) + EntityDeclaration decl, + String name) { super(location); - //this.decl = decl; + this.decl = decl; this.name = name; - this.baseUri = baseUri; - this.publicId = publicId; - this.systemId = systemId; - this.replacementText = replacementText; } public int getEventType() @@ -81,36 +71,16 @@ public class EntityReferenceImpl return ENTITY_REFERENCE; } - /*public EntityDeclaration getDeclaration() + public EntityDeclaration getDeclaration() { return decl; - }*/ + } public String getName() { return name; } - public String getBaseUri() - { - return baseUri; - } - - public String getPublicId() - { - return publicId; - } - - public String getSystemId() - { - return systemId; - } - - public String getReplacementText() - { - return replacementText; - } - public void writeAsEncodedUnicode(Writer writer) throws XMLStreamException { diff --git a/libjava/classpath/gnu/xml/stream/FilteredEventReader.java b/libjava/classpath/gnu/xml/stream/FilteredEventReader.java index 3bf0f25..fd6fe8b 100644 --- a/libjava/classpath/gnu/xml/stream/FilteredEventReader.java +++ b/libjava/classpath/gnu/xml/stream/FilteredEventReader.java @@ -1,5 +1,5 @@ /* FilteredEventReader.java -- - Copyright (C) 2005 Free Software Foundation, Inc. + Copyright (C) 2005,2006 Free Software Foundation, Inc. This file is part of GNU Classpath. @@ -56,24 +56,37 @@ class FilteredEventReader } public boolean hasNext() - throws XMLStreamException { // XXX ??? return super.hasNext(); } - public XMLEvent next() + public XMLEvent nextEvent() throws XMLStreamException { XMLEvent ret; do { - ret = super.next(); + ret = super.nextEvent(); } while (!filter.accept(ret)); return ret; } + public Object next() + { + try + { + return nextEvent(); + } + catch (XMLStreamException e) + { + RuntimeException e2 = new RuntimeException(); + e2.initCause(e); + throw e2; + } + } + public XMLEvent peek() throws XMLStreamException { diff --git a/libjava/classpath/gnu/xml/stream/SAXParser.java b/libjava/classpath/gnu/xml/stream/SAXParser.java index 54c8b36..fd768a4 100644 --- a/libjava/classpath/gnu/xml/stream/SAXParser.java +++ b/libjava/classpath/gnu/xml/stream/SAXParser.java @@ -1,5 +1,5 @@ /* SAXParser.java -- - Copyright (C) 2005 Free Software Foundation, Inc. + Copyright (C) 2005, 2006 Free Software Foundation, Inc. This file is part of GNU Classpath. @@ -92,8 +92,7 @@ import org.xml.sax.ext.Locator2; */ public class SAXParser extends javax.xml.parsers.SAXParser - implements XMLReader, Attributes2, Locator2, XMLReporter, - XMLParser.XMLResolver2 + implements XMLReader, Attributes2, Locator2, XMLReporter, XMLResolver { ContentHandler contentHandler; @@ -323,6 +322,7 @@ public class SAXParser supportDTD, baseAware, stringInterning, + true, this, this); else @@ -338,6 +338,7 @@ public class SAXParser supportDTD, baseAware, stringInterning, + true, this, this); } @@ -357,6 +358,7 @@ public class SAXParser supportDTD, baseAware, stringInterning, + true, this, this); } @@ -486,14 +488,14 @@ public class SAXParser contentHandler.processingInstruction(target, data); } break; - case XMLStreamConstants.START_ENTITY: + case XMLParser.START_ENTITY: if (lexicalHandler != null) { String name = reader.getText(); lexicalHandler.startEntity(name); } break; - case XMLStreamConstants.END_ENTITY: + case XMLParser.END_ENTITY: if (lexicalHandler != null) { String name = reader.getText(); @@ -649,24 +651,36 @@ public class SAXParser lexicalHandler.endDTD(); } } + reset(); + if (opened) + in.close(); } - catch (XMLStreamException e) + catch (Exception e) { - if (!startDocumentDone && contentHandler != null) - contentHandler.startDocument(); SAXParseException e2 = new SAXParseException(e.getMessage(), this); e2.initCause(e); - if (errorHandler != null) - errorHandler.fatalError(e2); - if (contentHandler != null) - contentHandler.endDocument(); - throw e2; - } - finally - { + try + { + if (!startDocumentDone && contentHandler != null) + contentHandler.startDocument(); + if (errorHandler != null) + errorHandler.fatalError(e2); + if (contentHandler != null) + contentHandler.endDocument(); + } + catch (SAXException sex) + { + // Ignored, we will rethrow the original exception. + } + reset(); if (opened) in.close(); - reset(); + if (e instanceof SAXException) + throw (SAXException) e; + if (e instanceof IOException) + throw (IOException) e; + else + throw e2; } } @@ -685,7 +699,7 @@ public class SAXParser int ac = reader.getAttributeCount(); for (int i = 0; i < ac; i++) { - QName aname = reader.getAttributeQName(i); + QName aname = reader.getAttributeName(i); if ("space".equals(aname.getLocalPart()) && XMLConstants.XML_NS_URI.equals(aname.getNamespaceURI())) { @@ -726,7 +740,7 @@ public class SAXParser int len = reader.getAttributeCount(); for (int i = 0; i < len; i++) { - QName q = reader.getAttributeQName(i); + QName q = reader.getAttributeName(i); String localName = q.getLocalPart(); String prefix = q.getPrefix(); String qn = ("".equals(prefix)) ? localName : prefix + ":" + localName; @@ -741,7 +755,7 @@ public class SAXParser int len = reader.getAttributeCount(); for (int i = 0; i < len; i++) { - QName q = reader.getAttributeQName(i); + QName q = reader.getAttributeName(i); String ln = q.getLocalPart(); String u = q.getNamespaceURI(); if (u == null && uri != null) @@ -761,12 +775,12 @@ public class SAXParser public String getLocalName(int index) { - return reader.getAttributeName(index); + return reader.getAttributeLocalName(index); } public String getQName(int index) { - QName q = reader.getAttributeQName(index); + QName q = reader.getAttributeName(index); String localName = q.getLocalPart(); String prefix = q.getPrefix(); return ("".equals(prefix)) ? localName : prefix + ":" + localName; @@ -864,13 +878,14 @@ public class SAXParser public String getPublicId() { - return null; + Location l = reader.getLocation(); + return l.getPublicId(); } public String getSystemId() { Location l = reader.getLocation(); - return l.getLocationURI(); + return l.getSystemId(); } public String getEncoding() @@ -885,13 +900,8 @@ public class SAXParser // -- XMLResolver -- - public InputStream resolve(String uri) - throws XMLStreamException - { - return resolve(null, uri); - } - - public InputStream resolve(String publicId, String systemId) + public Object resolveEntity(String publicId, String systemId, + String baseURI, String namespace) throws XMLStreamException { if (entityResolver != null) @@ -901,7 +911,16 @@ public class SAXParser InputSource input = entityResolver.resolveEntity(publicId, systemId); if (input != null) - return input.getByteStream(); + { + InputStream in = input.getByteStream(); + if (in == null) + { + String newSystemId = input.getSystemId(); + if (newSystemId != null && !newSystemId.equals(systemId)) + in = XMLParser.resolve(newSystemId); + } + return in; + } } catch (SAXException e) { diff --git a/libjava/classpath/gnu/xml/stream/UnicodeReader.java b/libjava/classpath/gnu/xml/stream/UnicodeReader.java index c38516c..9350cb2 100644 --- a/libjava/classpath/gnu/xml/stream/UnicodeReader.java +++ b/libjava/classpath/gnu/xml/stream/UnicodeReader.java @@ -45,7 +45,7 @@ import java.io.Reader; * * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> */ -class UnicodeReader +public class UnicodeReader { final Reader in; @@ -152,6 +152,10 @@ class UnicodeReader in.close(); } + /** + * Returns the specified UTF-16 char array as an array of Unicode code + * points. + */ public static int[] toCodePointArray(String text) throws IOException { diff --git a/libjava/classpath/gnu/xml/stream/XIncludeFilter.java b/libjava/classpath/gnu/xml/stream/XIncludeFilter.java index e151ac6..7e70782 100644 --- a/libjava/classpath/gnu/xml/stream/XIncludeFilter.java +++ b/libjava/classpath/gnu/xml/stream/XIncludeFilter.java @@ -42,6 +42,7 @@ import java.io.InputStreamReader; import java.io.IOException; import java.io.Reader; import java.net.HttpURLConnection; +import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.util.HashSet; @@ -121,7 +122,17 @@ class XIncludeFilter boolean expandERefs) { super(reader); - this.systemId = XMLParser.absolutize(null, systemId); + try + { + this.systemId = XMLParser.absolutize(null, systemId); + } + catch (MalformedURLException e) + { + RuntimeException e2 = new RuntimeException("unsupported URL: " + + systemId); + e2.initCause(e); + throw e2; + } this.namespaceAware = namespaceAware; this.validating = validating; this.expandERefs = expandERefs; @@ -137,7 +148,7 @@ class XIncludeFilter return super.getAttributeCount(); } - public String getAttributeName(int index) + public String getAttributeLocalName(int index) { if (current != null) { @@ -147,7 +158,7 @@ class XIncludeFilter Node attr = attrs.item(index); return attr.getLocalName(); } - return super.getAttributeName(index); + return super.getAttributeLocalName(index); } public String getAttributeNamespace(int index) @@ -176,7 +187,7 @@ class XIncludeFilter return super.getAttributePrefix(index); } - public QName getAttributeQName(int index) + public QName getAttributeName(int index) { if (current != null) { @@ -189,7 +200,7 @@ class XIncludeFilter String prefix = attr.getPrefix(); return new QName(uri, localName, prefix); } - return super.getAttributeQName(index); + return super.getAttributeName(index); } public String getAttributeType(int index) diff --git a/libjava/classpath/gnu/xml/stream/XMLEventAllocatorImpl.java b/libjava/classpath/gnu/xml/stream/XMLEventAllocatorImpl.java index 4b21b6c..666bffa 100644 --- a/libjava/classpath/gnu/xml/stream/XMLEventAllocatorImpl.java +++ b/libjava/classpath/gnu/xml/stream/XMLEventAllocatorImpl.java @@ -1,5 +1,5 @@ /* XMLEventAllocatorImpl.java -- - Copyright (C) 2005 Free Software Foundation, Inc. + Copyright (C) 2005,2006 Free Software Foundation, Inc. This file is part of GNU Classpath. @@ -116,10 +116,9 @@ public class XMLEventAllocatorImpl namespaces); case XMLStreamConstants.ENTITY_REFERENCE: String name = reader.getLocalName(); - //EntityDeclaration decl = - // (EntityDeclaration) entityDeclarations.get(name); - //return new EntityReferenceImpl(location, decl, name); - return new EntityReferenceImpl(location, name, null, null, null, null); + EntityDeclaration decl = + (EntityDeclaration) entityDeclarations.get(name); + return new EntityReferenceImpl(location, decl, name); case XMLStreamConstants.PROCESSING_INSTRUCTION: return new ProcessingInstructionImpl(location, reader.getPITarget(), @@ -132,7 +131,7 @@ public class XMLEventAllocatorImpl return new CharactersImpl(location, text, whitespace, false, ignorableWhitespace); case XMLStreamConstants.START_DOCUMENT: - String systemId = location.getLocationURI(); + String systemId = location.getSystemId(); String encoding = reader.getCharacterEncodingScheme(); boolean encodingDeclared = encoding != null; if (encoding == null) @@ -164,7 +163,7 @@ public class XMLEventAllocatorImpl List attributes = new LinkedList(); for (int i = 0; i < len; i++) attributes.add(new AttributeImpl(location, - reader.getAttributeQName(i), + reader.getAttributeName(i), reader.getAttributeValue(i), QName.valueOf(reader.getAttributeType(i)), reader.isAttributeSpecified(i))); diff --git a/libjava/classpath/gnu/xml/stream/XMLEventFactoryImpl.java b/libjava/classpath/gnu/xml/stream/XMLEventFactoryImpl.java index a839b18..e1d7d6a 100644 --- a/libjava/classpath/gnu/xml/stream/XMLEventFactoryImpl.java +++ b/libjava/classpath/gnu/xml/stream/XMLEventFactoryImpl.java @@ -1,5 +1,5 @@ /* XMLEventFactoryImpl.java -- - Copyright (C) 2005 Free Software Foundation, Inc. + Copyright (C) 2005,2006 Free Software Foundation, Inc. This file is part of GNU Classpath. @@ -233,12 +233,9 @@ public class XMLEventFactoryImpl } public EntityReference createEntityReference(String name, - //EntityDeclaration declaration) - String replacementText) + EntityDeclaration declaration) { - //return new EntityReferenceImpl(location, declaration, name); - return new EntityReferenceImpl(location, name, null, null, null, - replacementText); + return new EntityReferenceImpl(location, declaration, name); } public Comment createComment(String text) diff --git a/libjava/classpath/gnu/xml/stream/XMLEventImpl.java b/libjava/classpath/gnu/xml/stream/XMLEventImpl.java index a8b522f..9f57d89 100644 --- a/libjava/classpath/gnu/xml/stream/XMLEventImpl.java +++ b/libjava/classpath/gnu/xml/stream/XMLEventImpl.java @@ -1,5 +1,5 @@ /* XMLEventImpl.java -- - Copyright (C) 2005 Free Software Foundation, Inc. + Copyright (C) 2005,2006 Free Software Foundation, Inc. This file is part of GNU Classpath. @@ -116,16 +116,6 @@ public abstract class XMLEventImpl return getEventType() == END_DOCUMENT; } - public boolean isStartEntity() - { - return getEventType() == START_ENTITY; - } - - public boolean isEndEntity() - { - return getEventType() == END_ENTITY; - } - public StartElement asStartElement() { return (StartElement) this; diff --git a/libjava/classpath/gnu/xml/stream/XMLEventReaderImpl.java b/libjava/classpath/gnu/xml/stream/XMLEventReaderImpl.java index 70481d7..bb64b1e 100644 --- a/libjava/classpath/gnu/xml/stream/XMLEventReaderImpl.java +++ b/libjava/classpath/gnu/xml/stream/XMLEventReaderImpl.java @@ -67,7 +67,7 @@ public class XMLEventReaderImpl this.systemId = systemId; } - public XMLEvent next() + public XMLEvent nextEvent() throws XMLStreamException { XMLEvent ret = peek(); @@ -75,10 +75,32 @@ public class XMLEventReaderImpl return ret; } + public Object next() + { + try + { + return nextEvent(); + } + catch (XMLStreamException e) + { + RuntimeException e2 = new RuntimeException(); + e2.initCause(e); + throw e2; + } + } + public boolean hasNext() - throws XMLStreamException { - return peekEvent != null || reader.hasNext(); + if (peekEvent != null) + return true; + try + { + return reader.hasNext(); + } + catch (XMLStreamException e) + { + return false; + } } public XMLEvent peek() @@ -121,5 +143,16 @@ public class XMLEventReaderImpl return reader.getProperty(name); } + public void close() + throws XMLStreamException + { + reader.close(); + } + + public void remove() + { + throw new UnsupportedOperationException(); + } + } diff --git a/libjava/classpath/gnu/xml/stream/XMLEventWriterImpl.java b/libjava/classpath/gnu/xml/stream/XMLEventWriterImpl.java index 4502415..72b7adc 100644 --- a/libjava/classpath/gnu/xml/stream/XMLEventWriterImpl.java +++ b/libjava/classpath/gnu/xml/stream/XMLEventWriterImpl.java @@ -155,7 +155,7 @@ public class XMLEventWriterImpl throws XMLStreamException { while (reader.hasNext()) - add(reader.next()); + add(reader.nextEvent()); } public String getPrefix(String uri) diff --git a/libjava/classpath/gnu/xml/stream/XMLInputFactoryImpl.java b/libjava/classpath/gnu/xml/stream/XMLInputFactoryImpl.java index 164774d..5f72e36 100644 --- a/libjava/classpath/gnu/xml/stream/XMLInputFactoryImpl.java +++ b/libjava/classpath/gnu/xml/stream/XMLInputFactoryImpl.java @@ -1,5 +1,5 @@ /* XMLInputFactoryImpl.java -- - Copyright (C) 2005 Free Software Foundation, Inc. + Copyright (C) 2005,2006 Free Software Foundation, Inc. This file is part of GNU Classpath. @@ -89,14 +89,15 @@ public class XMLInputFactoryImpl public XMLStreamReader createXMLStreamReader(Reader reader) throws XMLStreamException { - /* - return new XMLStreamReaderImpl(reader, null, null, - resolver, reporter, - validating, namespaceAware, - coalescing, replacingEntityReferences, - externalEntities, supportDTD); - */ - XMLParser ret = new XMLParser(reader, null, + return createXMLStreamReader(null, reader); + } + + public XMLStreamReader createXMLStreamReader(Source source) + throws XMLStreamException + { + String systemId = source.getSystemId(); + InputStream in = getInputStream(source); + XMLParser ret = new XMLParser(in, systemId, validating, namespaceAware, coalescing, @@ -105,24 +106,30 @@ public class XMLInputFactoryImpl supportDTD, baseAware, stringInterning, + false, reporter, resolver); if (xIncludeAware) - return new XIncludeFilter(ret, null, namespaceAware, validating, + return new XIncludeFilter(ret, systemId, namespaceAware, validating, replacingEntityReferences); return ret; } - public XMLStreamReader createXMLStreamReader(Source source) + public XMLStreamReader createXMLStreamReader(InputStream in) + throws XMLStreamException + { + return createXMLStreamReader(null, in); + } + + public XMLStreamReader createXMLStreamReader(InputStream in, String encoding) + throws XMLStreamException + { + return createXMLStreamReader(in); + } + + public XMLStreamReader createXMLStreamReader(String systemId, InputStream in) throws XMLStreamException { - String systemId = source.getSystemId(); - InputStream in = getInputStream(source); - /*return new XMLStreamReaderImpl(in, null, systemId, - resolver, reporter, - validating, namespaceAware, - coalescing, replacingEntityReferences, - externalEntities, supportDTD);*/ XMLParser ret = new XMLParser(in, systemId, validating, namespaceAware, @@ -132,23 +139,19 @@ public class XMLInputFactoryImpl supportDTD, baseAware, stringInterning, + false, reporter, resolver); if (xIncludeAware) - return new XIncludeFilter(ret, systemId, namespaceAware, validating, + return new XIncludeFilter(ret, null, namespaceAware, validating, replacingEntityReferences); return ret; } - - public XMLStreamReader createXMLStreamReader(InputStream in) + + public XMLStreamReader createXMLStreamReader(String systemId, Reader reader) throws XMLStreamException { - /*return new XMLStreamReaderImpl(in, null, null, - resolver, reporter, - validating, namespaceAware, - coalescing, replacingEntityReferences, - externalEntities, supportDTD);*/ - XMLParser ret = new XMLParser(in, null, + XMLParser ret = new XMLParser(reader, systemId, validating, namespaceAware, coalescing, @@ -157,6 +160,7 @@ public class XMLInputFactoryImpl supportDTD, baseAware, stringInterning, + false, reporter, resolver); if (xIncludeAware) @@ -164,12 +168,6 @@ public class XMLInputFactoryImpl replacingEntityReferences); return ret; } - - public XMLStreamReader createXMLStreamReader(InputStream in, String encoding) - throws XMLStreamException - { - return createXMLStreamReader(in); - } public XMLEventReader createXMLEventReader(Reader reader) throws XMLStreamException @@ -178,6 +176,13 @@ public class XMLInputFactoryImpl return new XMLEventReaderImpl(sr, allocator, null); } + public XMLEventReader createXMLEventReader(String systemId, Reader reader) + throws XMLStreamException + { + XMLStreamReader sr = createXMLStreamReader(systemId, reader); + return new XMLEventReaderImpl(sr, allocator, null); + } + public XMLEventReader createXMLEventReader(XMLStreamReader reader) throws XMLStreamException { @@ -205,6 +210,13 @@ public class XMLInputFactoryImpl return new XMLEventReaderImpl(sr, allocator, null); } + public XMLEventReader createXMLEventReader(String systemId, InputStream in) + throws XMLStreamException + { + XMLStreamReader sr = createXMLStreamReader(systemId, in); + return new XMLEventReaderImpl(sr, allocator, null); + } + public XMLStreamReader createFilteredReader(XMLStreamReader reader, StreamFilter filter) throws XMLStreamException diff --git a/libjava/classpath/gnu/xml/stream/XMLOutputFactoryImpl.java b/libjava/classpath/gnu/xml/stream/XMLOutputFactoryImpl.java index 05b6d6c..c8c651f 100644 --- a/libjava/classpath/gnu/xml/stream/XMLOutputFactoryImpl.java +++ b/libjava/classpath/gnu/xml/stream/XMLOutputFactoryImpl.java @@ -42,6 +42,8 @@ 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; @@ -94,6 +96,22 @@ public class XMLOutputFactoryImpl } } + 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 { @@ -116,10 +134,26 @@ public class XMLOutputFactoryImpl 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_PREFIX_DEFAULTING.equals(name)) + if (IS_REPAIRING_NAMESPACES.equals(name)) prefixDefaulting = ((Boolean) value).booleanValue(); else throw new IllegalArgumentException(name); @@ -128,14 +162,14 @@ public class XMLOutputFactoryImpl public Object getProperty(String name) throws IllegalArgumentException { - if (IS_PREFIX_DEFAULTING.equals(name)) + if (IS_REPAIRING_NAMESPACES.equals(name)) return new Boolean(prefixDefaulting); throw new IllegalArgumentException(name); } public boolean isPropertySupported(String name) { - if (IS_PREFIX_DEFAULTING.equals(name)) + if (IS_REPAIRING_NAMESPACES.equals(name)) return true; return false; } diff --git a/libjava/classpath/gnu/xml/stream/XMLParser.java b/libjava/classpath/gnu/xml/stream/XMLParser.java index 6f10b93..9bb4834 100644 --- a/libjava/classpath/gnu/xml/stream/XMLParser.java +++ b/libjava/classpath/gnu/xml/stream/XMLParser.java @@ -137,6 +137,10 @@ public class XMLParser 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. */ @@ -318,6 +322,12 @@ public class XMLParser 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; @@ -389,6 +399,7 @@ public class XMLParser boolean supportDTD, boolean baseAware, boolean stringInterning, + boolean extendedEventTypes, XMLReporter reporter, XMLResolver resolver) { @@ -400,6 +411,7 @@ public class XMLParser this.supportDTD = supportDTD; this.baseAware = baseAware; this.stringInterning = stringInterning; + this.extendedEventTypes = extendedEventTypes; this.reporter = reporter; this.resolver = resolver; if (validating) @@ -446,6 +458,7 @@ public class XMLParser boolean supportDTD, boolean baseAware, boolean stringInterning, + boolean extendedEventTypes, XMLReporter reporter, XMLResolver resolver) { @@ -457,6 +470,7 @@ public class XMLParser this.supportDTD = supportDTD; this.baseAware = baseAware; this.stringInterning = stringInterning; + this.extendedEventTypes = extendedEventTypes; this.reporter = reporter; this.resolver = resolver; if (validating) @@ -561,7 +575,7 @@ public class XMLParser return attrs.size(); } - public String getAttributeName(int index) + public String getAttributeLocalName(int index) { Attribute a = (Attribute) attrs.get(index); return a.localName; @@ -579,7 +593,7 @@ public class XMLParser return a.prefix; } - public QName getAttributeQName(int index) + public QName getAttributeName(int index) { Attribute a = (Attribute) attrs.get(index); String namespaceURI = getNamespaceURI(a.prefix); @@ -710,7 +724,7 @@ public class XMLParser public int getNamespaceCount() { - if (!namespaceAware) + if (!namespaceAware || namespaces.isEmpty()) return 0; switch (event) { @@ -984,10 +998,10 @@ public class XMLParser if (event == XMLStreamConstants.END_ELEMENT) { // Pop namespace context - if (namespaceAware) + if (namespaceAware && !namespaces.isEmpty()) namespaces.removeFirst(); // Pop base context - if (baseAware) + if (baseAware && !bases.isEmpty()) bases.removeFirst(); } if (!startEntityStack.isEmpty()) @@ -995,16 +1009,16 @@ public class XMLParser String entityName = (String) startEntityStack.removeFirst(); buf.setLength(0); buf.append(entityName); - event = XMLStreamConstants.START_ENTITY; - return event; + event = START_ENTITY; + return extendedEventTypes ? event : next(); } else if (!endEntityStack.isEmpty()) { String entityName = (String) endEntityStack.removeFirst(); buf.setLength(0); buf.append(entityName); - event = XMLStreamConstants.END_ENTITY; - return event; + event = END_ENTITY; + return extendedEventTypes ? event : next(); } try { @@ -1484,7 +1498,6 @@ public class XMLParser { if (!externalEntities) return; - InputStream in = null; String url = absolutize(input.systemId, ids.systemId); // Check for recursion for (Iterator i = inputStack.iterator(); i.hasNext(); ) @@ -1497,12 +1510,13 @@ public class XMLParser } if (name == null || "".equals(name)) report = false; - if (in == null && url != null && resolver != null) + InputStream in = null; + if (resolver != null) { - if (resolver instanceof XMLResolver2) - in = ((XMLResolver2) resolver).resolve(ids.publicId, url); - else - in = resolver.resolve(url); + Object obj = resolver.resolveEntity(ids.publicId, url, getXMLBase(), + null); + if (obj instanceof InputStream) + in = (InputStream) obj; } if (in == null) in = resolve(url); @@ -1535,12 +1549,13 @@ public class XMLParser * @param base the current base URL * @param href the (absolute or relative) URL to resolve */ - static String absolutize(String base, String href) + public static String absolutize(String base, String href) + throws MalformedURLException { if (href == null) return null; int ci = href.indexOf(':'); - if (ci > 1 && isLowercaseAscii(href.substring(0, ci))) + if (ci > 1 && isURLScheme(href.substring(0, ci))) { // href is absolute already return href; @@ -1565,40 +1580,23 @@ public class XMLParser if (!base.endsWith("/")) base += "/"; } - if (href.startsWith("/")) - { - if (base.startsWith("file:")) - return "file://" + href; - int i = base.indexOf("://"); - if (i != -1) - { - i = base.indexOf('/', i + 3); - if (i != -1) - base = base.substring(0, i); - } - } - else - { - while (href.startsWith("..")) - { - int i = base.lastIndexOf('/', base.length() - 2); - if (i != -1) - base = base.substring(0, i + 1); - href = href.substring(2); - if (href.startsWith("/")) - href = href.substring(1); - } - } - return base + href; + return new URL(new URL(base), href).toString(); } - private static boolean isLowercaseAscii(String text) + /** + * 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 < 97 || c > 122) + if (c == '+' || c == '.' || c == '-') + continue; + if (c < 65 || (c > 90 && c < 97) || c > 122) return false; } return true; @@ -1607,7 +1605,7 @@ public class XMLParser /** * Returns an input stream for the given URL. */ - private InputStream resolve(String url) + static InputStream resolve(String url) throws IOException { try @@ -1618,6 +1616,12 @@ public class XMLParser { return null; } + catch (IOException e) + { + IOException e2 = new IOException("error resolving " + url); + e2.initCause(e); + throw e2; + } } /** @@ -1891,7 +1895,10 @@ public class XMLParser throws IOException, XMLStreamException { requireWhitespace(); + boolean saved = expandPE; + expandPE = (inputStack.size() > 1); String name = readNmtoken(true); + expandPE = saved; requireWhitespace(); readContentspec(name); skipWhitespace(); @@ -2106,7 +2113,10 @@ public class XMLParser throws IOException, XMLStreamException { requireWhitespace(); + boolean saved = expandPE; + expandPE = (inputStack.size() > 1); String elementName = readNmtoken(true); + expandPE = saved; boolean white = tryWhitespace(); while (!tryRead('>')) { @@ -2419,11 +2429,11 @@ public class XMLParser } else { - if (!isNameStartCharacter(cp[0])) + 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])) + if (!isNameCharacter(cp[i], input.xml11)) error("malformed reference in entity value", value); } } @@ -2838,8 +2848,6 @@ public class XMLParser error("Duplicate default namespace declaration"); if (XMLConstants.XML_NS_URI.equals(attr.value)) error("can't bind XML namespace"); - if ("".equals(attr.value) && !input.xml11) - error("illegal use of 1.1-style prefix unbinding in 1.0 document"); ctx.put(XMLConstants.DEFAULT_NS_PREFIX, attr.value); return true; } @@ -3087,7 +3095,15 @@ public class XMLParser break; case 0x3c: // '<' reset(); - read(tmpBuf, 0, i); + // 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 @@ -3258,15 +3274,7 @@ public class XMLParser reset(); char[] ref = readCharacterRef(hex ? 16 : 10); for (int i = 0; i < ref.length; i++) - { - char x = ref[i]; - if ((flags & (LIT_ATTRIBUTE | LIT_PUBID)) != 0 && - (x == 0x0a || x == 0x0d)) - x = 0x20; // normalize - else if ((flags & LIT_ATTRIBUTE) != 0 && x == 0x09) - x = 0x20; // normalize - literalBuf.append(x); - } + literalBuf.append(ref[i]); entities = true; continue; } @@ -3469,13 +3477,13 @@ public class XMLParser int c = readCh(); if (isName) { - if (!isNameStartCharacter(c)) + if (!isNameStartCharacter(c, input.xml11)) error("not a name start character", "U+" + Integer.toHexString(c)); } else { - if (!isNameCharacter(c)) + if (!isNameCharacter(c, input.xml11)) error("not a name character", "U+" + Integer.toHexString(c)); } @@ -3510,7 +3518,7 @@ public class XMLParser reset(); return intern(buf.toString()); default: - if (!isNameCharacter(c)) + if (!isNameCharacter(c, input.xml11)) error("not a name character", "U+" + Integer.toHexString(c)); else @@ -3523,7 +3531,7 @@ public class XMLParser /** * Indicates whether the specified Unicode character is an XML 1.1 Char. */ - private boolean isXML11Char(int c) + public static boolean isXML11Char(int c) { return ((c >= 0x0001 && c <= 0xD7FF) || (c >= 0xE000 && c < 0xFFFD) || // NB exclude 0xfffd @@ -3534,7 +3542,7 @@ public class XMLParser * Indicates whether the specified Unicode character is an XML 1.1 * RestrictedChar. */ - private boolean isXML11RestrictedChar(int c) + public static boolean isXML11RestrictedChar(int c) { return ((c >= 0x0001 && c <= 0x0008) || (c >= 0x000B && c <= 0x000C) || @@ -3556,17 +3564,17 @@ public class XMLParser return false; if (isName) { - if (!isNameStartCharacter(cp[0])) + if (!isNameStartCharacter(cp[0], input.xml11)) return false; } else { - if (!isNameCharacter(cp[0])) + if (!isNameCharacter(cp[0], input.xml11)) return false; } for (int i = 1; i < cp.length; i++) { - if (!isNameCharacter(cp[i])) + if (!isNameCharacter(cp[i], input.xml11)) return false; } return true; @@ -3581,9 +3589,9 @@ public class XMLParser * Indicates whether the specified Unicode character is a Name start * character. */ - private boolean isNameStartCharacter(int c) + public static boolean isNameStartCharacter(int c, boolean xml11) { - if (input.xml11) + if (xml11) return ((c >= 0x0041 && c <= 0x005a) || (c >= 0x0061 && c <= 0x007a) || c == 0x3a | @@ -3608,9 +3616,9 @@ public class XMLParser * Indicates whether the specified Unicode character is a Name non-initial * character. */ - private boolean isNameCharacter(int c) + public static boolean isNameCharacter(int c, boolean xml11) { - if (input.xml11) + if (xml11) return ((c >= 0x0041 && c <= 0x005a) || (c >= 0x0061 && c <= 0x007a) || (c >= 0x0030 && c <= 0x0039) || @@ -4255,6 +4263,7 @@ public class XMLParser true, // supportDTD true, // baseAware true, // stringInterning + true, // extendedEventTypes null, null); XMLStreamReader reader = p; @@ -4286,7 +4295,7 @@ public class XMLParser "='"+reader.getNamespaceURI(i)+"'"); l = reader.getAttributeCount(); for (int i = 0; i < l; i++) - System.out.println("\tattribute "+reader.getAttributeQName(i)+ + System.out.println("\tattribute "+reader.getAttributeName(i)+ "='"+reader.getAttributeValue(i)+"'"); break; case XMLStreamConstants.END_ELEMENT: @@ -4314,10 +4323,10 @@ public class XMLParser System.out.println("PROCESSING_INSTRUCTION "+reader.getPITarget()+ " "+reader.getPIData()); break; - case XMLStreamConstants.START_ENTITY: + case START_ENTITY: System.out.println("START_ENTITY "+reader.getText()); break; - case XMLStreamConstants.END_ENTITY: + case END_ENTITY: System.out.println("END_ENTITY "+reader.getText()); break; default: @@ -4330,7 +4339,7 @@ public class XMLParser Location l = reader.getLocation(); System.out.println("At line "+l.getLineNumber()+ ", column "+l.getColumnNumber()+ - " of "+l.getLocationURI()); + " of "+l.getSystemId()); throw e; } } @@ -4939,19 +4948,6 @@ public class XMLParser } /** - * Compatibility interface that can be used to resolve based on a public - * ID, not just an URL. - */ - interface XMLResolver2 - extends XMLResolver - { - - InputStream resolve(String publicId, String systemId) - throws XMLStreamException; - - } - - /** * An XML input source. */ static class Input @@ -5019,7 +5015,12 @@ public class XMLParser return line; } - public String getLocationURI() + public String getPublicId() + { + return publicId; + } + + public String getSystemId() { return systemId; } diff --git a/libjava/classpath/gnu/xml/stream/XMLStreamReaderImpl.java b/libjava/classpath/gnu/xml/stream/XMLStreamReaderImpl.java deleted file mode 100644 index 568d800..0000000 --- a/libjava/classpath/gnu/xml/stream/XMLStreamReaderImpl.java +++ /dev/null @@ -1,1037 +0,0 @@ -/* XMLStreamReaderImpl.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.InputStream; -import java.io.IOException; -import java.io.Reader; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.Map; -import javax.xml.namespace.NamespaceContext; -import javax.xml.namespace.QName; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.parsers.SAXParser; -import javax.xml.parsers.SAXParserFactory; -import javax.xml.stream.Location; -import javax.xml.stream.XMLResolver; -import javax.xml.stream.XMLReporter; -import javax.xml.stream.XMLStreamConstants; -import javax.xml.stream.XMLStreamException; -import javax.xml.stream.XMLStreamReader; - -import javax.xml.stream.events.Attribute; -import javax.xml.stream.events.Characters; -import javax.xml.stream.events.Comment; -import javax.xml.stream.events.DTD; -import javax.xml.stream.events.EndDocument; -import javax.xml.stream.events.EndElement; -import javax.xml.stream.events.EndEntity; -import javax.xml.stream.events.EntityDeclaration; -import javax.xml.stream.events.EntityReference; -import javax.xml.stream.events.Namespace; -import javax.xml.stream.events.NotationDeclaration; -import javax.xml.stream.events.ProcessingInstruction; -import javax.xml.stream.events.StartDocument; -import javax.xml.stream.events.StartElement; -import javax.xml.stream.events.StartEntity; -import javax.xml.stream.events.XMLEvent; - -import org.xml.sax.Attributes; -import org.xml.sax.ContentHandler; -import org.xml.sax.DTDHandler; -import org.xml.sax.EntityResolver; -import org.xml.sax.ErrorHandler; -import org.xml.sax.InputSource; -import org.xml.sax.Locator; -import org.xml.sax.SAXException; -import org.xml.sax.SAXParseException; -import org.xml.sax.XMLReader; -import org.xml.sax.ext.Attributes2; -import org.xml.sax.ext.DeclHandler; -import org.xml.sax.ext.LexicalHandler; -import org.xml.sax.ext.Locator2; -import org.xml.sax.helpers.NamespaceSupport; - -/** - * An XML parser. - * - * This implementation uses SAX to create a series of events in memory, - * and then iterates over this series. This has the advantage of being simple - * and unifying the existing XML parsing code. However, it is quite - * memory-inefficient and obviously won't cope with streams of arbitrary - * length. - * - * A future task could be to write a real, progressive/incremental - * implementation of this class. In that case we should consider making that - * the default XML parser implementation and using a SAX wrapper to it to - * provide the GNU SAX implementation. - * - * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> - */ -public class XMLStreamReaderImpl - implements XMLStreamReader, NamespaceContext -{ - - private LinkedList events; - private XMLEvent currentEvent; - private int eventType; - private NamespaceSupport namespaces; - - protected String publicId; - protected String systemId; - - protected XMLResolver resolver; - protected XMLReporter reporter; - protected boolean validating; - protected boolean namespaceAware; - protected boolean coalescing; - protected boolean replacingEntityReferences; - protected boolean externalEntities; - protected boolean supportDTD; - - protected XMLStreamReaderImpl(InputStream in, - String publicId, - String systemId, - XMLResolver resolver, - XMLReporter reporter, - boolean validating, - boolean namespaceAware, - boolean coalescing, - boolean replacingEntityReferences, - boolean externalEntities, - boolean supportDTD) - throws XMLStreamException - { - //this.in = in; - this.publicId = publicId; - this.systemId = systemId; - this.resolver = resolver; - this.reporter = reporter; - this.validating = validating; - this.namespaceAware = namespaceAware; - this.coalescing = coalescing; - this.replacingEntityReferences = replacingEntityReferences; - this.externalEntities = externalEntities; - this.supportDTD = supportDTD; - namespaces = new NamespaceSupport(); - events = new LinkedList(); - - // Configure the SAX parser and perform the parse - try - { - SAXParserFactory f = SAXParserFactory.newInstance(); - f.setNamespaceAware(namespaceAware); - f.setValidating(validating); - SAXParser p = f.newSAXParser(); - XMLReader r = p.getXMLReader(); - CallbackHandler ch = this.new CallbackHandler(r); - r.setFeature("http://xml.org/sax/features/external-general-entities", - externalEntities); - r.setFeature("http://xml.org/sax/features/namespaces", - namespaceAware); - r.setContentHandler(ch); - r.setDTDHandler(ch); - r.setEntityResolver(ch); - r.setErrorHandler(ch); - r.setProperty("http://xml.org/sax/properties/lexical-handler", - ch); - InputSource source = new InputSource(in); - source.setSystemId(systemId); - r.parse(source); - } - catch (SAXException e) - { - events.add(e); - } - catch (IOException e) - { - events.add(e); - } - catch (ParserConfigurationException e) - { - XMLStreamException e2 = new XMLStreamException(e); - e2.initCause(e); - throw e2; - } - } - - protected XMLStreamReaderImpl(Reader reader, - String publicId, - String systemId, - XMLResolver resolver, - XMLReporter reporter, - boolean validating, - boolean namespaceAware, - boolean coalescing, - boolean replacingEntityReferences, - boolean externalEntities, - boolean supportDTD) - throws XMLStreamException - { - //this.reader = reader; - this.publicId = publicId; - this.systemId = systemId; - this.resolver = resolver; - this.reporter = reporter; - this.validating = validating; - this.namespaceAware = namespaceAware; - this.coalescing = coalescing; - this.replacingEntityReferences = replacingEntityReferences; - this.externalEntities = externalEntities; - this.supportDTD = supportDTD; - namespaces = new NamespaceSupport(); - events = new LinkedList(); - - // Configure the SAX parser and perform the parse - try - { - SAXParserFactory f = SAXParserFactory.newInstance(); - f.setNamespaceAware(namespaceAware); - f.setValidating(validating); - SAXParser p = f.newSAXParser(); - XMLReader r = p.getXMLReader(); - CallbackHandler ch = this.new CallbackHandler(r); - r.setFeature("http://xml.org/sax/features/external-general-entities", - externalEntities); - r.setFeature("http://xml.org/sax/features/namespaces", - namespaceAware); - r.setContentHandler(ch); - r.setDTDHandler(ch); - r.setEntityResolver(ch); - r.setErrorHandler(ch); - r.setProperty("http://xml.org/sax/properties/lexical-handler", - ch); - InputSource source = new InputSource(reader); - source.setSystemId(systemId); - r.parse(source); - } - catch (SAXException e) - { - events.add(e); - } - catch (IOException e) - { - events.add(e); - } - catch (ParserConfigurationException e) - { - XMLStreamException e2 = new XMLStreamException(e); - e2.initCause(e); - throw e2; - } - } - - public Object getProperty(String name) - throws IllegalArgumentException - { - throw new IllegalArgumentException(name); - } - - public int next() - throws XMLStreamException - { - if (events.isEmpty()) - throw new XMLStreamException("EOF"); - Object event = events.removeFirst(); - if (event instanceof Exception) - { - Exception e = (Exception) event; - XMLStreamException e2 = new XMLStreamException(e); - e2.initCause(e); - throw e2; - } - currentEvent = (XMLEvent) event; - eventType = currentEvent.getEventType(); - return eventType; - } - - public void require(int type, String namespaceURI, String localName) - throws XMLStreamException - { - // TODO - throw new UnsupportedOperationException(); - } - - public String getElementText() - throws XMLStreamException - { - // TODO - throw new UnsupportedOperationException(); - } - - public int nextTag() - throws XMLStreamException - { - int ret; - do - { - ret = next(); - } - while (ret != XMLStreamConstants.START_ELEMENT && - ret != XMLStreamConstants.END_ELEMENT); - return ret; - } - - public boolean hasNext() - throws XMLStreamException - { - return !events.isEmpty(); - } - - public void close() - throws XMLStreamException - { - } - - public String getNamespaceURI(String prefix) - { - return namespaces.getURI(prefix); - } - - public String getPrefix(String namespaceURI) - { - return namespaces.getPrefix(namespaceURI); - } - - public Iterator getPrefixes(String namespaceURI) - { - LinkedList acc = new LinkedList(); - for (Enumeration e = namespaces.getPrefixes(namespaceURI); - e.hasMoreElements(); ) - acc.add(e.nextElement()); - return acc.iterator(); - } - - public boolean isStartElement() - { - return eventType == START_ELEMENT; - } - - public boolean isEndElement() - { - return eventType == END_ELEMENT; - } - - public boolean isCharacters() - { - return eventType == CHARACTERS || eventType == CDATA; - } - - public boolean isWhiteSpace() - { - return eventType == SPACE; - } - - public String getAttributeValue(String namespaceURI, String localName) - { - StartElement se = (StartElement) currentEvent; - for (Iterator i = se.getAttributes(); i.hasNext(); ) - { - Attribute attr = (Attribute) i.next(); - QName name = attr.getName(); - if (namespaceURI != null && - !namespaceURI.equals(name.getNamespaceURI())) - continue; - if (!localName.equals(name.getLocalPart())) - continue; - return attr.getValue(); - } - return null; - } - - public int getAttributeCount() - { - StartElement se = (StartElement) currentEvent; - int count = 0; - for (Iterator i = se.getAttributes(); i.hasNext(); ) - { - i.next(); - count++; - } - return count; - } - - public QName getAttributeQName(int index) - { - StartElement se = (StartElement) currentEvent; - int count = 0; - for (Iterator i = se.getAttributes(); i.hasNext(); ) - { - Attribute attr = (Attribute) i.next(); - if (index == count) - return attr.getName(); - count++; - } - return null; - } - - public String getAttributeNamespace(int index) - { - QName name = getAttributeQName(index); - return (name == null) ? null : name.getNamespaceURI(); - } - - public String getAttributeName(int index) - { - QName name = getAttributeQName(index); - return (name == null) ? null : name.getLocalPart(); - } - - public String getAttributePrefix(int index) - { - QName name = getAttributeQName(index); - return (name == null) ? null : name.getPrefix(); - } - - public String getAttributeType(int index) - { - StartElement se = (StartElement) currentEvent; - int count = 0; - for (Iterator i = se.getAttributes(); i.hasNext(); ) - { - Attribute attr = (Attribute) i.next(); - if (index == count) - { - QName type = attr.getDTDType(); - return (type == null) ? "CDATA" : type.toString(); - } - count++; - } - return null; - } - - public String getAttributeValue(int index) - { - StartElement se = (StartElement) currentEvent; - int count = 0; - for (Iterator i = se.getAttributes(); i.hasNext(); ) - { - Attribute attr = (Attribute) i.next(); - if (index == count) - return attr.getValue(); - count++; - } - return null; - } - - public boolean isAttributeSpecified(int index) - { - StartElement se = (StartElement) currentEvent; - int count = 0; - for (Iterator i = se.getAttributes(); i.hasNext(); ) - { - Attribute attr = (Attribute) i.next(); - if (index == count) - return attr.isSpecified(); - count++; - } - return false; - } - - public int getNamespaceCount() - { - Iterator i = null; - switch (eventType) - { - case XMLStreamConstants.START_ELEMENT: - i = ((StartElement) currentEvent).getNamespaces(); - break; - case XMLStreamConstants.END_ELEMENT: - i = ((EndElement) currentEvent).getNamespaces(); - break; - default: - throw new IllegalStateException(); - } - int count = 0; - while (i.hasNext()) - { - i.next(); - count++; - } - return count; - } - - public String getNamespacePrefix(int index) - { - Iterator i = null; - switch (eventType) - { - case XMLStreamConstants.START_ELEMENT: - i = ((StartElement) currentEvent).getNamespaces(); - break; - case XMLStreamConstants.END_ELEMENT: - i = ((EndElement) currentEvent).getNamespaces(); - break; - default: - throw new IllegalStateException(); - } - int count = 0; - while (i.hasNext()) - { - Namespace ns = (Namespace) i.next(); - if (index == count) - return ns.getPrefix(); - count++; - } - return null; - } - - public String getNamespaceURI(int index) - { - Iterator i = null; - switch (eventType) - { - case XMLStreamConstants.START_ELEMENT: - i = ((StartElement) currentEvent).getNamespaces(); - break; - case XMLStreamConstants.END_ELEMENT: - i = ((EndElement) currentEvent).getNamespaces(); - break; - default: - throw new IllegalStateException(); - } - int count = 0; - while (i.hasNext()) - { - Namespace ns = (Namespace) i.next(); - if (index == count) - return ns.getNamespaceURI(); - count++; - } - return null; - } - - public NamespaceContext getNamespaceContext() - { - return this; - } - - public int getEventType() - { - return eventType; - } - - public String getText() - { - switch (eventType) - { - case XMLStreamConstants.CHARACTERS: - case XMLStreamConstants.CDATA: - case XMLStreamConstants.SPACE: - return ((Characters) currentEvent).getData(); - case XMLStreamConstants.COMMENT: - return ((Comment) currentEvent).getText(); - case XMLStreamConstants.ENTITY_REFERENCE: - return ((EntityReference) currentEvent).getReplacementText(); - case XMLStreamConstants.DTD: - return ((DTD) currentEvent).getDocumentTypeDeclaration(); - } - return null; - } - - public char[] getTextCharacters() - { - String text = getText(); - return (text == null) ? null : text.toCharArray(); - } - - public int getTextCharacters(int sourceStart, char[] target, - int targetStart, int length) - throws XMLStreamException - { - char[] source = getTextCharacters(); - int len = Math.min(source.length, length); - System.arraycopy(source, sourceStart, target, targetStart, len); - return len; - } - - public int getTextStart() - { - return 0; - } - - public int getTextLength() - { - String text = getText(); - return (text == null) ? 0 : text.length(); - } - - public String getEncoding() - { - // XXX SAX doesn't provide this - return null; - } - - public boolean hasText() - { - return eventType == CHARACTERS || eventType == DTD || - eventType == SPACE || eventType == ENTITY_REFERENCE || - eventType == COMMENT || eventType == DTD; - } - - public Location getLocation() - { - return currentEvent.getLocation(); - } - - public QName getName() - { - switch (eventType) - { - case XMLStreamConstants.START_ELEMENT: - return ((StartElement) currentEvent).getName(); - case XMLStreamConstants.END_ELEMENT: - return ((EndElement) currentEvent).getName(); - case XMLStreamConstants.ATTRIBUTE: - return ((Attribute) currentEvent).getName(); - } - return null; - } - - public String getLocalName() - { - QName name = getName(); - return (name == null) ? null : name.getLocalPart(); - } - - public boolean hasName() - { - return getName() != null; - } - - public String getNamespaceURI() - { - QName name = getName(); - return (name == null) ? null : name.getNamespaceURI(); - } - - public String getPrefix() - { - QName name = getName(); - return (name == null) ? null : name.getPrefix(); - } - - public String getVersion() - { - StartDocument sd = (StartDocument) currentEvent; - return sd.getVersion(); - } - - public boolean isStandalone() - { - StartDocument sd = (StartDocument) currentEvent; - return sd.isStandalone(); - } - - public boolean standaloneSet() - { - StartDocument sd = (StartDocument) currentEvent; - return sd.standaloneSet(); - } - - public String getCharacterEncodingScheme() - { - StartDocument sd = (StartDocument) currentEvent; - return sd.getCharacterEncodingScheme(); - } - - public String getPITarget() - { - ProcessingInstruction pi = (ProcessingInstruction) currentEvent; - return pi.getTarget(); - } - - public String getPIData() - { - ProcessingInstruction pi = (ProcessingInstruction) currentEvent; - return pi.getData(); - } - - /** - * This class is used to construct the event series from SAX callbacks. - */ - class CallbackHandler - implements ContentHandler, DTDHandler, LexicalHandler, - DeclHandler, EntityResolver, ErrorHandler - { - - XMLReader reader; - Locator locator; - Location location; - private boolean inCDATA; - private LinkedList namespaces = new LinkedList(); - private LinkedList notations; - private LinkedList entities; - - CallbackHandler(XMLReader reader) - { - this.reader = reader; - } - - public void setDocumentLocator(Locator locator) - { - this.locator = locator; - location = new LocationImpl(-1, - locator.getColumnNumber(), - locator.getLineNumber(), - locator.getSystemId()); - } - - public void startDocument() - throws SAXException - { - String version = (locator instanceof Locator2) ? - ((Locator2) locator).getXMLVersion() : null; - String encoding = (locator instanceof Locator2) ? - ((Locator2) locator).getEncoding() : null; - boolean standalone = - reader.getFeature("http://xml.org/sax/features/is-standalone"); - boolean standaloneDeclared = standalone; - boolean encodingDeclared = (encoding != null); - events.add(new StartDocumentImpl(location, - location.getLocationURI(), - encoding, - version, - standalone, - standaloneDeclared, - encodingDeclared)); - } - - public void endDocument() - throws SAXException - { - events.add(new EndDocumentImpl(location)); - } - - public void startPrefixMapping(String prefix, String uri) - throws SAXException - { - namespaces.add(new NamespaceImpl(location, prefix, uri)); - } - - public void endPrefixMapping(String prefix) - throws SAXException - { - } - - public void startElement(String namespaceURI, String localName, - String qName, Attributes atts) - throws SAXException - { - LinkedList ns = namespaces; - namespaces = new LinkedList(); - int ci = qName.indexOf(':'); - String prefix = null; - localName = qName; - if (ci != -1) - { - prefix = qName.substring(0, ci); - localName = qName.substring(ci + 1); - } - QName name = new QName(namespaceURI, localName, prefix); - LinkedList attrs = new LinkedList(); - StartElementImpl se = new StartElementImpl(location, name, - attrs, ns, null); - events.add(se); - // Add namespaces - //for (Iterator i = ns.iterator(); i.hasNext(); ) - // events.add(i.next()); - // Add attributes - int len = atts.getLength(); - for (int i = 0; i < len; i++) - { - String attURI = atts.getURI(i); - String attQName = atts.getQName(i); - String value = atts.getValue(i); - QName type = QName.valueOf(atts.getType(i)); - boolean specified = (atts instanceof Attributes2) && - ((Attributes2) atts).isSpecified(i); - ci = attQName.indexOf(':'); - String attPrefix = null; - String attLocalName = attQName; - if (ci != -1) - { - attPrefix = attQName.substring(0, ci); - attLocalName = attQName.substring(ci + 1); - } - if ("xmlns".equals(attPrefix) || "xmlns".equals(attQName)) - continue; - QName attrName = new QName(attURI, attLocalName, attPrefix); - AttributeImpl attr = new AttributeImpl(location, attrName, - value, type, specified); - attrs.add(attr); - //events.add(attr); - } - } - - public void endElement(String namespaceURI, String localName, - String qName) - throws SAXException - { - int ci = qName.indexOf(':'); - String prefix = null; - localName = qName; - if (ci != -1) - { - prefix = qName.substring(0, ci); - localName = qName.substring(ci + 1); - } - QName name = new QName(namespaceURI, localName, prefix); - events.add(new EndElementImpl(location, name, new LinkedList())); - // TODO namespaces out of scope - } - - public void characters(char[] ch, int start, int length) - throws SAXException - { - boolean whitespace = isWhitespace(ch, start, length); - events.add(new CharactersImpl(location, new String(ch, start, length), - whitespace, inCDATA, false)); - } - - public void ignorableWhitespace(char[] ch, int start, int length) - throws SAXException - { - boolean whitespace = isWhitespace(ch, start, length); - events.add(new CharactersImpl(location, new String(ch, start, length), - whitespace, inCDATA, true)); - } - - boolean isWhitespace(char[] ch, int start, int len) - { - int end = start + len; - for (int i = start; i < end; i++) - { - char c = ch[i]; - if (c != ' ' && c != '\t' && c != '\n' && c != '\r') - return false; - } - return true; - } - - public void processingInstruction(String target, String data) - throws SAXException - { - events.add(new ProcessingInstructionImpl(location, target, data)); - } - - public void skippedEntity(String name) - throws SAXException - { - } - - public void startDTD(String name, String publicId, String systemId) - throws SAXException - { - notations = new LinkedList(); - entities = new LinkedList(); - events.add(new DTDImpl(location, null, null, notations, entities)); - } - - public void endDTD() - throws SAXException - { - } - - public void startEntity(String name) - throws SAXException - { - events.add(new StartEntityImpl(location, name)); - } - - public void endEntity(String name) - throws SAXException - { - events.add(new EndEntityImpl(location, name)); - } - - public void startCDATA() - throws SAXException - { - inCDATA = true; - } - - public void endCDATA() - throws SAXException - { - inCDATA = false; - } - - public void comment(char[] ch, int start, int length) - throws SAXException - { - events.add(new CommentImpl(location, new String(ch, start, length))); - } - - public void notationDecl(String name, String publicId, String systemId) - throws SAXException - { - Object n = new NotationDeclarationImpl(location, name, publicId, - systemId); - notations.add(n); - //events.add(n); - } - - public void unparsedEntityDecl(String name, String publicId, - String systemId, String notationName) - throws SAXException - { - Object e = new EntityDeclarationImpl(location, publicId, systemId, - name, notationName, - null, null); - entities.add(e); - //events.add(e); - } - - public void elementDecl(String name, String model) - throws SAXException - { - } - - public void attributeDecl(String eName, String aName, String type, - String valueDefault, String value) - throws SAXException - { - } - - public void internalEntityDecl(String name, String value) - throws SAXException - { - Object e = new EntityDeclarationImpl(location, null, null, - name, null, value, null); - entities.add(e); - //events.add(e); - } - - public void externalEntityDecl(String name, String publicId, - String systemId) - throws SAXException - { - Object e = new EntityDeclarationImpl(location, publicId, systemId, - name, null, null, null); - entities.add(e); - //events.add(e); - } - - public void warning(SAXParseException e) - throws SAXException - { - if (reporter != null) - { - try - { - reporter.report(e.getMessage(), "warning", e, location); - } - catch (XMLStreamException e2) - { - SAXException e3 = new SAXException(e2.getMessage()); - e3.initCause(e2); - throw e3; - } - } - } - - public void error(SAXParseException e) - throws SAXException - { - if (reporter != null) - { - try - { - reporter.report(e.getMessage(), "error", e, location); - } - catch (XMLStreamException e2) - { - SAXException e3 = new SAXException(e2.getMessage()); - e3.initCause(e2); - throw e3; - } - } - } - - public void fatalError(SAXParseException e) - throws SAXException - { - if (reporter != null) - { - try - { - reporter.report(e.getMessage(), "fatal-error", e, location); - } - catch (XMLStreamException e2) - { - SAXException e3 = new SAXException(e2.getMessage()); - e3.initCause(e2); - throw e3; - } - } - } - - public InputSource resolveEntity(String publicId, String systemId) - throws SAXException, IOException - { - if (resolver != null) - { - try - { - InputStream in = resolver.resolve(systemId); - if (in != null) - { - InputSource ret = new InputSource(in); - ret.setPublicId(publicId); - ret.setSystemId(systemId); - return ret; - } - } - catch (XMLStreamException e) - { - SAXException e2 = new SAXException(e.getMessage()); - e2.initCause(e); - throw e2; - } - } - return null; - } - - } - -} - diff --git a/libjava/classpath/gnu/xml/stream/XMLStreamWriterImpl.java b/libjava/classpath/gnu/xml/stream/XMLStreamWriterImpl.java index 6157296..291016e 100644 --- a/libjava/classpath/gnu/xml/stream/XMLStreamWriterImpl.java +++ b/libjava/classpath/gnu/xml/stream/XMLStreamWriterImpl.java @@ -104,6 +104,9 @@ public class XMLStreamWriterImpl private NamespaceSupport namespaces; private int count = 0; + private boolean xml11; + private boolean hasXML11RestrictedChars; + /** * Constructor. * @see #writer @@ -145,6 +148,9 @@ public class XMLStreamWriterImpl { try { + if (!isName(localName)) + throw new IllegalArgumentException("illegal Name: " + localName); + endStartElement(); namespaces.pushContext(); @@ -167,6 +173,11 @@ public class XMLStreamWriterImpl { try { + if (namespaceURI != null && !isURI(namespaceURI)) + throw new IllegalArgumentException("illegal URI: " + namespaceURI); + if (!isName(localName)) + throw new IllegalArgumentException("illegal Name: " + localName); + endStartElement(); namespaces.pushContext(); @@ -190,7 +201,7 @@ public class XMLStreamWriterImpl inStartElement = true; if (!isDeclared) { - writeNamespace(prefix, namespaceURI); + writeNamespaceImpl(prefix, namespaceURI); } elements.addLast(new String[] { prefix, localName }); @@ -229,6 +240,13 @@ public class XMLStreamWriterImpl { 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(); @@ -243,7 +261,7 @@ public class XMLStreamWriterImpl writer.write(localName); if (prefixDefaulting && !isCurrent) { - writeNamespace(prefix, namespaceURI); + writeNamespaceImpl(prefix, namespaceURI); } elements.addLast(new String[] { prefix, localName }); @@ -343,11 +361,19 @@ public class XMLStreamWriterImpl 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('"'); - writeEncoded(value, true); + if (hasXML11RestrictedChars) + writeEncodedWithRestrictedChars(value, true); + else + writeEncoded(value, true); writer.write('"'); } catch (IOException e) @@ -366,11 +392,20 @@ public class XMLStreamWriterImpl 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) - writeNamespace(prefix, namespaceURI); + writeNamespaceImpl(prefix, namespaceURI); else throw new XMLStreamException("namespace " + namespaceURI + " is not bound"); @@ -388,7 +423,10 @@ public class XMLStreamWriterImpl writer.write(localName); writer.write('='); writer.write('"'); - writeEncoded(value, true); + if (hasXML11RestrictedChars) + writeEncodedWithRestrictedChars(value, true); + else + writeEncoded(value, true); writer.write('"'); } catch (IOException e) @@ -407,13 +445,20 @@ public class XMLStreamWriterImpl 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; - writeNamespace(prefix, namespaceURI); + writeNamespaceImpl(prefix, namespaceURI); } else throw new XMLStreamException("namespace " + namespaceURI + @@ -428,7 +473,10 @@ public class XMLStreamWriterImpl writer.write(localName); writer.write('='); writer.write('"'); - writeEncoded(value, true); + if (hasXML11RestrictedChars) + writeEncodedWithRestrictedChars(value, true); + else + writeEncoded(value, true); writer.write('"'); } catch (IOException e) @@ -446,6 +494,25 @@ public class XMLStreamWriterImpl 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; @@ -474,21 +541,41 @@ public class XMLStreamWriterImpl public void writeDefaultNamespace(String namespaceURI) throws XMLStreamException { - writeNamespace(XMLConstants.DEFAULT_NS_PREFIX, namespaceURI); + 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(); - if (data != null && data.indexOf("--") != -1) - throw new IllegalArgumentException(data); - writer.write("<!--"); - if (data != null) + 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("-->"); } @@ -511,6 +598,11 @@ public class XMLStreamWriterImpl { 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('<'); @@ -519,7 +611,20 @@ public class XMLStreamWriterImpl if (data != null) { writer.write(' '); - writer.write(data); + 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('>'); @@ -537,10 +642,12 @@ public class XMLStreamWriterImpl { try { - endStartElement(); - + if (!isChars(data) || hasXML11RestrictedChars) + throw new IllegalArgumentException("illegal XML character: " + data); if (data.indexOf("]]") != -1) - throw new IllegalArgumentException(data); + throw new IllegalArgumentException("illegal CDATA section: " + data); + + endStartElement(); writer.write("<![CDATA["); writer.write(data); @@ -557,8 +664,12 @@ public class XMLStreamWriterImpl 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('>'); @@ -576,6 +687,9 @@ public class XMLStreamWriterImpl { try { + if (!isName(name)) + throw new IllegalArgumentException("illegal Name: " + name); + endStartElement(); writer.write('&'); @@ -607,6 +721,8 @@ public class XMLStreamWriterImpl { 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"; @@ -632,11 +748,18 @@ public class XMLStreamWriterImpl public void writeCharacters(String text) throws XMLStreamException { + if (text == null) + return; try { + if (!isChars(text)) + throw new IllegalArgumentException("illegal XML character: " + text); + endStartElement(); - if (text != null) + if (hasXML11RestrictedChars) + writeEncodedWithRestrictedChars(text, false); + else writeEncoded(text, false); } catch (IOException e) @@ -650,39 +773,7 @@ public class XMLStreamWriterImpl public void writeCharacters(char[] text, int start, int len) throws XMLStreamException { - try - { - endStartElement(); - - int end = start + len; - len = 0; - for (int i = start; i < end; i++) - { - char c = text[i]; - if (c == '<' || c == '>' || c == '&') - { - writer.write(text, start, len); - if (c == '<') - writer.write("<"); - else if (c == '>') - writer.write(">"); - else - writer.write("&"); - start = i + 1; - len = 0; - } - else - len++; - } - if (len > 0) - writer.write(text, start, len); - } - catch (IOException e) - { - XMLStreamException e2 = new XMLStreamException(e); - e2.initCause(e); - throw e2; - } + writeCharacters(new String(text, start, len)); } public String getPrefix(String uri) @@ -697,6 +788,19 @@ public class XMLStreamWriterImpl 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); } @@ -704,6 +808,8 @@ public class XMLStreamWriterImpl 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"); } @@ -769,6 +875,131 @@ public class XMLStreamWriterImpl 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; + } } diff --git a/libjava/classpath/gnu/xml/transform/AbstractNumberNode.java b/libjava/classpath/gnu/xml/transform/AbstractNumberNode.java index 91029d6..6d1202e 100644 --- a/libjava/classpath/gnu/xml/transform/AbstractNumberNode.java +++ b/libjava/classpath/gnu/xml/transform/AbstractNumberNode.java @@ -317,7 +317,7 @@ abstract class AbstractNumberNode public String toString() { - StringBuffer buf = new StringBuffer(getClass().getName()); + StringBuffer buf = new StringBuffer("number"); buf.append('['); buf.append("format="); buf.append(format); diff --git a/libjava/classpath/gnu/xml/transform/ApplyImportsNode.java b/libjava/classpath/gnu/xml/transform/ApplyImportsNode.java index 60dec85..4b06eea 100644 --- a/libjava/classpath/gnu/xml/transform/ApplyImportsNode.java +++ b/libjava/classpath/gnu/xml/transform/ApplyImportsNode.java @@ -1,5 +1,5 @@ /* ApplyImportsNode.java -- - Copyright (C) 2004 Free Software Foundation, Inc. + Copyright (C) 2004,2006 Free Software Foundation, Inc. This file is part of GNU Classpath. @@ -54,13 +54,9 @@ final class ApplyImportsNode { TemplateNode ret = new ApplyImportsNode(); if (children != null) - { - ret.children = children.clone(stylesheet); - } + ret.children = children.clone(stylesheet); if (next != null) - { - ret.next = next.clone(stylesheet); - } + ret.next = next.clone(stylesheet); return ret; } @@ -71,15 +67,16 @@ final class ApplyImportsNode { TemplateNode t = stylesheet.getTemplate(mode, context, true); if (t != null) - { - t.apply(stylesheet, mode, context, pos, len, - parent, nextSibling); - } + t.apply(stylesheet, mode, context, pos, len, + parent, nextSibling); if (next != null) - { - next.apply(stylesheet, mode, context, pos, len, - parent, nextSibling); - } + next.apply(stylesheet, mode, context, pos, len, + parent, nextSibling); + } + + public String toString() + { + return "apply-imports"; } } diff --git a/libjava/classpath/gnu/xml/transform/ApplyTemplatesNode.java b/libjava/classpath/gnu/xml/transform/ApplyTemplatesNode.java index ab26058..38b605a 100644 --- a/libjava/classpath/gnu/xml/transform/ApplyTemplatesNode.java +++ b/libjava/classpath/gnu/xml/transform/ApplyTemplatesNode.java @@ -1,5 +1,5 @@ /* ApplyTemplatesNode.java -- - Copyright (C) 2004 Free Software Foundation, Inc. + Copyright (C) 2004,2006 Free Software Foundation, Inc. This file is part of GNU Classpath. @@ -76,29 +76,21 @@ final class ApplyTemplatesNode TemplateNode clone(Stylesheet stylesheet) { - int len = sortKeys.size(); + 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)); - } + sortKeys2.add(((Key) sortKeys.get(i)).clone(stylesheet)); len = withParams.size(); List withParams2 = new ArrayList(len); for (int i = 0; i < len; i++) - { - withParams2.add(((WithParam) withParams.get(i)).clone(stylesheet)); - } + 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); - } + ret.children = children.clone(stylesheet); if (next != null) - { - ret.next = next.clone(stylesheet); - } + ret.next = next.clone(stylesheet); return ret; } @@ -147,9 +139,7 @@ final class ApplyTemplatesNode Collections.sort(nodes, new XSLComparator(sortKeys)); } else - { - Collections.sort(nodes, documentOrderComparator); - } + Collections.sort(nodes, documentOrderComparator); int l = nodes.size(); QName effectiveMode = isDefault ? mode : this.mode; for (int i = 0; i < l; i++) @@ -172,27 +162,21 @@ final class ApplyTemplatesNode } // apply-templates doesn't have processable children if (next != null) - { - next.apply(stylesheet, mode, - context, pos, len, - parent, nextSibling); - } + next.apply(stylesheet, mode, + context, pos, len, + parent, nextSibling); } public boolean references(QName var) { if (select != null && select.references(var)) - { - return true; - } + return true; if (withParams != null) { for (Iterator i = withParams.iterator(); i.hasNext(); ) { if (((WithParam) i.next()).references(var)) - { - return true; - } + return true; } } if (sortKeys != null) @@ -200,9 +184,7 @@ final class ApplyTemplatesNode for (Iterator i = sortKeys.iterator(); i.hasNext(); ) { if (((SortKey) i.next()).references(var)) - { - return true; - } + return true; } } return super.references(var); @@ -210,7 +192,7 @@ final class ApplyTemplatesNode public String toString() { - StringBuffer buf = new StringBuffer(getClass().getName()); + StringBuffer buf = new StringBuffer("apply-templates"); buf.append('['); boolean o = false; if (select != null) diff --git a/libjava/classpath/gnu/xml/transform/AttributeNode.java b/libjava/classpath/gnu/xml/transform/AttributeNode.java index bc5bc30..71e2ed0 100644 --- a/libjava/classpath/gnu/xml/transform/AttributeNode.java +++ b/libjava/classpath/gnu/xml/transform/AttributeNode.java @@ -231,7 +231,7 @@ final class AttributeNode public String toString() { - StringBuffer buf = new StringBuffer(getClass().getName()); + StringBuffer buf = new StringBuffer("attribute"); buf.append('['); buf.append("name="); buf.append(name); diff --git a/libjava/classpath/gnu/xml/transform/CallTemplateNode.java b/libjava/classpath/gnu/xml/transform/CallTemplateNode.java index b678219..31b26cb 100644 --- a/libjava/classpath/gnu/xml/transform/CallTemplateNode.java +++ b/libjava/classpath/gnu/xml/transform/CallTemplateNode.java @@ -1,5 +1,5 @@ /* CallTemplateNode.java -- - Copyright (C) 2004 Free Software Foundation, Inc. + Copyright (C) 2004,2006 Free Software Foundation, Inc. This file is part of GNU Classpath. @@ -69,18 +69,12 @@ final class CallTemplateNode int len = withParams.size(); List withParams2 = new ArrayList(len); for (int i = 0; i < len; i++) - { - withParams2.add(((WithParam) withParams.get(i)).clone(stylesheet)); - } + withParams2.add(((WithParam) withParams.get(i)).clone(stylesheet)); TemplateNode ret = new CallTemplateNode(name, withParams2); if (children != null) - { - ret.children = children.clone(stylesheet); - } + ret.children = children.clone(stylesheet); if (next != null) - { - ret.next = next.clone(stylesheet); - } + ret.next = next.clone(stylesheet); return ret; } @@ -89,52 +83,52 @@ final class CallTemplateNode Node parent, Node nextSibling) throws TransformerException { - if (withParams != null) + TemplateNode t = stylesheet.getTemplate(mode, name); + if (t != null) { - // compute the parameter values - LinkedList values = new LinkedList(); - for (Iterator i = withParams.iterator(); i.hasNext(); ) + if (withParams != null) { - 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); - if (stylesheet.debug) + // 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(); ) { - System.err.println("with-param: " + name + " = " + value); + 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); } } - } - TemplateNode t = stylesheet.getTemplate(mode, name); - if (t != null) - { t.apply(stylesheet, mode, context, pos, len, parent, nextSibling); - } - if (withParams != null) - { - // pop the variable context - stylesheet.bindings.pop(Bindings.WITH_PARAM); + 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) @@ -144,9 +138,7 @@ final class CallTemplateNode for (Iterator i = withParams.iterator(); i.hasNext(); ) { if (((WithParam) i.next()).references(var)) - { - return true; - } + return true; } } return super.references(var); @@ -154,7 +146,7 @@ final class CallTemplateNode public String toString() { - StringBuffer buf = new StringBuffer(getClass().getName()); + StringBuffer buf = new StringBuffer("call-template"); buf.append('['); buf.append("name="); buf.append(name); diff --git a/libjava/classpath/gnu/xml/transform/ChooseNode.java b/libjava/classpath/gnu/xml/transform/ChooseNode.java index fb1f2c4..cf07fa5 100644 --- a/libjava/classpath/gnu/xml/transform/ChooseNode.java +++ b/libjava/classpath/gnu/xml/transform/ChooseNode.java @@ -1,5 +1,5 @@ /* ChooseNode.java -- - Copyright (C) 2004 Free Software Foundation, Inc. + Copyright (C) 2004,2006 Free Software Foundation, Inc. This file is part of GNU Classpath. @@ -54,13 +54,9 @@ final class ChooseNode { TemplateNode ret = new ChooseNode(); if (children != null) - { - ret.children = children.clone(stylesheet); - } + ret.children = children.clone(stylesheet); if (next != null) - { - ret.next = next.clone(stylesheet); - } + ret.next = next.clone(stylesheet); return ret; } @@ -70,22 +66,18 @@ final class ChooseNode throws TransformerException { if (children != null) - { - children.apply(stylesheet, mode, - context, pos, len, - parent, nextSibling); - } + children.apply(stylesheet, mode, + context, pos, len, + parent, nextSibling); if (next != null) - { - next.apply(stylesheet, mode, - context, pos, len, - parent, nextSibling); - } + next.apply(stylesheet, mode, + context, pos, len, + parent, nextSibling); } public String toString() { - StringBuffer buf = new StringBuffer(getClass().getName()); + StringBuffer buf = new StringBuffer("choose"); buf.append('['); buf.append(']'); return buf.toString(); diff --git a/libjava/classpath/gnu/xml/transform/CommentNode.java b/libjava/classpath/gnu/xml/transform/CommentNode.java index 1428a46..8131fb2 100644 --- a/libjava/classpath/gnu/xml/transform/CommentNode.java +++ b/libjava/classpath/gnu/xml/transform/CommentNode.java @@ -1,5 +1,5 @@ /* CommentNode.java -- - Copyright (C) 2004 Free Software Foundation, Inc. + Copyright (C) 2004,2006 Free Software Foundation, Inc. This file is part of GNU Classpath. @@ -58,13 +58,9 @@ final class CommentNode { TemplateNode ret = new CommentNode(); if (children != null) - { - ret.children = children.clone(stylesheet); - } + ret.children = children.clone(stylesheet); if (next != null) - { - ret.next = next.clone(stylesheet); - } + ret.next = next.clone(stylesheet); return ret; } @@ -90,27 +86,18 @@ final class CommentNode Comment comment = doc.createComment(value); // Insert into result tree if (nextSibling != null) - { - parent.insertBefore(comment, nextSibling); - } + parent.insertBefore(comment, nextSibling); else - { - parent.appendChild(comment); - } + parent.appendChild(comment); if (next != null) - { - next.apply(stylesheet, mode, - context, pos, len, - parent, nextSibling); - } + next.apply(stylesheet, mode, + context, pos, len, + parent, nextSibling); } public String toString() { - StringBuffer buf = new StringBuffer(getClass().getName()); - buf.append('['); - buf.append(']'); - return buf.toString(); + return "comment"; } } diff --git a/libjava/classpath/gnu/xml/transform/CopyNode.java b/libjava/classpath/gnu/xml/transform/CopyNode.java index 3e01944..64cfa51 100644 --- a/libjava/classpath/gnu/xml/transform/CopyNode.java +++ b/libjava/classpath/gnu/xml/transform/CopyNode.java @@ -1,5 +1,5 @@ /* CopyNode.java -- - Copyright (C) 2004 Free Software Foundation, Inc. + Copyright (C) 2004,2006 Free Software Foundation, Inc. This file is part of GNU Classpath. @@ -65,13 +65,9 @@ final class CopyNode { TemplateNode ret = new CopyNode(uas); if (children != null) - { - ret.children = children.clone(stylesheet); - } + ret.children = children.clone(stylesheet); if (next != null) - { - ret.next = next.clone(stylesheet); - } + ret.next = next.clone(stylesheet); return ret; } @@ -102,44 +98,32 @@ final class CopyNode { NamedNodeMap attrs = parent.getAttributes(); if (attrs != null) - { - attrs.setNamedItemNS(copy); - } + attrs.setNamedItemNS(copy); } } else { if (nextSibling != null) - { - parent.insertBefore(copy, nextSibling); - } + parent.insertBefore(copy, nextSibling); else - { - parent.appendChild(copy); - } + parent.appendChild(copy); } } if (uas != null) { StringTokenizer st = new StringTokenizer(uas, " "); while (st.hasMoreTokens()) - { - addAttributeSet(stylesheet, mode, context, pos, len, - copy, null, st.nextToken()); - } + addAttributeSet(stylesheet, mode, context, pos, len, + copy, null, st.nextToken()); } if (children != null) - { - children.apply(stylesheet, mode, - context, pos, len, - copy, null); - } + children.apply(stylesheet, mode, + context, pos, len, + copy, null); if (next != null) - { - next.apply(stylesheet, mode, - context, pos, len, - parent, nextSibling); - } + next.apply(stylesheet, mode, + context, pos, len, + parent, nextSibling); } void addAttributeSet(Stylesheet stylesheet, QName mode, @@ -151,32 +135,31 @@ final class CopyNode { AttributeSet as = (AttributeSet) i.next(); if (!as.name.equals(attributeSet)) - { - continue; - } + continue; if (as.uas != null) { StringTokenizer st = new StringTokenizer(as.uas, " "); while (st.hasMoreTokens()) - { - addAttributeSet(stylesheet, mode, context, pos, len, - parent, nextSibling, st.nextToken()); - } + addAttributeSet(stylesheet, mode, context, pos, len, + parent, nextSibling, st.nextToken()); } if (as.children != null) - { - as.children.apply(stylesheet, mode, - context, pos, len, - parent, nextSibling); - } + as.children.apply(stylesheet, mode, + context, pos, len, + parent, nextSibling); } } public String toString() { - StringBuffer buf = new StringBuffer(getClass().getName()); - buf.append('['); - buf.append(']'); + StringBuffer buf = new StringBuffer("copy"); + if (uas != null) + { + buf.append('['); + buf.append("uas="); + buf.append(uas); + buf.append(']'); + } return buf.toString(); } diff --git a/libjava/classpath/gnu/xml/transform/CopyOfNode.java b/libjava/classpath/gnu/xml/transform/CopyOfNode.java index a43e3ba..ed4358c 100644 --- a/libjava/classpath/gnu/xml/transform/CopyOfNode.java +++ b/libjava/classpath/gnu/xml/transform/CopyOfNode.java @@ -1,5 +1,5 @@ /* CopyOfNode.java -- - Copyright (C) 2004 Free Software Foundation, Inc. + Copyright (C) 2004,2006 Free Software Foundation, Inc. This file is part of GNU Classpath. @@ -70,13 +70,9 @@ final class CopyOfNode { TemplateNode ret = new CopyOfNode(select.clone(stylesheet)); if (children != null) - { - ret.children = children.clone(stylesheet); - } + ret.children = children.clone(stylesheet); if (next != null) - { - ret.next = next.clone(stylesheet); - } + ret.next = next.clone(stylesheet); return ret; } @@ -102,9 +98,7 @@ final class CopyOfNode // Use document element src = ((Document) src).getDocumentElement(); if (src == null) - { - continue; - } + continue; nodeType = Node.ELEMENT_NODE; } else if (nodeType == Node.ATTRIBUTE_NODE) @@ -128,20 +122,14 @@ final class CopyOfNode { NamedNodeMap attrs = parent.getAttributes(); if (attrs != null) - { - attrs.setNamedItemNS(node); - } + attrs.setNamedItemNS(node); } else { if (nextSibling != null) - { - parent.insertBefore(node, nextSibling); - } + parent.insertBefore(node, nextSibling); else - { - parent.appendChild(node); - } + parent.appendChild(node); } } } @@ -152,36 +140,28 @@ final class CopyOfNode { Text textNode = doc.createTextNode(value); if (nextSibling != null) - { - parent.insertBefore(textNode, nextSibling); - } + parent.insertBefore(textNode, nextSibling); else - { - parent.appendChild(textNode); - } + parent.appendChild(textNode); } } // copy-of doesn't process children if (next != null) - { - next.apply(stylesheet, mode, - context, pos, len, - parent, nextSibling); - } + next.apply(stylesheet, mode, + context, pos, len, + parent, nextSibling); } public boolean references(QName var) { if (select != null && select.references(var)) - { - return true; - } + return true; return super.references(var); } public String toString() { - StringBuffer buf = new StringBuffer(getClass().getName()); + StringBuffer buf = new StringBuffer("copy-of"); buf.append('['); buf.append("select="); buf.append(select); diff --git a/libjava/classpath/gnu/xml/transform/DocumentFunction.java b/libjava/classpath/gnu/xml/transform/DocumentFunction.java index d8f6090..29f3d4a 100644 --- a/libjava/classpath/gnu/xml/transform/DocumentFunction.java +++ b/libjava/classpath/gnu/xml/transform/DocumentFunction.java @@ -126,9 +126,7 @@ final class DocumentFunction Object arg1 = values.get(0); Object arg2 = values.get(1); if (!(arg2 instanceof Collection)) - { - throw new RuntimeException("second argument is not a node-set"); - } + throw new RuntimeException("second argument is not a node-set"); Collection arg2ns = (Collection) arg2; String base2 = arg2ns.isEmpty() ? null : ((Node) arg2ns.iterator().next()).getBaseURI(); @@ -166,9 +164,7 @@ final class DocumentFunction Collection document(String uri, String base) { if ("".equals(uri) || uri == null) - { - uri = this.base.getBaseURI(); - } + uri = this.base.getBaseURI(); // Get fragment Expr fragment = null; @@ -197,10 +193,10 @@ final class DocumentFunction source = resolver.resolveDOM(null, base, uri); } Node node = source.getNode(); + // Strip whitespace + TransformerImpl.strip(stylesheet, node); if (fragment == null) - { - return Collections.singleton(node); - } + return Collections.singleton(node); else { Object ret = fragment.evaluate(node, 1, 1); @@ -216,9 +212,7 @@ final class DocumentFunction { String msg = "can't open " + uri; if (base != null) - { - msg += " with base " + base; - } + msg += " with base " + base; throw new RuntimeException(msg); } } @@ -227,16 +221,12 @@ final class DocumentFunction { Stylesheet s = stylesheet; if (context instanceof Stylesheet) - { - s = (Stylesheet) context; - } + 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)); - } + args2.add(((Expr) args.get(i)).clone(context)); f.setArguments(args2); return f; } @@ -246,9 +236,7 @@ final class DocumentFunction for (Iterator i = args.iterator(); i.hasNext(); ) { if (((Expr) i.next()).references(var)) - { - return true; - } + return true; } return false; } diff --git a/libjava/classpath/gnu/xml/transform/ElementNode.java b/libjava/classpath/gnu/xml/transform/ElementNode.java index 092c56a..b6a5c36 100644 --- a/libjava/classpath/gnu/xml/transform/ElementNode.java +++ b/libjava/classpath/gnu/xml/transform/ElementNode.java @@ -1,5 +1,5 @@ /* ElementNode.java -- - Copyright (C) 2004 Free Software Foundation, Inc. + Copyright (C) 2004,2006 Free Software Foundation, Inc. This file is part of GNU Classpath. @@ -238,7 +238,7 @@ final class ElementNode public String toString() { - StringBuffer buf = new StringBuffer(getClass().getName()); + StringBuffer buf = new StringBuffer("element"); buf.append('['); buf.append("name="); if (namespace != null) diff --git a/libjava/classpath/gnu/xml/transform/ForEachNode.java b/libjava/classpath/gnu/xml/transform/ForEachNode.java index 8f9220f..c8f51a6 100644 --- a/libjava/classpath/gnu/xml/transform/ForEachNode.java +++ b/libjava/classpath/gnu/xml/transform/ForEachNode.java @@ -1,5 +1,5 @@ /* ForEachNode.java -- - Copyright (C) 2004 Free Software Foundation, Inc. + Copyright (C) 2004,2006 Free Software Foundation, Inc. This file is part of GNU Classpath. @@ -70,19 +70,13 @@ final class ForEachNode int len = sortKeys.size(); List sortKeys2 = new ArrayList(len); for (int i = 0; i < len; i++) - { - sortKeys2.add(((Key) sortKeys.get(i)).clone(stylesheet)); - } + sortKeys2.add(((Key) sortKeys.get(i)).clone(stylesheet)); TemplateNode ret = new ForEachNode(select.clone(stylesheet), sortKeys2); if (children != null) - { - ret.children = children.clone(stylesheet); - } + ret.children = children.clone(stylesheet); if (next != null) - { - ret.next = next.clone(stylesheet); - } + ret.next = next.clone(stylesheet); return ret; } @@ -113,9 +107,7 @@ final class ForEachNode Collections.sort(list, new XSLComparator(sortKeys)); } else - { - Collections.sort(list, documentOrderComparator); - } + Collections.sort(list, documentOrderComparator); // Perform children for each node int l = list.size(); int p = 1; @@ -132,27 +124,21 @@ final class ForEachNode stylesheet.currentTemplate = saved; } if (next != null) - { - next.apply(stylesheet, mode, - context, pos, len, - parent, nextSibling); - } + next.apply(stylesheet, mode, + context, pos, len, + parent, nextSibling); } public boolean references(QName var) { if (select != null && select.references(var)) - { - return true; - } + return true; if (sortKeys != null) { for (Iterator i = sortKeys.iterator(); i.hasNext(); ) { if (((SortKey) i.next()).references(var)) - { - return true; - } + return true; } } return super.references(var); @@ -160,7 +146,7 @@ final class ForEachNode public String toString() { - StringBuffer buf = new StringBuffer(getClass().getName()); + StringBuffer buf = new StringBuffer("for-each"); buf.append('['); buf.append("select="); buf.append(select); diff --git a/libjava/classpath/gnu/xml/transform/IfNode.java b/libjava/classpath/gnu/xml/transform/IfNode.java index 17e2486..2a00d64 100644 --- a/libjava/classpath/gnu/xml/transform/IfNode.java +++ b/libjava/classpath/gnu/xml/transform/IfNode.java @@ -1,5 +1,5 @@ /* IfNode.java -- - Copyright (C) 2004 Free Software Foundation, Inc. + Copyright (C) 2004,2006 Free Software Foundation, Inc. This file is part of GNU Classpath. @@ -62,19 +62,15 @@ final class IfNode { TemplateNode ret = new IfNode(test.clone(stylesheet)); if (children != null) - { - ret.children = children.clone(stylesheet); - } + ret.children = children.clone(stylesheet); if (next != null) - { - ret.next = next.clone(stylesheet); - } + ret.next = next.clone(stylesheet); return ret; } void doApply(Stylesheet stylesheet, QName mode, - Node context, int pos, int len, - Node parent, Node nextSibling) + Node context, int pos, int len, + Node parent, Node nextSibling) throws TransformerException { Object ret = test.evaluate(context, pos, len); @@ -84,32 +80,26 @@ final class IfNode if (success) { if (children != null) - { - children.apply(stylesheet, mode, - context, pos, len, - parent, nextSibling); - } + children.apply(stylesheet, mode, + context, pos, len, + parent, nextSibling); } if (next != null) - { - next.apply(stylesheet, mode, - context, pos, len, - parent, nextSibling); - } + next.apply(stylesheet, mode, + context, pos, len, + parent, nextSibling); } public boolean references(QName var) { if (test != null && test.references(var)) - { - return true; - } + return true; return super.references(var); } public String toString() { - StringBuffer buf = new StringBuffer(getClass().getName()); + StringBuffer buf = new StringBuffer("if"); buf.append('['); buf.append("test="); buf.append(test); diff --git a/libjava/classpath/gnu/xml/transform/LiteralNode.java b/libjava/classpath/gnu/xml/transform/LiteralNode.java index 453c22c..d4e283a 100644 --- a/libjava/classpath/gnu/xml/transform/LiteralNode.java +++ b/libjava/classpath/gnu/xml/transform/LiteralNode.java @@ -196,12 +196,7 @@ final class LiteralNode public String toString() { - StringBuffer buf = new StringBuffer(getClass().getName()); - buf.append('['); - buf.append("source="); - buf.append(source); - buf.append(']'); - return buf.toString(); + return source.toString(); } } diff --git a/libjava/classpath/gnu/xml/transform/MessageNode.java b/libjava/classpath/gnu/xml/transform/MessageNode.java index e8e07c6..890d76f 100644 --- a/libjava/classpath/gnu/xml/transform/MessageNode.java +++ b/libjava/classpath/gnu/xml/transform/MessageNode.java @@ -92,5 +92,17 @@ final class MessageNode 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(); + } } diff --git a/libjava/classpath/gnu/xml/transform/OtherwiseNode.java b/libjava/classpath/gnu/xml/transform/OtherwiseNode.java index 570310f..9d8168c 100644 --- a/libjava/classpath/gnu/xml/transform/OtherwiseNode.java +++ b/libjava/classpath/gnu/xml/transform/OtherwiseNode.java @@ -1,5 +1,5 @@ /* OtherwiseNode.java -- - Copyright (C) 2004 Free Software Foundation, Inc. + Copyright (C) 2004,2006 Free Software Foundation, Inc. This file is part of GNU Classpath. @@ -54,13 +54,9 @@ final class OtherwiseNode { TemplateNode ret = new OtherwiseNode(); if (children != null) - { - ret.children = children.clone(stylesheet); - } + ret.children = children.clone(stylesheet); if (next != null) - { - ret.next = next.clone(stylesheet); - } + ret.next = next.clone(stylesheet); return ret; } @@ -70,25 +66,18 @@ final class OtherwiseNode throws TransformerException { if (children != null) - { - children.apply(stylesheet, mode, - context, pos, len, - parent, nextSibling); - } + children.apply(stylesheet, mode, + context, pos, len, + parent, nextSibling); if (next != null) - { - next.apply(stylesheet, mode, - context, pos, len, - parent, nextSibling); - } + next.apply(stylesheet, mode, + context, pos, len, + parent, nextSibling); } public String toString() { - StringBuffer buf = new StringBuffer(getClass().getName()); - buf.append('['); - buf.append(']'); - return buf.toString(); + return "otherwise"; } } diff --git a/libjava/classpath/gnu/xml/transform/ParameterNode.java b/libjava/classpath/gnu/xml/transform/ParameterNode.java index ef09ea5..8cd2677 100644 --- a/libjava/classpath/gnu/xml/transform/ParameterNode.java +++ b/libjava/classpath/gnu/xml/transform/ParameterNode.java @@ -1,5 +1,5 @@ /* ParameterNode.java -- - Copyright (C) 2004 Free Software Foundation, Inc. + Copyright (C) 2004,2006 Free Software Foundation, Inc. This file is part of GNU Classpath. @@ -73,13 +73,9 @@ final class ParameterNode select.clone(stylesheet), type); if (children != null) - { - ret.children = children.clone(stylesheet); - } + ret.children = children.clone(stylesheet); if (next != null) - { - ret.next = next.clone(stylesheet); - } + ret.next = next.clone(stylesheet); return ret; } @@ -96,18 +92,14 @@ final class ParameterNode { stylesheet.bindings.set(name, value, type); if (stylesheet.debug) - { - System.err.println(this + ": set to " + value); - } + 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); - } + next.apply(stylesheet, mode, + context, pos, len, + parent, nextSibling); // pop the variable context stylesheet.bindings.pop(type); } @@ -117,9 +109,7 @@ final class ParameterNode throws TransformerException { if (select != null) - { - return select.evaluate(context, pos, len); - } + return select.evaluate(context, pos, len); else if (children != null) { Document doc = (context instanceof Document) ? (Document) context : @@ -129,17 +119,13 @@ final class ParameterNode return Collections.singleton(fragment); } else - { - return null; - } + return null; } public boolean references(QName var) { if (select != null && select.references(var)) - { - return true; - } + return true; return super.references(var); } @@ -151,33 +137,18 @@ final class ParameterNode boolean r1 = references(pn.name); boolean r2 = pn.references(name); if (r1 && r2) - { - throw new IllegalArgumentException("circular definitions"); - } + throw new IllegalArgumentException("circular definitions"); if (r1) - { - return 1; - } + return 1; if (r2) - { - return -1; - } + return -1; } return 0; } public String toString() { - StringBuffer buf = new StringBuffer(getClass().getName()); - buf.append('['); - buf.append("name="); - buf.append(name); - if (select != null) - { - buf.append(",select="); - buf.append(select); - } - buf.append(",type="); + StringBuffer buf = new StringBuffer(); switch (type) { case Bindings.VARIABLE: @@ -190,6 +161,14 @@ final class ParameterNode 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(); } diff --git a/libjava/classpath/gnu/xml/transform/ProcessingInstructionNode.java b/libjava/classpath/gnu/xml/transform/ProcessingInstructionNode.java index d75f693..bf61fc0 100644 --- a/libjava/classpath/gnu/xml/transform/ProcessingInstructionNode.java +++ b/libjava/classpath/gnu/xml/transform/ProcessingInstructionNode.java @@ -1,5 +1,5 @@ /* ProcessingInstructionNode.java -- - Copyright (C) 2004 Free Software Foundation, Inc. + Copyright (C) 2004,2006 Free Software Foundation, Inc. This file is part of GNU Classpath. @@ -66,19 +66,15 @@ final class ProcessingInstructionNode { TemplateNode ret = new ProcessingInstructionNode(name); if (children != null) - { - ret.children = children.clone(stylesheet); - } + ret.children = children.clone(stylesheet); if (next != null) - { - ret.next = next.clone(stylesheet); - } + ret.next = next.clone(stylesheet); return ret; } void doApply(Stylesheet stylesheet, QName mode, - Node context, int pos, int len, - Node parent, Node nextSibling) + Node context, int pos, int len, + Node parent, Node nextSibling) throws TransformerException { String data = null; @@ -98,24 +94,18 @@ final class ProcessingInstructionNode ProcessingInstruction pi = doc.createProcessingInstruction(name, data); // Insert into result tree if (nextSibling != null) - { - parent.insertBefore(pi, nextSibling); - } + parent.insertBefore(pi, nextSibling); else - { - parent.appendChild(pi); - } + parent.appendChild(pi); if (next != null) - { - next.apply(stylesheet, mode, - context, pos, len, - parent, nextSibling); - } + next.apply(stylesheet, mode, + context, pos, len, + parent, nextSibling); } public String toString() { - StringBuffer buf = new StringBuffer(getClass().getName()); + StringBuffer buf = new StringBuffer("processing-instruction"); buf.append('['); buf.append("name="); buf.append(name); diff --git a/libjava/classpath/gnu/xml/transform/Stylesheet.java b/libjava/classpath/gnu/xml/transform/Stylesheet.java index 51accaa..73b2296 100644 --- a/libjava/classpath/gnu/xml/transform/Stylesheet.java +++ b/libjava/classpath/gnu/xml/transform/Stylesheet.java @@ -408,7 +408,7 @@ class Stylesheet { if (debug) System.err.println("getTemplate: mode="+mode+" context="+context); - Set candidates = new TreeSet(); + Template selected = null; for (Iterator j = templates.iterator(); j.hasNext(); ) { Template t = (Template) j.next(); @@ -426,10 +426,21 @@ class Stylesheet } //System.err.println("\t"+context+" "+t+"="+isMatch); if (isMatch) - candidates.add(t); + { + // 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; + } + } } - //System.err.println("\tcandidates="+candidates); - if (candidates.isEmpty()) + if (selected == null) { // Apply built-in template // Current template is unchanged @@ -451,32 +462,39 @@ class Stylesheet return null; } } - else - { - Template t = (Template) candidates.iterator().next(); - // Set current template - currentTemplate = t; - if (debug) - System.err.println("\ttemplate="+t+" context="+context); - return t.node; - } + // 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 { - Set candidates = new TreeSet(); + Template selected = null; for (Iterator j = templates.iterator(); j.hasNext(); ) { Template t = (Template) j.next(); boolean isMatch = t.matches(name); if (isMatch) - candidates.add(t); + { + // 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 (candidates.isEmpty()) + if (selected == null) return null; - Template t = (Template) candidates.iterator().next(); - return t.node; + return selected.node; } /** @@ -504,11 +522,9 @@ class Stylesheet String p = getAttribute(attrs, "priority"); String mm = getAttribute(attrs, "mode"); QName mode = (mm == null) ? null : getQName(mm); - double priority = (p == null) ? Template.DEFAULT_PRIORITY : - Double.parseDouble(p); Node children = node.getFirstChild(); return new Template(this, name, match, parse(children), - precedence, priority, mode); + precedence, p, mode); } /** @@ -799,7 +815,7 @@ class Stylesheet templates.add(new Template(this, null, new Root(), parse(rootClone), precedence, - Template.DEFAULT_PRIORITY, + null, null)); } else diff --git a/libjava/classpath/gnu/xml/transform/Template.java b/libjava/classpath/gnu/xml/transform/Template.java index e3c172f..1414dac 100644 --- a/libjava/classpath/gnu/xml/transform/Template.java +++ b/libjava/classpath/gnu/xml/transform/Template.java @@ -1,5 +1,5 @@ /* Template.java -- - Copyright (C) 2004 Free Software Foundation, Inc. + Copyright (C) 2004,2006 Free Software Foundation, Inc. This file is part of GNU Classpath. @@ -66,51 +66,77 @@ class Template 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, double priority, QName mode) + int precedence, String priorityAttr, QName mode) { this.stylesheet = stylesheet; this.name = name; this.match = match; this.node = node; - // adjust priority if necessary - // see XSLT section 5.5 - Test test = getNodeTest(match); - if (test != null) + this.precedence = precedence; + this.mode = mode; + + double p = DEFAULT_PRIORITY; + boolean a = false; + if (priorityAttr != null) + p = Double.parseDouble(priorityAttr); + else { - if (test instanceof NameTest) + // adjust priority if necessary + // see XSLT section 5.5 + if (match instanceof Selector) { - NameTest nameTest = (NameTest) test; - if (nameTest.matchesAny() || - nameTest.matchesAnyLocalName()) - { - priority = -0.25d; - } - else + Selector selector = (Selector) match; + Test[] tests = selector.getTests(); + if (tests.length > 0) { - priority = 0.0d; - } - } - else - { - NodeTypeTest nodeTypeTest = (NodeTypeTest) test; - if (nodeTypeTest.getNodeType() == - Node.PROCESSING_INSTRUCTION_NODE && - nodeTypeTest.getData() != null) - { - priority = 0.0d; - } - else - { - priority = -0.5d; + 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) @@ -124,7 +150,8 @@ class Template (node == null) ? null : node.clone(stylesheet), precedence, priority, - mode); + mode, + isAnyNode); } public int compareTo(Object other) @@ -134,29 +161,16 @@ class Template Template t = (Template) other; int d = t.precedence - precedence; if (d != 0) - { - return d; - } + return d; double d2 = t.priority - priority; if (d2 != 0.0d) - { - return (int) Math.round(d2 * 1000.0d); - } + return (int) Math.round(d2 * 1000.0d); } return 0; } Test getNodeTest(Expr expr) { - if (expr instanceof Selector) - { - Selector selector = (Selector) expr; - Test[] tests = selector.getTests(); - if (tests.length > 0) - { - return tests[0]; - } - } return null; } @@ -164,13 +178,11 @@ class Template { if ((mode == null && this.mode != null) || (mode != null && !mode.equals(this.mode))) - { - return false; - } + return false; if (match == null) - { - return false; - } + return false; + if (isAnyNode && node.getNodeType() == Node.DOCUMENT_NODE) + return false; // don't match document node return match.matches(node); } @@ -186,9 +198,7 @@ class Template ctx = ctx.parent) { if (ctx == stylesheet) - { - return true; - } + return true; } return false; } @@ -206,13 +216,12 @@ class Template Node parent, Node nextSibling) throws TransformerException { - System.err.println("...applying " + toString() + " to " + context); + if (stylesheet.debug) + System.err.println("...applying " + toString() + " to " + context); if (node != null) - { - node.apply(stylesheet, mode, - context, pos, len, - parent, nextSibling); - } + node.apply(stylesheet, mode, + context, pos, len, + parent, nextSibling); } public String toString() @@ -244,9 +253,7 @@ class Template { out.println(toString()); if (node != null) - { - node.list(1, out, true); - } + node.list(1, out, true); } } diff --git a/libjava/classpath/gnu/xml/transform/TemplateNode.java b/libjava/classpath/gnu/xml/transform/TemplateNode.java index 36b25cf..6ff727c 100644 --- a/libjava/classpath/gnu/xml/transform/TemplateNode.java +++ b/libjava/classpath/gnu/xml/transform/TemplateNode.java @@ -64,9 +64,7 @@ abstract class TemplateNode throws TransformerException { if (stylesheet.terminated) - { - return; - } + return; if (Thread.currentThread().isInterrupted()) { // Try to head off any infinite loops at the pass @@ -91,13 +89,9 @@ abstract class TemplateNode public boolean references(QName var) { if (children != null && children.references(var)) - { - return true; - } + return true; if (next != null && next.references(var)) - { - return true; - } + return true; return false; } @@ -107,18 +101,30 @@ abstract class TemplateNode void list(int depth, PrintStream out, boolean listNext) { for (int i = 0; i < depth; i++) - { - out.print(" "); - } + out.print(" "); out.println(toString()); if (children != null) - { - children.list(depth + 1, out, true); - } + 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) { - next.list(depth, out, listNext); + if (ctx instanceof ParameterNode) + { + ParameterNode param = (ParameterNode) ctx; + if (param.type == Bindings.PARAM && param.name.equals(name)) + return true; + } } + return false; } } diff --git a/libjava/classpath/gnu/xml/transform/TextNode.java b/libjava/classpath/gnu/xml/transform/TextNode.java index 1b581e5..39423b2 100644 --- a/libjava/classpath/gnu/xml/transform/TextNode.java +++ b/libjava/classpath/gnu/xml/transform/TextNode.java @@ -1,5 +1,5 @@ /* TextNode.java -- - Copyright (C) 2004 Free Software Foundation, Inc. + Copyright (C) 2004,2006 Free Software Foundation, Inc. This file is part of GNU Classpath. @@ -65,19 +65,15 @@ final class TextNode { TemplateNode ret = new TextNode(disableOutputEscaping); if (children != null) - { - ret.children = children.clone(stylesheet); - } + ret.children = children.clone(stylesheet); if (next != null) - { - ret.next = next.clone(stylesheet); - } + ret.next = next.clone(stylesheet); return ret; } void doApply(Stylesheet stylesheet, QName mode, - Node context, int pos, int len, - Node parent, Node nextSibling) + Node context, int pos, int len, + Node parent, Node nextSibling) throws TransformerException { String value = ""; @@ -96,24 +92,28 @@ final class TextNode } Text text = doc.createTextNode(value); if (disableOutputEscaping) - { - text.setUserData("disable-output-escaping", "yes", stylesheet); - } + text.setUserData("disable-output-escaping", "yes", stylesheet); // Insert into result tree if (nextSibling != null) - { - parent.insertBefore(text, nextSibling); - } + parent.insertBefore(text, nextSibling); else - { - parent.appendChild(text); - } + 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) { - next.apply(stylesheet, mode, - context, pos, len, - parent, nextSibling); + buf.append('['); + buf.append("disable-output-escaping"); + buf.append(']'); } + return buf.toString(); } } diff --git a/libjava/classpath/gnu/xml/transform/TransformerImpl.java b/libjava/classpath/gnu/xml/transform/TransformerImpl.java index b7ff668..2c57e97 100644 --- a/libjava/classpath/gnu/xml/transform/TransformerImpl.java +++ b/libjava/classpath/gnu/xml/transform/TransformerImpl.java @@ -162,7 +162,7 @@ class TransformerImpl } // Make a copy of the source node, and strip it context = context.cloneNode(true); - strip(context); + strip(stylesheet, context); // XSLT transformation try { @@ -321,7 +321,7 @@ class TransformerImpl if (indent) { parent.normalize(); - strip(parent); + strip(stylesheet, parent); Document resultDoc = (parent instanceof Document) ? (Document) parent : parent.getOwnerDocument(); @@ -393,7 +393,7 @@ class TransformerImpl /** * Strip whitespace from the source tree. */ - boolean strip(Node node) + static boolean strip(Stylesheet stylesheet, Node node) throws TransformerConfigurationException { short nt = node.getNodeType(); @@ -444,7 +444,7 @@ class TransformerImpl Node child = node.getFirstChild(); while (child != null) { - boolean remove = strip(child); + boolean remove = strip(stylesheet, child); Node next = child.getNextSibling(); if (remove) node.removeChild(child); @@ -691,7 +691,7 @@ class TransformerImpl for (Iterator i = children.iterator(); i.hasNext(); ) { ctx = (Node) i.next(); - reindent(doc, ctx, offset + 1); + reindent(doc, ctx, offset); } } else @@ -709,9 +709,9 @@ class TransformerImpl } buf = new StringBuffer(); buf.append('\n'); - ws = buf.toString(); for (int i = 0; i < offset; i++) buf.append(INDENT_WHITESPACE); + ws = buf.toString(); node.appendChild(doc.createTextNode(ws)); } } diff --git a/libjava/classpath/gnu/xml/transform/ValueOfNode.java b/libjava/classpath/gnu/xml/transform/ValueOfNode.java index 24c229e..68f31e0 100644 --- a/libjava/classpath/gnu/xml/transform/ValueOfNode.java +++ b/libjava/classpath/gnu/xml/transform/ValueOfNode.java @@ -126,7 +126,7 @@ final class ValueOfNode public String toString() { - StringBuffer buf = new StringBuffer(getClass().getName()); + StringBuffer buf = new StringBuffer("value-of"); buf.append('['); buf.append("select="); buf.append(select); diff --git a/libjava/classpath/gnu/xml/transform/WhenNode.java b/libjava/classpath/gnu/xml/transform/WhenNode.java index 231f269..fe3f403 100644 --- a/libjava/classpath/gnu/xml/transform/WhenNode.java +++ b/libjava/classpath/gnu/xml/transform/WhenNode.java @@ -1,5 +1,5 @@ /* WhenNode.java -- - Copyright (C) 2004 Free Software Foundation, Inc. + Copyright (C) 2004,2006 Free Software Foundation, Inc. This file is part of GNU Classpath. @@ -62,19 +62,15 @@ final class WhenNode { TemplateNode ret = new WhenNode(test.clone(stylesheet)); if (children != null) - { - ret.children = children.clone(stylesheet); - } + ret.children = children.clone(stylesheet); if (next != null) - { - ret.next = next.clone(stylesheet); - } + ret.next = next.clone(stylesheet); return ret; } void doApply(Stylesheet stylesheet, QName mode, - Node context, int pos, int len, - Node parent, Node nextSibling) + Node context, int pos, int len, + Node parent, Node nextSibling) throws TransformerException { Object ret = test.evaluate(context, pos, len); @@ -84,35 +80,29 @@ final class WhenNode if (success) { if (children != null) - { - children.apply(stylesheet, mode, - context, pos, len, - parent, nextSibling); - } + children.apply(stylesheet, mode, + context, pos, len, + parent, nextSibling); } else { if (next != null) - { - next.apply(stylesheet, mode, - context, pos, len, - parent, nextSibling); - } + next.apply(stylesheet, mode, + context, pos, len, + parent, nextSibling); } } public boolean references(QName var) { if (test != null && test.references(var)) - { - return true; - } + return true; return super.references(var); } public String toString() { - StringBuffer buf = new StringBuffer(getClass().getName()); + StringBuffer buf = new StringBuffer("when"); buf.append('['); buf.append("test="); buf.append(test); diff --git a/libjava/classpath/gnu/xml/util/XHTMLWriter.java b/libjava/classpath/gnu/xml/util/XHTMLWriter.java index 272c66c..02a0afc 100644 --- a/libjava/classpath/gnu/xml/util/XHTMLWriter.java +++ b/libjava/classpath/gnu/xml/util/XHTMLWriter.java @@ -55,6 +55,8 @@ import java.io.Writer; * data loss. * * @author David Brownell + * + * @deprecated Please use the javax.xml.stream APIs instead */ public class XHTMLWriter extends XMLWriter { diff --git a/libjava/classpath/gnu/xml/util/XMLWriter.java b/libjava/classpath/gnu/xml/util/XMLWriter.java index fd36b71..24b3892 100644 --- a/libjava/classpath/gnu/xml/util/XMLWriter.java +++ b/libjava/classpath/gnu/xml/util/XMLWriter.java @@ -102,6 +102,8 @@ import org.xml.sax.helpers.*; * @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 diff --git a/libjava/classpath/gnu/xml/validation/datatype/Annotation.java b/libjava/classpath/gnu/xml/validation/datatype/Annotation.java new file mode 100644 index 0000000..cba6954 --- /dev/null +++ b/libjava/classpath/gnu/xml/validation/datatype/Annotation.java @@ -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@gnu.org'>Chris Burdess</a> + */ +public class Annotation +{ + + public final String documentation; + + public Annotation(String documentation) + { + this.documentation = documentation; + } + + public String toString() + { + return documentation; + } + +} + diff --git a/libjava/classpath/gnu/xml/validation/datatype/AnySimpleType.java b/libjava/classpath/gnu/xml/validation/datatype/AnySimpleType.java new file mode 100644 index 0000000..63441c7 --- /dev/null +++ b/libjava/classpath/gnu/xml/validation/datatype/AnySimpleType.java @@ -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); + } + +} + diff --git a/libjava/classpath/gnu/xml/validation/datatype/AnyType.java b/libjava/classpath/gnu/xml/validation/datatype/AnyType.java new file mode 100644 index 0000000..f26a075 --- /dev/null +++ b/libjava/classpath/gnu/xml/validation/datatype/AnyType.java @@ -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); + } + +} + diff --git a/libjava/classpath/gnu/xml/validation/datatype/AnyURIType.java b/libjava/classpath/gnu/xml/validation/datatype/AnyURIType.java new file mode 100644 index 0000000..56c0a06 --- /dev/null +++ b/libjava/classpath/gnu/xml/validation/datatype/AnyURIType.java @@ -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@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; + } + } + +} + diff --git a/libjava/classpath/gnu/xml/validation/datatype/AtomicSimpleType.java b/libjava/classpath/gnu/xml/validation/datatype/AtomicSimpleType.java new file mode 100644 index 0000000..d685e5c --- /dev/null +++ b/libjava/classpath/gnu/xml/validation/datatype/AtomicSimpleType.java @@ -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@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); + } + +} + diff --git a/libjava/classpath/gnu/xml/validation/datatype/Base64BinaryType.java b/libjava/classpath/gnu/xml/validation/datatype/Base64BinaryType.java new file mode 100644 index 0000000..5a72a28 --- /dev/null +++ b/libjava/classpath/gnu/xml/validation/datatype/Base64BinaryType.java @@ -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@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"); + } + } + +} + diff --git a/libjava/classpath/gnu/xml/validation/datatype/BooleanType.java b/libjava/classpath/gnu/xml/validation/datatype/BooleanType.java new file mode 100644 index 0000000..5a2d9ec --- /dev/null +++ b/libjava/classpath/gnu/xml/validation/datatype/BooleanType.java @@ -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@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; + } + +} + diff --git a/libjava/classpath/gnu/xml/validation/datatype/ByteType.java b/libjava/classpath/gnu/xml/validation/datatype/ByteType.java new file mode 100644 index 0000000..539dba2 --- /dev/null +++ b/libjava/classpath/gnu/xml/validation/datatype/ByteType.java @@ -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@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; + } + } + +} + diff --git a/libjava/classpath/gnu/xml/validation/datatype/DateTimeType.java b/libjava/classpath/gnu/xml/validation/datatype/DateTimeType.java new file mode 100644 index 0000000..749ba81 --- /dev/null +++ b/libjava/classpath/gnu/xml/validation/datatype/DateTimeType.java @@ -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@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; + } + } + +} + diff --git a/libjava/classpath/gnu/xml/validation/datatype/DateType.java b/libjava/classpath/gnu/xml/validation/datatype/DateType.java new file mode 100644 index 0000000..6a4e1d7 --- /dev/null +++ b/libjava/classpath/gnu/xml/validation/datatype/DateType.java @@ -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@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; + } + } + +} + diff --git a/libjava/classpath/gnu/xml/validation/datatype/DecimalType.java b/libjava/classpath/gnu/xml/validation/datatype/DecimalType.java new file mode 100644 index 0000000..08fe330 --- /dev/null +++ b/libjava/classpath/gnu/xml/validation/datatype/DecimalType.java @@ -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@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; + } + } + +} + diff --git a/libjava/classpath/gnu/xml/validation/datatype/DoubleType.java b/libjava/classpath/gnu/xml/validation/datatype/DoubleType.java new file mode 100644 index 0000000..e25d060 --- /dev/null +++ b/libjava/classpath/gnu/xml/validation/datatype/DoubleType.java @@ -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@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; + } + } + +} + diff --git a/libjava/classpath/gnu/xml/validation/datatype/DurationType.java b/libjava/classpath/gnu/xml/validation/datatype/DurationType.java new file mode 100644 index 0000000..2cb92ba --- /dev/null +++ b/libjava/classpath/gnu/xml/validation/datatype/DurationType.java @@ -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@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; + } + +} + diff --git a/libjava/classpath/gnu/xml/validation/datatype/EntitiesType.java b/libjava/classpath/gnu/xml/validation/datatype/EntitiesType.java new file mode 100644 index 0000000..98554e1 --- /dev/null +++ b/libjava/classpath/gnu/xml/validation/datatype/EntitiesType.java @@ -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@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; + } + +} + diff --git a/libjava/classpath/gnu/xml/validation/datatype/EntityType.java b/libjava/classpath/gnu/xml/validation/datatype/EntityType.java new file mode 100644 index 0000000..f1443bc --- /dev/null +++ b/libjava/classpath/gnu/xml/validation/datatype/EntityType.java @@ -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@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; + } + +} + diff --git a/libjava/classpath/gnu/xml/validation/datatype/EnumerationFacet.java b/libjava/classpath/gnu/xml/validation/datatype/EnumerationFacet.java new file mode 100644 index 0000000..0ad3d3f --- /dev/null +++ b/libjava/classpath/gnu/xml/validation/datatype/EnumerationFacet.java @@ -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@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)); + } + +} + diff --git a/libjava/classpath/gnu/xml/validation/datatype/Facet.java b/libjava/classpath/gnu/xml/validation/datatype/Facet.java new file mode 100644 index 0000000..490abf8 --- /dev/null +++ b/libjava/classpath/gnu/xml/validation/datatype/Facet.java @@ -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@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; + } + +} + diff --git a/libjava/classpath/gnu/xml/validation/datatype/FloatType.java b/libjava/classpath/gnu/xml/validation/datatype/FloatType.java new file mode 100644 index 0000000..a81a56c --- /dev/null +++ b/libjava/classpath/gnu/xml/validation/datatype/FloatType.java @@ -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@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; + } + } + +} + diff --git a/libjava/classpath/gnu/xml/validation/datatype/FractionDigitsFacet.java b/libjava/classpath/gnu/xml/validation/datatype/FractionDigitsFacet.java new file mode 100644 index 0000000..efd9862 --- /dev/null +++ b/libjava/classpath/gnu/xml/validation/datatype/FractionDigitsFacet.java @@ -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@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); + } + +} + diff --git a/libjava/classpath/gnu/xml/validation/datatype/GDayType.java b/libjava/classpath/gnu/xml/validation/datatype/GDayType.java new file mode 100644 index 0000000..009af35 --- /dev/null +++ b/libjava/classpath/gnu/xml/validation/datatype/GDayType.java @@ -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@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; + } + } + +} + diff --git a/libjava/classpath/gnu/xml/validation/datatype/GMonthDayType.java b/libjava/classpath/gnu/xml/validation/datatype/GMonthDayType.java new file mode 100644 index 0000000..a39a1cc --- /dev/null +++ b/libjava/classpath/gnu/xml/validation/datatype/GMonthDayType.java @@ -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@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; + } + } + +} + diff --git a/libjava/classpath/gnu/xml/validation/datatype/GMonthType.java b/libjava/classpath/gnu/xml/validation/datatype/GMonthType.java new file mode 100644 index 0000000..5a08af2 --- /dev/null +++ b/libjava/classpath/gnu/xml/validation/datatype/GMonthType.java @@ -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@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; + } + } + +} + diff --git a/libjava/classpath/gnu/xml/validation/datatype/GYearMonthType.java b/libjava/classpath/gnu/xml/validation/datatype/GYearMonthType.java new file mode 100644 index 0000000..9ec38c0 --- /dev/null +++ b/libjava/classpath/gnu/xml/validation/datatype/GYearMonthType.java @@ -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@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; + } + } + +} + diff --git a/libjava/classpath/gnu/xml/validation/datatype/GYearType.java b/libjava/classpath/gnu/xml/validation/datatype/GYearType.java new file mode 100644 index 0000000..6dea89b --- /dev/null +++ b/libjava/classpath/gnu/xml/validation/datatype/GYearType.java @@ -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@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; + } + } + +} + diff --git a/libjava/classpath/gnu/xml/validation/datatype/HexBinaryType.java b/libjava/classpath/gnu/xml/validation/datatype/HexBinaryType.java new file mode 100644 index 0000000..686e09d --- /dev/null +++ b/libjava/classpath/gnu/xml/validation/datatype/HexBinaryType.java @@ -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@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"); + } + } + +} + diff --git a/libjava/classpath/gnu/xml/validation/datatype/IDRefType.java b/libjava/classpath/gnu/xml/validation/datatype/IDRefType.java new file mode 100644 index 0000000..8ea9805 --- /dev/null +++ b/libjava/classpath/gnu/xml/validation/datatype/IDRefType.java @@ -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@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; + } + +} + diff --git a/libjava/classpath/gnu/xml/validation/datatype/IDRefsType.java b/libjava/classpath/gnu/xml/validation/datatype/IDRefsType.java new file mode 100644 index 0000000..57f7e56 --- /dev/null +++ b/libjava/classpath/gnu/xml/validation/datatype/IDRefsType.java @@ -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@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; + } + +} + diff --git a/libjava/classpath/gnu/xml/validation/datatype/IDType.java b/libjava/classpath/gnu/xml/validation/datatype/IDType.java new file mode 100644 index 0000000..c55601a --- /dev/null +++ b/libjava/classpath/gnu/xml/validation/datatype/IDType.java @@ -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@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; + } + +} + diff --git a/libjava/classpath/gnu/xml/validation/datatype/IntType.java b/libjava/classpath/gnu/xml/validation/datatype/IntType.java new file mode 100644 index 0000000..6bf7866 --- /dev/null +++ b/libjava/classpath/gnu/xml/validation/datatype/IntType.java @@ -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@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; + } + } + +} + diff --git a/libjava/classpath/gnu/xml/validation/datatype/IntegerType.java b/libjava/classpath/gnu/xml/validation/datatype/IntegerType.java new file mode 100644 index 0000000..2098a7d --- /dev/null +++ b/libjava/classpath/gnu/xml/validation/datatype/IntegerType.java @@ -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@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; + } + } + +} + diff --git a/libjava/classpath/gnu/xml/validation/datatype/LanguageType.java b/libjava/classpath/gnu/xml/validation/datatype/LanguageType.java new file mode 100644 index 0000000..3df903c --- /dev/null +++ b/libjava/classpath/gnu/xml/validation/datatype/LanguageType.java @@ -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@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"); + } + +} + diff --git a/libjava/classpath/gnu/xml/validation/datatype/LengthFacet.java b/libjava/classpath/gnu/xml/validation/datatype/LengthFacet.java new file mode 100644 index 0000000..cab4496 --- /dev/null +++ b/libjava/classpath/gnu/xml/validation/datatype/LengthFacet.java @@ -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@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); + } + +} + diff --git a/libjava/classpath/gnu/xml/validation/datatype/ListSimpleType.java b/libjava/classpath/gnu/xml/validation/datatype/ListSimpleType.java new file mode 100644 index 0000000..1f0cb76 --- /dev/null +++ b/libjava/classpath/gnu/xml/validation/datatype/ListSimpleType.java @@ -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@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); + } + } + +} + diff --git a/libjava/classpath/gnu/xml/validation/datatype/LongType.java b/libjava/classpath/gnu/xml/validation/datatype/LongType.java new file mode 100644 index 0000000..eaf69df --- /dev/null +++ b/libjava/classpath/gnu/xml/validation/datatype/LongType.java @@ -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@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; + } + } + +} + diff --git a/libjava/classpath/gnu/xml/validation/datatype/MaxExclusiveFacet.java b/libjava/classpath/gnu/xml/validation/datatype/MaxExclusiveFacet.java new file mode 100644 index 0000000..7aac1f7 --- /dev/null +++ b/libjava/classpath/gnu/xml/validation/datatype/MaxExclusiveFacet.java @@ -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@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(); + } + +} + diff --git a/libjava/classpath/gnu/xml/validation/datatype/MaxInclusiveFacet.java b/libjava/classpath/gnu/xml/validation/datatype/MaxInclusiveFacet.java new file mode 100644 index 0000000..bb145ed --- /dev/null +++ b/libjava/classpath/gnu/xml/validation/datatype/MaxInclusiveFacet.java @@ -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@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(); + } + +} + diff --git a/libjava/classpath/gnu/xml/stream/LocationImpl.java b/libjava/classpath/gnu/xml/validation/datatype/MaxLengthFacet.java index 1900aeb..d033263 100644 --- a/libjava/classpath/gnu/xml/stream/LocationImpl.java +++ b/libjava/classpath/gnu/xml/validation/datatype/MaxLengthFacet.java @@ -1,5 +1,5 @@ -/* LocationImpl.java -- - Copyright (C) 2005 Free Software Foundation, Inc. +/* MaxLengthFacet.java -- + Copyright (C) 2006 Free Software Foundation, Inc. This file is part of GNU Classpath. @@ -35,54 +35,37 @@ 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 javax.xml.stream.Location; +package gnu.xml.validation.datatype; /** - * Information about the location of an XML event within the underlying - * stream. + * The <code>maxLength</code> facet. * * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> */ -public class LocationImpl - implements Location +public final class MaxLengthFacet + extends Facet { - protected final int offset; - - protected final int col; - - protected final int line; + public final int value; - protected final String systemId; - - protected LocationImpl(int offset, int col, int line, String systemId) - { - this.offset = offset; - this.col = col; - this.line = line; - this.systemId = systemId; - } - - public int getLineNumber() - { - return line; - } + public final boolean fixed; - public int getColumnNumber() + public MaxLengthFacet(int value, boolean fixed, Annotation annotation) { - return col; + super(MAX_LENGTH, annotation); + this.value = value; + this.fixed = fixed; } - public int getCharacterOffset() + public int hashCode() { - return offset; + return value; } - public String getLocationURI() + public boolean equals(Object other) { - return systemId; + return (other instanceof MaxLengthFacet && + ((MaxLengthFacet) other).value == value); } } diff --git a/libjava/classpath/gnu/xml/validation/datatype/MinExclusiveFacet.java b/libjava/classpath/gnu/xml/validation/datatype/MinExclusiveFacet.java new file mode 100644 index 0000000..2289bb1 --- /dev/null +++ b/libjava/classpath/gnu/xml/validation/datatype/MinExclusiveFacet.java @@ -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@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(); + } + +} + diff --git a/libjava/classpath/gnu/xml/validation/datatype/MinInclusiveFacet.java b/libjava/classpath/gnu/xml/validation/datatype/MinInclusiveFacet.java new file mode 100644 index 0000000..6c07c36 --- /dev/null +++ b/libjava/classpath/gnu/xml/validation/datatype/MinInclusiveFacet.java @@ -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@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(); + } + +} + diff --git a/libjava/classpath/gnu/xml/validation/datatype/MinLengthFacet.java b/libjava/classpath/gnu/xml/validation/datatype/MinLengthFacet.java new file mode 100644 index 0000000..c7dee20 --- /dev/null +++ b/libjava/classpath/gnu/xml/validation/datatype/MinLengthFacet.java @@ -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@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); + } + +} + diff --git a/libjava/classpath/gnu/xml/validation/datatype/NCNameType.java b/libjava/classpath/gnu/xml/validation/datatype/NCNameType.java new file mode 100644 index 0000000..4188d88 --- /dev/null +++ b/libjava/classpath/gnu/xml/validation/datatype/NCNameType.java @@ -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@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; + } + } + +} + diff --git a/libjava/classpath/gnu/xml/validation/datatype/NMTokenType.java b/libjava/classpath/gnu/xml/validation/datatype/NMTokenType.java new file mode 100644 index 0000000..4498fec --- /dev/null +++ b/libjava/classpath/gnu/xml/validation/datatype/NMTokenType.java @@ -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@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; + } + } + +} + diff --git a/libjava/classpath/gnu/xml/validation/datatype/NMTokensType.java b/libjava/classpath/gnu/xml/validation/datatype/NMTokensType.java new file mode 100644 index 0000000..62524ed --- /dev/null +++ b/libjava/classpath/gnu/xml/validation/datatype/NMTokensType.java @@ -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@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; + } + } + + +} + diff --git a/libjava/classpath/gnu/xml/validation/datatype/NameType.java b/libjava/classpath/gnu/xml/validation/datatype/NameType.java new file mode 100644 index 0000000..a2fbb9d --- /dev/null +++ b/libjava/classpath/gnu/xml/validation/datatype/NameType.java @@ -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@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; + } + } + +} + diff --git a/libjava/classpath/gnu/xml/validation/datatype/NegativeIntegerType.java b/libjava/classpath/gnu/xml/validation/datatype/NegativeIntegerType.java new file mode 100644 index 0000000..fd436cb --- /dev/null +++ b/libjava/classpath/gnu/xml/validation/datatype/NegativeIntegerType.java @@ -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@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; + } + } + +} + diff --git a/libjava/classpath/gnu/xml/validation/datatype/NonNegativeIntegerType.java b/libjava/classpath/gnu/xml/validation/datatype/NonNegativeIntegerType.java new file mode 100644 index 0000000..8577785 --- /dev/null +++ b/libjava/classpath/gnu/xml/validation/datatype/NonNegativeIntegerType.java @@ -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@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; + } + } + +} + diff --git a/libjava/classpath/gnu/xml/validation/datatype/NonPositiveIntegerType.java b/libjava/classpath/gnu/xml/validation/datatype/NonPositiveIntegerType.java new file mode 100644 index 0000000..0b43d52 --- /dev/null +++ b/libjava/classpath/gnu/xml/validation/datatype/NonPositiveIntegerType.java @@ -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@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; + } + } + +} + diff --git a/libjava/classpath/gnu/xml/validation/datatype/NormalizedStringType.java b/libjava/classpath/gnu/xml/validation/datatype/NormalizedStringType.java new file mode 100644 index 0000000..a74312d --- /dev/null +++ b/libjava/classpath/gnu/xml/validation/datatype/NormalizedStringType.java @@ -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@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"); + } + } + +} + diff --git a/libjava/classpath/gnu/xml/validation/datatype/NotationType.java b/libjava/classpath/gnu/xml/validation/datatype/NotationType.java new file mode 100644 index 0000000..59c7f25 --- /dev/null +++ b/libjava/classpath/gnu/xml/validation/datatype/NotationType.java @@ -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@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; + } + +} + diff --git a/libjava/classpath/gnu/xml/validation/datatype/PatternFacet.java b/libjava/classpath/gnu/xml/validation/datatype/PatternFacet.java new file mode 100644 index 0000000..d594b26b --- /dev/null +++ b/libjava/classpath/gnu/xml/validation/datatype/PatternFacet.java @@ -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@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)); + } + +} + diff --git a/libjava/classpath/gnu/xml/validation/datatype/PositiveIntegerType.java b/libjava/classpath/gnu/xml/validation/datatype/PositiveIntegerType.java new file mode 100644 index 0000000..0c10df3 --- /dev/null +++ b/libjava/classpath/gnu/xml/validation/datatype/PositiveIntegerType.java @@ -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@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; + } + } + +} + diff --git a/libjava/classpath/gnu/xml/validation/datatype/QNameType.java b/libjava/classpath/gnu/xml/validation/datatype/QNameType.java new file mode 100644 index 0000000..1eaa518 --- /dev/null +++ b/libjava/classpath/gnu/xml/validation/datatype/QNameType.java @@ -0,0 +1,122 @@ +/* QNameType.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 QName type. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +final class QNameType + extends AtomicSimpleType +{ + + static final int[] CONSTRAINING_FACETS = { + Facet.LENGTH, + Facet.MIN_LENGTH, + Facet.MAX_LENGTH, + Facet.PATTERN, + Facet.ENUMERATION, + Facet.WHITESPACE + }; + + QNameType() + { + super(new QName(XMLConstants.W3C_XML_SCHEMA_NS_URI, "QName"), + TypeLibrary.ANY_SIMPLE_TYPE); + } + + public int[] getConstrainingFacets() + { + return CONSTRAINING_FACETS; + } + + public void checkValid(String value, ValidationContext context) + throws DatatypeException + { + super.checkValid(value, context); + int ci = -1; + 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"); + for (int i = 1; i < cp.length; i++) + { + if (cp[i] == ':') + { + if (ci != -1 || (i + 1 == cp.length)) + throw new DatatypeException(i, "invalid NCName value"); + ci = i; + } + 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; + } + if (ci != -1) + { + String prefix = value.substring(0, ci); + if (context.resolveNamespacePrefix(prefix) == null) + throw new DatatypeException("invalid namespace prefix"); + } + } + + public boolean isContextDependent() + { + return true; + } + +} + diff --git a/libjava/classpath/gnu/xml/validation/datatype/ShortType.java b/libjava/classpath/gnu/xml/validation/datatype/ShortType.java new file mode 100644 index 0000000..3179c8d --- /dev/null +++ b/libjava/classpath/gnu/xml/validation/datatype/ShortType.java @@ -0,0 +1,133 @@ +/* ShortType.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 short type. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +final class ShortType + 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 = "32767"; + static final String MIN_VALUE = "32768"; + static final int LENGTH = MAX_VALUE.length(); + + ShortType() + { + super(new QName(XMLConstants.W3C_XML_SCHEMA_NS_URI, "short"), + TypeLibrary.INT); + } + + 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 short 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 short 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 short value"); + } + off++; + continue; + } + throw new DatatypeException(i, "invalid short value"); + } + } + + public Object createValue(String literal, ValidationContext context) { + try + { + return new Short(literal); + } + catch (NumberFormatException e) + { + return null; + } + } + +} + diff --git a/libjava/classpath/gnu/xml/validation/datatype/SimpleType.java b/libjava/classpath/gnu/xml/validation/datatype/SimpleType.java new file mode 100644 index 0000000..6554f2f --- /dev/null +++ b/libjava/classpath/gnu/xml/validation/datatype/SimpleType.java @@ -0,0 +1,257 @@ +/* SimpleType.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.Iterator; +import java.util.Set; +import java.util.regex.Matcher; +import javax.xml.XMLConstants; +import javax.xml.namespace.QName; +import org.relaxng.datatype.Datatype; +import org.relaxng.datatype.DatatypeException; +import org.relaxng.datatype.DatatypeStreamingValidator; +import org.relaxng.datatype.ValidationContext; + +/** + * An XML Schema simple type. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +public class SimpleType + extends Type + implements Datatype +{ + + /** + * The variety of the <code>anySimpleType</code> datatype. + */ + public static final int ANY = 0; + + /** + * The atomic variety. + */ + public static final int ATOMIC = 1; + + /** + * The list variety. + */ + public static final int LIST = 2; + + /** + * The union variety. + */ + public static final int UNION = 3; + + public static final int ID_TYPE_NULL = 0; + public static final int ID_TYPE_ID = 1; + public static final int ID_TYPE_IDREF = 2; + public static final int ID_TYPE_IDREFS = 3; + + /** + * The variety of this simple type. + */ + public final int variety; + + /** + * The facets of this simple type. + */ + public Set facets; + + /** + * The fundamental facets of this simple type. + */ + public int fundamentalFacets; + + /** + * If this datatype has been derived by restriction, then the component + * from which it was derived. + */ + public final SimpleType baseType; + + /** + * Optional annotation. + */ + public final Annotation annotation; + + public SimpleType(QName name, int variety, Set facets, + int fundamentalFacets, SimpleType baseType, + Annotation annotation) + { + super(name); + this.variety = variety; + this.facets = facets; + this.fundamentalFacets = fundamentalFacets; + this.baseType = baseType; + this.annotation = annotation; + } + + /** + * Indicates whether this type permits the specified value. + */ + public boolean isValid(String value, ValidationContext context) + { + try + { + checkValid(value, context); + return true; + } + catch (DatatypeException e) + { + return false; + } + } + + public void checkValid(String value, ValidationContext context) + throws DatatypeException + { + if (facets != null && !facets.isEmpty()) + { + Object parsedValue = createValue(value, context); + for (Iterator i = facets.iterator(); i.hasNext(); ) + { + Facet facet = (Facet) i.next(); + switch (facet.type) + { + case Facet.LENGTH: + LengthFacet lf = (LengthFacet) facet; + if (value.length() != lf.value) + throw new DatatypeException("invalid length"); + break; + case Facet.MIN_LENGTH: + MinLengthFacet nlf = (MinLengthFacet) facet; + if (value.length() < nlf.value) + throw new DatatypeException("invalid minimum length"); + break; + case Facet.MAX_LENGTH: + MaxLengthFacet xlf = (MaxLengthFacet) facet; + if (value.length() > xlf.value) + throw new DatatypeException("invalid maximum length"); + break; + case Facet.PATTERN: + PatternFacet pf = (PatternFacet) facet; + Matcher matcher = pf.value.matcher(value); + if (!matcher.find()) + throw new DatatypeException("invalid match for pattern"); + break; + case Facet.ENUMERATION: + // TODO + break; + case Facet.WHITESPACE: + // TODO + break; + case Facet.MAX_INCLUSIVE: + MaxInclusiveFacet xif = (MaxInclusiveFacet) facet; + if (!xif.matches(parsedValue)) + throw new DatatypeException("beyond upper bound"); + break; + case Facet.MAX_EXCLUSIVE: + MaxExclusiveFacet xef = (MaxExclusiveFacet) facet; + if (!xef.matches(parsedValue)) + throw new DatatypeException("beyond upper bound"); + break; + case Facet.MIN_EXCLUSIVE: + MinExclusiveFacet nef = (MinExclusiveFacet) facet; + if (!nef.matches(parsedValue)) + throw new DatatypeException("beyond lower bound"); + break; + case Facet.MIN_INCLUSIVE: + MinInclusiveFacet nif = (MinInclusiveFacet) facet; + if (!nif.matches(parsedValue)) + throw new DatatypeException("beyond lower bound"); + break; + case Facet.TOTAL_DIGITS: + TotalDigitsFacet tdf = (TotalDigitsFacet) facet; + if (countDigits(value, true) > tdf.value) + throw new DatatypeException("too many digits"); + break; + case Facet.FRACTION_DIGITS: + FractionDigitsFacet fdf = (FractionDigitsFacet) facet; + if (countDigits(value, false) > fdf.value) + throw new DatatypeException("too many fraction digits"); + break; + } + } + } + } + + private static int countDigits(String value, boolean any) + { + int count = 0; + int len = value.length(); + boolean seenDecimal = false; + for (int i = 0; i < len; i++) + { + char c = value.charAt(i); + if (c == 0x2e) + seenDecimal = true; + else if (c >= 0x30 && c <= 0x39 && (any || seenDecimal)) + count++; + } + return count; + } + + // TODO createStreamingValidator + public DatatypeStreamingValidator createStreamingValidator(ValidationContext context) + { + throw new UnsupportedOperationException(); + } + + public Object createValue(String literal, ValidationContext context) { + return literal; + } + + public boolean sameValue(Object value1, Object value2) { + return value1.equals(value2); + } + + public int valueHashCode(Object value) { + return value.hashCode(); + } + + public int getIdType() + { + return ID_TYPE_NULL; + } + + public boolean isContextDependent() + { + return false; + } + +} + diff --git a/libjava/classpath/gnu/xml/validation/datatype/StringType.java b/libjava/classpath/gnu/xml/validation/datatype/StringType.java new file mode 100644 index 0000000..a2235f2 --- /dev/null +++ b/libjava/classpath/gnu/xml/validation/datatype/StringType.java @@ -0,0 +1,77 @@ +/* StringType.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 string type. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +final class StringType + extends AtomicSimpleType +{ + + static final int[] CONSTRAINING_FACETS = { + Facet.LENGTH, + Facet.MIN_LENGTH, + Facet.MAX_LENGTH, + Facet.PATTERN, + Facet.ENUMERATION, + Facet.WHITESPACE + }; + + StringType() + { + super(new QName(XMLConstants.W3C_XML_SCHEMA_NS_URI, "string"), + TypeLibrary.ANY_SIMPLE_TYPE); + } + + public int[] getConstrainingFacets() + { + return CONSTRAINING_FACETS; + } + +} + diff --git a/libjava/classpath/gnu/xml/validation/datatype/TimeType.java b/libjava/classpath/gnu/xml/validation/datatype/TimeType.java new file mode 100644 index 0000000..0152e11 --- /dev/null +++ b/libjava/classpath/gnu/xml/validation/datatype/TimeType.java @@ -0,0 +1,303 @@ +/* TimeType.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.TimeZone; +import javax.xml.XMLConstants; +import javax.xml.namespace.QName; +import org.relaxng.datatype.DatatypeException; +import org.relaxng.datatype.ValidationContext; + +/** + * The XML Schema time type. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +final class TimeType + extends AtomicSimpleType +{ + + static class Time + implements Comparable + { + int minutes; + float seconds; + + public int hashCode() + { + return minutes * 31 + new Float(seconds).hashCode(); + } + + public boolean equals(Object other) + { + if (other instanceof Time) + { + Time time = (Time) other; + return time.minutes == minutes && time.seconds == seconds; + } + return false; + } + + public int compareTo(Object other) + { + if (other instanceof Time) + { + Time time = (Time) other; + if (time.minutes != minutes) + return minutes - time.minutes; + if (time.seconds == seconds) + return 0; + return (seconds < time.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 + }; + + TimeType() + { + super(new QName(XMLConstants.W3C_XML_SCHEMA_NS_URI, "time"), + 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 = 3; + int start = 0; + for (int i = 0; i < len; i++) + { + char c = value.charAt(i); + if (c == '-' && state == 0) + { + start++; + continue; + } + if (c >= 0x30 && c <= 0x39) + continue; + switch (state) + { + case 3: // hour + if (c == ':') + { + if (i - start != 2) + throw new DatatypeException(i, "invalid time value"); + state = 4; + start = i + 1; + continue; + } + break; + case 4: // minute + if (c == ':') + { + if (i - start != 2) + throw new DatatypeException(i, "invalid time value"); + state = 5; + start = i + 1; + continue; + } + break; + case 5: // second + if (c == '.') + { + if (i - start != 2) + throw new DatatypeException(i, "invalid time value"); + state = 6; + start = i + 1; + continue; + } + else if (c == ' ') + { + if (i - start != 2) + throw new DatatypeException(i, "invalid time 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 time value"); + state = 8; + start = i + 1; + continue; + } + break; + } + throw new DatatypeException(i, "invalid time value"); + } + switch (state) + { + case 5: // second + if (len - start != 2) + throw new DatatypeException(len, "invalid time value"); + break; + case 6: // second fraction + break; + case 8: // timezone 2 + if (len - start != 2) + throw new DatatypeException(len, "invalid time value"); + break; + case 9: // post Z + break; + default: + throw new DatatypeException(len, "invalid time value"); + } + } + + public Object createValue(String value, ValidationContext context) { + int len = value.length(); + int state = 3; + int start = 0; + Time time = new Time(); + try + { + for (int i = 0; i < len; i++) + { + char c = value.charAt(i); + if (c >= 0x30 && c <= 0x39) + continue; + switch (state) + { + case 3: // hour + if (c == ':') + { + time.minutes = + Integer.parseInt(value.substring(start, i)) * 60; + state = 4; + start = i + 1; + continue; + } + break; + case 4: // minute + if (c == ':') + { + time.minutes += + Integer.parseInt(value.substring(start, i)); + state = 5; + start = i + 1; + continue; + } + break; + case 5: // second + if (c == ' ') + { + time.seconds = + Float.parseFloat(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; + time.minutes += tz.getRawOffset(); + } + else + { + String tzh = timezone.substring(0, i); + String tzm = timezone.substring(i + 1); + int offset = Integer.parseInt(tzh) * 60; + if (offset < 0) + offset -= Integer.parseInt(tzm); + else + offset += Integer.parseInt(tzm); + time.minutes += offset; + } + } + return time; + } + catch (NumberFormatException e) + { + return null; + } + } + +} + diff --git a/libjava/classpath/gnu/xml/validation/datatype/TokenType.java b/libjava/classpath/gnu/xml/validation/datatype/TokenType.java new file mode 100644 index 0000000..18e1e8a --- /dev/null +++ b/libjava/classpath/gnu/xml/validation/datatype/TokenType.java @@ -0,0 +1,96 @@ +/* TokenType.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 token type. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +final class TokenType + extends AtomicSimpleType +{ + + static final int[] CONSTRAINING_FACETS = { + Facet.LENGTH, + Facet.MIN_LENGTH, + Facet.MAX_LENGTH, + Facet.PATTERN, + Facet.ENUMERATION, + Facet.WHITESPACE + }; + + TokenType() + { + super(new QName(XMLConstants.W3C_XML_SCHEMA_NS_URI, "token"), + TypeLibrary.NORMALIZED_STRING); + } + + 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 token value"); + if (value.charAt(0) == ' ' || value.charAt(len - 1) == ' ') + throw new DatatypeException(0, "invalid token value"); + char last = '\u0000'; + for (int i = 0; i < len; i++) + { + char c = value.charAt(i); + if (c == 0x0a || c == 0x0d || c == 0x09) + throw new DatatypeException(i, "invalid token value"); + if (c == ' ' && last == ' ') + throw new DatatypeException(i, "invalid token value"); + last = c; + } + } + +} + diff --git a/libjava/classpath/gnu/xml/validation/datatype/TotalDigitsFacet.java b/libjava/classpath/gnu/xml/validation/datatype/TotalDigitsFacet.java new file mode 100644 index 0000000..4debc63 --- /dev/null +++ b/libjava/classpath/gnu/xml/validation/datatype/TotalDigitsFacet.java @@ -0,0 +1,72 @@ +/* TotalDigitsFacet.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>totalDigits</code> facet. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +public final class TotalDigitsFacet + extends Facet +{ + + public final int value; + + public final boolean fixed; + + public TotalDigitsFacet(int value, boolean fixed, Annotation annotation) + { + super(TOTAL_DIGITS, annotation); + this.value = value; + this.fixed = fixed; + } + + public int hashCode() + { + return value; + } + + public boolean equals(Object other) + { + return (other instanceof TotalDigitsFacet && + ((TotalDigitsFacet) other).value == value); + } + +} + diff --git a/libjava/classpath/gnu/xml/stream/StartEntityImpl.java b/libjava/classpath/gnu/xml/validation/datatype/Type.java index 6e4ca25..e066276 100644 --- a/libjava/classpath/gnu/xml/stream/StartEntityImpl.java +++ b/libjava/classpath/gnu/xml/validation/datatype/Type.java @@ -1,5 +1,5 @@ -/* StartEntityImpl.java -- - Copyright (C) 2005 Free Software Foundation, Inc. +/* Type.java -- + Copyright (C) 2006 Free Software Foundation, Inc. This file is part of GNU Classpath. @@ -35,45 +35,30 @@ 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 javax.xml.stream.Location; -import javax.xml.stream.XMLStreamException; -import javax.xml.stream.events.StartEntity; +package gnu.xml.validation.datatype; +import java.util.HashMap; +import java.util.Map; +import javax.xml.namespace.QName; /** - * A start-entity event. + * Abstract base class for XML Schema datatypes. + * @see http://www.w3.org/TR/xmlschema-2/ * * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> */ -public class StartEntityImpl - extends XMLEventImpl - implements StartEntity +public abstract class Type { - protected final String name; + public static final Type ANY_TYPE = new AnyType(); - protected StartEntityImpl(Location location, String name) - { - super(location); - this.name = name; - } + /** + * The name of this type. + */ + public final QName name; - public int getEventType() - { - return START_ENTITY; - } - - public String getName() - { - return name; - } - - public void writeAsEncodedUnicode(Writer writer) - throws XMLStreamException + public Type(QName name) { + this.name = name; } } diff --git a/libjava/classpath/gnu/xml/validation/datatype/TypeBuilder.java b/libjava/classpath/gnu/xml/validation/datatype/TypeBuilder.java new file mode 100644 index 0000000..606fd0e --- /dev/null +++ b/libjava/classpath/gnu/xml/validation/datatype/TypeBuilder.java @@ -0,0 +1,279 @@ +/* TypeBuilder.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.LinkedHashSet; +import java.util.regex.Pattern; +import javax.xml.namespace.QName; +import org.relaxng.datatype.Datatype; +import org.relaxng.datatype.DatatypeBuilder; +import org.relaxng.datatype.DatatypeException; +import org.relaxng.datatype.ValidationContext; + +/** + * Datatype builder. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +public class TypeBuilder + implements DatatypeBuilder +{ + + final SimpleType type; + + TypeBuilder(SimpleType type) + { + this.type = type; + // TODO fundamental facets + type.facets = new LinkedHashSet(); + } + + public void addParameter(String name, String value, ValidationContext context) + throws DatatypeException + { + // TODO fundamental facets + if ("length".equals(name)) + type.facets.add(parseLengthFacet(value)); + else if ("minLength".equals(name)) + type.facets.add(parseMinLengthFacet(value)); + else if ("maxLength".equals(name)) + type.facets.add(parseMaxLengthFacet(value)); + else if ("pattern".equals(name)) + type.facets.add(parsePatternFacet(value)); + else if ("enumeration".equals(name)) + type.facets.add(parseEnumerationFacet(value)); + else if ("whiteSpace".equals(name)) + type.facets.add(parseWhiteSpaceFacet(value)); + else if ("maxInclusive".equals(name)) + type.facets.add(parseMaxInclusiveFacet(value, context)); + else if ("maxExclusive".equals(name)) + type.facets.add(parseMaxExclusiveFacet(value, context)); + else if ("minExclusive".equals(name)) + type.facets.add(parseMinExclusiveFacet(value, context)); + else if ("minInclusive".equals(name)) + type.facets.add(parseMinInclusiveFacet(value, context)); + else if ("totalDigits".equals(name)) + type.facets.add(parseTotalDigitsFacet(value)); + else if ("fractionDigits".equals(name)) + type.facets.add(parseFractionDigitsFacet(value)); + } + + LengthFacet parseLengthFacet(String value) + throws DatatypeException + { + int si = value.indexOf(' '); + boolean fixed = false; + if (si != -1) + { + if (!"FIXED".equalsIgnoreCase(value.substring(si + 1))) + throw new DatatypeException("second argument must be FIXED if present"); + fixed = true; + value = value.substring(0, si); + } + return new LengthFacet(Integer.parseInt(value), fixed, null); + } + + MinLengthFacet parseMinLengthFacet(String value) + throws DatatypeException + { + int si = value.indexOf(' '); + boolean fixed = false; + if (si != -1) + { + if (!"FIXED".equalsIgnoreCase(value.substring(si + 1))) + throw new DatatypeException("second argument must be FIXED if present"); + fixed = true; + value = value.substring(0, si); + } + return new MinLengthFacet(Integer.parseInt(value), fixed, null); + } + + MaxLengthFacet parseMaxLengthFacet(String value) + throws DatatypeException + { + int si = value.indexOf(' '); + boolean fixed = false; + if (si != -1) + { + if (!"FIXED".equalsIgnoreCase(value.substring(si + 1))) + throw new DatatypeException("second argument must be FIXED if present"); + fixed = true; + value = value.substring(0, si); + } + return new MaxLengthFacet(Integer.parseInt(value), fixed, null); + } + + PatternFacet parsePatternFacet(String value) + throws DatatypeException + { + return new PatternFacet(Pattern.compile(value), null); + } + + EnumerationFacet parseEnumerationFacet(String value) + throws DatatypeException + { + return new EnumerationFacet(value, null); + } + + WhiteSpaceFacet parseWhiteSpaceFacet(String value) + throws DatatypeException + { + int si = value.indexOf(' '); + boolean fixed = false; + if (si != -1) + { + if (!"FIXED".equalsIgnoreCase(value.substring(si + 1))) + throw new DatatypeException("second argument must be FIXED if present"); + fixed = true; + value = value.substring(0, si); + } + if ("preserve".equals(value)) + return new WhiteSpaceFacet(WhiteSpaceFacet.PRESERVE, fixed, null); + if ("replace".equals(value)) + return new WhiteSpaceFacet(WhiteSpaceFacet.REPLACE, fixed, null); + if ("collapse".equals(value)) + return new WhiteSpaceFacet(WhiteSpaceFacet.COLLAPSE, fixed, null); + throw new DatatypeException("argument must be preserve, replace, or collapse"); + } + + MaxInclusiveFacet parseMaxInclusiveFacet(String value, + ValidationContext context) + throws DatatypeException + { + int si = value.indexOf(' '); + boolean fixed = false; + if (si != -1) + { + if (!"FIXED".equalsIgnoreCase(value.substring(si + 1))) + throw new DatatypeException("second argument must be FIXED if present"); + fixed = true; + value = value.substring(0, si); + } + return new MaxInclusiveFacet(type.createValue(value, context), fixed, null); + } + + MaxExclusiveFacet parseMaxExclusiveFacet(String value, + ValidationContext context) + throws DatatypeException + { + int si = value.indexOf(' '); + boolean fixed = false; + if (si != -1) + { + if (!"FIXED".equalsIgnoreCase(value.substring(si + 1))) + throw new DatatypeException("second argument must be FIXED if present"); + fixed = true; + value = value.substring(0, si); + } + return new MaxExclusiveFacet(type.createValue(value, context), fixed, null); + } + + MinExclusiveFacet parseMinExclusiveFacet(String value, + ValidationContext context) + throws DatatypeException + { + int si = value.indexOf(' '); + boolean fixed = false; + if (si != -1) + { + if (!"FIXED".equalsIgnoreCase(value.substring(si + 1))) + throw new DatatypeException("second argument must be FIXED if present"); + fixed = true; + value = value.substring(0, si); + } + return new MinExclusiveFacet(type.createValue(value, context), fixed, null); + } + + MinInclusiveFacet parseMinInclusiveFacet(String value, + ValidationContext context) + throws DatatypeException + { + int si = value.indexOf(' '); + boolean fixed = false; + if (si != -1) + { + if (!"FIXED".equalsIgnoreCase(value.substring(si + 1))) + throw new DatatypeException("second argument must be FIXED if present"); + fixed = true; + value = value.substring(0, si); + } + return new MinInclusiveFacet(type.createValue(value, context), fixed, null); + } + + TotalDigitsFacet parseTotalDigitsFacet(String value) + throws DatatypeException + { + int si = value.indexOf(' '); + boolean fixed = false; + if (si != -1) + { + if (!"FIXED".equalsIgnoreCase(value.substring(si + 1))) + throw new DatatypeException("second argument must be FIXED if present"); + fixed = true; + value = value.substring(0, si); + } + int val = Integer.parseInt(value); + if (val < 0) + throw new DatatypeException("value must be a positiveInteger"); + return new TotalDigitsFacet(val, fixed, null); + } + + FractionDigitsFacet parseFractionDigitsFacet(String value) + throws DatatypeException + { + int si = value.indexOf(' '); + boolean fixed = false; + if (si != -1) + { + if (!"FIXED".equalsIgnoreCase(value.substring(si + 1))) + throw new DatatypeException("second argument must be FIXED if present"); + fixed = true; + value = value.substring(0, si); + } + int val = Integer.parseInt(value); + if (val < 0) + throw new DatatypeException("value must be a positiveInteger"); + return new FractionDigitsFacet(val, fixed, null); + } + + public Datatype createDatatype() + { + return type; + } + +} diff --git a/libjava/classpath/gnu/xml/validation/datatype/TypeLibrary.java b/libjava/classpath/gnu/xml/validation/datatype/TypeLibrary.java new file mode 100644 index 0000000..f1daece --- /dev/null +++ b/libjava/classpath/gnu/xml/validation/datatype/TypeLibrary.java @@ -0,0 +1,173 @@ +/* TypeLibrary.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.HashMap; +import java.util.Map; +import org.relaxng.datatype.Datatype; +import org.relaxng.datatype.DatatypeBuilder; +import org.relaxng.datatype.DatatypeException; +import org.relaxng.datatype.DatatypeLibrary; + +/** + * Datatype library for XML Schema datatypes. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +public class TypeLibrary + implements DatatypeLibrary +{ + + public static final SimpleType ANY_SIMPLE_TYPE = new AnySimpleType(); + + public static final SimpleType STRING = new StringType(); + public static final SimpleType BOOLEAN = new BooleanType(); + public static final SimpleType DECIMAL = new DecimalType(); + public static final SimpleType FLOAT = new FloatType(); + public static final SimpleType DOUBLE = new DoubleType(); + public static final SimpleType DURATION = new DurationType(); + public static final SimpleType DATE_TIME = new DateTimeType(); + public static final SimpleType TIME = new TimeType(); + public static final SimpleType DATE = new DateType(); + public static final SimpleType G_YEAR_MONTH = new GYearMonthType(); + public static final SimpleType G_YEAR = new GYearType(); + public static final SimpleType G_MONTH_DAY = new GMonthDayType(); + public static final SimpleType G_DAY = new GDayType(); + public static final SimpleType G_MONTH = new GMonthType(); + public static final SimpleType HEX_BINARY = new HexBinaryType(); + public static final SimpleType BASE64_BINARY = new Base64BinaryType(); + public static final SimpleType ANY_URI = new AnyURIType(); + public static final SimpleType QNAME = new QNameType(); + public static final SimpleType NOTATION = new NotationType(); + + public static final SimpleType NORMALIZED_STRING = new NormalizedStringType(); + public static final SimpleType TOKEN = new TokenType(); + public static final SimpleType LANGUAGE = new LanguageType(); + public static final SimpleType NMTOKEN = new NMTokenType(); + public static final SimpleType NMTOKENS = new NMTokensType(); + public static final SimpleType NAME = new NameType(); + public static final SimpleType NCNAME = new NCNameType(); + public static final SimpleType ID = new IDType(); + public static final SimpleType IDREF = new IDRefType(); + public static final SimpleType IDREFS = new IDRefsType(); + public static final SimpleType ENTITY = new EntityType(); + public static final SimpleType ENTITIES = new EntitiesType(); + public static final SimpleType INTEGER = new IntegerType(); + public static final SimpleType NON_POSITIVE_INTEGER = new NonPositiveIntegerType(); + public static final SimpleType NEGATIVE_INTEGER = new NegativeIntegerType(); + public static final SimpleType LONG = new LongType(); + public static final SimpleType INT = new IntType(); + public static final SimpleType SHORT = new ShortType(); + public static final SimpleType BYTE = new ByteType(); + public static final SimpleType NON_NEGATIVE_INTEGER = new NonNegativeIntegerType(); + public static final SimpleType UNSIGNED_LONG = new UnsignedLongType(); + public static final SimpleType UNSIGNED_INT = new UnsignedIntType(); + public static final SimpleType UNSIGNED_SHORT = new UnsignedShortType(); + public static final SimpleType UNSIGNED_BYTE = new UnsignedByteType(); + public static final SimpleType POSITIVE_INTEGER = new PositiveIntegerType(); + + private static Map byName; + static + { + byName = new HashMap(); + byName.put("anySimpleType", ANY_SIMPLE_TYPE); + byName.put("string", STRING); + byName.put("boolean", BOOLEAN); + byName.put("decimal", DECIMAL); + byName.put("float", FLOAT); + byName.put("double", DOUBLE); + byName.put("duration", DURATION); + byName.put("dateTime", DATE_TIME); + byName.put("time", TIME); + byName.put("date", DATE); + byName.put("gYearMonth", G_YEAR_MONTH); + byName.put("gYear", G_YEAR); + byName.put("gMonthDay", G_MONTH_DAY); + byName.put("gDay", G_DAY); + byName.put("gMonth",G_MONTH); + byName.put("hexBinary", HEX_BINARY); + byName.put("base64Binary", BASE64_BINARY); + byName.put("anyURI", ANY_URI); + byName.put("QName", QNAME); + byName.put("NOTATION", NOTATION); + byName.put("normalizedString", NORMALIZED_STRING); + byName.put("token", TOKEN); + byName.put("language", LANGUAGE); + byName.put("NMTOKEN", NMTOKEN); + byName.put("NMTOKENS", NMTOKENS); + byName.put("Name", NAME); + byName.put("NCName", NCNAME); + byName.put("ID", ID); + byName.put("IDREF", IDREF); + byName.put("IDREFS", IDREFS); + byName.put("ENTITY", ENTITY); + byName.put("ENTITIES", ENTITIES); + byName.put("integer", INTEGER); + byName.put("nonPositiveInteger", NON_POSITIVE_INTEGER); + byName.put("negativeInteger", NEGATIVE_INTEGER); + byName.put("long", LONG); + byName.put("int", INT); + byName.put("short", SHORT); + byName.put("byte", BYTE); + byName.put("nonNegativeInteger", NON_NEGATIVE_INTEGER); + byName.put("unsignedLong", UNSIGNED_LONG); + byName.put("unsignedInt", UNSIGNED_INT); + byName.put("unsignedShort", UNSIGNED_SHORT); + byName.put("unsignedByte", UNSIGNED_BYTE); + byName.put("positiveInteger", POSITIVE_INTEGER); + } + + public DatatypeBuilder createDatatypeBuilder(String baseTypeLocalName) + throws DatatypeException + { + SimpleType type = (SimpleType) byName.get(baseTypeLocalName); + if (type == null) + throw new DatatypeException("Unknown type name: " + baseTypeLocalName); + return new TypeBuilder(type); + } + + public Datatype createDatatype(String typeLocalName) + throws DatatypeException + { + SimpleType type = (SimpleType) byName.get(typeLocalName); + if (type == null) + throw new DatatypeException("Unknown type name: " + typeLocalName); + return type; + } + +} diff --git a/libjava/classpath/gnu/xml/validation/datatype/TypeLibraryFactory.java b/libjava/classpath/gnu/xml/validation/datatype/TypeLibraryFactory.java new file mode 100644 index 0000000..21ee642 --- /dev/null +++ b/libjava/classpath/gnu/xml/validation/datatype/TypeLibraryFactory.java @@ -0,0 +1,60 @@ +/* TypeLibraryFactory.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 org.relaxng.datatype.DatatypeLibrary; +import org.relaxng.datatype.DatatypeLibraryFactory; + +/** + * Datatype library factory for XML Schema datatypes. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +public class TypeLibraryFactory + implements DatatypeLibraryFactory +{ + + public DatatypeLibrary createDatatypeLibrary(String namespaceURI) + { + if (XMLConstants.W3C_XML_SCHEMA_NS_URI.equals(namespaceURI)) + return new TypeLibrary(); + return null; + } + +} diff --git a/libjava/classpath/gnu/xml/validation/datatype/UnionSimpleType.java b/libjava/classpath/gnu/xml/validation/datatype/UnionSimpleType.java new file mode 100644 index 0000000..d87c2aa --- /dev/null +++ b/libjava/classpath/gnu/xml/validation/datatype/UnionSimpleType.java @@ -0,0 +1,83 @@ +/* UnionSimpleType.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.Iterator; +import java.util.List; +import java.util.Set; +import javax.xml.namespace.QName; +import org.relaxng.datatype.DatatypeException; +import org.relaxng.datatype.ValidationContext; + +/** + * An XML Schema union simple type. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +public class UnionSimpleType + extends SimpleType +{ + + /** + * The member types in this union. + */ + public final List memberTypes; + + public UnionSimpleType(QName name, Set facets, + int fundamentalFacets, SimpleType baseType, + Annotation annotation, List memberTypes) + { + super(name, UNION, facets, fundamentalFacets, baseType, annotation); + this.memberTypes = memberTypes; + } + + public void checkValid(String value, ValidationContext context) + throws DatatypeException + { + super.checkValid(value, context); + for (Iterator i = memberTypes.iterator(); i.hasNext(); ) + { + SimpleType type = (SimpleType) i.next(); + if (type.isValid(value, context)) + return; + } + throw new DatatypeException("invalid union type value"); + } + +} + diff --git a/libjava/classpath/gnu/xml/validation/datatype/UnsignedByteType.java b/libjava/classpath/gnu/xml/validation/datatype/UnsignedByteType.java new file mode 100644 index 0000000..772c9cc --- /dev/null +++ b/libjava/classpath/gnu/xml/validation/datatype/UnsignedByteType.java @@ -0,0 +1,121 @@ +/* UnsignedByteType.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 unsignedByte type. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +final class UnsignedByteType + 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 = "255"; + static final int LENGTH = MAX_VALUE.length(); + + UnsignedByteType() + { + super(new QName(XMLConstants.W3C_XML_SCHEMA_NS_URI, "unsignedByte"), + TypeLibrary.UNSIGNED_SHORT); + } + + 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 unsigned byte value"); + boolean compare = false; + for (int i = 0; i < len; i++) + { + if (len - i > LENGTH) + throw new DatatypeException(i, "invalid unsigned byte value"); + else if (len - i == LENGTH) + compare = true; + char c = value.charAt(i); + if (c >= 0x30 && c <= 0x39) + { + if (compare) + { + char d = MAX_VALUE.charAt(i); + if (Character.digit(c, 10) > Character.digit(d, 10)) + throw new DatatypeException(i, "invalid unsigned byte value"); + } + continue; + } + throw new DatatypeException(i, "invalid unsigned byte value"); + } + } + + public Object createValue(String literal, ValidationContext context) { + try + { + return new Byte(literal); + } + catch (NumberFormatException e) + { + return null; + } + } + +} + diff --git a/libjava/classpath/gnu/xml/validation/datatype/UnsignedIntType.java b/libjava/classpath/gnu/xml/validation/datatype/UnsignedIntType.java new file mode 100644 index 0000000..a4e8a68 --- /dev/null +++ b/libjava/classpath/gnu/xml/validation/datatype/UnsignedIntType.java @@ -0,0 +1,121 @@ +/* UnsignedIntType.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 unsignedInt type. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +final class UnsignedIntType + 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 = "4294967295"; + static final int LENGTH = MAX_VALUE.length(); + + UnsignedIntType() + { + super(new QName(XMLConstants.W3C_XML_SCHEMA_NS_URI, "unsignedInt"), + TypeLibrary.UNSIGNED_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 unsigned int value"); + boolean compare = false; + for (int i = 0; i < len; i++) + { + if (len - i > LENGTH) + throw new DatatypeException(i, "invalid unsigned int value"); + else if (len - i == LENGTH) + compare = true; + char c = value.charAt(i); + if (c >= 0x30 && c <= 0x39) + { + if (compare) + { + char d = MAX_VALUE.charAt(i); + if (Character.digit(c, 10) > Character.digit(d, 10)) + throw new DatatypeException(i, "invalid unsigned int value"); + } + continue; + } + throw new DatatypeException(i, "invalid unsigned int value"); + } + } + + public Object createValue(String literal, ValidationContext context) { + try + { + return new Integer(literal); + } + catch (NumberFormatException e) + { + return null; + } + } + +} + diff --git a/libjava/classpath/gnu/xml/validation/datatype/UnsignedLongType.java b/libjava/classpath/gnu/xml/validation/datatype/UnsignedLongType.java new file mode 100644 index 0000000..5a36d8a --- /dev/null +++ b/libjava/classpath/gnu/xml/validation/datatype/UnsignedLongType.java @@ -0,0 +1,121 @@ +/* UnsignedLongType.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 unsignedLong type. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +final class UnsignedLongType + 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 = "18446744073709551615"; + static final int LENGTH = MAX_VALUE.length(); + + UnsignedLongType() + { + super(new QName(XMLConstants.W3C_XML_SCHEMA_NS_URI, "unsignedLong"), + 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 unsigned long value"); + boolean compare = false; + for (int i = 0; i < len; i++) + { + if (len - i > LENGTH) + throw new DatatypeException(i, "invalid unsigned long value"); + else if (len - i == LENGTH) + compare = true; + char c = value.charAt(i); + if (c >= 0x30 && c <= 0x39) + { + if (compare) + { + char d = MAX_VALUE.charAt(i); + if (Character.digit(c, 10) > Character.digit(d, 10)) + throw new DatatypeException(i, "invalid unsigned long value"); + } + continue; + } + throw new DatatypeException(i, "invalid unsigned long value"); + } + } + + public Object createValue(String literal, ValidationContext context) { + try + { + return new Long(literal); + } + catch (NumberFormatException e) + { + return null; + } + } + +} + diff --git a/libjava/classpath/gnu/xml/validation/datatype/UnsignedShortType.java b/libjava/classpath/gnu/xml/validation/datatype/UnsignedShortType.java new file mode 100644 index 0000000..49f621b --- /dev/null +++ b/libjava/classpath/gnu/xml/validation/datatype/UnsignedShortType.java @@ -0,0 +1,122 @@ +/* UnsignedShortType.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 unsignedShort type. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +final class UnsignedShortType + 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 = "65535"; + static final int LENGTH = MAX_VALUE.length(); + + UnsignedShortType() + { + super(new QName(XMLConstants.W3C_XML_SCHEMA_NS_URI, "unsignedShort"), + TypeLibrary.UNSIGNED_INT); + } + + 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 unsigned short value"); + boolean compare = false; + for (int i = 0; i < len; i++) + { + if (len - i > LENGTH) + throw new DatatypeException(i, "invalid unsigned short value"); + else if (len - i == LENGTH) + compare = true; + char c = value.charAt(i); + if (c >= 0x30 && c <= 0x39) + { + if (compare) + { + char d = MAX_VALUE.charAt(i); + if (Character.digit(c, 10) > Character.digit(d, 10)) + throw new DatatypeException(i, + "invalid unsigned short value"); + } + continue; + } + throw new DatatypeException(i, "invalid unsigned short value"); + } + } + + public Object createValue(String literal, ValidationContext context) { + try + { + return new Short(literal); + } + catch (NumberFormatException e) + { + return null; + } + } + +} + diff --git a/libjava/classpath/gnu/xml/validation/datatype/WhiteSpaceFacet.java b/libjava/classpath/gnu/xml/validation/datatype/WhiteSpaceFacet.java new file mode 100644 index 0000000..5920e1c --- /dev/null +++ b/libjava/classpath/gnu/xml/validation/datatype/WhiteSpaceFacet.java @@ -0,0 +1,75 @@ +/* WhiteSpaceFacet.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>whiteSpace</code> facet. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +public final class WhiteSpaceFacet + extends Facet +{ + + public static final int PRESERVE = 0; + public static final int REPLACE = 1; + public static final int COLLAPSE = 2; + + public final int value; + public final boolean fixed; + + public WhiteSpaceFacet(int value, boolean fixed, Annotation annotation) + { + super(WHITESPACE, annotation); + this.value = value; + this.fixed = fixed; + } + + public int hashCode() + { + return value; + } + + public boolean equals(Object other) + { + return (other instanceof WhiteSpaceFacet && + ((WhiteSpaceFacet) other).value == value); + } + +} + diff --git a/libjava/classpath/gnu/xml/validation/relaxng/AnyNameNameClass.java b/libjava/classpath/gnu/xml/validation/relaxng/AnyNameNameClass.java new file mode 100644 index 0000000..ecc016d --- /dev/null +++ b/libjava/classpath/gnu/xml/validation/relaxng/AnyNameNameClass.java @@ -0,0 +1,58 @@ +/* AnyNameNameClass.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.relaxng; + +/** + * A RELAX NG anyName element. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +class AnyNameNameClass + extends NameClass +{ + + NameClass exceptNameClass; + + boolean matchesName(String uri, String localName) + { + return (exceptNameClass == null) ? true : + !exceptNameClass.matchesName(uri, localName); + } + +} + diff --git a/libjava/classpath/gnu/xml/validation/relaxng/AttributePattern.java b/libjava/classpath/gnu/xml/validation/relaxng/AttributePattern.java new file mode 100644 index 0000000..48443d6 --- /dev/null +++ b/libjava/classpath/gnu/xml/validation/relaxng/AttributePattern.java @@ -0,0 +1,53 @@ +/* AttributePattern.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.relaxng; + +/** + * A RELAX NG attribute element. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +class AttributePattern + extends Pattern +{ + + NameClass nameClass; + Pattern pattern; + +} + diff --git a/libjava/classpath/gnu/xml/validation/relaxng/ChoiceNameClass.java b/libjava/classpath/gnu/xml/validation/relaxng/ChoiceNameClass.java new file mode 100644 index 0000000..e196cd4 --- /dev/null +++ b/libjava/classpath/gnu/xml/validation/relaxng/ChoiceNameClass.java @@ -0,0 +1,59 @@ +/* ChoiceNameClass.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.relaxng; + +/** + * A RELAX NG choice element (in the context of a name class). + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +class ChoiceNameClass + extends NameClass +{ + + NameClass name1; + NameClass name2; + + boolean matchesName(String uri, String localName) + { + return name1.matchesName(uri, localName) || + name2.matchesName(uri, localName); + } + +} + diff --git a/libjava/classpath/gnu/xml/validation/relaxng/ChoicePattern.java b/libjava/classpath/gnu/xml/validation/relaxng/ChoicePattern.java new file mode 100644 index 0000000..54739b2 --- /dev/null +++ b/libjava/classpath/gnu/xml/validation/relaxng/ChoicePattern.java @@ -0,0 +1,53 @@ +/* ChoicePattern.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.relaxng; + +/** + * A RELAX NG choice element. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +class ChoicePattern + extends Pattern +{ + + Pattern pattern1; + Pattern pattern2; + +} + diff --git a/libjava/classpath/gnu/xml/validation/relaxng/DataPattern.java b/libjava/classpath/gnu/xml/validation/relaxng/DataPattern.java new file mode 100644 index 0000000..2315b2c --- /dev/null +++ b/libjava/classpath/gnu/xml/validation/relaxng/DataPattern.java @@ -0,0 +1,60 @@ +/* DataPattern.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.relaxng; + +import java.util.LinkedList; +import java.util.List; +import org.relaxng.datatype.Datatype; +import org.relaxng.datatype.DatatypeLibrary; + +/** + * A RELAX NG data element. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +class DataPattern + extends Pattern +{ + + Datatype type; + DatatypeLibrary datatypeLibrary; + List params = new LinkedList(); + Pattern exceptPattern; + +} + diff --git a/libjava/classpath/gnu/xml/validation/relaxng/Define.java b/libjava/classpath/gnu/xml/validation/relaxng/Define.java new file mode 100644 index 0000000..8801d58 --- /dev/null +++ b/libjava/classpath/gnu/xml/validation/relaxng/Define.java @@ -0,0 +1,52 @@ +/* Define.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.relaxng; + +/** + * A RELAX NG define. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +class Define +{ + + String name; + ElementPattern element; + +} + diff --git a/libjava/classpath/gnu/xml/validation/relaxng/ElementPattern.java b/libjava/classpath/gnu/xml/validation/relaxng/ElementPattern.java new file mode 100644 index 0000000..9ff3570 --- /dev/null +++ b/libjava/classpath/gnu/xml/validation/relaxng/ElementPattern.java @@ -0,0 +1,53 @@ +/* ElementPattern.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.relaxng; + +/** + * A RELAX NG element. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +class ElementPattern + extends Pattern +{ + + NameClass nameClass; + Pattern pattern; + +} + diff --git a/libjava/classpath/gnu/xml/validation/relaxng/EmptyPattern.java b/libjava/classpath/gnu/xml/validation/relaxng/EmptyPattern.java new file mode 100644 index 0000000..ce568f8 --- /dev/null +++ b/libjava/classpath/gnu/xml/validation/relaxng/EmptyPattern.java @@ -0,0 +1,52 @@ +/* EmptyPattern.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.relaxng; + +/** + * A RELAX NG empty element. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +class EmptyPattern + extends Pattern +{ + + static final EmptyPattern INSTANCE = new EmptyPattern(); + +} + diff --git a/libjava/classpath/gnu/xml/validation/relaxng/FullSyntaxBuilder.java b/libjava/classpath/gnu/xml/validation/relaxng/FullSyntaxBuilder.java new file mode 100644 index 0000000..2a68337 --- /dev/null +++ b/libjava/classpath/gnu/xml/validation/relaxng/FullSyntaxBuilder.java @@ -0,0 +1,1651 @@ +/* FullSyntaxBuilder.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.relaxng; + +import java.io.InputStream; +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.net.URL; +import java.net.URLEncoder; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Set; +import javax.xml.XMLConstants; +import javax.xml.namespace.QName; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; + +import org.relaxng.datatype.DatatypeException; +import org.relaxng.datatype.DatatypeLibrary; +import org.relaxng.datatype.helpers.DatatypeLibraryLoader; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.NamedNodeMap; +import org.w3c.dom.Node; +import org.xml.sax.SAXException; + +import gnu.xml.stream.XMLParser; + +/** + * Parses a RELAX NG XML DOM tree, constructing a compiled internal + * representation. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +class FullSyntaxBuilder +{ + + /** + * Complete vocabulary (elements and attributes) of the full syntax. + */ + static final Map VOCABULARY = new HashMap(); + static final Set STRIPPED_ATTRIBUTES = new HashSet(); + static final Set PATTERN_ELEMENTS = new HashSet(); + static + { + Set elementAttrs = Collections.singleton("name"); + Set dataAttrs = new HashSet(); + dataAttrs.add("type"); + dataAttrs.add("datatypeLibrary"); + Set valueAttrs = new HashSet(); + valueAttrs.add("type"); + valueAttrs.add("datatypeLibrary"); + valueAttrs.add("ns"); + Set externalAttrs = Collections.singleton("href"); + Set startAttrs = Collections.singleton("combine"); + Set defineAttrs = new HashSet(); + defineAttrs.add("name"); + defineAttrs.add("combine"); + Set nsAttrs = Collections.singleton("ns"); + + VOCABULARY.put("element", elementAttrs); + VOCABULARY.put("attribute", elementAttrs); + VOCABULARY.put("group", Collections.EMPTY_SET); + VOCABULARY.put("interleave", Collections.EMPTY_SET); + VOCABULARY.put("choice", Collections.EMPTY_SET); + VOCABULARY.put("optional", Collections.EMPTY_SET); + VOCABULARY.put("zeroOrMore", Collections.EMPTY_SET); + VOCABULARY.put("oneOrMore", Collections.EMPTY_SET); + VOCABULARY.put("list", Collections.EMPTY_SET); + VOCABULARY.put("mixed", Collections.EMPTY_SET); + VOCABULARY.put("ref", elementAttrs); + VOCABULARY.put("parentRef", elementAttrs); + VOCABULARY.put("empty", Collections.EMPTY_SET); + VOCABULARY.put("text", Collections.EMPTY_SET); + VOCABULARY.put("value", valueAttrs); + VOCABULARY.put("data", dataAttrs); + VOCABULARY.put("notAllowed", Collections.EMPTY_SET); + VOCABULARY.put("externalRef", externalAttrs); + VOCABULARY.put("grammar", Collections.EMPTY_SET); + VOCABULARY.put("param", elementAttrs); + VOCABULARY.put("except", Collections.EMPTY_SET); + VOCABULARY.put("div", Collections.EMPTY_SET); + VOCABULARY.put("include", externalAttrs); + VOCABULARY.put("start", startAttrs); + VOCABULARY.put("define", defineAttrs); + VOCABULARY.put("name", nsAttrs); + VOCABULARY.put("anyName", Collections.EMPTY_SET); + VOCABULARY.put("nsName", nsAttrs); + + STRIPPED_ATTRIBUTES.add("name"); + STRIPPED_ATTRIBUTES.add("type"); + STRIPPED_ATTRIBUTES.add("combine"); + + PATTERN_ELEMENTS.add("element"); + PATTERN_ELEMENTS.add("attribute"); + PATTERN_ELEMENTS.add("group"); + PATTERN_ELEMENTS.add("interleave"); + PATTERN_ELEMENTS.add("choice"); + PATTERN_ELEMENTS.add("optional"); + PATTERN_ELEMENTS.add("zeroOrMore"); + PATTERN_ELEMENTS.add("oneOrMore"); + PATTERN_ELEMENTS.add("list"); + PATTERN_ELEMENTS.add("mixed"); + PATTERN_ELEMENTS.add("ref"); + PATTERN_ELEMENTS.add("parentRef"); + PATTERN_ELEMENTS.add("empty"); + PATTERN_ELEMENTS.add("text"); + PATTERN_ELEMENTS.add("value"); + PATTERN_ELEMENTS.add("data"); + PATTERN_ELEMENTS.add("notAllowed"); + PATTERN_ELEMENTS.add("externalRef"); + PATTERN_ELEMENTS.add("grammar"); + } + + private Set urls; // recursion checking + private int refCount; // creation of ref names + private Map datatypeLibraries; + + /** + * Parse the specified document into a grammar. + */ + synchronized Grammar parse(Document doc) + throws IOException + { + urls = new HashSet(); + refCount = 1; + + doc.normalizeDocument(); // Normalize XML document + transform(doc); // Apply transformation rules to provide simple syntax + + // 4.18. grammar element + Element p = doc.getDocumentElement(); + Element grammar = + doc.createElementNS(XMLConstants.RELAXNG_NS_URI, "grammar"); + Element start = + doc.createElementNS(XMLConstants.RELAXNG_NS_URI, "start"); + doc.removeChild(p); + doc.appendChild(grammar); + grammar.appendChild(start); + start.appendChild(p); + transformGrammar(grammar, p); + Element define = getNextSiblingElement(start); + while (define != null) + { + Element next = getNextSiblingElement(define); + String name = define.getAttribute("new-name"); + if (name != null) + { + define.setAttribute("name", name); + define.removeAttribute("new-name"); + } + else + grammar.removeChild(define); // unreferenced + define = next; + } + + // 4.19. define and ref elements + Set allDefines = new HashSet(), reachableDefines = new HashSet(); + getDefines(allDefines, grammar, grammar, false); + getDefines(reachableDefines, grammar, start, true); + allDefines.removeAll(reachableDefines); + for (Iterator i = allDefines.iterator(); i.hasNext(); ) + { + // remove unreachable defines + Element d = (Element) i.next(); + Node parent = d.getParentNode(); + parent.removeChild(d); + } + // replace all elements that are not children of defines by refs to new + // defines + Set elements = new HashSet(); + getElements(elements, grammar, grammar); + for (Iterator i = elements.iterator(); i.hasNext(); ) + { + Element element = (Element) i.next(); + Node parent = element.getParentNode(); + if (!reachableDefines.contains(parent)) + { + define = + doc.createElementNS(XMLConstants.RELAXNG_NS_URI, "define"); + Element ref = + doc.createElementNS(XMLConstants.RELAXNG_NS_URI, "ref"); + String name = createRefName(); + define.setAttribute("name", name); + ref.setAttribute("name", name); + parent.insertBefore(ref, element); + define.appendChild(element); + grammar.appendChild(define); + reachableDefines.add(define); + } + } + // Get defines that don't have element children + for (Iterator i = reachableDefines.iterator(); i.hasNext(); ) + { + Element d = (Element) i.next(); + Element child = getFirstChildElement(d); + if (child != null && "element".equals(child.getLocalName())) + i.remove(); + } + // Expand refs that refer to these defines + expandRefs(reachableDefines, grammar); + // Remove any defines that don't have element children + for (Iterator i = reachableDefines.iterator(); i.hasNext(); ) + { + Element d = (Element) i.next(); + Node parent = d.getParentNode(); + parent.removeChild(d); + } + + transform2(p); // Apply second stage transformation rules + + Grammar ret = parseGrammar(grammar); + datatypeLibraries = null; // free datatype libraries cache + return ret; + } + + private void getDefines(Set defines, Element grammar, Element node, + boolean followRefs) + { + String elementName = node.getLocalName(); + if ("define".equals(elementName)) + defines.add(node); + else if ("ref".equals(elementName) && followRefs) + { + String rname = node.getAttribute("name"); + Element define = getFirstChildElement(grammar); + define = getNextSiblingElement(define); + while (define != null) + { + String dname = define.getAttribute("name"); + if (rname.equals(dname)) + { + getDefines(defines, grammar, node, followRefs); + break; + } + define = getNextSiblingElement(define); + } + } + for (Element child = getFirstChildElement(node); child != null; + child = getNextSiblingElement(child)) + getDefines(defines, grammar, child, followRefs); + } + + private void getElements(Set elements, Element grammar, Element node) + { + String elementName = node.getLocalName(); + if ("element".equals(elementName)) + elements.add(node); + for (Element child = getFirstChildElement(node); child != null; + child = getNextSiblingElement(child)) + getElements(elements, grammar, child); + } + + private void expandRefs(Set defines, Element node) + throws GrammarException + { + String elementName = node.getLocalName(); + if ("ref".equals(elementName)) + { + String rname = node.getAttribute("name"); + for (Iterator i = defines.iterator(); i.hasNext(); ) + { + Element define = (Element) i.next(); + String dname = define.getAttribute("name"); + if (rname.equals(dname)) + { + Element child = getFirstChildElement(define); + forbidRefs(child, rname); + Element refChild = (Element) child.cloneNode(true); + Node parent = node.getParentNode(); + parent.insertBefore(refChild, node); + parent.removeChild(node); + node = refChild; + break; + } + } + } + for (Element child = getFirstChildElement(node); child != null; + child = getNextSiblingElement(child)) + expandRefs(defines, child); + } + + private void forbidRefs(Element node, String name) + throws GrammarException + { + String elementName = node.getLocalName(); + if ("ref".equals(elementName)) + { + String rname = node.getAttribute("name"); + if (name.equals(rname)) + throw new GrammarException("cannot expand ref with name '" + name + + "' due to circularity"); + } + for (Element child = getFirstChildElement(node); child != null; + child = getNextSiblingElement(child)) + forbidRefs(child, name); + } + + private void transform(Node node) + throws IOException + { + Node parent = node.getParentNode(); + switch (node.getNodeType()) + { + case Node.ELEMENT_NODE: + // 4.1 Annotations + String elementNs = node.getNamespaceURI(); + String elementName = node.getLocalName(); + if (!XMLConstants.RELAXNG_NS_URI.equals(elementNs) || + !VOCABULARY.containsKey(elementName)) + parent.removeChild(node); + else + { + Set allowedAttrs = (Set) VOCABULARY.get(elementName); + NamedNodeMap attrs = node.getAttributes(); + int len = attrs.getLength(); + for (int i = len - 1; i >= 0; i--) + { + Node attr = attrs.item(i); + String attrNs = attr.getNamespaceURI(); + String attrName = attr.getLocalName(); + if (XMLConstants.XMLNS_ATTRIBUTE_NS_URI.equals(attrNs)) + continue; // ignore namespace nodes + if (!(XMLConstants.RELAXNG_NS_URI.equals(attrNs) || + attrNs == null) || + !allowedAttrs.contains(attrName)) + attrs.removeNamedItemNS(attrNs, attrName); + else + { + // 4.2 Whitespace + if (STRIPPED_ATTRIBUTES.contains(attrName)) + attr.setNodeValue(attr.getNodeValue().trim()); + // 4.3 datatypeLibrary attribute + else if ("datatypeLibrary".equals(attrName)) + { + String dl = attr.getNodeValue(); + attr.setNodeValue(escapeURL(dl)); + } + // 4.5. href attribute + else if ("href".equals(attrName)) + { + String href = attr.getNodeValue(); + href = XMLParser.absolutize(node.getBaseURI(), + escapeURL(href)); + attr.setNodeValue(href); + } + } + } + // 4.3 datatypeLibrary attribute + if ("data".equals(elementName) || "value".equals(elementName)) + { + Element element = (Element) node; + String dl = element.getAttribute("datatypeLibrary"); + if (dl == null) + { + Node p = parent; + while (dl == null && p != null && + p.getNodeType() == Node.ELEMENT_NODE) + { + dl = ((Element) p) + .getAttribute("datatypeLibrary"); + p = p.getParentNode(); + } + if (dl == null) + dl = ""; + element.setAttribute("datatypeLibrary", dl); + } + // 4.4. type attribute of value element + if ("value".equals(elementName)) + { + String type = element.getAttribute("type"); + if (type == null) + { + element.setAttribute("type", "token"); + element.setAttribute("datatypeLibrary", ""); + } + } + // 4.16. Constraints + // TODO validate type + } + // 4.6. externalRef element + else if ("externalRef".equals(elementName)) + { + Element externalRef = (Element) node; + String href = externalRef.getAttribute("href"); + // check for recursion + if (urls.contains(href)) + throw new GrammarException("recursive href"); + urls.add(href); + Element element = resolve(href); + String eNs = element.getNamespaceURI(); + String eName = element.getLocalName(); + if (!(XMLConstants.RELAXNG_NS_URI.equals(eNs) || + eNs == null) || + !PATTERN_ELEMENTS.contains(eName)) + throw new GrammarException("externally referenced element " + + "is not a pattern"); + transform(element); + urls.remove(href); + String ns = element.getAttribute("ns"); + if (ns != null) + element.setAttribute("ns", + externalRef.getAttribute("ns")); + element = (Element) externalRef.getOwnerDocument() + .importNode(element, true); + parent.replaceChild(element, externalRef); + return; + } + // 4.7 include element + else if ("include".equals(elementName)) + { + Element include = (Element) node; + String href = include.getAttribute("href"); + // check for recursion + if (urls.contains(href)) + throw new GrammarException("recursive href"); + urls.add(href); + Element element = resolve(href); + String eNs = element.getNamespaceURI(); + String eName = element.getLocalName(); + if (!(XMLConstants.RELAXNG_NS_URI.equals(eNs) || + eNs == null) || + !"grammar".equals(eName)) + throw new GrammarException("included element is not " + + "a grammar"); + + transform(element); + urls.remove(href); + // handle components + List includeComponents = getComponents(include); + List grammarComponents = getComponents(element); + for (Iterator i = includeComponents.iterator(); i.hasNext(); ) + { + Element comp = (Element) i.next(); + String compName = comp.getLocalName(); + if ("start".equals(compName)) + { + boolean found = false; + for (Iterator j = grammarComponents.iterator(); + j.hasNext(); ) + { + Element c2 = (Element) j.next(); + if ("start".equals(c2.getLocalName())) + { + c2.getParentNode().removeChild(c2); + found = true; + } + } + if (!found) + throw new GrammarException("no start component in " + + "included grammar"); + } + else if ("define".equals(compName)) + { + String name = comp.getAttribute("name"); + boolean found = false; + for (Iterator j = grammarComponents.iterator(); + j.hasNext(); ) + { + Element c2 = (Element) j.next(); + if ("define".equals(c2.getLocalName()) && + name.equals(c2.getAttribute("name"))) + { + c2.getParentNode().removeChild(c2); + found = true; + } + } + if (!found) + throw new GrammarException("no define component " + + "with name '" + name + + "' in included grammar"); + } + } + // transform to div element + Document doc = include.getOwnerDocument(); + Element includeDiv = + doc.createElementNS(XMLConstants.RELAXNG_NS_URI, "div"); + Element grammarDiv = + doc.createElementNS(XMLConstants.RELAXNG_NS_URI, "div"); + // XXX copy include non-href attributes (none defined?) + element = (Element) doc.importNode(element, true); + Node ctx = element.getFirstChild(); + while (ctx != null) + { + Node next = ctx.getNextSibling(); + grammarDiv.appendChild(ctx); + ctx = next; + } + includeDiv.appendChild(grammarDiv); + ctx = include.getFirstChild(); + while (ctx != null) + { + Node next = ctx.getNextSibling(); + includeDiv.appendChild(ctx); + ctx = next; + } + parent.replaceChild(includeDiv, include); + transform(includeDiv); + return; + } + // 4.8. name attribute of element and attribute elements + else if ("attribute".equals(elementName) || + "element".equals(elementName)) + { + Element element = (Element) node; + String name = element.getAttribute("name"); + if (name != null) + { + Document doc = element.getOwnerDocument(); + Element n = + doc.createElementNS(XMLConstants.RELAXNG_NS_URI, "name"); + n.appendChild(doc.createTextNode(name)); + Node first = element.getFirstChild(); + if (first != null) + element.insertBefore(n, first); + else + element.appendChild(n); + if ("attribute".equals(elementName)) + { + String ns = element.getAttribute("ns"); + if (ns != null) + { + n.setAttribute("ns", ns); + element.removeAttribute("ns"); + } + } + element.removeAttribute("name"); + } + // 4.12. Number of child elements + if ("attribute".equals(elementName)) + { + if (getComponents(node).size() == 1) + { + Document doc = node.getOwnerDocument(); + Element text = + doc.createElementNS(XMLConstants.RELAXNG_NS_URI, + "text"); + node.appendChild(text); + } + } + else // element + { + if (node.getChildNodes().getLength() > 2) + { + // transform to 2 child elements + Document doc = node.getOwnerDocument(); + Element child = + doc.createElementNS(XMLConstants.RELAXNG_NS_URI, + "group"); + Node ctx = getFirstChildElement(node); + ctx = getNextSiblingElement(ctx); // skip 1 + while (ctx != null) + { + Node next = getNextSiblingElement(ctx); + child.appendChild(ctx); + ctx = next; + } + node.appendChild(child); + } + } + } + // 4.11. div element + else if ("div".equals(elementName)) + { + Node ctx = node.getFirstChild(); + while (ctx != null) + { + Node next = ctx.getNextSibling(); + parent.insertBefore(ctx, node); + transform(ctx); + ctx = next; + } + parent.removeChild(node); + return; + } + else if ("mixed".equals(elementName)) + { + // 4.12. Number of child elements + transformToOneChildElement(node, "group"); + // 4.13. mixed element + Document doc = node.getOwnerDocument(); + Node interleave = + doc.createElementNS(XMLConstants.RELAXNG_NS_URI, + "interleave"); + Node ctx = node.getFirstChild(); + while (ctx != null) + { + Node next = ctx.getNextSibling(); + interleave.appendChild(ctx); + ctx = next; + } + Node text = + doc.createElementNS(XMLConstants.RELAXNG_NS_URI, + "text"); + interleave.appendChild(text); + parent.insertBefore(interleave, node); + parent.removeChild(node); + node = interleave; + } + else if ("optional".equals(elementName)) + { + // 4.12. Number of child elements + transformToOneChildElement(node, "group"); + // 4.14. optional element + Document doc = node.getOwnerDocument(); + Node choice = + doc.createElementNS(XMLConstants.RELAXNG_NS_URI, + "choice"); + Node ctx = node.getFirstChild(); + while (ctx != null) + { + Node next = ctx.getNextSibling(); + choice.appendChild(ctx); + ctx = next; + } + Node empty = + doc.createElementNS(XMLConstants.RELAXNG_NS_URI, + "empty"); + choice.appendChild(empty); + parent.insertBefore(choice, node); + parent.removeChild(node); + node = choice; + } + else if ("zeroOrMore".equals(elementName)) + { + // 4.12. Number of child elements + transformToOneChildElement(node, "group"); + // 4.15. zeroOrMore element + Document doc = node.getOwnerDocument(); + Node choice = + doc.createElementNS(XMLConstants.RELAXNG_NS_URI, + "choice"); + Node oneOrMore = + doc.createElementNS(XMLConstants.RELAXNG_NS_URI, + "oneOrMore"); + Node ctx = node.getFirstChild(); + while (ctx != null) + { + Node next = ctx.getNextSibling(); + oneOrMore.appendChild(ctx); + ctx = next; + } + Node empty = + doc.createElementNS(XMLConstants.RELAXNG_NS_URI, + "empty"); + choice.appendChild(oneOrMore); + choice.appendChild(empty); + parent.insertBefore(choice, node); + parent.removeChild(node); + node = choice; + } + else if ("list".equals(elementName) || + "oneOrMore".equals(elementName) || + "define".equals(elementName)) + { + // 4.12. Number of child elements + transformToOneChildElement(node, "group"); + } + else if ("except".equals(elementName)) + { + // 4.12. Number of child elements + transformToOneChildElement(node, "choice"); + // 4.16. Constraints + String parentName = parent.getLocalName(); + if ("anyName".equals(parentName)) + forbidDescendants(node, Collections.singleton("anyName")); + else if ("nsName".equals(parentName)) + { + Set names = new HashSet(); + names.add("nsName"); + names.add("anyName"); + forbidDescendants(node, names); + } + } + else if ("choice".equals(elementName) || + "group".equals(elementName) || + "interleave".equals(elementName)) + { + // 4.12. Number of child elements + Node ctx = getFirstChildElement(node); + Node next = getNextSiblingElement(ctx); + if (next == null) + { + // replace + parent.insertBefore(ctx, node); + parent.removeChild(node); + transform(ctx); + return; + } + else + { + // transform to 2 child elements + Node next2 = getNextSiblingElement(next); + if (next2 != null) + { + Document doc = node.getOwnerDocument(); + Node child = + doc.createElementNS(XMLConstants.RELAXNG_NS_URI, + elementName); + child.appendChild(ctx); + child.appendChild(next); + node.insertBefore(next2, child); + transform(node); // recurse + } + } + } + // 4.17. combine attribute + else if ("grammar".equals(elementName)) + { + String combine = null; + List nodes = new LinkedList(); + Node ctx = node.getFirstChild(); + while (ctx != null) + { + Node next = ctx.getNextSibling(); + if ("start".equals(ctx.getLocalName())) + { + String c = ((Element) ctx).getAttribute("combine"); + if (combine != null && !combine.equals(c)) + throw new GrammarException("multiple start elements "+ + "but no combine attribute"); + combine = c; + nodes.add(ctx); + } + ctx = next; + } + if (!nodes.isEmpty()) + combineNodes(node, combine, "start", nodes); + // defines + Map defines = new HashMap(); + Map defineCombines = new HashMap(); + ctx = node.getFirstChild(); + while (ctx != null) + { + Node next = ctx.getNextSibling(); + if ("define".equals(ctx.getLocalName())) + { + String name = ((Element) ctx).getAttribute("name"); + combine = (String) defineCombines.get(name); + String c = ((Element) ctx).getAttribute("combine"); + if (combine != null && !combine.equals(c)) + throw new GrammarException("multiple define " + + "elements with name '"+ + name + "' but no " + + "combine attribute"); + defineCombines.put(name, c); + nodes = (List) defines.get(name); + if (nodes == null) + { + nodes = new LinkedList(); + defines.put(name, nodes); + } + nodes.add(ctx); + } + ctx = next; + } + for (Iterator i = defines.keySet().iterator(); i.hasNext(); ) + { + String name = (String) i.next(); + combine = (String) defineCombines.get(name); + nodes = (List) defines.get(name); + if (!nodes.isEmpty()) + combineNodes(node, combine, "define", nodes); + } + } + // 4.9. ns attribute + if ("name".equals(elementName) || + "nsName".equals(elementName) || + "value".equals(elementName)) + { + Element element = (Element) node; + String ns = element.getAttribute("ns"); + if (ns == null) + { + Node ctx = parent; + while (ns == null && ctx != null && + ctx.getNodeType() == Node.ELEMENT_NODE) + { + ns = ((Element) ctx).getAttribute("ns"); + ctx = ctx.getParentNode(); + } + element.setAttribute("ns", (ns == null) ? "" : ns); + } + if ("name".equals(elementName)) + { + // 4.10. QNames + String name = element.getTextContent(); + int ci = name.indexOf(':'); + if (ci != -1) + { + String prefix = name.substring(0, ci); + element.setTextContent(name.substring(ci + 1)); + ns = element.lookupNamespaceURI(prefix); + element.setAttribute("ns", (ns == null) ? "" : ns); + } + // 4.16. Constraints + if (isDescendantOfFirstChildOfAttribute(element) && + "".equals(element.getAttribute("ns")) && + "xmlns".equals(element.getTextContent())) + throw new GrammarException("name cannot be xmlns"); + } + else if ("nsName".equals(elementName)) + { + // 4.16. Constraints + if (isDescendantOfFirstChildOfAttribute(element) && + "http://www.w3.org/2000/xmlns" + .equals(element.getAttribute("ns"))) + throw new GrammarException("nsName cannot be XMLNS URI"); + } + } + } + + break; + case Node.TEXT_NODE: + case Node.CDATA_SECTION_NODE: + // 4.2 Whitespace + String parentName = parent.getLocalName(); + if ("name".equals(parentName)) + node.setNodeValue(node.getNodeValue().trim()); + if (!"param".equals(parentName) && + !"value".equals(parentName) && + isWhitespace(node.getNodeValue())) + parent.removeChild(node); + break; + case Node.DOCUMENT_NODE: + break; + default: + parent.removeChild(node); + } + // Transform children + Node ctx = node.getFirstChild(); + while (ctx != null) + { + Node next = ctx.getNextSibling(); + transform(ctx); + ctx = next; + } + } + + /** + * Transforms the schema to place all defines under the top-level grammar + * element and replace all other grammar elements by their start child. + */ + private void transformGrammar(Node grammar, Node node) + throws GrammarException + { + if (node.getNodeType() == Node.ELEMENT_NODE) + { + String elementName = node.getLocalName(); + if ("grammar".equals(elementName)) + { + handleRefs(grammar, node, node); + Node start = null; + Node ctx = node.getFirstChild(); + while (ctx != null) + { + Node next = ctx.getNextSibling(); + String childName = ctx.getLocalName(); + if ("define".equals(childName)) + grammar.appendChild(ctx); + else if ("start".equals(childName)) + start = ctx; + ctx = next; + } + if (start == null) + throw new GrammarException("no start element for grammar"); + Node p = getFirstChildElement(start); + Node parent = node.getParentNode(); + parent.insertBefore(p, node); + parent.removeChild(node); + node = p; + } + Node ctx = node.getFirstChild(); + while (ctx != null) + { + Node next = ctx.getNextSibling(); + transformGrammar(grammar, ctx); + ctx = next; + } + } + } + + /** + * Checks that all references in the specified grammar match a define in + * the grammar. + */ + private void handleRefs(Node grammar1, Node grammar2, Node node) + throws GrammarException + { + if (node.getNodeType() == Node.ELEMENT_NODE) + { + String elementName = node.getLocalName(); + if ("ref".equals(elementName) || "parentRef".equals(elementName)) + { + Node grammar = grammar2; + if ("parentRef".equals(elementName)) + grammar = grammar1; + + String name = ((Element) node).getAttribute("name"); + if (name != null) + throw new GrammarException("no name attribute on " + + elementName); + Node define = null; + for (Node ctx = grammar.getFirstChild(); + define == null && ctx != null; + ctx = ctx.getNextSibling()) + { + if ("define".equals(ctx.getLocalName())) + { + String dname = ((Element) ctx).getAttribute("name"); + if (name.equals(dname)) + define = ctx; + } + } + if (define == null) + throw new GrammarException("no define for '" + name + "'"); + name = ((Element) define).getAttribute("new-name"); + if (name == null) + { + name = createRefName(); + ((Element) define).setAttribute("new-name", name); + } + if ("parentRef".equals(elementName)) + { + Document doc = node.getOwnerDocument(); + Node ref = doc.createElementNS(XMLConstants.RELAXNG_NS_URI, + "ref"); + Node ctx = node.getFirstChild(); + while (ctx != null) + { + Node next = ctx.getNextSibling(); + ref.appendChild(ctx); + ctx = next; + } + Node parent = node.getParentNode(); + parent.insertBefore(ref, node); + parent.removeChild(node); + node = ref; + } + ((Element) node).setAttribute("name", name); + } + else if ("grammar".equals(elementName)) + { + grammar1 = grammar2; + grammar2 = node; + } + Node ctx = node.getFirstChild(); + while (ctx != null) + { + Node next = ctx.getNextSibling(); + handleRefs(grammar1, grammar2, ctx); + ctx = next; + } + } + } + + private String createRefName() + { + return "ref" + Integer.toString(refCount++); + } + + private void transform2(Node node) + throws GrammarException + { + Node parent = node.getParentNode(); + if (node.getNodeType() == Node.ELEMENT_NODE) + { + String elementName = node.getLocalName(); + // 4.20. notAllowed element + if ("notAllowed".equals(elementName)) + { + String parentName = parent.getLocalName(); + if ("attribute".equals(parentName) || + "list".equals(parentName) || + "group".equals(parentName) || + "interleave".equals(parentName) || + "oneOrMore".equals(parentName)) + { + Node pp = parent.getParentNode(); + pp.insertBefore(node, parent); + pp.removeChild(parent); + transform2(node); // apply recursively + return; + } + else if ("choice".equals(parentName)) + { + Node p1 = getFirstChildElement(parent); + Node p2 = getNextSiblingElement(p1); + if (p1 == null || p2 == null) + throw new GrammarException("choice does not have two " + + "children"); + String p1Name = p1.getLocalName(); + String p2Name = p2.getLocalName(); + Node pp = parent.getParentNode(); + if ("notAllowed".equals(p1Name) && + "notAllowed".equals(p2Name)) + { + pp.insertBefore(p1, parent); + pp.removeChild(parent); + transform2(p1); //apply recursively + return; + } + else if ("notAllowed".equals(p1Name)) + { + pp.insertBefore(p2, parent); + pp.removeChild(parent); + transform2(p2); + return; + } + else + { + pp.insertBefore(p1, parent); + pp.removeChild(parent); + transform2(p1); + return; + } + } + else if ("except".equals(parentName)) + { + Node pp = parent.getParentNode(); + pp.removeChild(parent); + return; + } + } + // 4.21. empty element + else if ("empty".equals(elementName)) + { + String parentName = parent.getLocalName(); + if ("group".equals(parentName) || + "interleave".equals(parentName)) + { + Node p1 = getFirstChildElement(parent); + Node p2 = getNextSiblingElement(p1); + if (p1 == null || p2 == null) + throw new GrammarException(parentName + " does not have " + + "two children"); + String p1Name = p1.getLocalName(); + String p2Name = p2.getLocalName(); + Node pp = parent.getParentNode(); + if ("empty".equals(p1Name) && + "empty".equals(p2Name)) + { + pp.insertBefore(p1, parent); + pp.removeChild(parent); + transform2(p1); + return; + } + else if ("empty".equals(p1Name)) + { + pp.insertBefore(p2, parent); + pp.removeChild(parent); + transform2(p2); + return; + } + else + { + pp.insertBefore(p1, parent); + pp.removeChild(parent); + transform2(p1); + return; + } + } + else if ("choice".equals(parentName)) + { + Node p1 = getFirstChildElement(parent); + Node p2 = getNextSiblingElement(p1); + if (p1 == null || p2 == null) + throw new GrammarException(parentName + " does not have " + + "two children"); + String p1Name = p1.getLocalName(); + String p2Name = p2.getLocalName(); + Node pp = parent.getParentNode(); + if ("empty".equals(p1Name) && + "empty".equals(p2Name)) + { + pp.insertBefore(p1, parent); + pp.removeChild(parent); + transform2(p1); + return; + } + } + else if ("oneOrMore".equals(parentName)) + { + Node pp = parent.getParentNode(); + pp.insertBefore(node, parent); + pp.removeChild(parent); + transform2(node); + return; + } + } + Node ctx = node.getFirstChild(); + while (ctx != null) + { + Node next = ctx.getNextSibling(); + transform2(ctx); + ctx = next; + } + } + } + + private static boolean isWhitespace(String text) + { + int len = text.length(); + for (int i = 0; i < len; i++) + { + char c = text.charAt(i); + if (c != ' ' && c != '\t' && c != '\n' && c != '\r') + return false; + } + return true; + } + + private static String escapeURL(String url) + { + try + { + return URLEncoder.encode(url, "UTF-8"); + } + catch (UnsupportedEncodingException e) + { + RuntimeException e2 = new RuntimeException("UTF-8 is unsupported"); + e2.initCause(e); + throw e2; + } + } + + /** + * Resolve a URL to an element, as described in section 4.5. + */ + private static Element resolve(String url) + throws IOException + { + try + { + URL u = new URL(url); + InputStream in = u.openStream(); + DocumentBuilderFactory f = DocumentBuilderFactory.newInstance(); + f.setNamespaceAware(true); + f.setCoalescing(true); + f.setExpandEntityReferences(true); + f.setIgnoringComments(true); + f.setIgnoringElementContentWhitespace(true); + DocumentBuilder b = f.newDocumentBuilder(); + Document doc = b.parse(in, url); + in.close(); + String fragment = u.getRef(); + if (fragment != null) + return doc.getElementById(fragment); + return doc.getDocumentElement(); + } + catch (SAXException e) + { + IOException e2 = new IOException("error parsing included element"); + e2.initCause(e); + throw e2; + } + catch (ParserConfigurationException e) + { + IOException e2 = new IOException("error parsing included element"); + e2.initCause(e); + throw e2; + } + } + + /** + * Returns the "components" of an element, as described in section 4.7. + */ + private List getComponents(Node node) + { + List ret = new LinkedList(); + for (Node ctx = node.getFirstChild(); ctx != null; + ctx = ctx.getNextSibling()) + { + if (ctx.getNodeType() != Node.ELEMENT_NODE) + continue; + String ns = ctx.getNamespaceURI(); + if (ns != null && !ns.equals(XMLConstants.RELAXNG_NS_URI)) + continue; + String name = ctx.getLocalName(); + if ("div".equals(name)) + ret.addAll(getComponents(ctx)); + else if (VOCABULARY.containsKey(name)) + ret.add(ctx); + } + return ret; + } + + private static void transformToOneChildElement(Node node, String name) + { + if (node.getChildNodes().getLength() < 2) + return; + Document doc = node.getOwnerDocument(); + Element child = doc.createElementNS(XMLConstants.RELAXNG_NS_URI, name); + Node ctx = getFirstChildElement(node); + while (ctx != null) + { + Node next = getNextSiblingElement(ctx); + child.appendChild(ctx); + ctx = next; + } + node.appendChild(child); + } + + private static Element getFirstChildElement(Node node) + { + Node ctx = node.getFirstChild(); + while (ctx != null && ctx.getNodeType() != Node.ELEMENT_NODE) + ctx = ctx.getNextSibling(); + return (Element) ctx; + } + + private static Element getNextSiblingElement(Node node) + { + Node ctx = node.getNextSibling(); + while (ctx != null && ctx.getNodeType() != Node.ELEMENT_NODE) + ctx = ctx.getNextSibling(); + return (Element) ctx; + } + + private static void forbidDescendants(Node node, Set names) + throws GrammarException + { + for (Node ctx = node.getFirstChild(); ctx != null; + ctx = ctx.getNextSibling()) + { + String ns = ctx.getNamespaceURI(); + if (!XMLConstants.RELAXNG_NS_URI.equals(ns)) + continue; + String name = ctx.getLocalName(); + if (names.contains(name)) + throw new GrammarException("name not allowed: " + name); + forbidDescendants(ctx, names); + } + } + + private static boolean isDescendantOfFirstChildOfAttribute(Node node) + { + Node child = node; + Node parent = node.getParentNode(); + while (parent != null && !"attribute".equals(parent.getLocalName())) + { + child = parent; + parent = child.getParentNode(); + } + if (parent == null) + return false; + Node firstChild = getFirstChildElement(parent); + return firstChild == child; + } + + private static void combineNodes(Node node, String combine, String name, + List nodes) + { + Document doc = node.getOwnerDocument(); + Node child = + doc.createElementNS(XMLConstants.RELAXNG_NS_URI, name); + Node combineNode = + doc.createElementNS(XMLConstants.RELAXNG_NS_URI, combine); + child.appendChild(combineNode); + boolean inserted = false; + for (Iterator i = nodes.iterator(); i.hasNext(); ) + { + Node startNode = (Node) i.next(); + if (!inserted) + { + node.insertBefore(child, startNode); + inserted = true; + } + Node ctx = startNode.getFirstChild(); + while (ctx != null) + { + Node next = ctx.getNextSibling(); + combineNode.appendChild(ctx); + ctx = next; + } + node.removeChild(startNode); + } + } + + Grammar parseGrammar(Element node) + throws GrammarException + { + checkName(node, "grammar"); + Grammar grammar = new Grammar(); + Element start = getFirstChildElement(node); + grammar.start = parsePattern(getFirstChildElement(start)); + for (Element define = getNextSiblingElement(start); define != null; + define = getNextSiblingElement(define)) + grammar.defines.add(parseDefine(define)); + return grammar; + } + + Define parseDefine(Element node) + throws GrammarException + { + checkName(node, "define"); + Define define = new Define(); + define.name = node.getAttribute("name"); + define.element = parseElement(getFirstChildElement(node)); + return define; + } + + Pattern parseTop(Element node) + throws GrammarException + { + String name = node.getLocalName(); + if ("notAllowed".equals(name)) + return parseNotAllowed(node); + return parsePattern(node); + } + + Pattern parsePattern(Element node) + throws GrammarException + { + String name = node.getLocalName(); + if ("empty".equals(name)) + return parseEmpty(node); + return parseNonEmptyPattern(node); + } + + Pattern parseNonEmptyPattern(Element node) + throws GrammarException + { + String name = node.getLocalName(); + if ("text".equals(name)) + return parseText(node); + else if ("data".equals(name)) + return parseData(node); + else if ("value".equals(name)) + return parseValue(node); + else if ("list".equals(name)) + return parseList(node); + else if ("attribute".equals(name)) + return parseAttribute(node); + else if ("ref".equals(name)) + return parseRef(node); + else if ("oneOrMore".equals(name)) + return parseOneOrMore(node); + else if ("choice".equals(name)) + return parseChoice(node); + else if ("group".equals(name)) + return parseGroup(node); + else if ("interleave".equals(name)) + return parseInterleave(node); + throw new GrammarException("invalid pattern: " + name); + } + + ElementPattern parseElement(Element node) + throws GrammarException + { + checkName(node, "element"); + ElementPattern element = new ElementPattern(); + Element nameClass = getFirstChildElement(node); + element.nameClass = parseNameClass(nameClass); + element.pattern = parseTop(getNextSiblingElement(nameClass)); + return element; + } + + NotAllowedPattern parseNotAllowed(Element node) + throws GrammarException + { + checkName(node, "notAllowed"); + return NotAllowedPattern.INSTANCE; + } + + EmptyPattern parseEmpty(Element node) + throws GrammarException + { + checkName(node, "empty"); + return EmptyPattern.INSTANCE; + } + + TextPattern parseText(Element node) + throws GrammarException + { + checkName(node, "text"); + return TextPattern.INSTANCE; + } + + DataPattern parseData(Element node) + throws GrammarException + { + checkName(node, "data"); + DataPattern data = new DataPattern(); + DatatypeLibrary dl = + getDatatypeLibrary(node.getAttribute("datatypeLibrary")); + String type = node.getAttribute("type"); + try + { + data.type = dl.createDatatype(type); + data.datatypeLibrary = dl; + } + catch (DatatypeException e) + { + GrammarException e2 = new GrammarException(type); + e2.initCause(e); + throw e2; + } + Element ctx = getFirstChildElement(node); + while (ctx != null) + { + Element next = getNextSiblingElement(ctx); + String name = ctx.getLocalName(); + if ("param".equals(name)) + data.params.add(parseParam(ctx)); + else if ("except".equals(name) && next == null) + data.exceptPattern = parsePattern(getFirstChildElement(ctx)); + else + throw new GrammarException("invalid element: " + name); + ctx = next; + } + return data; + } + + Param parseParam(Element node) + throws GrammarException + { + checkName(node, "param"); + Param param = new Param(); + param.name = node.getAttribute("name"); + param.value = node.getTextContent(); + return param; + } + + ValuePattern parseValue(Element node) + throws GrammarException + { + checkName(node, "value"); + ValuePattern value = new ValuePattern(); + DatatypeLibrary dl = + getDatatypeLibrary(node.getAttribute("datatypeLibrary")); + String type = node.getAttribute("type"); + try + { + value.type = dl.createDatatype(type); + value.datatypeLibrary = dl; + } + catch (DatatypeException e) + { + GrammarException e2 = new GrammarException(type); + e2.initCause(e); + throw e2; + } + value.ns = node.getAttribute("ns"); + value.value = node.getTextContent(); + return value; + } + + ListPattern parseList(Element node) + throws GrammarException + { + checkName(node, "list"); + ListPattern list = new ListPattern(); + list.pattern = parsePattern(getFirstChildElement(node)); + return list; + } + + AttributePattern parseAttribute(Element node) + throws GrammarException + { + checkName(node, "attribute"); + AttributePattern attribute = new AttributePattern(); + Element nameClass = getFirstChildElement(node); + attribute.nameClass = parseNameClass(nameClass); + attribute.pattern = parsePattern(getNextSiblingElement(nameClass)); + return attribute; + } + + RefPattern parseRef(Element node) + throws GrammarException + { + checkName(node, "ref"); + RefPattern ref = new RefPattern(); + ref.name = node.getAttribute("name"); + return ref; + } + + OneOrMorePattern parseOneOrMore(Element node) + throws GrammarException + { + checkName(node, "oneOrMore"); + OneOrMorePattern oneOrMore = new OneOrMorePattern(); + oneOrMore.pattern = parseNonEmptyPattern(getFirstChildElement(node)); + return oneOrMore; + } + + ChoicePattern parseChoice(Element node) + throws GrammarException + { + checkName(node, "choice"); + ChoicePattern choice = new ChoicePattern(); + Element p1 = getFirstChildElement(node); + Element p2 = getNextSiblingElement(p1); + choice.pattern1 = parsePattern(p1); + choice.pattern2 = parseNonEmptyPattern(p2); + return choice; + } + + GroupPattern parseGroup(Element node) + throws GrammarException + { + checkName(node, "group"); + GroupPattern group = new GroupPattern(); + Element p1 = getFirstChildElement(node); + Element p2 = getNextSiblingElement(p1); + group.pattern1 = parseNonEmptyPattern(p1); + group.pattern2 = parseNonEmptyPattern(p2); + return group; + } + + InterleavePattern parseInterleave(Element node) + throws GrammarException + { + checkName(node, "interleave"); + InterleavePattern interleave = new InterleavePattern(); + Element p1 = getFirstChildElement(node); + Element p2 = getNextSiblingElement(p1); + interleave.pattern1 = parseNonEmptyPattern(p1); + interleave.pattern2 = parseNonEmptyPattern(p2); + return interleave; + } + + NameClass parseNameClass(Element node) + throws GrammarException + { + String name = node.getLocalName(); + if ("anyName".equals(name)) + return parseAnyName(node); + else if ("name".equals(name)) + return parseName(node); + else if ("nsName".equals(name)) + return parseNsName(node); + else if ("choice".equals(name)) + return parseChoiceNameClass(node); + throw new GrammarException("invalid name class: " + name); + } + + AnyNameNameClass parseAnyName(Element node) + throws GrammarException + { + checkName(node, "anyName"); + AnyNameNameClass anyName = new AnyNameNameClass(); + Element except = getFirstChildElement(node); + if (except != null) { + checkName(except, "except"); + anyName.exceptNameClass = parseNameClass(getFirstChildElement(except)); + } + return anyName; + } + + NameNameClass parseName(Element node) + throws GrammarException + { + checkName(node, "name"); + NameNameClass name = new NameNameClass(); + name.ns = node.getAttribute("ns"); + name.name = node.getTextContent(); + return name; + } + + NSNameNameClass parseNsName(Element node) + throws GrammarException + { + checkName(node, "nsName"); + NSNameNameClass nsName = new NSNameNameClass(); + nsName.ns = node.getAttribute("ns"); + Element except = getFirstChildElement(node); + if (except != null) { + checkName(except, "except"); + nsName.exceptNameClass = parseNameClass(getFirstChildElement(except)); + } + return nsName; + } + + ChoiceNameClass parseChoiceNameClass(Element node) + throws GrammarException + { + checkName(node, "choice"); + ChoiceNameClass choice = new ChoiceNameClass(); + Element c1 = getFirstChildElement(node); + Element c2 = getNextSiblingElement(c1); + choice.name1 = parseNameClass(c1); + choice.name2 = parseNameClass(c2); + return choice; + } + + void checkName(Element node, String name) + throws GrammarException + { + if (!name.equals(node.getLocalName())) + throw new GrammarException("expecting " + name); + } + + DatatypeLibrary getDatatypeLibrary(String uri) + throws GrammarException + { + if (datatypeLibraries == null) + datatypeLibraries = new HashMap(); + DatatypeLibrary library = (DatatypeLibrary) datatypeLibraries.get(uri); + if (library == null) + { + library = new DatatypeLibraryLoader().createDatatypeLibrary(uri); + if (library == null) + throw new GrammarException("Datatype library not supported: " + uri); + datatypeLibraries.put(uri, library); + } + return library; + } + +} diff --git a/libjava/classpath/gnu/xml/validation/relaxng/Grammar.java b/libjava/classpath/gnu/xml/validation/relaxng/Grammar.java new file mode 100644 index 0000000..76eff4f --- /dev/null +++ b/libjava/classpath/gnu/xml/validation/relaxng/Grammar.java @@ -0,0 +1,70 @@ +/* Grammar.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.relaxng; + +import java.util.LinkedList; +import java.util.List; +import javax.xml.validation.Schema; +import javax.xml.validation.Validator; +import javax.xml.validation.ValidatorHandler; + +/** + * A RELAX NG grammar. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +class Grammar + extends Schema +{ + + Pattern start; + List defines = new LinkedList(); + + public Validator newValidator() + { + return new GrammarValidator(this); + } + + public ValidatorHandler newValidatorHandler() + { + // TODO + return null; + } + +} + diff --git a/libjava/classpath/gnu/xml/stream/EndEntityImpl.java b/libjava/classpath/gnu/xml/validation/relaxng/GrammarException.java index fd36ee2..71d03de 100644 --- a/libjava/classpath/gnu/xml/stream/EndEntityImpl.java +++ b/libjava/classpath/gnu/xml/validation/relaxng/GrammarException.java @@ -1,5 +1,5 @@ -/* EndEntityImpl.java -- - Copyright (C) 2005 Free Software Foundation, Inc. +/* GrammarException.java -- + Copyright (C) 2006 Free Software Foundation, Inc. This file is part of GNU Classpath. @@ -35,46 +35,22 @@ 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; +package gnu.xml.validation.relaxng; import java.io.IOException; -import java.io.Writer; -import javax.xml.stream.Location; -import javax.xml.stream.XMLStreamException; -import javax.xml.stream.events.EndEntity; /** - * An end-entity event. + * Exception parsing a grammar. * * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> */ -public class EndEntityImpl - extends XMLEventImpl - implements EndEntity +class GrammarException + extends IOException { - protected final String name; - - protected EndEntityImpl(Location location, String name) - { - super(location); - this.name = name; - } - - public int getEventType() - { - return END_ENTITY; - } - - public String getName() - { - return name; - } - - public void writeAsEncodedUnicode(Writer writer) - throws XMLStreamException + GrammarException(String message) { + super(message); } } - diff --git a/libjava/classpath/gnu/xml/validation/relaxng/GrammarValidator.java b/libjava/classpath/gnu/xml/validation/relaxng/GrammarValidator.java new file mode 100644 index 0000000..d811aee --- /dev/null +++ b/libjava/classpath/gnu/xml/validation/relaxng/GrammarValidator.java @@ -0,0 +1,97 @@ +/* GrammarValidator.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.relaxng; + +import java.io.IOException; +import javax.xml.transform.Source; +import javax.xml.transform.Result; +import javax.xml.validation.Validator; +import org.w3c.dom.ls.LSResourceResolver; +import org.xml.sax.ErrorHandler; +import org.xml.sax.SAXException; + +/** + * RELAX NG validator. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +class GrammarValidator + extends Validator +{ + + final Grammar grammar; + ErrorHandler errorHandler; + LSResourceResolver resourceResolver; + + GrammarValidator(Grammar grammar) + { + this.grammar = grammar; + } + + public ErrorHandler getErrorHandler() + { + return errorHandler; + } + + public void setErrorHandler(ErrorHandler errorHandler) + { + this.errorHandler = errorHandler; + } + + public LSResourceResolver getResourceResolver() + { + return resourceResolver; + } + + public void setResourceResolver(LSResourceResolver resourceResolver) + { + this.resourceResolver = resourceResolver; + } + + public void reset() + { + // TODO + } + + public void validate(Source source, Result result) + throws SAXException, IOException + { + // TODO + } + +} diff --git a/libjava/classpath/gnu/xml/validation/relaxng/GroupPattern.java b/libjava/classpath/gnu/xml/validation/relaxng/GroupPattern.java new file mode 100644 index 0000000..b01090e --- /dev/null +++ b/libjava/classpath/gnu/xml/validation/relaxng/GroupPattern.java @@ -0,0 +1,53 @@ +/* GroupPattern.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.relaxng; + +/** + * A RELAX NG group element. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +class GroupPattern + extends Pattern +{ + + Pattern pattern1; + Pattern pattern2; + +} + diff --git a/libjava/classpath/gnu/xml/validation/relaxng/InterleavePattern.java b/libjava/classpath/gnu/xml/validation/relaxng/InterleavePattern.java new file mode 100644 index 0000000..aa7c28e --- /dev/null +++ b/libjava/classpath/gnu/xml/validation/relaxng/InterleavePattern.java @@ -0,0 +1,53 @@ +/* InterleavePattern.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.relaxng; + +/** + * A RELAX NG interleave element. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +class InterleavePattern + extends Pattern +{ + + Pattern pattern1; + Pattern pattern2; + +} + diff --git a/libjava/classpath/gnu/xml/validation/relaxng/ListPattern.java b/libjava/classpath/gnu/xml/validation/relaxng/ListPattern.java new file mode 100644 index 0000000..4c0393a --- /dev/null +++ b/libjava/classpath/gnu/xml/validation/relaxng/ListPattern.java @@ -0,0 +1,52 @@ +/* ListPattern.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.relaxng; + +/** + * A RELAX NG list element. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +class ListPattern + extends Pattern +{ + + Pattern pattern; + +} + diff --git a/libjava/classpath/gnu/xml/validation/relaxng/NSNameNameClass.java b/libjava/classpath/gnu/xml/validation/relaxng/NSNameNameClass.java new file mode 100644 index 0000000..f485e99 --- /dev/null +++ b/libjava/classpath/gnu/xml/validation/relaxng/NSNameNameClass.java @@ -0,0 +1,61 @@ +/* NSNameNameClass.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.relaxng; + +/** + * A RELAX NG nsName element. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +class NSNameNameClass + extends NameClass +{ + + String ns; + NameClass exceptNameClass; + + boolean matchesName(String uri, String localName) + { + if (!ns.equals(uri)) + return false; + return (exceptNameClass == null) ? true : + !exceptNameClass.matchesName(uri, localName); + } + +} + diff --git a/libjava/classpath/gnu/xml/validation/relaxng/NameClass.java b/libjava/classpath/gnu/xml/validation/relaxng/NameClass.java new file mode 100644 index 0000000..2a3dc83 --- /dev/null +++ b/libjava/classpath/gnu/xml/validation/relaxng/NameClass.java @@ -0,0 +1,50 @@ +/* NameClass.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.relaxng; + +/** + * A RELAX NG name class. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +abstract class NameClass +{ + + abstract boolean matchesName(String uri, String localName); + +} diff --git a/libjava/classpath/gnu/xml/validation/relaxng/NameNameClass.java b/libjava/classpath/gnu/xml/validation/relaxng/NameNameClass.java new file mode 100644 index 0000000..d5a0c5f --- /dev/null +++ b/libjava/classpath/gnu/xml/validation/relaxng/NameNameClass.java @@ -0,0 +1,60 @@ +/* NameNameClass.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.relaxng; + +/** + * A RELAX NG name element. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +class NameNameClass + extends NameClass +{ + + String ns; + String name; + + boolean matchesName(String uri, String localName) + { + if (!ns.equals(uri)) + return false; + return name.equals(localName); + } + +} + diff --git a/libjava/classpath/gnu/xml/validation/relaxng/NotAllowedPattern.java b/libjava/classpath/gnu/xml/validation/relaxng/NotAllowedPattern.java new file mode 100644 index 0000000..8263a45 --- /dev/null +++ b/libjava/classpath/gnu/xml/validation/relaxng/NotAllowedPattern.java @@ -0,0 +1,53 @@ +/* NotAllowedPattern.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.relaxng; + +/** + * A RELAX NG notAllowed element. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +class NotAllowedPattern + extends Pattern +{ + + static final NotAllowedPattern INSTANCE = new NotAllowedPattern(); + +} + + diff --git a/libjava/classpath/gnu/xml/validation/relaxng/OneOrMorePattern.java b/libjava/classpath/gnu/xml/validation/relaxng/OneOrMorePattern.java new file mode 100644 index 0000000..99864d7 --- /dev/null +++ b/libjava/classpath/gnu/xml/validation/relaxng/OneOrMorePattern.java @@ -0,0 +1,52 @@ +/* OneOrMorePattern.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.relaxng; + +/** + * A RELAX NG oneOrMore element. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +class OneOrMorePattern + extends Pattern +{ + + Pattern pattern; + +} + diff --git a/libjava/classpath/gnu/xml/validation/relaxng/Param.java b/libjava/classpath/gnu/xml/validation/relaxng/Param.java new file mode 100644 index 0000000..246ad20 --- /dev/null +++ b/libjava/classpath/gnu/xml/validation/relaxng/Param.java @@ -0,0 +1,52 @@ +/* Param.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.relaxng; + +/** + * A RELAX NG param element. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +class Param +{ + + String name; + String value; + +} + diff --git a/libjava/classpath/gnu/xml/validation/relaxng/Pattern.java b/libjava/classpath/gnu/xml/validation/relaxng/Pattern.java new file mode 100644 index 0000000..3bf9a99 --- /dev/null +++ b/libjava/classpath/gnu/xml/validation/relaxng/Pattern.java @@ -0,0 +1,48 @@ +/* Pattern.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.relaxng; + +/** + * A RELAX NG pattern. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +abstract class Pattern +{ +} + diff --git a/libjava/classpath/gnu/xml/validation/relaxng/RELAXNGSchemaFactory.java b/libjava/classpath/gnu/xml/validation/relaxng/RELAXNGSchemaFactory.java new file mode 100644 index 0000000..e1eb758 --- /dev/null +++ b/libjava/classpath/gnu/xml/validation/relaxng/RELAXNGSchemaFactory.java @@ -0,0 +1,151 @@ +/* RelaxNGSchemaFactory.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.relaxng; + +import java.io.IOException; +import java.net.URL; +import javax.xml.XMLConstants; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.Source; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamSource; +import javax.xml.validation.Schema; +import javax.xml.validation.SchemaFactory; +import org.w3c.dom.Document; +import org.w3c.dom.Node; +import org.w3c.dom.ls.LSResourceResolver; +import org.xml.sax.InputSource; +import org.xml.sax.SAXException; + +/** + * Schema factory for RELAX NG grammars. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +public class RELAXNGSchemaFactory + extends SchemaFactory +{ + + LSResourceResolver resourceResolver; + + public LSResourceResolver getResourceResolver() + { + return resourceResolver; + } + + public void setResourceResolver(LSResourceResolver resourceResolver) + { + this.resourceResolver = resourceResolver; + } + + public boolean isSchemaLanguageSupported(String schemaLanguage) + { + return XMLConstants.RELAXNG_NS_URI.equals(schemaLanguage); + } + + public Schema newSchema() + throws SAXException + { + // TODO + throw new UnsupportedOperationException(); + } + + public Schema newSchema(Source[] schemata) + throws SAXException + { + if (schemata == null || schemata.length != 1) + throw new IllegalArgumentException("must specify one source"); + // TODO multiple schemata + // TODO compact syntax + try + { + Document doc = getDocument(schemata[0]); + FullSyntaxBuilder builder = new FullSyntaxBuilder(); + return builder.parse(doc); + } + catch (IOException e) + { + SAXException e2 = new SAXException(e.getMessage()); + e2.initCause(e); + throw e2; + } + } + + private static Document getDocument(Source source) + throws SAXException, IOException + { + if (source instanceof DOMSource) + { + Node node = ((DOMSource) source).getNode(); + if (node != null && node instanceof Document) + return (Document) node; + } + String url = source.getSystemId(); + try + { + InputSource input = new InputSource(url); + if (source instanceof StreamSource) + { + StreamSource streamSource = (StreamSource) source; + input.setByteStream(streamSource.getInputStream()); + input.setCharacterStream(streamSource.getReader()); + } + if (input.getByteStream() == null && + input.getCharacterStream() == null && + url != null) + input.setByteStream(new URL(url).openStream()); + DocumentBuilderFactory f = DocumentBuilderFactory.newInstance(); + f.setNamespaceAware(true); + f.setCoalescing(true); + f.setExpandEntityReferences(true); + f.setIgnoringComments(true); + f.setIgnoringElementContentWhitespace(true); + DocumentBuilder b = f.newDocumentBuilder(); + return b.parse(input); + } + catch (ParserConfigurationException e) + { + SAXException e2 = new SAXException(e.getMessage()); + e2.initCause(e); + throw e2; + } + } + +} diff --git a/libjava/classpath/gnu/xml/validation/relaxng/RefPattern.java b/libjava/classpath/gnu/xml/validation/relaxng/RefPattern.java new file mode 100644 index 0000000..d7de095 --- /dev/null +++ b/libjava/classpath/gnu/xml/validation/relaxng/RefPattern.java @@ -0,0 +1,52 @@ +/* RefPattern.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.relaxng; + +/** + * A RELAX NG ref element. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +class RefPattern + extends Pattern +{ + + String name; + +} + diff --git a/libjava/classpath/gnu/xml/validation/relaxng/TextPattern.java b/libjava/classpath/gnu/xml/validation/relaxng/TextPattern.java new file mode 100644 index 0000000..06af3c3 --- /dev/null +++ b/libjava/classpath/gnu/xml/validation/relaxng/TextPattern.java @@ -0,0 +1,52 @@ +/* TextPattern.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.relaxng; + +/** + * A RELAX NG text element. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +class TextPattern + extends Pattern +{ + + static final TextPattern INSTANCE = new TextPattern(); + +} + diff --git a/libjava/classpath/gnu/xml/validation/relaxng/ValuePattern.java b/libjava/classpath/gnu/xml/validation/relaxng/ValuePattern.java new file mode 100644 index 0000000..81260b0 --- /dev/null +++ b/libjava/classpath/gnu/xml/validation/relaxng/ValuePattern.java @@ -0,0 +1,58 @@ +/* ValuePattern.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.relaxng; + +import org.relaxng.datatype.Datatype; +import org.relaxng.datatype.DatatypeLibrary; + +/** + * A RELAX NG value element. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +class ValuePattern + extends Pattern +{ + + DatatypeLibrary datatypeLibrary; + Datatype type; + String ns; + String value; + +} + diff --git a/libjava/classpath/gnu/xml/validation/xmlschema/AnyAttribute.java b/libjava/classpath/gnu/xml/validation/xmlschema/AnyAttribute.java new file mode 100644 index 0000000..df90dc6 --- /dev/null +++ b/libjava/classpath/gnu/xml/validation/xmlschema/AnyAttribute.java @@ -0,0 +1,67 @@ +/* AnyAttribute.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.xmlschema; + +import gnu.xml.validation.datatype.Annotation; + +/** + * An attribute wildcard. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +final class AnyAttribute +{ + + static final int STRICT = 0; + static final int LAX = 1; + static final int SKIP = 2; + + final String namespace; + + final int processContents; + + Annotation annotation; + + AnyAttribute(String namespace, int processContents) + { + this.namespace = namespace; + this.processContents = processContents; + } + +} + diff --git a/libjava/classpath/gnu/xml/validation/xmlschema/AttributeDeclaration.java b/libjava/classpath/gnu/xml/validation/xmlschema/AttributeDeclaration.java new file mode 100644 index 0000000..98b322b --- /dev/null +++ b/libjava/classpath/gnu/xml/validation/xmlschema/AttributeDeclaration.java @@ -0,0 +1,99 @@ +/* AttributeDeclaration.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.xmlschema; + +import gnu.xml.validation.datatype.Annotation; +import gnu.xml.validation.datatype.SimpleType; +import javax.xml.namespace.QName; + +/** + * An XML Schema attribute declaration schema component. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +class AttributeDeclaration +{ + + static final int NONE = 0; + static final int DEFAULT = 1; + static final int FIXED = 2; + + /** + * The scope of this attribute declaration (global or local). + */ + final boolean scope; + + /** + * The constraint type. + * One of NONE, DEFAULT, FIXED. + */ + final int type; + + /** + * The value constraint. + */ + final String value; + + /** + * The name of the attribute to which this declaration refers. + */ + final QName name; + + /** + * The type definition corresponding to this attribute. + */ + final SimpleType datatype; + + /** + * The annotation associated with this attribute declaration, if any. + */ + final Annotation annotation; + + AttributeDeclaration(boolean scope, int type, String value, QName name, + SimpleType datatype, Annotation annotation) + { + this.scope = scope; + this.type = type; + this.value = value; + this.name = name; + this.datatype = datatype; + this.annotation = annotation; + } + +} + diff --git a/libjava/classpath/gnu/xml/validation/xmlschema/AttributeUse.java b/libjava/classpath/gnu/xml/validation/xmlschema/AttributeUse.java new file mode 100644 index 0000000..f8bb11b --- /dev/null +++ b/libjava/classpath/gnu/xml/validation/xmlschema/AttributeUse.java @@ -0,0 +1,79 @@ +/* AttributeUse.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.xmlschema; + +/** + * An XML Schema attribute use schema component. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +class AttributeUse +{ + + /** + * Whether the attribute is required. + */ + final boolean required; + + /** + * The constraint type. + * One of NONE, DEFAULT, FIXED. + */ + final int type; + + /** + * The value constraint. + */ + final String value; + + /** + * The name of the attribute to which this declaration refers. + */ + final AttributeDeclaration declaration; + + AttributeUse(boolean required, int type, String value, + AttributeDeclaration declaration) + { + this.required = required; + this.type = type; + this.value = value; + this.declaration = declaration; + } + +} + diff --git a/libjava/classpath/gnu/xml/validation/xmlschema/ComplexType.java b/libjava/classpath/gnu/xml/validation/xmlschema/ComplexType.java new file mode 100644 index 0000000..2c7acb1 --- /dev/null +++ b/libjava/classpath/gnu/xml/validation/xmlschema/ComplexType.java @@ -0,0 +1,102 @@ +/* ComplexType.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.xmlschema; + +import java.util.LinkedHashSet; +import java.util.Set; +import javax.xml.namespace.QName; +import gnu.xml.validation.datatype.Type; + +/** + * A complex type definition. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +class ComplexType + extends Type +{ + + /** + * Either a simple type definition or a complex type definition. + */ + QName baseType; + + /** + * Either EXTENSION or RESTRICTION. + */ + int derivationMethod; + + /** + * A subset of {EXTENSION, RESTRICTION}. + */ + final int finality; + + final boolean isAbstract; + + Set attributeUses; + + AnyAttribute attributeWildcard; + + /** + * One of EMPTY, SIMPLE, MIXED, or ELEMENT_ONLY. + */ + int contentType; + + /** + * A simple type definition or a Particle. + */ + Object contentModel; + + final int prohibitedSubstitutions; + + Set annotations; + + ComplexType(QName name, + boolean isAbstract, + int prohibitedSubstitutions, + int finality) + { + super(name); + this.isAbstract = isAbstract; + this.prohibitedSubstitutions = prohibitedSubstitutions; + this.finality = finality; + attributeUses = new LinkedHashSet(); + } + +} + diff --git a/libjava/classpath/gnu/xml/validation/xmlschema/ElementDeclaration.java b/libjava/classpath/gnu/xml/validation/xmlschema/ElementDeclaration.java new file mode 100644 index 0000000..d41f5e5 --- /dev/null +++ b/libjava/classpath/gnu/xml/validation/xmlschema/ElementDeclaration.java @@ -0,0 +1,125 @@ +/* ElementDeclaration.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.xmlschema; + +import gnu.xml.validation.datatype.Annotation; +import gnu.xml.validation.datatype.Type; +import javax.xml.namespace.QName; + +/** + * An XML Schema element declaration schema component. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +class ElementDeclaration +{ + + /** + * The name of the element to which this declaration refers. + */ + final QName name; + + /** + * The type definition corresponding to this element. + */ + Type datatype; + + /** + * The scope of this schema component. + * One of GLOBAL, LOCAL, or ABSENT. + */ + final int scope; + + /** + * If scope is LOCAL, the parent element definition. + */ + final ElementDeclaration parent; + + /** + * The constraint type. + * One of NONE, DEFAULT, FIXED. + */ + final int type; + + /** + * The value constraint. + */ + final String value; + + final boolean nillable; + + // TODO identity-constraint definitions + + final QName substitutionGroup; + + final int substitutionGroupExclusions; + + final int disallowedSubstitutions; + + final boolean isAbstract; + + /** + * The annotation associated with this attribute declaration, if any. + */ + Annotation annotation; + + ElementDeclaration(QName name, + Type datatype, + int scope, ElementDeclaration parent, + int type, String value, + boolean nillable, + QName substitutionGroup, + int substitutionGroupExclusions, + int disallowedSubstitutions, + boolean isAbstract) + { + this.name = name; + this.datatype = datatype; + this.scope = scope; + this.parent = parent; + this.type = type; + this.value = value; + this.nillable = nillable; + this.substitutionGroup = substitutionGroup; + this.substitutionGroupExclusions = substitutionGroupExclusions; + this.disallowedSubstitutions = disallowedSubstitutions; + this.isAbstract = isAbstract; + } + +} + diff --git a/libjava/classpath/gnu/xml/validation/xmlschema/Particle.java b/libjava/classpath/gnu/xml/validation/xmlschema/Particle.java new file mode 100644 index 0000000..995c4ff --- /dev/null +++ b/libjava/classpath/gnu/xml/validation/xmlschema/Particle.java @@ -0,0 +1,61 @@ +/* Particle.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.xmlschema; + +/** + * Container for element content. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +class Particle +{ + + final Integer minOccurs; + final Integer maxOccurs; + + final Object term; + + Particle(Integer minOccurs, Integer maxOccurs, Object term) + { + this.minOccurs = minOccurs; + this.maxOccurs = maxOccurs; + this.term = term; + } + +} + diff --git a/libjava/classpath/gnu/xml/validation/xmlschema/ValidationException.java b/libjava/classpath/gnu/xml/validation/xmlschema/ValidationException.java new file mode 100644 index 0000000..f2d6843 --- /dev/null +++ b/libjava/classpath/gnu/xml/validation/xmlschema/ValidationException.java @@ -0,0 +1,58 @@ +/* ValidationException.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.xmlschema; + +import org.xml.sax.Locator; +import org.xml.sax.SAXParseException; + +/** + * An XML Schema validation rule violation. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +class ValidationException + extends SAXParseException +{ + + ValidationException(String message, Locator locator) + { + super(message, locator); + } + +} + diff --git a/libjava/classpath/gnu/xml/validation/xmlschema/XMLSchema.java b/libjava/classpath/gnu/xml/validation/xmlschema/XMLSchema.java new file mode 100644 index 0000000..647cbde --- /dev/null +++ b/libjava/classpath/gnu/xml/validation/xmlschema/XMLSchema.java @@ -0,0 +1,134 @@ +/* XMLSchema.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.xmlschema; + +import java.util.LinkedHashMap; +import java.util.Map; +import javax.xml.validation.Schema; +import javax.xml.validation.Validator; +import javax.xml.validation.ValidatorHandler; + +/** + * An XML Schema schema. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +final class XMLSchema + extends Schema +{ + + static final int FINAL_NONE = 0x00; + static final int FINAL_EXTENSION = 0x01; + static final int FINAL_RESTRICTION = 0x02; + static final int FINAL_LIST = 0x04; + static final int FINAL_UNION = 0x08; + static final int FINAL_ALL = 0x0f; + + static final int BLOCK_NONE = 0x00; + static final int BLOCK_EXTENSION = 0x01; + static final int BLOCK_RESTRICTION = 0x02; + static final int BLOCK_SUBSTITUTION = 0x04; + static final int BLOCK_ALL = 0x07; + + static final int GLOBAL = 0x00; + static final int LOCAL = 0x01; + static final int ABSENT = 0x02; + + static final int CONSTRAINT_NONE = 0x00; + static final int CONSTRAINT_DEFAULT = 0x01; + static final int CONSTRAINT_FIXED = 0x02; + + static final int CONTENT_EMPTY = 0x00; + static final int CONTENT_SIMPLE = 0x01; + static final int CONTENT_MIXED = 0x02; + static final int CONTENT_ELEMENT_ONLY = 0x03; + + final String targetNamespace; + final String version; + final int finalDefault; + final int blockDefault; + final boolean attributeFormQualified; + final boolean elementFormQualified; + + /** + * The element declarations in this schema. + */ + final Map elementDeclarations; + + /** + * The attribute declarations in this schema. + */ + final Map attributeDeclarations; + + /** + * The type declarations in this schema. + */ + final Map types; + + XMLSchema(String targetNamespace, String version, + int finalDefault, int blockDefault, + boolean attributeFormQualified, + boolean elementFormQualified) + { + this.targetNamespace = targetNamespace; + this.version = version; + this.finalDefault = finalDefault; + this.blockDefault = blockDefault; + this.attributeFormQualified = attributeFormQualified; + this.elementFormQualified = elementFormQualified; + elementDeclarations = new LinkedHashMap(); + attributeDeclarations = new LinkedHashMap(); + types = new LinkedHashMap(); + } + + public Validator newValidator() + { + // TODO + //return new XMLSchemaValidator(this); + return null; + } + + public ValidatorHandler newValidatorHandler() + { + // TODO + //return new XMLSchemaValidatorHandler(this); + return null; + } + +} + diff --git a/libjava/classpath/gnu/xml/validation/xmlschema/XMLSchemaAttributeTypeInfo.java b/libjava/classpath/gnu/xml/validation/xmlschema/XMLSchemaAttributeTypeInfo.java new file mode 100644 index 0000000..758bc94 --- /dev/null +++ b/libjava/classpath/gnu/xml/validation/xmlschema/XMLSchemaAttributeTypeInfo.java @@ -0,0 +1,100 @@ +/* XMLSchemaAttributeTypeInfo.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.xmlschema; + +import org.w3c.dom.TypeInfo; +import gnu.xml.validation.datatype.SimpleType; + +/** + * Attribute type information provided by validation against an XML Schema. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +final class XMLSchemaAttributeTypeInfo + extends XMLSchemaTypeInfo +{ + + final XMLSchema schema; + final AttributeDeclaration decl; + final SimpleType type; + boolean id; + final boolean specified; + + XMLSchemaAttributeTypeInfo(XMLSchema schema, AttributeDeclaration decl, + boolean specified) + { + this.schema = schema; + this.decl = decl; + this.specified = specified; + type = (decl == null) ? null : decl.datatype; + } + + public String getTypeName() + { + if (type == null) + { + return "CDATA"; + } + return type.name.getLocalPart(); + } + + public String getTypeNamespace() + { + if (type == null) + { + return ""; + } + return type.name.getNamespaceURI(); + } + + public boolean isDerivedFrom(String typeNamespace, String typeName, + int derivationMethod) + { + if (type == null) + { + return false; + } + else + { + return simpleTypeIsDerivedFrom(type, typeNamespace, typeName, + derivationMethod); + } + } + +} + diff --git a/libjava/classpath/gnu/xml/validation/xmlschema/XMLSchemaBuilder.java b/libjava/classpath/gnu/xml/validation/xmlschema/XMLSchemaBuilder.java new file mode 100644 index 0000000..ddf9140 --- /dev/null +++ b/libjava/classpath/gnu/xml/validation/xmlschema/XMLSchemaBuilder.java @@ -0,0 +1,844 @@ +/* XMLSchemaBuilder.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.xmlschema; + +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; +import java.util.StringTokenizer; +import javax.xml.XMLConstants; +import javax.xml.namespace.QName; +import org.relaxng.datatype.DatatypeException; +import org.relaxng.datatype.DatatypeLibrary; +import org.relaxng.datatype.helpers.DatatypeLibraryLoader; +import org.w3c.dom.NamedNodeMap; +import org.w3c.dom.Node; +import gnu.xml.validation.datatype.Annotation; +import gnu.xml.validation.datatype.AtomicSimpleType; +import gnu.xml.validation.datatype.ListSimpleType; +import gnu.xml.validation.datatype.SimpleType; +import gnu.xml.validation.datatype.Type; +import gnu.xml.validation.datatype.UnionSimpleType; + +/** + * Parses an XML Schema DOM tree, constructing a compiled internal + * representation. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +class XMLSchemaBuilder +{ + + XMLSchema schema; + final DatatypeLibrary typeLibrary; + + XMLSchemaBuilder() + { + final String ns = XMLConstants.W3C_XML_SCHEMA_NS_URI; + typeLibrary = new DatatypeLibraryLoader().createDatatypeLibrary(ns); + } + + void parseSchema(Node node) + throws DatatypeException + { + String uri = node.getNamespaceURI(); + String name = node.getLocalName(); + if (XMLConstants.W3C_XML_SCHEMA_NS_URI.equals(uri) && + node.getNodeType() == Node.ELEMENT_NODE) + { + if ("schema".equals(name)) + { + NamedNodeMap attrs = node.getAttributes(); + String targetNamespace = getAttribute(attrs, "targetNamespace"); + String version = getAttribute(attrs, "version"); + String fd = getAttribute(attrs, "finalDefault"); + int finalDefault = parseFullDerivationSet(fd); + String bd = getAttribute(attrs, "blockDefault"); + int blockDefault = parseBlockSet(bd); + String afd = getAttribute(attrs, "attributeFormDefault"); + boolean attributeFormQualified = "qualified".equals(afd); + String efd = getAttribute(attrs, "elementFormDefault"); + boolean elementFormQualified = "qualified".equals(efd); + schema = new XMLSchema(targetNamespace, version, + finalDefault, blockDefault, + attributeFormQualified, + elementFormQualified); + for (Node child = node.getFirstChild(); child != null; + child = child.getNextSibling()) + { + parseTopLevelElement(child); + } + return; + } + } + // TODO throw schema exception + } + + void parseTopLevelElement(Node node) + throws DatatypeException + { + String uri = node.getNamespaceURI(); + String name = node.getLocalName(); + if (XMLConstants.W3C_XML_SCHEMA_NS_URI.equals(uri) && + node.getNodeType() == Node.ELEMENT_NODE) + { + if ("element".equals(name)) + { + ElementDeclaration ed = + (ElementDeclaration) parseElement(node, null); + schema.elementDeclarations.put(ed.name, ed); + // TODO + } + else if ("attribute".equals(name)) + { + AttributeDeclaration ad = + (AttributeDeclaration) parseAttribute(node, true); + schema.attributeDeclarations.put(ad.name, ad); + // TODO + } + else if ("type".equals(name)) + { + // TODO + } + else if ("group".equals(name)) + { + // TODO + } + else if ("attributeGroup".equals(name)) + { + // TODO + } + else if ("notation".equals(name)) + { + // TODO + } + else if ("identityConstraint".equals(name)) + { + // TODO + } + } + // TODO throw schema exception + } + + Object parseAttribute(Node node, boolean scope) + throws DatatypeException + { + NamedNodeMap attrs = node.getAttributes(); + String def = getAttribute(attrs, "default"); + String fixed = getAttribute(attrs, "fixed"); + int constraintType = AttributeDeclaration.NONE; + String constraintValue = null; + if (def != null) + { + constraintType = AttributeDeclaration.DEFAULT; + constraintValue = def; + } + else if (fixed != null) + { + constraintType = AttributeDeclaration.FIXED; + constraintValue = fixed; + } + // TODO form = (qualified | unqualified) + String attrName = getAttribute(attrs, "name"); + String attrNamespace = getAttribute(attrs, "targetNamespace"); + String ref = getAttribute(attrs, "ref"); + String use = getAttribute(attrs, "use"); + String type = getAttribute(attrs, "type"); + SimpleType datatype = (type == null) ? null : + parseSimpleType(asQName(type, node)); + Annotation annotation = null; + for (Node child = node.getFirstChild(); child != null; + child = child.getNextSibling()) + { + String uri = child.getNamespaceURI(); + String name = child.getLocalName(); + if (XMLConstants.W3C_XML_SCHEMA_NS_URI.equals(uri) && + child.getNodeType() == Node.ELEMENT_NODE) + { + if ("annotation".equals(name)) + { + annotation = parseAnnotation(child); + } + else if ("simpleType".equals(name)) + { + datatype = parseSimpleType(child); + } + else + { + // TODO throw schema exception + } + } + } + if (scope) + { + return new AttributeDeclaration(scope, + constraintType, + constraintValue, + new QName(attrNamespace, attrName), + datatype, + annotation); + } + else + { + boolean required = "required".equals(use); + // TODO ref + AttributeDeclaration decl = (ref == null) ? + new AttributeDeclaration(scope, + AttributeDeclaration.NONE, + null, + new QName(attrNamespace, attrName), + datatype, + annotation) : + /*schema.getAttributeDeclaration(ref)*/ null; + return new AttributeUse(required, + constraintType, + constraintValue, + decl); + } + } + + int parseFullDerivationSet(String value) + { + int ret = XMLSchema.FINAL_NONE; + if ("#all".equals(value)) + { + ret = XMLSchema.FINAL_ALL; + } + else + { + StringTokenizer st = new StringTokenizer(value, " "); + while (st.hasMoreTokens()) + { + String token = st.nextToken(); + if ("extension".equals(token)) + { + ret |= XMLSchema.FINAL_EXTENSION; + } + else if ("restriction".equals(token)) + { + ret |= XMLSchema.FINAL_RESTRICTION; + } + else if ("list".equals(token)) + { + ret |= XMLSchema.FINAL_LIST; + } + else if ("union".equals(token)) + { + ret |= XMLSchema.FINAL_UNION; + } + } + } + return ret; + } + + int parseSimpleTypeDerivationSet(String value) + { + int ret = XMLSchema.FINAL_NONE; + if ("#all".equals(value)) + { + ret = XMLSchema.FINAL_LIST | + XMLSchema.FINAL_UNION | + XMLSchema.FINAL_RESTRICTION; + } + else + { + StringTokenizer st = new StringTokenizer(value, " "); + while (st.hasMoreTokens()) + { + String token = st.nextToken(); + if ("list".equals(token)) + { + ret |= XMLSchema.FINAL_LIST; + } + else if ("union".equals(token)) + { + ret |= XMLSchema.FINAL_UNION; + } + else if ("restriction".equals(token)) + { + ret |= XMLSchema.FINAL_RESTRICTION; + } + } + } + return ret; + } + + int parseComplexTypeDerivationSet(String value) + { + int ret = XMLSchema.FINAL_NONE; + if ("#all".equals(value)) + { + ret = XMLSchema.FINAL_EXTENSION | XMLSchema.FINAL_RESTRICTION; + } + else + { + StringTokenizer st = new StringTokenizer(value, " "); + while (st.hasMoreTokens()) + { + String token = st.nextToken(); + if ("extension".equals(token)) + { + ret |= XMLSchema.FINAL_EXTENSION; + } + else if ("restriction".equals(token)) + { + ret |= XMLSchema.FINAL_RESTRICTION; + } + } + } + return ret; + } + + int parseBlockSet(String value) + { + int ret = XMLSchema.BLOCK_NONE; + if ("#all".equals(value)) + { + ret = XMLSchema.BLOCK_ALL; + } + else + { + StringTokenizer st = new StringTokenizer(value, " "); + while (st.hasMoreTokens()) + { + String token = st.nextToken(); + if ("extension".equals(token)) + { + ret |= XMLSchema.BLOCK_EXTENSION; + } + else if ("restriction".equals(token)) + { + ret |= XMLSchema.BLOCK_RESTRICTION; + } + else if ("substitution".equals(token)) + { + ret |= XMLSchema.BLOCK_SUBSTITUTION; + } + } + } + return ret; + } + + int parseComplexTypeBlockSet(String value) + { + int ret = XMLSchema.BLOCK_NONE; + if ("#all".equals(value)) + { + ret = XMLSchema.BLOCK_EXTENSION | XMLSchema.BLOCK_RESTRICTION; + } + else + { + StringTokenizer st = new StringTokenizer(value, " "); + while (st.hasMoreTokens()) + { + String token = st.nextToken(); + if ("extension".equals(token)) + { + ret |= XMLSchema.BLOCK_EXTENSION; + } + else if ("restriction".equals(token)) + { + ret |= XMLSchema.BLOCK_RESTRICTION; + } + } + } + return ret; + } + + Object parseElement(Node node, ElementDeclaration parent) + throws DatatypeException + { + NamedNodeMap attrs = node.getAttributes(); + Integer minOccurs = null; + Integer maxOccurs = null; + Node parentNode = node.getParentNode(); + boolean notTopLevel = !"schema".equals(parentNode.getLocalName()); + if (notTopLevel) + { + String ref = getAttribute(attrs, "ref"); + if (ref != null) + { + minOccurs = getOccurrence(getAttribute(attrs, "minOccurs")); + maxOccurs = getOccurrence(getAttribute(attrs, "maxOccurs")); + // TODO resolve top-level element declaration + ElementDeclaration ad = null; + return new Particle(minOccurs, maxOccurs, ad); + } + } + String elementName = getAttribute(attrs, "name"); + String elementNamespace = getAttribute(attrs, "targetNamespace"); + String type = getAttribute(attrs, "type"); + Type datatype = (type != null) ? + parseSimpleType(asQName(type, node)) : null; + int scope = (parent == null) ? + XMLSchema.GLOBAL : + XMLSchema.LOCAL; + String def = getAttribute(attrs, "default"); + String fixed = getAttribute(attrs, "fixed"); + int constraintType = AttributeDeclaration.NONE; + String constraintValue = null; + if (def != null) + { + constraintType = AttributeDeclaration.DEFAULT; + constraintValue = def; + } + else if (fixed != null) + { + constraintType = AttributeDeclaration.FIXED; + constraintValue = fixed; + } + String sg = getAttribute(attrs, "substitutionGroup"); + QName substitutionGroup = QName.valueOf(sg); + String sgPrefix = substitutionGroup.getPrefix(); + if (sgPrefix != null && !"".equals(sgPrefix)) + { + String sgName = substitutionGroup.getLocalPart(); + String sgNamespace = node.lookupNamespaceURI(sgPrefix); + substitutionGroup = new QName(sgNamespace, sgName); + } + + String block = getAttribute(attrs, "block"); + int substitutionGroupExclusions = (block == null) ? + schema.blockDefault : + parseBlockSet(block); + String final_ = getAttribute(attrs, "final"); + int disallowedSubstitutions = (final_ == null) ? + schema.finalDefault : + parseFullDerivationSet(final_); + + boolean nillable = "true".equals(getAttribute(attrs, "nillable")); + boolean isAbstract = "true".equals(getAttribute(attrs, "abstract")); + + if (notTopLevel) + { + minOccurs = getOccurrence(getAttribute(attrs, "minOccurs")); + maxOccurs = getOccurrence(getAttribute(attrs, "maxOccurs")); + String form = getAttribute(attrs, "form"); + if (form != null) + { + if ("qualified".equals(form)) + { + elementNamespace = schema.targetNamespace; + } + } + else if (schema.elementFormQualified) + { + elementNamespace = schema.targetNamespace; + } + } + ElementDeclaration ed = + new ElementDeclaration(new QName(elementNamespace, elementName), + datatype, + scope, parent, + constraintType, constraintValue, + nillable, + substitutionGroup, + substitutionGroupExclusions, + disallowedSubstitutions, + isAbstract); + + for (Node child = node.getFirstChild(); child != null; + child = child.getNextSibling()) + { + String uri = child.getNamespaceURI(); + String name = child.getLocalName(); + if (XMLConstants.W3C_XML_SCHEMA_NS_URI.equals(uri) && + child.getNodeType() == Node.ELEMENT_NODE) + { + if ("annotation".equals(name)) + { + ed.annotation = parseAnnotation(child); + } + else if ("simpleType".equals(name) && datatype == null) + { + ed.datatype = parseSimpleType(child); + } + else if ("complexType".equals(name) && datatype == null) + { + ed.datatype = parseComplexType(child, ed); + } + else + { + // throw schema exception + } + } + } + + if (notTopLevel) + { + return new Particle(minOccurs, maxOccurs, ed); + } + else + { + return ed; + } + } + + Integer getOccurrence(String value) + { + if (value == null) + { + return new Integer(1); + } + else if ("unbounded".equals(value)) + { + return null; + } + else + { + return new Integer(value); + } + } + + SimpleType parseSimpleType(QName typeName) + throws DatatypeException + { + SimpleType type = (SimpleType) schema.types.get(typeName); + if (!XMLConstants.W3C_XML_SCHEMA_NS_URI.equals(typeName.getNamespaceURI())) + return null; + String localName = typeName.getLocalPart(); + return (SimpleType) typeLibrary.createDatatype(localName); + } + + SimpleType parseSimpleType(Node simpleType) + throws DatatypeException + { + NamedNodeMap attrs = simpleType.getAttributes(); + String typeFinal = getAttribute(attrs, "final"); + if (typeFinal == null) + { + Node schema = simpleType.getParentNode(); + while (schema != null && !"schema".equals(schema.getLocalName())) + { + schema = schema.getParentNode(); + } + if (schema != null) + { + NamedNodeMap schemaAttrs = schema.getAttributes(); + typeFinal = getAttribute(schemaAttrs, "finalDefault"); + } + } + int typeFinality = parseSimpleTypeDerivationSet(typeFinal); + QName typeName = asQName(getAttribute(attrs, "name"), simpleType); + int variety = 0; + Set facets = new LinkedHashSet(); + int fundamentalFacets = 0; // TODO + SimpleType baseType = null; // TODO + Annotation annotation = null; + // TODO use DatatypeBuilder + for (Node child = simpleType.getFirstChild(); child != null; + child = child.getNextSibling()) + { + String uri = child.getNamespaceURI(); + String name = child.getLocalName(); + if (XMLConstants.W3C_XML_SCHEMA_NS_URI.equals(uri) && + child.getNodeType() == Node.ELEMENT_NODE) + { + if ("annotation".equals(name)) + { + annotation = parseAnnotation(child); + } + else if ("restriction".equals(name)) + { + // TODO + } + else if ("list".equals(name)) + { + variety = SimpleType.LIST; + // TODO + } + else if ("union".equals(name)) + { + variety = SimpleType.UNION; + // TODO + } + } + } + return new SimpleType(typeName, variety, facets, fundamentalFacets, + baseType, annotation); + } + + Type parseComplexType(Node complexType, ElementDeclaration parent) + throws DatatypeException + { + NamedNodeMap attrs = complexType.getAttributes(); + QName typeName = asQName(getAttribute(attrs, "name"), complexType); + boolean isAbstract = "true".equals(getAttribute(attrs, "abstract")); + String block = getAttribute(attrs, "block"); + int prohibitedSubstitutions = (block == null) ? + schema.blockDefault : + parseComplexTypeBlockSet(block); + String final_ = getAttribute(attrs, "final"); + int finality = (final_ == null) ? + schema.finalDefault : + parseComplexTypeDerivationSet(final_); + ComplexType type = new ComplexType(typeName, isAbstract, + prohibitedSubstitutions, finality); + boolean mixed = "true".equals(getAttribute(attrs, "mixed")); + for (Node child = complexType.getFirstChild(); child != null; + child = child.getNextSibling()) + { + String uri = child.getNamespaceURI(); + String name = child.getLocalName(); + if (XMLConstants.W3C_XML_SCHEMA_NS_URI.equals(uri) && + child.getNodeType() == Node.ELEMENT_NODE) + { + if ("simpleContent".equals(name)) + { + parseSimpleContent(child, type); + } + } + } + if (mixed) + { + type.contentType = XMLSchema.CONTENT_MIXED; + } + return type; + } + + void parseSimpleContent(Node simpleContent, ComplexType type) + throws DatatypeException + { + for (Node child = simpleContent.getFirstChild(); child != null; + child = child.getNextSibling()) + { + String uri = child.getNamespaceURI(); + String name = child.getLocalName(); + if (XMLConstants.W3C_XML_SCHEMA_NS_URI.equals(uri) && + child.getNodeType() == Node.ELEMENT_NODE) + { + if ("annotation".equals(name)) + { + type.annotations.add(parseAnnotation(child)); + } + else if ("restriction".equals(name)) + { + type.derivationMethod = XMLSchema.FINAL_RESTRICTION; + parseRestriction(child, type); + } + else if ("extension".equals(name)) + { + type.derivationMethod = XMLSchema.FINAL_EXTENSION; + parseExtension(child, type); + } + } + } + } + + void parseRestriction(Node restriction, ComplexType type) + throws DatatypeException + { + NamedNodeMap attrs = restriction.getAttributes(); + String base = getAttribute(attrs, "base"); + QName baseType = asQName(base, restriction); + SimpleType simpleType = null; + for (Node child = restriction.getFirstChild(); child != null; + child = child.getNextSibling()) + { + String uri = child.getNamespaceURI(); + String name = child.getLocalName(); + if (XMLConstants.W3C_XML_SCHEMA_NS_URI.equals(uri) && + child.getNodeType() == Node.ELEMENT_NODE) + { + if ("annotation".equals(name)) + { + type.annotations.add(parseAnnotation(child)); + } + else if ("simpleType".equals(name)) + { + type.contentType = XMLSchema.CONTENT_SIMPLE; + simpleType = parseSimpleType(child); + } + else if ("minExclusive".equals(name)) + { + } + else if ("minInclusive".equals(name)) + { + } + else if ("maxExclusive".equals(name)) + { + } + else if ("maxInclusive".equals(name)) + { + } + else if ("totalDigits".equals(name)) + { + } + else if ("fractionDigits".equals(name)) + { + } + else if ("length".equals(name)) + { + } + else if ("minLength".equals(name)) + { + } + else if ("maxLength".equals(name)) + { + } + else if ("enumeration".equals(name)) + { + } + else if ("whiteSpace".equals(name)) + { + } + else if ("pattern".equals(name)) + { + } + else if ("attribute".equals(name)) + { + AttributeUse use = + (AttributeUse) parseAttribute(child, false); + schema.attributeDeclarations.put(use.declaration.name, + use.declaration); + type.attributeUses.add(use); + } + else if ("attributeGroup".equals(name)) + { + NamedNodeMap agAttrs = child.getAttributes(); + String ref = getAttribute(agAttrs, "ref"); + QName ag = asQName(ref, child); + type.attributeUses.add(ag); + } + else if ("anyAttribute".equals(name)) + { + type.attributeWildcard = parseAnyAttribute(child); + } + } + } + } + + void parseExtension(Node extension, ComplexType type) + throws DatatypeException + { + NamedNodeMap attrs = extension.getAttributes(); + String base = getAttribute(attrs, "base"); + QName baseType = asQName(base, extension); + for (Node child = extension.getFirstChild(); child != null; + child = child.getNextSibling()) + { + String uri = child.getNamespaceURI(); + String name = child.getLocalName(); + if (XMLConstants.W3C_XML_SCHEMA_NS_URI.equals(uri) && + child.getNodeType() == Node.ELEMENT_NODE) + { + if ("annotation".equals(name)) + { + type.annotations.add(parseAnnotation(child)); + } + else if ("attribute".equals(name)) + { + AttributeUse use = + (AttributeUse) parseAttribute(child, false); + schema.attributeDeclarations.put(use.declaration.name, + use.declaration); + type.attributeUses.add(use); + } + else if ("attributeGroup".equals(name)) + { + NamedNodeMap agAttrs = child.getAttributes(); + String ref = getAttribute(agAttrs, "ref"); + QName ag = asQName(ref, child); + type.attributeUses.add(ag); + } + else if ("anyAttribute".equals(name)) + { + type.attributeWildcard = parseAnyAttribute(child); + } + } + } + } + + AnyAttribute parseAnyAttribute(Node node) + { + NamedNodeMap attrs = node.getAttributes(); + String namespace = getAttribute(attrs, "namespace"); + String pc = getAttribute(attrs, "processContents"); + int processContents = AnyAttribute.STRICT; + if ("lax".equals(pc)) + { + processContents = AnyAttribute.LAX; + } + else if ("skip".equals(pc)) + { + processContents = AnyAttribute.SKIP; + } + AnyAttribute ret = new AnyAttribute(namespace, processContents); + for (Node child = node.getFirstChild(); child != null; + child = child.getNextSibling()) + { + String uri = child.getNamespaceURI(); + String name = child.getLocalName(); + if (XMLConstants.W3C_XML_SCHEMA_NS_URI.equals(uri) && + child.getNodeType() == Node.ELEMENT_NODE) + { + if ("annotation".equals(name)) + { + ret.annotation = parseAnnotation(child); + } + } + } + return ret; + } + + Annotation parseAnnotation(Node node) + { + // TODO + return null; + } + + private static String getAttribute(NamedNodeMap attrs, String name) + { + Node attr = attrs.getNamedItem(name); + return (attr == null) ? null : attr.getNodeValue(); + } + + private static QName asQName(String text, Node resolver) + { + QName name = QName.valueOf(text); + String prefix = name.getPrefix(); + if (prefix != null && prefix.length() > 0) + { + String uri = resolver.lookupNamespaceURI(prefix); + name = new QName(uri, name.getLocalPart()); + } + return name; + } + +} + diff --git a/libjava/classpath/gnu/xml/validation/xmlschema/XMLSchemaElementTypeInfo.java b/libjava/classpath/gnu/xml/validation/xmlschema/XMLSchemaElementTypeInfo.java new file mode 100644 index 0000000..98a5fb7 --- /dev/null +++ b/libjava/classpath/gnu/xml/validation/xmlschema/XMLSchemaElementTypeInfo.java @@ -0,0 +1,93 @@ +/* XMLSchemaElementTypeInfo.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.xmlschema; + +import org.w3c.dom.TypeInfo; +import gnu.xml.validation.datatype.SimpleType; +import gnu.xml.validation.datatype.Type; + +/** + * Element type information provided by validation against an XML Schema. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +final class XMLSchemaElementTypeInfo + extends XMLSchemaTypeInfo +{ + + final XMLSchema schema; + final ElementDeclaration decl; + final Type type; + boolean nil; + + XMLSchemaElementTypeInfo(XMLSchema schema, ElementDeclaration decl, + Type type) + { + this.schema = schema; + this.decl = decl; + this.type = type; + } + + public String getTypeName() + { + return type.name.getLocalPart(); + } + + public String getTypeNamespace() + { + return type.name.getNamespaceURI(); + } + + public boolean isDerivedFrom(String typeNamespace, String typeName, + int derivationMethod) + { + if (type instanceof SimpleType) + { + SimpleType simpleType = (SimpleType) type; + return simpleTypeIsDerivedFrom(simpleType, typeNamespace, typeName, + derivationMethod); + } + else + { + // TODO + return false; + } + } + +} + diff --git a/libjava/classpath/gnu/xml/validation/xmlschema/XMLSchemaSchemaFactory.java b/libjava/classpath/gnu/xml/validation/xmlschema/XMLSchemaSchemaFactory.java new file mode 100644 index 0000000..b37ae54 --- /dev/null +++ b/libjava/classpath/gnu/xml/validation/xmlschema/XMLSchemaSchemaFactory.java @@ -0,0 +1,159 @@ +/* XMLSchemaSchemaFactory.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.xmlschema; + +import java.io.IOException; +import java.net.URL; +import javax.xml.XMLConstants; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.Source; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamSource; +import javax.xml.validation.Schema; +import javax.xml.validation.SchemaFactory; +import org.relaxng.datatype.DatatypeException; +import org.w3c.dom.Document; +import org.w3c.dom.Node; +import org.w3c.dom.ls.LSResourceResolver; +import org.xml.sax.InputSource; +import org.xml.sax.SAXException; + +/** + * Schema factory for W3C XML Schema schemata. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +public class XMLSchemaSchemaFactory + extends SchemaFactory +{ + + LSResourceResolver resourceResolver; + + public LSResourceResolver getResourceResolver() + { + return resourceResolver; + } + + public void setResourceResolver(LSResourceResolver resourceResolver) + { + this.resourceResolver = resourceResolver; + } + + public boolean isSchemaLanguageSupported(String schemaLanguage) + { + return XMLConstants.W3C_XML_SCHEMA_NS_URI.equals(schemaLanguage); + } + + public Schema newSchema() + throws SAXException + { + // TODO + throw new UnsupportedOperationException(); + } + + public Schema newSchema(Source[] schemata) + throws SAXException + { + if (schemata == null || schemata.length != 1) + throw new IllegalArgumentException("must specify one source"); + // TODO multiple sources + try + { + Document doc = getDocument(schemata[0]); + XMLSchemaBuilder builder = new XMLSchemaBuilder(); + builder.parseSchema(doc); + return builder.schema; + } + catch (IOException e) + { + SAXException e2 = new SAXException(e.getMessage()); + e2.initCause(e); + throw e2; + } + catch (DatatypeException e) + { + SAXException e2 = new SAXException(e.getMessage()); + e2.initCause(e); + throw e2; + } + } + + private static Document getDocument(Source source) + throws SAXException, IOException + { + if (source instanceof DOMSource) + { + Node node = ((DOMSource) source).getNode(); + if (node != null && node instanceof Document) + return (Document) node; + } + String url = source.getSystemId(); + try + { + InputSource input = new InputSource(url); + if (source instanceof StreamSource) + { + StreamSource streamSource = (StreamSource) source; + input.setByteStream(streamSource.getInputStream()); + input.setCharacterStream(streamSource.getReader()); + } + if (input.getByteStream() == null && + input.getCharacterStream() == null && + url != null) + input.setByteStream(new URL(url).openStream()); + DocumentBuilderFactory f = DocumentBuilderFactory.newInstance(); + f.setNamespaceAware(true); + f.setCoalescing(true); + f.setExpandEntityReferences(true); + f.setIgnoringComments(true); + f.setIgnoringElementContentWhitespace(true); + DocumentBuilder b = f.newDocumentBuilder(); + return b.parse(input); + } + catch (ParserConfigurationException e) + { + SAXException e2 = new SAXException(e.getMessage()); + e2.initCause(e); + throw e2; + } + } + +} + diff --git a/libjava/classpath/gnu/xml/validation/xmlschema/XMLSchemaTypeInfo.java b/libjava/classpath/gnu/xml/validation/xmlschema/XMLSchemaTypeInfo.java new file mode 100644 index 0000000..60cc25f --- /dev/null +++ b/libjava/classpath/gnu/xml/validation/xmlschema/XMLSchemaTypeInfo.java @@ -0,0 +1,77 @@ +/* XMLSchemaTypeInfo.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.xmlschema; + +import org.w3c.dom.TypeInfo; +import gnu.xml.validation.datatype.SimpleType; + +/** + * Abstract superclass providing simple type derivation. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +abstract class XMLSchemaTypeInfo + implements TypeInfo +{ + + protected boolean simpleTypeIsDerivedFrom(SimpleType simpleType, + String typeNamespace, + String typeName, + int derivationMethod) + { + switch (derivationMethod) + { + case TypeInfo.DERIVATION_RESTRICTION: + SimpleType baseType = simpleType.baseType; + while (baseType != null) + { + if (baseType.name.getNamespaceURI().equals(typeNamespace) && + baseType.name.getLocalPart().equals(typeName)) + { + return true; + } + baseType = baseType.baseType; + } + break; + // TODO other methods + } + return false; + } + +} + diff --git a/libjava/classpath/gnu/xml/validation/xmlschema/XMLSchemaTypeInfoProvider.java b/libjava/classpath/gnu/xml/validation/xmlschema/XMLSchemaTypeInfoProvider.java new file mode 100644 index 0000000..9b20c0c --- /dev/null +++ b/libjava/classpath/gnu/xml/validation/xmlschema/XMLSchemaTypeInfoProvider.java @@ -0,0 +1,82 @@ +/* XMLSchemaTypeInfoProvider.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.xmlschema; + +import javax.xml.validation.TypeInfoProvider; +import org.w3c.dom.TypeInfo; + +/** + * TypeInfo provider for XML Schema validator handler. + * This simply delegates to the handler. It wouldn't be required if + * TypeInfoProvider were an interface instead of an abstract class. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +final class XMLSchemaTypeInfoProvider + extends TypeInfoProvider +{ + + final XMLSchemaValidatorHandler handler; + + XMLSchemaTypeInfoProvider(XMLSchemaValidatorHandler handler) + { + this.handler = handler; + } + + public TypeInfo getElementTypeInfo() + { + return handler.getElementTypeInfo(); + } + + public TypeInfo getAttributeTypeInfo(int index) + { + return handler.getAttributeTypeInfo(index); + } + + public boolean isIdAttribute(int index) + { + return handler.isIdAttribute(index); + } + + public boolean isSpecified(int index) + { + return handler.isSpecified(index); + } + +} + diff --git a/libjava/classpath/gnu/xml/validation/xmlschema/XMLSchemaValidator.java b/libjava/classpath/gnu/xml/validation/xmlschema/XMLSchemaValidator.java new file mode 100644 index 0000000..056babf --- /dev/null +++ b/libjava/classpath/gnu/xml/validation/xmlschema/XMLSchemaValidator.java @@ -0,0 +1,98 @@ +/* XMLSchemaValidator.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.xmlschema; + +import java.io.IOException; +import javax.xml.validation.Validator; +import javax.xml.transform.Result; +import javax.xml.transform.Source; +import org.w3c.dom.ls.LSResourceResolver; +import org.xml.sax.ErrorHandler; +import org.xml.sax.SAXException; + +/** + * JAXP validator for an XML Schema. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +final class XMLSchemaValidator + extends Validator +{ + + final XMLSchema schema; + + ErrorHandler errorHandler; + LSResourceResolver resourceResolver; + + XMLSchemaValidator(XMLSchema schema) + { + this.schema = schema; + } + + public void reset() + { + } + + public void validate(Source source, Result result) + throws SAXException, IOException + { + // TODO + } + + public ErrorHandler getErrorHandler() + { + return errorHandler; + } + + public void setErrorHandler(ErrorHandler errorHandler) + { + this.errorHandler = errorHandler; + } + + public LSResourceResolver getResourceResolver() + { + return resourceResolver; + } + + public void setResourceResolver(LSResourceResolver resourceResolver) + { + this.resourceResolver = resourceResolver; + } + +} + diff --git a/libjava/classpath/gnu/xml/validation/xmlschema/XMLSchemaValidatorHandler.java b/libjava/classpath/gnu/xml/validation/xmlschema/XMLSchemaValidatorHandler.java new file mode 100644 index 0000000..9e6d8e9 --- /dev/null +++ b/libjava/classpath/gnu/xml/validation/xmlschema/XMLSchemaValidatorHandler.java @@ -0,0 +1,394 @@ +/* XMLSchemaValidatorHandler.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.xmlschema; + +import java.util.ArrayList; +import java.util.LinkedList; +import javax.xml.XMLConstants; +import javax.xml.namespace.QName; +import javax.xml.validation.TypeInfoProvider; +import javax.xml.validation.ValidatorHandler; +import org.relaxng.datatype.DatatypeException; +import org.relaxng.datatype.DatatypeLibrary; +import org.relaxng.datatype.helpers.DatatypeLibraryLoader; +import org.w3c.dom.TypeInfo; +import org.w3c.dom.ls.LSResourceResolver; +import org.xml.sax.Attributes; +import org.xml.sax.ContentHandler; +import org.xml.sax.ErrorHandler; +import org.xml.sax.Locator; +import org.xml.sax.SAXException; +import org.xml.sax.ext.Attributes2Impl; +import org.xml.sax.helpers.NamespaceSupport; +import gnu.xml.validation.datatype.SimpleType; +import gnu.xml.validation.datatype.Type; + +/** + * Streaming validator. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +final class XMLSchemaValidatorHandler + extends ValidatorHandler +{ + + final XMLSchema schema; + final TypeInfoProvider typeInfoProvider; + final NamespaceSupport namespaceSupport; + final DatatypeLibrary typeLibrary; + Locator loc; + ContentHandler contentHandler; + ErrorHandler errorHandler; + LSResourceResolver resourceResolver; + final LinkedList context; // element context + final ArrayList attributes; // attribute context; + + XMLSchemaValidatorHandler(XMLSchema schema) + { + this.schema = schema; + typeInfoProvider = new XMLSchemaTypeInfoProvider(this); + namespaceSupport = new NamespaceSupport(); + context = new LinkedList(); + attributes = new ArrayList(); + final String ns = XMLConstants.W3C_XML_SCHEMA_NS_URI; + typeLibrary = new DatatypeLibraryLoader().createDatatypeLibrary(ns); + } + + public ContentHandler getContentHandler() + { + return contentHandler; + } + + public void setContentHandler(ContentHandler contentHandler) + { + this.contentHandler = contentHandler; + } + + public ErrorHandler getErrorHandler() + { + return errorHandler; + } + + public void setErrorHandler(ErrorHandler errorHandler) + { + this.errorHandler = errorHandler; + } + + public LSResourceResolver getResourceResolver() + { + return resourceResolver; + } + + public void setResourceResolver(LSResourceResolver resourceResolver) + { + this.resourceResolver = resourceResolver; + } + + public TypeInfoProvider getTypeInfoProvider() + { + return typeInfoProvider; + } + + TypeInfo getElementTypeInfo() + { + return (XMLSchemaElementTypeInfo) context.getFirst(); + } + + TypeInfo getAttributeTypeInfo(int index) + { + return (XMLSchemaAttributeTypeInfo) attributes.get(index); + } + + boolean isIdAttribute(int index) + { + XMLSchemaAttributeTypeInfo typeInfo = + (XMLSchemaAttributeTypeInfo) attributes.get(index); + return typeInfo.id; + } + + boolean isSpecified(int index) + { + XMLSchemaAttributeTypeInfo typeInfo = + (XMLSchemaAttributeTypeInfo) attributes.get(index); + return typeInfo.specified; + } + + public void setDocumentLocator(Locator locator) + { + loc = locator; + if (contentHandler != null) + { + contentHandler.setDocumentLocator(locator); + } + } + + public void startDocument() + throws SAXException + { + namespaceSupport.reset(); + context.clear(); + attributes.clear(); + if (contentHandler != null) + { + contentHandler.startDocument(); + } + } + + public void endDocument() + throws SAXException + { + if (contentHandler != null) + { + contentHandler.endDocument(); + } + } + + public void startPrefixMapping(String prefix, String uri) + throws SAXException + { + namespaceSupport.declarePrefix(prefix, uri); + if (contentHandler != null) + { + contentHandler.startPrefixMapping(prefix, uri); + } + } + + public void endPrefixMapping(String prefix) + throws SAXException + { + if (contentHandler != null) + { + contentHandler.endPrefixMapping(prefix); + } + } + + public void startElement(String uri, String localName, String qName, + Attributes atts) + throws SAXException + { + namespaceSupport.pushContext(); + QName name = new QName(uri, localName); + ElementDeclaration decl = + (ElementDeclaration) schema.elementDeclarations.get(name); + // Validation Rule: Element Locally Valid (Element) + String xsiType = + atts.getValue(XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI, "type"); + xsiType = xsiType.trim(); // normalise + String xsiNil = + atts.getValue(XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI, "nil"); + Type type = decl.datatype; + if (xsiType.length() > 0) + { + try + { + Type specifiedType = resolveType(xsiType); + // TODO 4.3 + type = specifiedType; + } + catch (DatatypeException e) // 4.1, 4.2 + { + ValidationException e2 = + new ValidationException("Can't resolve type " + xsiType, + loc); + e2.initCause(e); + throw e2; + } + } + XMLSchemaElementTypeInfo typeInfo = + new XMLSchemaElementTypeInfo(schema, decl, type); + if (decl == null) // 1 + { + throw new ValidationException("No declaration for " + name, loc); + } + if (decl.isAbstract) // 2 + { + throw new ValidationException("Declaration for " + name + + " is abstract", loc); + } + if (xsiNil.length() > 0) + { + if (!decl.nillable) // 3.1 + { + throw new ValidationException("Declaration for " + name + + " is nillable but xsi:nil present", + loc); + } + else if ("true".equals(xsiNil)) // 3.2 + { + typeInfo.nil = true; + if (decl.type == XMLSchema.CONSTRAINT_FIXED) // 3.2.2 + { + throw new ValidationException("Declaration for " + name + + " is fixed but xsi:nil is true", + loc); + } + } + } + // TODO 5, 6, 7 + + // parent + if (!context.isEmpty()) + { + XMLSchemaElementTypeInfo parent = + (XMLSchemaElementTypeInfo) context.getFirst(); + if (parent.nil) // Element Locally Valid (Element) 3.2.1 + { + throw new ValidationException("Parent of " + qName + + " is declared xsi:nil", loc); + } + // TODO + } + context.addFirst(typeInfo); + // attributes + int len = atts.getLength(); + Attributes2Impl atts2 = new Attributes2Impl(); + int count = 0; + for (int i = 0; i < len; i++) + { + String attUri = atts.getURI(i); + String attLocalName = atts.getLocalName(i); + String attQName = atts.getQName(i); + String attValue = atts.getValue(i); + + if (XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI.equals(attUri)) + { + continue; // ? + } + + QName attName = new QName(attUri, attLocalName); + AttributeDeclaration attDecl = + (AttributeDeclaration) schema.attributeDeclarations.get(attName); + boolean declared = (attDecl != null); + + String attType = (attDecl != null) ? + attDecl.datatype.toString() : "CDATA"; + XMLSchemaAttributeTypeInfo attTypeInfo = + new XMLSchemaAttributeTypeInfo(schema, attDecl, true); + attributes.add(attTypeInfo); + + atts2.addAttribute(attUri, attLocalName, attQName, attType, attValue); + atts2.setDeclared(count, declared); + atts2.setSpecified(count, true); + count++; + } + // add defaulted attributes to atts2 + // TODO + // atts2.setSpecified(count, false); + if (contentHandler != null) + { + contentHandler.startElement(uri, localName, qName, atts2); + } + } + + public void endElement(String uri, String localName, String qName) + throws SAXException + { + // TODO check all required have been seen + context.removeFirst(); + attributes.clear(); + namespaceSupport.popContext(); + if (contentHandler != null) + { + contentHandler.endElement(uri, localName, qName); + } + } + + public void characters(char[] ch, int start, int length) + throws SAXException + { + XMLSchemaElementTypeInfo parent = + (XMLSchemaElementTypeInfo) context.getFirst(); + if (parent.nil) // Element Locally Valid (Element) 3.2.1 + { + throw new ValidationException(parent.decl.name.toString() + + " is declared xsi:nil", + loc); + } + // TODO + if (contentHandler != null) + { + contentHandler.characters(ch, start, length); + } + } + + public void ignorableWhitespace(char[] ch, int start, int length) + throws SAXException + { + if (contentHandler != null) + { + contentHandler.ignorableWhitespace(ch, start, length); + } + } + + public void processingInstruction(String target, String data) + throws SAXException + { + if (contentHandler != null) + { + contentHandler.processingInstruction(target, data); + } + } + + public void skippedEntity(String name) + throws SAXException + { + if (contentHandler != null) + { + contentHandler.skippedEntity(name); + } + } + + Type resolveType(String value) + throws DatatypeException + { + QName name = QName.valueOf(value); + String prefix = name.getPrefix(); + String localName = name.getLocalPart(); + if (prefix != null && prefix.length() > 0) + { + String uri = namespaceSupport.getURI(prefix); + if (!XMLConstants.W3C_XML_SCHEMA_NS_URI.equals(uri)) + return null; + } + if ("anyType".equals(localName)) + return Type.ANY_TYPE; + return (SimpleType) typeLibrary.createDatatype(localName); + } + +} + diff --git a/libjava/classpath/gnu/xml/xpath/LangFunction.java b/libjava/classpath/gnu/xml/xpath/LangFunction.java index 2c2506d..584787e 100644 --- a/libjava/classpath/gnu/xml/xpath/LangFunction.java +++ b/libjava/classpath/gnu/xml/xpath/LangFunction.java @@ -1,5 +1,5 @@ /* LangFunction.java -- - Copyright (C) 2004 Free Software Foundation, Inc. + Copyright (C) 2004,2006 Free Software Foundation, Inc. This file is part of GNU Classpath. @@ -91,9 +91,15 @@ final class LangFunction String getLang(Node node) { - if (node.getNodeType() == Node.ELEMENT_NODE) + while (node != null) { - return ((Element) node).getAttribute("xml:lang"); + if (node.getNodeType() == Node.ELEMENT_NODE) + { + String lang = ((Element) node).getAttribute("xml:lang"); + if (lang != null) + return lang; + } + node = node.getParentNode(); } return null; } diff --git a/libjava/classpath/gnu/xml/xpath/NodeTypeTest.java b/libjava/classpath/gnu/xml/xpath/NodeTypeTest.java index 09e92d0..4fe1646 100644 --- a/libjava/classpath/gnu/xml/xpath/NodeTypeTest.java +++ b/libjava/classpath/gnu/xml/xpath/NodeTypeTest.java @@ -84,6 +84,7 @@ public final class NodeTypeTest case Node.TEXT_NODE: case Node.CDATA_SECTION_NODE: case Node.COMMENT_NODE: + case Node.DOCUMENT_NODE: if (type > 0) { if (nodeType != type) diff --git a/libjava/classpath/gnu/xml/xpath/Selector.java b/libjava/classpath/gnu/xml/xpath/Selector.java index 93408e4..c7abb33 100644 --- a/libjava/classpath/gnu/xml/xpath/Selector.java +++ b/libjava/classpath/gnu/xml/xpath/Selector.java @@ -90,7 +90,7 @@ public final class Selector if (len > 0) tests.toArray(this.tests); else - this.tests[0] = new NameTest(null, true, true); + this.tests[0] = new NodeTypeTest((short) 0); if (axis == NAMESPACE && this.tests[0] instanceof NameTest) { NameTest nt = (NameTest) this.tests[0]; @@ -108,6 +108,14 @@ public final class Selector public boolean matches(Node context) { + // If called directly, selector is the top level of the path + return matches(context, + getContextPosition(context), + getContextSize(context)); + } + + boolean matches(Node context, int pos, int len) + { short nodeType = context.getNodeType(); switch (axis) { @@ -125,19 +133,11 @@ public final class Selector default: return false; } - int tlen = tests.length; - if (tlen > 0) + for (int j = 0; j < tests.length && len > 0; j++) { - int pos = getContextPosition(context); - int len = getContextSize(context); - if (len == 0) - System.err.println("WARNING: context size is 0"); - for (int j = 0; j < tlen && len > 0; j++) - { - Test test = tests[j]; - if (!test.matches(context, pos, len)) - return false; - } + Test test = tests[j]; + if (!test.matches(context, pos, len)) + return false; } return true; } @@ -147,7 +147,10 @@ public final class Selector int pos = 1; for (ctx = ctx.getPreviousSibling(); ctx != null; ctx = ctx.getPreviousSibling()) - pos++; + { + if (tests[0].matches(ctx, 1, 1)) + pos++; + } return pos; } @@ -161,10 +164,16 @@ public final class Selector int count = 1; Node sib = ctx.getPreviousSibling(); for (; sib != null; sib = sib.getPreviousSibling()) - count++; + { + if (tests[0].matches(ctx, 1, 1)) + count++; + } sib = ctx.getNextSibling(); for (; sib != null; sib = sib.getNextSibling()) - count++; + { + if (tests[0].matches(ctx, 1, 1)) + count++; + } return count; } |